function Fannkuch($n, $_i, $print) { $check = 0; $perm = array(); $perm1 = array(); $count = array(); $maxFlipsCount = 0; $m = $n - 1; $perm1 = range(0, $n - 1); $r = $n; if (!$print) { $perm1[$_i] = $n - 1; $perm1[$n - 1] = $_i; } while (TRUE) { // write-out the first 30 permutations if ($print) { foreach ($perm1 as $v) { echo $v + 1; } echo "\n"; if (++$check >= 30) { return Fannkuch($n, $_i, FALSE); } } while ($r !== 1) { $count[$r - 1] = $r--; } if ($perm1[0] !== 0 && $perm1[$m] !== $m) { $perm = $perm1; $flipsCount = 0; $k = $perm[0]; do { $i = 1; $j = $k - 1; while ($i < $j) { $tmp = $perm[$i]; $perm[$i++] = $perm[$j]; $perm[$j--] = $tmp; } ++$flipsCount; $tmp = $perm[$k]; $perm[$k] = $k; } while ($k = $tmp); if ($flipsCount > $maxFlipsCount) { $maxFlipsCount = $flipsCount; } } do { if ($r >= $m) { return $maxFlipsCount; } $perm0 = $perm1[0]; $i = 0; while ($i < $r) { $perm1[$i++] = $perm1[$i]; } $perm1[$r] = $perm0; if (--$count[$r] > 0) { break; } ++$r; } while (TRUE); } }
$p[1] = $p[2]; $p[2] = $t; $sign = 1; // Rotate 0<-1 and 0<-1<-2. for ($i = 2; $i < $n; $i++) { $sx = $s[$i]; if ($sx != 0) { $s[$i] = $sx - 1; break; } if ($i == $m) { return array($sum, $maxflips); } // Out of permutations. $s[$i] = $i; // Rotate 0<-...<-i+1. $t = $p[0]; for ($j = 0; $j <= $i; $j++) { $p[$j] = $p[$j + 1]; } $p[$i + 1] = $t; } } } while (true); } $n = $argv[1]; list($checksum, $pf) = Fannkuch($n); printf("%d\nPfannkuchen(%d) = %d", $checksum, $n, $pf); ?>
} if ($flipsCount > $maxFlipsCount) { $maxFlipsCount = $flipsCount; for ($i = 0; $i < $n; $i++) { $maxPerm[$i] = $perm1[$i]; } } } while (TRUE) { if ($r == $n) { return $maxFlipsCount; } $perm0 = $perm1[0]; $i = 0; while ($i < $r) { $j = $i + 1; $perm1[$i] = $perm1[$j]; $i = $j; } $perm1[$r] = $perm0; $count[$r] = $count[$r] - 1; if ($count[$r] > 0) { break; } $r++; } } } $n = $argc == 2 ? $argv[1] : 1; printf("Pfannkuchen(%d) = %d\n", $n, Fannkuch($n));