[Question]
  [
Your task is to write a program which, given a number and a string, splits the string into chunks of that size and reverses them.
## Rules
Your program will receive a positive integer `n`, as well as a string `s` with length at least one consisting of only printable ASCII (not including whitespace). The string should then be split into chunks of length `n`, if the length of the string isn't divisible by `n` any leftover at the end should be considered its own chunk. Then, reverse the order of the chunks and put them together again.
## Test Cases
```
n   s           Output
2   abcdefgh    ghefcdab
3   foobarbaz   bazbarfoo
3   abcdefgh    ghdefabc
2   a           a
1   abcdefgh    hgfedcba
2   aaaaaa      aaaaaa
2   baaaab      abaaba
50  abcdefgh    abcdefgh
6   abcdefghi   ghiabcdef
```
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so you should aim for as few bytes as possible.
  
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 2 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
sṚ
```
A full program that prints the result.
**[Try it online!](https://tio.run/nexus/jelly#@1/8cOes////JyYlp6SmpWf8NwIA "Jelly – TIO Nexus")**
### How?
```
sṚ - Main link: string, number                                   e.g. 'abcdefg', 3
s  - split string into chunks of length number (keeping any overflow) ["abc","def","g"]
 Ṛ - reverse the resulting list                                       ["g","def","abc"]
   - implicit print                                                   gdefabc
```
[Answer]
# [Python 3](https://docs.python.org/3/), 35 bytes
```
f=lambda s,n:s and f(s[n:],n)+s[:n]
```
[Try it online!](https://tio.run/nexus/python3#XYxBDoMgEEXXcopZQmoabdMNiScxLAYBJbGjEVe9vB2pTWNnQd5/85ktNCM@rUNIJekESA6CTC1pU5K6pFaT2cK0wBjJQySYZk@yUloU2TR5cU3zGFepRDEvkVYZ5G7b2pSwxxwqo5TabgCAtnM@9AMj9IMPnUMr7hzCNFlcLL6Y@WVmkzfnL4wsRL4Fv0FR/1WHPnjXWfxU8xzVPFnbneyhOXD7UZ3PfPkN "Python 3 – TIO Nexus")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~5 4~~ 3 bytes
-1 thanks to Dennis  
-1 thanks to carusocomputing
```
ôRJ
```
[Try it online!](https://tio.run/##MzBNTDJM/f//8JYgr///jbgSk5JTUtPSMzIB "05AB1E – Try It Online")
```
     # Implicit: push input
 ô   # Split in pieces of length b
  RJ # Reverse and join
```
[Answer]
## JavaScript (ES6), 37 bytes
```
n=>F=s=>s&&F(s.slice(n))+s.slice(0,n)
```
Takes input by currying: number first, then string, like `f(2)("abcdefgh")`.
```
let f =
n=>F=s=>s&&F(s.slice(n))+s.slice(0,n)
let g = (n, s) => console.log(`f(${n})("${s}"): ${f(n)(s)}`)
g(2, "abcdefgh")
g(3, "foobarbaz")
g(3, "abcdefgh")
g(2, "a")
g(1, "abcdefgh")
g(2, "aaaaaa")
g(2, "baaaab")
g(50, "abcdefgh")
```
[Answer]
# [Perl 6](https://perl6.org), ~~28~~ 20 bytes
```
{$^b.comb($^a).reverse.join}
```
[Try it](https://tio.run/nexus/perl6#XU7ZTsMwEHz3V4wqCyVKSA8ED41S8Q/wiCrZzuZAzaE4rYAq/HrYuIW2rOTR7OzsrPeWcHiKTCyqT9yZJiUk41FudWSaSntyq/yoowN1lqL3pqyHkX3PPdkeCXZlTdbzo0q1axwFUK3tHN5bGviML384j3kWyEWIb7mcYCUGsefLr5wTi3anagQuNBZZ053z7zfwIOsQ0vKjj5ZMTyl8d6m0mD7r8Vxa/2oeYnbaQbK5qDMxjCsASpuUsrxgirygzKRKiwdusqbRqtPqizkjc1bc5HaFKQvCZeFSSiz/WYs8o9RodbK6OltdOVlPTJ9lbtj9uLiN@eU/ "Perl 6 – TIO Nexus")
```
{[R~] $^b.comb($^a)}
```
[Try it](https://tio.run/nexus/perl6#XU7bSsNAFHzfrxjKIgmJ6UX0oSHFb1Df1MJek0JzoZuKWtJfjyfb2FoP7GHOzJw5u3cGHw@JSln5hRtVa4OsP7w@Hd/B1zJRdSkDvhZh15P@2BrXIsN2UxkXhEkpmiUODCiXborgTUch9edzn6akRXwW48jnQ1uwju3p4gvlpKzZigqRD02ZrXdj/u0KAXgVgzt65rMxqjUaob@0cRg@GZDOXfhHjzE57SBbXdgJ6/oFACGVNjYvCCIvjFVaSHZHg61rKXZSfBOmTpgYr1yvECSC@SxcSrD5P2uRW6OVFCerr9Hqy9NyQHKkaSD3/ew65hf/AA "Perl 6 – TIO Nexus")
## Expanded:
```
{  # bare block lambda with placeholder parameters ｢$a｣ and ｢$b｣
  [R[~]] # reduce the following using the reverse meta operator `R`
         # combined with the string concatenation operator
    # `comb` with a number splits the invocant into chunks of that size
    $^b.comb($^a)
}
```
[Answer]
# Bash + coreutils, 22
```
fold -$1|tac|tr -d \\n
```
[Try it online](https://tio.run/nexus/bash#K8/IzElVKEpNTLFWSMnnKk4tUVAJcg3wieRKTc7IV1AxUqj5n5afk6Kgq2JYU5KYXFNSpKCbohATk/cfpIArJT8v9b@RgoJCYlJySmpaegaXMZCTlp@flFiUlFgF5sGlwOq4DDGEwADMTAKxkrhMDZCUAAA).
[Answer]
# [Haskell](https://www.haskell.org/), 32 bytes
```
n#""=""
n#s=n#drop n s++take n s
```
[Try it online!](https://tio.run/nexus/haskell#FcYxDoAgDAXQ3VP8tG6MzhymCkolVgLcv8Y3PTcmikSL8YjGqb8NhhHClJr/@SNqiGhdbWIFNjBI9iPl8yp6V/IP "Haskell – TIO Nexus")
[Answer]
# PHP, 53 Bytes
```
<?=join(array_reverse(str_split($argv[2],$argv[1])));
```
[Answer]
# [Röda](https://github.com/fergusq/roda), 36 bytes
```
f n{[[_]..[try head n-1]]|reverse|_}
```
[Try it online!](https://tio.run/nexus/roda#@5@mkFcdHR0fq6cXXVJUqZCRmpiikKdrGBtbU5RallpUnFoTX/s/NzEzT6GaizM5I7GoWEMpKREIkpQ0FWoU0jSMNK0VCooy80oUlJTgKtLy85MSi5ISq6CKjLEpSkxKTklNS8/AZxCaGkMi1JgaICuq/Q8A "Röda – TIO Nexus")
It's a function that takes one argument. The characters of the string must be in the stream.
`try` is used to discard errors in case that the `head` function can't read `n-1` values.
Explanation:
```
f n{[[_]..[try head n-1]]|reverse|_}
f n{                               } /* Function declaration */
                                     /* In a loop: */
      _                              /*   Pull one value */
           try head n-1              /*   Pull n-1 values (or less) */
     [ ]..[            ]             /*   Make an array */
    [                   ]            /*   Push it to the stream */
                         |reverse    /* Reverse all values in the stream */
                                 |_  /* Flat all arrays in the stream */
                                     /* Characters in the stream are printed */
```
Not as obfuscated as usually. I think it's quite beautiful. :)
[Answer]
# [CJam](https://sourceforge.net/p/cjam), 5 bytes
```
q~/W%
```
Input is a number and a string enclosed in double quotes, separated by whitespace.
[Try it online!](https://tio.run/nexus/cjam#@19Ypx@u@v@/kYJSYlJySmpaeoYSAA "CJam – TIO Nexus") Or [verify all test cases](https://tio.run/nexus/cjam#@1@dU6cfruoXX5v@/7@RgoKCUmJSckpqWnqGEpcxiJuWn5@UWJSUWAXlI6QhqpW4DLEJgwGUkwRiJylxmRogKwQA).
### Explanation
```
q~   e# Read all input and evaluate: pushes a number and a string
/    e# Split string into chunks of that size. Last chunk may be
     e# smaller. Gives an array of strings
W%   e# Reverse the array. Implicitly display
```
[Answer]
## Batch, 74 bytes
```
@if %2=="" (echo %~3)else set s=%~2&call %0 %1 "%%s:~%1%%" "%%s:~,%1%%%~3"
```
Rather annoyingly this ends up being recursive rather than tail recursive.
[Answer]
# [V](https://github.com/DJMcMayhem/V), ~~13~~ 10 bytes
```
òÀ|lDÏpòÍî
```
[Try it online!](https://tio.run/nexus/v#@3940@GGmhyXw/0FQFbv4XX//ycmJaekpqVn/DcCAA "V – TIO Nexus")
```
ò      ò    ' Recursively
 À|         ' Go to the "nth" column
   l        ' Move one character right (breaks loop when no more chunks)
    D       ' Delete from here to the end of the line
     Ï      ' Add a line above the current line (now contains one chunk)
      p     ' Paste the remainder of the line that was deleted
        Íî  ' Remove all newlines
```
In Action:
```
abcdefghijkl
```
turns into
```
efghijkl
abcd
```
which becomes
```
ijkl
efgh
abcd
```
before all newlines are removed
[Answer]
# [brainfuck](https://github.com/TryItOnline/tio-transpilers), 78 bytes
```
,<<<+[[>]>+>[[>],<[<]>+>-]<-[->>[>]>>+<<<[<]<]>>]<<<<[[<]>[-[+.[-]]+>]<[<]<<<]
```
The first byte of the input is the chunk size, given by byte value. The rest of the bytes are considered to be the string.
[Try it online!](https://tio.run/nexus/brainfuck#FYrJDcAwDMOAruO4EwhaRNCjZ7r/Aqn9EkFqDQAh0Qz2DAjNaaSS7MKoU@kKNJr7o1TsSjtKdgW81nac1/288/sB "brainfuck – TIO Nexus")
**Expanded and commented**
```
Read the chunk size byte
This cell will become a counter cell
,
Move left a few cells an increment; 
this is to make the starting position 
line up with the relative positioning
needed to fit in with the loop
<<<+
While the current cell is nonzero:
[
 Move right to the first zero cell
 [>]
 Move right once and increment and then move right to the counter cell
 The increment is required because of "move to zero cell" loops
 >+>
 This loop will store one chunk of the input in consecutive memory cells
 [
  [>]   Move right until a zero cell is hit
  ,     Store 1 byte of input there
  <[<]  Move back left until a zero cell (other than the current one) is hit
  >+>-  Increment the temporary cell by 1 and decrement the counter
 ] (end loop once the counter hits zero)
 Decrement the temp cell (because we needed to have 1 there initially to make the cell location work)
 <-
 Move the temp cell to three cells after the end of the chunk
 This is the new counter cell for the next chunk
 [->>[>]>>+<<<[<]<]
 Move two cells right from where the temp cell was
 This is the first cell of the chunk; if it's 0
 then the input is finished and the loop should end
 >>
]
Due to the way the counter is kept track of the tape head
will always be four cells to the right of the last input cell
when the loops breaks
<<<<
Now the chunks are printed one by one
At the start of an iteration the tape head is at the end of a chunk
[
 Locate the start of the last chunk
 [<]>
 Print the chunk:
 [
  Print the byte held in the current cell if it isn't 1
  This is necessary because we left a stray 1 in a cell at
  the start which shouldn't be printed
  -[+.[-]]+
  Move to the next cell
  >
 ]
 Move to just left of the chunk
 <[<]
 Move three cells over to the end of the next chunk
 <<<
]
```
[Answer]
# PowerShell, ~~56~~ 49 bytes
-7 bytes thanks to [mazzy](https://codegolf.stackexchange.com/users/80745/mazzy)
```
param($n,$s)$s-split"(.{$n})"-ne''|%{$r=$_+$r};$r
```
[Try it online!](https://tio.run/##XZDhSsQwEIT/5ymWsmdatKIn@kM5uAcRjqRN2kJNayIo9vrsdS6pnOdCwuzk2yXMOHwaH1rT9wtb2tG0jMqrt5zdDYeCQxnGvvvI8tuJ3VxkpTNSHjcT@x0frtnPL@yXWeyl2BKR0lVtbNNCUtMaW9VKiwc0dhi08lp9Q@OGhhNfLkcgYaRddC4l7v@hbWNNXWmV0FgrGiva@qT0aqMB/Xh3ueZXi6c/TRe/0qVWyD2lDEi@OklH2tAkTrNIiDjgfCG2FeFDevKwrpAnOyDRyjiHW5p38MUziOxMSinm5Qc)
[Answer]
# Mathematica, 46 bytes
```
""<>Reverse@Partition[Characters@#2,#,#,1,{}]&
```
Anonymous function. Takes a number and a string as input and returns a string as output. Not much to see here.
[Answer]
# **Javascript - ~~54~~ ~~47~~ 46 bytes**
Remade:
```
(s,n)=>s.match(eval(`/.{1,${n}}/g`)).reverse()
```
Used as
```
f=(s,n)=>s.match(eval(`/.{1,${n}}/g`)).reverse()
alert(f("abcdefgh",2));
```
Thank you to @ETHproductions for some RegEx quickenning
Thank you to @Shaggy for an extra byte in the eval!
Original:
```
(s,n)=>s.match(new RegExp('.{1,'+n+'}','g')).reverse()
```
[Answer]
# Pyth, 5 bytes
```
s_c.*
```
[Try it online](https://pyth.herokuapp.com/?code=s_c.%2A&test_suite=1&test_suite_input=%5B%22abcdefgh%22%2C%202%5D%0A%5B%22foobarbaz%22%2C%203%5D%0A%5B%22abcdefgh%22%2C%203%5D%0A%5B%22a%22%2C%202%5D%0A%5B%22abcdefgh%22%2C%201%5D%0A%5B%22aaaaaa%22%2C%202%5D%0A%5B%22baaaab%22%2C%202%5D%0A%5B%22abcdefgh%22%2C%2050%5D&debug=0).
### Explanation
```
   .*  splat implicit input
  c    split into chunks length n
 _     reverse
s      join
```
[Answer]
# [Retina](https://github.com/m-ender/retina), 38 bytes
*1 byte saved thanks to @LeakyNun*
```
^
 
+`(.* (1)+¶)((?<-2>.)+)
$3$1
 1+¶
```
(Note the space on the second line, and the trailing space)
This program takes input as unary on the first line, and the string on the second.
[Try it online!](https://tio.run/nexus/retina#@x/HpcClnaChp6WgYaipfWibpoaGvY2ukZ2eprYml4qxiiGXgiFQmOv/f0NDrsSk5JTUtPQMAA "Retina – TIO Nexus")
[Test Suite! (slightly modified)](https://tio.run/nexus/retina#U9VwT/gfx6XApZ2goaeloGGoqW2tqaFhb6NrZKenqa3JpWKsYsilYKhtzfX/v6GhdWJSckpqWnoGlyGQk5afn5RYlJRYBeYhSVkncqHxwQDESgIxkkAaSARw8wA "Retina – TIO Nexus")
### Explanation
The first step is to prepend a space (will become important later on).
```
^
 
```
Now we reverse. This uses .NET's balancing groups. It is important to note that groups here act as stacks, so every match is essentially pushed onto the stack. Here we capture every digit in the unary number into group 2. Now each time a character in the string is found, a match is popped from group 2. This ensures the the number of characters does not exceed that of the unary number.
```
+`(.* (1)+¶)                       Capture the unary number in group 2
             ((?<-2>.)+)           Balancing group for substrings
$3$1                               Reverse
```
And finally remove the unary number and the newline.
```
 1+¶
```
[Answer]
## Java, 147 138 Bytes
`String r(String s,int n){String r="";int l=s.length();for(int i=l/n*n;i>=0;i-=n)if(!(i>=l))r+=(i+n)>=l?s.substring(i):s.substring(i,i+n);return r;}`
Saved 9 Bytes thanks to Kevin Cruijssen!
```
String r(String s,int n){String r="";int l=s.length(),i=l/n*n;for(;i>=0;i-=n)if(i<l)r+=i+n>=l?s.substring(i):s.substring(i,i+n);return r;}
```
In expanded form:
```
String r(String s,int n){
    String r="";
    int l=s.length(),i=l/n*n;
    for(;i>=0;i-=n)
        if(i<l)
            r+=i+n>=l?s.substring(i):s.substring(i,i+n);
    return r;
}
```
This is actually my first try to codegolf ever, so any feedback is welcome!
[Answer]
# [Perl 5](https://www.perl.org/), 25 bytes
Uses the `-lnM5.010` flags.
```
say reverse<>=~/.{1,$_}/g
```
[Try it online!](https://tio.run/##K0gtyjH9/784sVKhKLUstag41cbOtk5fr9pQRyW@Vj/9/38jrsSk5JTUtPSMf/kFJZn5ecX/dXPyfE31DAwNAA "Perl 5 – Try It Online")
Shoutout to Grinnz for telling me about `=~ m/.{1,$n}/g`
`-M5.010` enables the use of the `say` function, which for our purposes is print with a shorter name.
`-n` puts the first line of input into `$_`, and `-l` chomps off the trailing newline.
We then get the second line of input using `<>`, and apply it to the regex `.{1,$_}`: any character, between 1 and $\_ (the first input) times. Since this is greedy by default, it tries to always match $\_ characters. The `1,` is needed for the possible leftover chunk at the end.
The `/g` modifier gives us *every* match of that regex in the input string as a list, which is then reversed and printed. In Perl, passing a list to `say` joins it without any delimiter by default.
[Answer]
# [Dyalog APL Extended](https://github.com/abrudz/dyalog-apl-extended), ~~16~~ 15 bytes
```
{∊⌽⍵⊂⍨(≢⍵)⍴=⍳⍺}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/qG9qZv6jtgkG/9OAZPWjjq5HPXsf9W591NX0qHeFxqPORUCO5qPeLbaPejc/6t1V@/@/gpFCmoJ6YlJySmpaeoY6l4IxiJ@Wn5@UWJSUWAUTQFIA0qCjnghkGWKRUU8EAxgvCcRJUucyNUBRCwA "APL (Dyalog Extended) – Try It Online")
[Answer]
# Python, 62 bytes
```
lambda n,s:''.join([s[i:i+n]for i in range(0,len(s),n)][::-1])
```
[Try it online!](https://tio.run/nexus/python2#TcjBDoIwDADQu1/RW7dYDZB4WeKXzB062aAECtn8/@nFhHd8@flqK29xZFCqDvG@7KLGVy9OrhryXkBAFArrlExHa1JTLakN3rlbH2w7iugHshkII/9EtJf/PTpCju8x5Wk@9XDe9gU "Python 2 – TIO Nexus")
[Answer]
# [Stacked](https://github.com/ConorOBrien-Foxx/stacked), 9 bytes
```
#<rev''#`
```
[Try it online!](https://tio.run/nexus/stacked#U09MSk5JTUvPUFcw@q9sU5Rapq6unPA/v7TkPwA "Stacked – TIO Nexus")
`#<` chunks, `rev` reverses, and `''#`` joins by empty string. Quite simple.
[Answer]
## [QBIC](https://drive.google.com/drive/folders/0B0R1Jgqp8Gg4cVJCZkRkdEthZDQ), 24 bytes
```
:;[1,_lA|,a|Z=_sA,b,a|+Z
```
This makes excellent use of the new substring-function I recently added to QBIC:
```
:;          Read in the cmd line params a (number) and A$ (text)
[1,_lA|,a|  Set up a FOR loop: FOR b = 1; b <= A$.length; b += a
Z=          Modify Z$; Z$ is autoprinted at the end of QBIC code
_sA,b,a|    SUBSTRING: _s is the function followed by the string 
               to take from, the starting pos and the # of chars
+Z          Take chunks from further into A$, put them before Z$
```
[Answer]
# Pyth, 4 bytes
```
s_cF
```
Takes input as `"s",n`: [Try it for yourself!](http://pyth.herokuapp.com/?code=s_cF&input=%22abcdefgh%22%2C2&debug=0)
[Answer]
# [Convex](https://github.com/GamrCorps/Convex), 2 bytes
```
/¥
```
[Try it online!](https://tio.run/nexus/convex#@69/aOn///@V0vLzkxKLkhKrlP4bAwA "Convex – TIO Nexus")
[Answer]
## C, 69 bytes
```
i;f(s,n)char*s;{i=strlen(s);for(i-=i%n;printf("%.*s",n,s+i),i;i-=n);}
```
Result is printed out to the standard output.
[Answer]
# Scala, 57 55 bytes
```
(n:Int,s:String)=>(""/:s.grouped(n).toSeq.reverse)(_+_)
```
Thanks Jacob! Try it [here](http://www.scala-repl.org/code/welcome).
Note: By using the symbol form of foldLeft ("/:"), I was able to take off a couple more bytes.
[Answer]
# [Ohm](https://github.com/MiningPotatoes/Ohm), 5 bytes
```
σ]QWJ
```
[Try it online!](https://tio.run/##y8/I/f//fHNsYLjX//9p@flJiUVJiVVcxgA "Ohm – Try It Online")
### Explanation
```
σ]QWJ
σ         # Split input1 into input2 pieces
 ]        # Flatten array
  Q       # Reverses stack
   W      # Wraps stack to array
    J     # Joins stack
          # Implicit print
```
[Answer]
# [R](https://www.r-project.org/), ~~69~~ 60 bytes
```
function(s,n)cat(substring(s,(x=nchar(s):0*n)+1,x+n),sep="")
```
[Try it online!](https://tio.run/##Dcg7DoAgDADQqximVmqii4ORwwDyW6qhkHh79I2vjjidy4idfSs3gxCjtw2kO2m1cPoHXsM@2wqCxzoz6o1ezUgSHqMUjgjKOn@FmHJRtOP4AA "R – Try It Online")
Thanks to [Kirill L.](https://codegolf.stackexchange.com/users/78274/kirill-l) for the suggestion to remove `seq`.
]