PHP 中的求解算法(Josephus 排列)

Solving Algorithm (Josephus permutation) in PHP

假设100个人围成一圈。从第 1 人数到第 14 人,将此人移出圈子。按照数数顺序,再次数数,去掉第 14 个人。重复。最后站着的是谁?

我已经尝试了所有方法来解决这个问题,但它似乎无法处理死循环。

<?php
//init array
$array = array();
for ($i = 0; $i < 100; $i++) { $array[] = $i; }

//start from 0
$pos = 0;
while (count_not_null($array) > 1) {
    //reset count
    $count = 0;
    while (true) {
        //ignore NULL for count, that position is already removed
        if ($array[$pos] !== NULL) {
            $count++;
            if($count == 14) { break; }
        }
        $pos++;
        //go back to beginning, we cant go over 0-99, for 100 elements
        if ($pos > 99) { $pos = 0; }
    }
    echo "set index {$pos} to NULL!" ."<br>";
    $array[$pos] = NULL;
    if (count_not_null($array) === 1) { break; }
}

echo "<pre>";
print_r($array);
echo "</pre>";


//counting not null elements
function count_not_null($array) {
    $count = 0;
    for ($i = 0; $i < count($array); $i++) {
        if ($array[$i] !== NULL) { $count++; }
    }
    return $count;
}
?>

问题是这个while循环

    while ($count < 14) {
        if ($array[$pos] != NULL) {
            $count++;
        }
        $pos++;
        if ($pos > 99) { $pos = 0; }
    }

因为即使 count 为 14 也增加了 $pos,您将以不正确的值结束并永远循环。将其替换为:

    while (true) {
        if ($array[$pos] != NULL) {
            $count++;
            if($count == 14) {break;}
        }
        $pos++;
        if ($pos > 99) { $pos = 0; }
    }

另外,将 0 与 NULL 进行比较不会得到@Barmar 提到的预期结果,因此您可以更改 NULL 比较,或者从 1

开始计数

注意:如果你不是每次都遍历数组,这会更快 :D 考虑使用变量来计算剩余的项目

要用尽可能少的代码最快地解决这个问题,您可以这样做:

function josephus($n,$k){
    if($n ==1)
        return 1;
    else
        return (josephus($n-1,$k)+$k-1) % $n+1;
}

echo josephus(100,14);

这里我们使用的是递归语句,因为你要解决的问题可以用这个数学语句来定义f(n,k) = (f(n-1,k) + k) % n
要阅读有关此数学公式的更多信息,您可以查看 here on the wiki page.

任何再次偶然发现这个问题的人,这里有一个稍微快一点的:

function josephus($n){
    $toBin = decbin($n); // to binary
    $toBack = substr($toBin,1) . "1"; // remove first bit and add to end
    return bindec($toBack); // back to value
}

基于 this 解决方案。