15
1
Background
Very skilled card handlers are capable of a technique whereby they cut a deck perfectly in half, then perfectly interleave the cards. If they start with a sorted deck and perform this technique flawlessly 52 times in a row, the deck will be restored to sorted order. Your challenge is to take a deck of cards an integer array and determine whether it can be sorted using only Faro shuffles.
Definition
Mathematically, a Faro shuffle is a permutation on 2 n elements (for any positive integer n) which takes the element in position i (1-indexed) to position 2 i (mod 2 n+1). We would also like to be able to handle odd-length lists, so in that case, just add one element to the end of the list (a Joker, if you have one handy) and Faro shuffle the new list as above, but ignore the added dummy element when checking the list's order.
Goal
Write a program or function that takes a list of integers and returns or outputs a truthy if some number of Faro shuffles would cause that list to be sorted in nondescending order (even if that number is zero--small lists should give a truthy). Otherwise, return or output a falsy.
Examples
[1,1,2,3,5,8,13,21] => True
[5,1,8,1,13,2,21,3] => True
[9,36,5,34,2,10,1] => True
[1,0] => True
[0] => True
[] => True
[3,2,1] => True
[3,1,2] => False
[9,8,7,6,5,4,3,2,1,0] => True
[9,8,7,6,5,4,3,2,0,1] => False
[3,1,4,1,5,9,2,6,9] => False
[-1,-1,-1,-2] => True
Scoring
This is code-golf so shortest source in bytes wins.
To avoid confusion with any fellow card handlers, it should be noted that there are two kinds of Faro shuffles. An in-shuffle and an out-shuffle. The method described here is an in-shuffle. Interestingly, it takes only 8 out-shuffles to return a deck to its original order. More Info
– BrainSteel – 2015-12-12T15:22:01.277Isn't this just "in-shuffle N+1 times and see if any of the lists along the way are sorted"? – lirtosiast – 2015-12-12T16:16:25.873
Actually n times is sufficient, because doing it 2n times is guaranteed to find all possible permutations, but you'll get at least one of either ascending or descending order in the first n. – quintopia – 2015-12-12T16:20:27.583
1Related. Related. – Martin Ender – 2015-12-12T16:32:22.183
1doesnt the first element always stay in the first position? – Eumel – 2015-12-13T16:28:15.180
@Eumel no. It always goes to the second position each shuffle. – quintopia – 2015-12-13T17:37:55.637
To make sure I understood: a shuffle would transform
1 2 3 4 5 6 7 8
into5 1 6 2 7 3 8 4
, right? – Luis Mendo – 2015-12-13T19:29:49.027