Merge branch 'master' of git://iolanguage.com/Io
[io.git] / samples / shootout / fannkuch.io
blob75f3825193a9ace34cfdba0b660972a12b464538
1 #!/usr/bin/env io
3 /* The Great Computer Language Shootout
4 http://shootout.alioth.debian.org/
5 contributed by Ian Osgood */
7 fannkuch := method(n,
8 a := List clone
9 for (i,1,n, a append(i))
10 r := n
11 counts := a clone
12 count := maxFlips := 0
14 loop (
15 // display the first 30 permutations
16 if (count < 30, writeln(a join("")); count = count + 1)
18 // eliminate bad choices
19 if (a first != 1 and a last != n,
20 // pour the batter
21 p := a clone
22 flips := 0
23 // start flipping
24 while ((j := p first) > 1,
25 // reverse 0..j-1
26 i := -1
27 while ((i=i+1) < (j=j-1), p swapIndices(i,j))
28 flips = flips + 1
30 if (flips > maxFlips, maxFlips = flips)
33 // generate another permutation
34 while (r>1, counts atPut(r-1, r); r=r-1)
35 loop (
36 // -roll(r)
37 a atInsert(r, a removeAt(0))
39 if (counts atPut(r, counts at(r) - 1) > 0, break)
41 if ((r=r+1) == n, return maxFlips)
46 n := System args at(1) asNumber
47 f := fannkuch(n)
48 writeln("Pfannkuchen(", n, ") = ", f)