rust/src/test/bench/shootout-fannkuchredux.rs

69 lines
1.7 KiB
Rust
Raw Normal View History

// Based on Isaac Gouy's fannkuchredux.csharp
use std;
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 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;
r = n;
2011-07-27 07:19:39 -05:00
while r > 0 {
i = 0;
while r != 1 { count[r - 1] = r; r -= 1; }
while i < n { perm[i] = perm1[i]; i += 1; }
// Count flips and update max and checksum
f = 0;
k = perm[0];
2011-07-27 07:19:39 -05:00
while k != 0 {
i = 0;
2011-07-27 07:19:39 -05:00
while 2 * i < k {
let t = perm[i];
perm[i] = perm[k - i];
perm[k - i] = t;
i += 1;
}
k = perm[0];
f += 1;
}
2011-07-27 07:19:39 -05:00
if f > flips { flips = f; }
if nperm & 0x1 == 0 { checksum += f; } else { checksum -= f; }
// 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 {
io::println(#fmt("%d", checksum));
2012-01-14 21:53:26 -06:00
ret flips;
}
let p0 = perm1[0];
i = 0;
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; }
}
nperm += 1;
2011-03-13 20:22:27 -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 {
option::get(int::from_str(args[1]))
2012-01-14 21:53:26 -06:00
} else {
8
2012-01-14 21:53:26 -06:00
};
io::println(#fmt("Pfannkuchen(%d) = %d", n, fannkuch(n)));
}