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; }
|
|
|
|
let perm1init_ = perm1init; // Rustboot workaround
|
2011-06-15 13:19:50 -05:00
|
|
|
|
2011-08-15 18:38:23 -05:00
|
|
|
let perm = vec::init_elt_mut(0, n as uint);
|
|
|
|
let perm1 = vec::init_fn_mut(perm1init_, n as uint);
|
|
|
|
let count = vec::init_elt_mut(0, n as uint);
|
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 {
|
2011-12-22 19:53:53 -06:00
|
|
|
if r == n { log(debug, checksum); 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]) {
|
2011-07-27 07:19:39 -05:00
|
|
|
let n = 7;
|
2011-12-22 16:42:52 -06:00
|
|
|
#debug("Pfannkuchen(%d) = %d", n, fannkuch(n));
|
2011-08-10 11:27:22 -05:00
|
|
|
}
|