2011-06-15 13:19:50 -05:00
|
|
|
// Based on Isaac Gouy's fannkuchredux.csharp
|
|
|
|
use std;
|
2011-12-13 18:25:51 -06:00
|
|
|
import int;
|
|
|
|
import vec;
|
2011-03-13 20:22:27 -05:00
|
|
|
|
2011-07-27 07:19:39 -05:00
|
|
|
fn fannkuch(n: int) -> int {
|
|
|
|
fn perm1init(i: uint) -> int { ret i as int; }
|
2011-06-15 13:19:50 -05:00
|
|
|
|
2012-03-01 01:44:52 -06:00
|
|
|
let perm = vec::to_mut(vec::init_elt(n as uint, 0));
|
|
|
|
let perm1 = vec::to_mut(vec::init_fn(n as uint, perm1init));
|
|
|
|
let count = vec::to_mut(vec::init_elt(n as uint, 0));
|
2011-07-27 07:19:39 -05:00
|
|
|
let f = 0;
|
|
|
|
let i = 0;
|
|
|
|
let k = 0;
|
|
|
|
let r = 0;
|
|
|
|
let flips = 0;
|
|
|
|
let nperm = 0;
|
|
|
|
let checksum = 0;
|
2011-06-15 13:19:50 -05:00
|
|
|
r = n;
|
2011-07-27 07:19:39 -05:00
|
|
|
while r > 0 {
|
2011-06-15 13:19:50 -05:00
|
|
|
i = 0;
|
2011-08-19 17:16:48 -05:00
|
|
|
while r != 1 { count[r - 1] = r; r -= 1; }
|
|
|
|
while i < n { perm[i] = perm1[i]; i += 1; }
|
2011-06-15 13:19:50 -05:00
|
|
|
// Count flips and update max and checksum
|
|
|
|
|
|
|
|
f = 0;
|
2011-08-19 17:16:48 -05:00
|
|
|
k = perm[0];
|
2011-07-27 07:19:39 -05:00
|
|
|
while k != 0 {
|
2011-06-15 13:19:50 -05:00
|
|
|
i = 0;
|
2011-07-27 07:19:39 -05:00
|
|
|
while 2 * i < k {
|
2011-08-19 17:16:48 -05:00
|
|
|
let t = perm[i];
|
|
|
|
perm[i] = perm[k - i];
|
|
|
|
perm[k - i] = t;
|
2011-06-15 13:19:50 -05:00
|
|
|
i += 1;
|
|
|
|
}
|
2011-08-19 17:16:48 -05:00
|
|
|
k = perm[0];
|
2011-06-15 13:19:50 -05:00
|
|
|
f += 1;
|
|
|
|
}
|
2011-07-27 07:19:39 -05:00
|
|
|
if f > flips { flips = f; }
|
|
|
|
if nperm & 0x1 == 0 { checksum += f; } else { checksum -= f; }
|
2011-06-15 13:19:50 -05:00
|
|
|
// Use incremental change to generate another permutation
|
|
|
|
|
2011-07-27 07:19:39 -05:00
|
|
|
let go = true;
|
|
|
|
while go {
|
2012-01-14 21:53:26 -06:00
|
|
|
if r == n {
|
2012-03-12 22:04:27 -05:00
|
|
|
io::println(#fmt("%d", checksum));
|
2012-01-14 21:53:26 -06:00
|
|
|
ret flips;
|
|
|
|
}
|
2011-08-19 17:16:48 -05:00
|
|
|
let p0 = perm1[0];
|
2011-06-15 13:19:50 -05:00
|
|
|
i = 0;
|
2011-08-19 17:16:48 -05:00
|
|
|
while i < r { let j = i + 1; perm1[i] = perm1[j]; i = j; }
|
|
|
|
perm1[r] = p0;
|
|
|
|
count[r] -= 1;
|
|
|
|
if count[r] > 0 { go = false; } else { r += 1; }
|
2011-06-15 13:19:50 -05:00
|
|
|
}
|
|
|
|
nperm += 1;
|
2011-03-13 20:22:27 -05:00
|
|
|
}
|
2011-06-15 13:19:50 -05:00
|
|
|
ret flips;
|
2011-03-13 20:22:27 -05:00
|
|
|
}
|
|
|
|
|
2011-09-02 17:34:58 -05:00
|
|
|
fn main(args: [str]) {
|
2012-01-14 21:53:26 -06:00
|
|
|
let n = if vec::len(args) == 2u {
|
2012-02-22 06:18:15 -06:00
|
|
|
option::get(int::from_str(args[1]))
|
2012-01-14 21:53:26 -06:00
|
|
|
} else {
|
2012-01-14 22:34:00 -06:00
|
|
|
8
|
2012-01-14 21:53:26 -06:00
|
|
|
};
|
2012-03-12 22:04:27 -05:00
|
|
|
io::println(#fmt("Pfannkuchen(%d) = %d", n, fannkuch(n)));
|
2011-08-10 11:27:22 -05:00
|
|
|
}
|