File: fannkuch.scala

package info (click to toggle)
scala 2.7.7.dfsg-4
  • links: PTS, VCS
  • area: main
  • in suites: squeeze
  • size: 75,804 kB
  • ctags: 1,852
  • sloc: java: 7,762; xml: 6,608; sh: 1,723; cs: 158; makefile: 9; ansic: 6
file content (48 lines) | stat: -rw-r--r-- 1,139 bytes parent folder | download
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
/*
 * The Computer Language Shootout
 * http://shootout.alioth.debian.org/
 *
 * contributed by Andrei Formiga
 */

object fannkuch
{
  var permN: Int = 0
  var maxFlips: Int = 0

  def flips(l: List[Int]): Int = (l: @unchecked) match { // bq: suppress warning
    case 1 :: ls => 0
    case n :: ls => flips((l take n reverse) ::: (l drop n)) + 1
  }

  def rotateLeft(l: List[Int]) = 
    l match { case List() => List() case x :: xs => xs ::: List(x) }

  def printPerm(perm: List[Int]) = 
    { perm foreach(x => Console.print(x.toString())); Console.println; }

  def processPerm(perm: List[Int]) = {
    val f = flips(perm)
    if (f > maxFlips) maxFlips = f
    if (permN < 30) { printPerm(perm); permN = permN + 1; }
  }

  def permutations(l: List[Int], n: Int, i: Int) {
    if (i < n) {
      if (n == 1)
	processPerm(l)
      else { 
	permutations(l, n - 1, 0)
	permutations(rotateLeft(l take n) ::: (l drop n), n, i + 1)
      }
    }
  }

  def main(args: Array[String])
  {
    val n = Integer.parseInt(args(0))

    permutations(List.range(1, n + 1), n, 0)
    Console.println("Pfannkuchen(" + n + ") = " + maxFlips)
  }
}