Faro shuffle an array

A Faro shuffle is a technique frequently used by magicians to "shuffle" a deck. To perform a Faro shuffle you first cut the deck into 2 equal halves then you interleave the two halves. For example

[1 2 3 4 5 6 7 8]


Faro shuffled is

[1 5 2 6 3 7 4 8]


This can be repeated any number of times. Interestingly enough, if you repeat this enough times, you will always end up back at the original array. For example:

[1 2 3 4 5 6 7 8]
[1 5 2 6 3 7 4 8]
[1 3 5 7 2 4 6 8]
[1 2 3 4 5 6 7 8]


Notice that 1 stays on the bottom and 8 stays on the top. That makes this an outer-shuffle. This is an important distinction.

The Challenge

Given an array of integers A, and a number N, output the array after N Faro shuffles. A may contain repeated or negative elements, but it will always have an even number of elements. You can assume the array will not be empty. You can also assume that N will be a non-negative integer, although it may be 0. You can take these inputs in any reasonable manner. The shortest answer in bytes wins!

Test IO:

#N, A,                                              Output
1,  [1, 2, 3, 4, 5, 6, 7, 8]                        [1, 5, 2, 6, 3, 7, 4, 8]
2,  [1, 2, 3, 4, 5, 6, 7, 8]                        [1, 3, 5, 7, 2, 4, 6, 8]
7,  [-23, -37, 52, 0, -6, -7, -8, 89]               [-23, -6, -37, -7, 52, -8, 0, 89]
0,  [4, 8, 15, 16, 23, 42]                          [4, 8, 15, 16, 23, 42]
11, [10, 11, 8, 15, 13, 13, 19, 3, 7, 3, 15, 19]    [10, 19, 11, 3, 8, 7, 15, 3, 13, 15, 13, 19]


And, a massive test case:

23, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100]


Should output:

[1, 30, 59, 88, 18, 47, 76, 6, 35, 64, 93, 23, 52, 81, 11, 40, 69, 98, 28, 57, 86, 16, 45, 74, 4, 33, 62, 91, 21, 50, 79, 9, 38, 67, 96, 26, 55, 84, 14, 43, 72, 2, 31, 60, 89, 19, 48, 77, 7, 36, 65, 94, 24, 53, 82, 12, 41, 70, 99, 29, 58, 87, 17, 46, 75, 5, 34, 63, 92, 22, 51, 80, 10, 39, 68, 97, 27, 56, 85, 15, 44, 73, 3, 32, 61, 90, 20, 49, 78, 8, 37, 66, 95, 25, 54, 83, 13, 42, 71, 100]

• Can the array contain zero elements? Jun 5, 2016 at 4:54
• @LeakyNun We'll say no, you don't have to handle zero elements. Jun 5, 2016 at 5:00
• Jun 5, 2016 at 15:12
• Related Jun 6, 2016 at 7:11
• Any permutation of a finite set, if repeated enough times, will end up back where it started; this isn't special to Faro shuffles. Aug 14, 2016 at 8:45

vim, 6259 54

qrma50%mb:norm@q<cr>ggqOjdd'apjma'b@q<esc>0"qDJ<C-a>D@"i@r<esc>xxdd@"


Wow. This is possibly the hackiest thing I've written for PPCG, and that's saying something.

Input is taken as N on the first line followed by the elements of the array, each on its own line.

qr         first, we're going to record the contents of the @r macro. this is
the macro which does the faro-shuffle operation.
ma       set the mark 'a at the beginning of the file
50%      move to the 50% point of the file (i.e. halfway down)
mb       set another mark here
:norm@q  evaluate the recursive macro @q. we'll get to what that does later,
but the interesting part here is that it's :norm@q instead of @q.
this is because a recursive macro terminates at the end of the
file, which means when @q terminates, @r would also abort, which
would make calling it with a count impossible. running @q under
:norm prevents this.
gg       move back to the top of the file for the next iteration
q          end recording
O          now we're inserting contents of the @q macro, the recursive part
we can't record it directly because it's destructive
j        move to line directly below mark 'b (which was just set before @q)
dd       delete this line and bring it...
'ap      up after mark 'a (which starts on line 1, bringing the N/2th line
directly below line 1, aka line 2)
jma      replace mark 'a one line below this so that the next time we call
'ap, the line from the second half is interleaved with the lines
from the first half
'b       jump back to mark 'b (remember, 'b is the last line of the first
half of the file, originally reached via 50%)
@q       call ourselves, causing the macro to run until hitting EOF
0"qD       delete this into register "q
J          delete the empty line that remains
<C-a>      here's another interesting bit: we want to run @r N times. but 0@r
means "go to column 0, and then run @r once." so we have to
increment the input number...
D@"        and then *that* many times...
i@r        insert @r...
xx         ... and finally, delete two characters, which is the extra @r from
the increment
dd         delete the sequence of @rs into the "" register...
@"         and run it!


I actually possibly found several vim bugs while writing this answer:

• recording macros is not possible within other macros (when setting their text manually, not with q) or within :*maps.

• :let @a='<C-v><cr>'<cr>i<C-r>a outputs two newlines, not one, for whatever arcane reason.

I might investigate those further later.

Thanks to Dr Green Eggs and Ham DJ for 3 bytes!

• This is beautiful and horrifying. I probably don't have enough patience to do this in vim. :P Also, you can take off 2 bytes by doing "rck instead of vgg"rc, and you can take off another 5 by doing dw@"i@r<esc> instead of AA@R<C-v><esc><esc>0D@" Jun 5, 2016 at 6:48
• @DrGreenEggsandHamDJ Can't do that first one because that grabs a trailing newline as well, but that second optimization works. Thanks! Jun 5, 2016 at 16:28

05AB1E, 5 bytes

Code:

F2äø˜


Explanation, input: N, array:

F      # Do the following N times
2ä    # Split the array into 2 pieces
ø   # Zip
˜  # Deep flatten


Uses the CP-1252 encoding. Try it online!.

• Damn, I was too slow!
– user53406
Jun 5, 2016 at 8:06

Python, 68 57 bytes

f=lambda n,x:n and f(n-1,sum(zip(x,x[len(x)/2:]),()))or x


Thanks to @Sp3000 for golfing off 11 bytes!

Test it on Ideone.

Python 2, 59 bytes

def f(n,L):exec"l=len(L)/2;L=(L+L[1:]*~-l)[::l];"*n;print L


A different approach, slightly longer than the other Python answers. Only works for positive even numbers of elements.

e.g. for 1, [1,2,3,4,5,6,7,8], take the array and append len(L)/2-1 copies of itself minus the first element, e.g.

[1,2,3,4,5,6,7,8,2,3,4,5,6,7,8,2,3,4,5,6,7,8,2,3,4,5,6,7,8]


Then take every len(L)/2th element.

[1,2,3,4,5,6,7,8,2,3,4,5,6,7,8,2,3,4,5,6,7,8,2,3,4,5,6,7,8]
^       ^       ^       ^       ^       ^       ^       ^


0!a=a
n!a|s<-length a=(n-1)![a!!mod(div(s*i+i)2)s|i<-[0..s-1]]


Let s = 2·t be the size of the list. The i-th element of the new list is obtained by taking the -th element of the old list, zero-indexed, modulo s.

Proof: if i = 2·k is even, then

and if i = 2·k + 1 is odd, then

Thus the values used for indexing are 0, t, 1, t + 1, 2, t + 2, …

J - 12 bytes

Adverb (!) taking number of shuffles on the left and the array to shuffle on the right.

/:#/:@$0,#^:  The J parser has rules for writing tacit adverbs, but they have very low precedence: if you want to use a train of verbs as a left argument, you can omit an otherwise necessary set of parentheses. So the above is actually short for (/:#/:@$0,#)^:, which takes the number of shuffles on the left as an adverb, and then becomes a monadic function taking the array to shuffle on the right.

That said, we shuffle as follows. # is the length of the array, so 0,# is a two element list: 0 followed by something nonzero. Then #/:@$ replicates that into a list as long as the input array, and takes its sort vector. The sort vector of a list is the information for how to sort the list: the (0-based) invdex of the smallest element, followed by the index of the next-smallest, and so on. For example, the sort vector of 0 1 0 1 ... will thus be 0 2 4 ... 1 3 5 .... If J were now to sort this sort vector, it would Faro-shuffle it; but that would be trivial, since we'd get 0 1 2 3 ... back. So we use dyadic /: to sort the input array as if it were 0 2 4 ... 1 3 5 ..., which Faro-shuffles it. Example usage below. Try it yourself at tryj.tk!  1 (/:#/:@$0,#^:) 1 2 3 4 5 6 7 8
1 5 2 6 3 7 4 8

Mathematica 44 bytes

With 4 bytes saved thanks to @miles.

Riffle@@TakeDrop[#,Length@#/2]&~Nest~##&


Riffle @@ TakeDrop[#, Length@#/2] &~Nest~## &[list, nShuffles] splits the list into two equal sublists and shuffles (Riffles) them.

 Riffle @@ TakeDrop[#, Length@#/2] &~Nest~## &[Range@8, 1]


{1, 5, 2, 6, 3, 7, 4, 8}

Riffle @@ TakeDrop[#, Length@#/2] &~Nest~## &[Range@100, 23]


{1, 30, 59, 88, 18, 47, 76, 6, 35, 64, 93, 23, 52, 81, 11, 40, 69, 98, 28, 57, 86, 16, 45, 74, 4, 33, 62, 91, 21, 50, 79, 9, 38, 67, 96, 26, 55, 84, 14, 43, 72, 2, 31, 60, 89, 19, 48, 77, 7, 36, 65, 94, 24, 53, 82, 12, 41, 70, 99, 29, 58, 87, 17, 46, 75, 5, 34, 63, 92, 22, 51, 80, 10, 39, 68, 97, 27, 56, 85, 15, 44, 73, 3, 32, 61, 90, 20, 49, 78, 8, 37, 66, 95, 25, 54, 83, 13, 42, 71, 100}

• Using TakeDrop we can find a solution using 40 bytes as Riffle@@TakeDrop[#,Length@#/2]&~Nest~##& while also taking the sequence ## to be parsed as additional arguments to Nest. Jun 5, 2016 at 23:34
• @miles. Very nice use of TakeDrop. And it is better to use ## to insert the sequence. Jun 6, 2016 at 0:12

APL, 23 21 chars

({⊃,/⍵(↑,¨↓)⍨2÷⍨⍴⍵}⍣N)A


Without the assumption (Thanks to Dennis) and 1 char shorter:

({{∊,⌿2(2÷⍨≢⍵)⍴⍵}⍣⎕)⎕


Try it on online.

java, 109 bytes

int[]f(int[]a,int n){for(int x,q=a.length,d[];0<n--;a=d){d=new int[q];for(x=0;x<q;x++)d[(2*x+2*x/q)%q]=a[x];}return a;}

Explanation: There is a pattern to how the elements move when they are faro shuffled:

let x be the original index

let y be the new index

let L be the length of the array

• y is double x
• if x is greater than or equal to half of L then increment y
• keep y within the array's bounds

or as code: y=(2*x+x/(L/2))%L

This assumes that indicies start at 0. Here's the code further explained:

int[] faroShuffle( int[] array, int numberOfShuffles ) {
//repeat the faro shuffle n times
for( int index, length=array.length, destination[]; 0<numberOfShuffles--; array=destination ) {
//new array to copy over the elements
destination=new int[length];
//copy the elements into the new array
for( index=0; index<length; index++ )
destination[(2*index+2*index/length)%length]=array[index];
//at the end of each loop, copy the reference to the new array and use it going forward
}
return array;
}


see ideone for test cases

• I know it's been more than a year, but you can golf a few parts: void f(int[]a,int n){for(int x,q=a.length,d[];0<n--;a=d)for(d=new int[q],x=0;x<q;)d[(2*x+2*x/q)%q]=a[x++];} (107 bytes - your current answer is 119 btw, not 109, so -12 bytes). Since you modify the input array, there is no need to return it, so you can change it to a void to reduce bytes. Oh, and if you convert to a Java 8 lambda with currying you could make it even shorter: a->n->{for(int x,q=a.length,d[];0<n--;a=d){d=new int[q];for(x=0;x<q;x++)d[(2*x+2*x/q)%q]=a[x];}} (96 bytes) Aug 31, 2017 at 14:52

Julia, 45 42 bytes

a\n=n>0?reshape(a,endof(a)÷2,2)'[:]\~-n:a


Try it online!

How it works

We (re)define the binary operator \ for this task. Let a be an array and n a non-negative integer.

If n is positive, we shuffle the array. This is achieved by reshaping it into a matrix of length(a) ÷ 2 rows and two columns. ' transposes the resulting matrix, creating of two rows, then flattening the result with [:]. Since Julia stores matrices in column-major order, this interleaves the two rows.

Afterwards, we call \ recursively with the shuffled a and n - 1 (~-n) as arguments, thus performing additional shuffles. Once n reaches 0, we return the current value of a.

Pyke, 7 bytes

VDlec,s


Try it here!

V       - Repeat N times:
D      -  a,b = a (2nd arg first time round)
le    -  b = len(b)//2
c   -  a = chunk(a,b)
,  -  a = zip(*a)
s -  a = sum(a, [])


Actually, 15 bytes

;l½≈@│t)HZ♂in


Try it online!

Explanation:

;l½≈@│t)HZ♂in
            n  do the following n times:
;l½≈              push half the length of the array
@             swap
│            duplicate entire stack
t)H         last L//2 elements, first L//2 elements
Z♂i      zip, flatten each element


Prolog, 116 bytes

a([],[[],[]]).
a([H,I|T],[[H|U],[I|V]]):-a(T,[U,V]).
f(X,0,X).
f(X,N,Y):-N>0,M is N-1,f(X,M,Z),a(Z,[A,B]),append(A,B,Y).


Usage

?- f([1,2,3,4,5,6,7,8],2,X).
X = [1, 5, 2, 6, 3, 7, 4, 8] ;
false.


$a=<>;@F=map@F[$_,@F/2+$_],0..$#F/2while$a--;say"@F"  Try it online! PHP, 98 bytes function($a,$n){while($n--)for($z=count($a)/2;$z;)array_splice($a,$z--,0,array_pop($a));return\$a;}