Fast Topswops calculation
JavaScript
function(d){for(t=0;x=(n=d[0])-1;t++)for(i=0;i<n/2;i++){m=d[x-i];d[x-i]=d[i];d[i]=m}return t}
You pass it the deck, like so:
f([3, 2, 1]) // 1
f([2, 3, 1]) // 2
f([1, 2, 3]) // 0
Scala: (This isn't a golf - is it?)
def transform (l: List[Int], sofar: Int = 0) : Int =
if (l(0) == 1) sofar else transform (l.take (l(0)).reverse ::: l.drop (l(0)), sofar + 1)
Complete application with testcase and stopwatch, including the shuffling of the Deck:
object DeckReverse extends Application {
def transform (l: List[Int], sofar: Int = 0) : Int =
if (l(0) == 1) sofar else transform (l.take (l(0)).reverse ::: l.drop (l(0)), sofar + 1)
def stopwatch (count: Int, size: Int) = {
val li = (1 until size).toList
val r = util.Random
val start = System.currentTimeMillis ()
(0 until count).foreach (_ => transform (r.shuffle (li)))
val stop = System.currentTimeMillis ()
println ("count: " + count + "\tsize: " + size + "\tduration: " + (stop - start) + " msecs")
}
stopwatch (1000, 100)
}
count: 1000 size: 100 duration: 1614 msecs machine: Single Pentium M 2Ghz
Python, 84 Chars
Golfing anyway... I'm using the numbers 0 through n-1. Assuming the array is stored in a variable x, it takes me 84 chars of Python.
while x[0]:x[:x[0]+1]=x[x[0]::-1]
However, performance is pretty bad due to memory abuse.