将总数分成 5 个不同的数字


Split total into 5 different numbers

好的,我想做的是将一个数字($row['count'])分成5,如果你想要相等的数字,这很容易:

$sum  = ($row['count'] / 5);
$fsum = floor($sum);

我希望每个数字都不同,并且仍然加起来就是总数,即$row['count']如何实现这一目标?

更新:

如果这有助于使用它来更新数据库中的 5 行:

$query  = "SELECT * FROM foo";
$result = mysql_query($query);
while ($row = mysql_fetch_array($result)) {
    $sum  = ($row['count'] / 5);
    $fsum = floor($sum);
    $id   = $row['id'];
    $update = "UPDATE foo SET foo1='$fsum', foo2='$fsum', foo3='$fsum', foo4='$fsum', foo5='$fsum' WHERE id='$id'";
    mysql_query($update);
    }// while

因此,理想情况下,$update查询将是这样的:

$update = "UPDATE foo SET foo1='$fsum1', foo2='$fsum2', foo3='$fsum3', foo4='$fsum4', foo5='$fsum5' WHERE id='$id'";
这是我

的看法:

function randomize($sum, $parts) {
    $part_no = count($parts);
    $continnue_counter = 0;
    while (count(array_unique($parts)) != $part_no) {
        $changing = array_rand($parts, 2);
        if (($parts[$changing[0]] - 1) == 0 || ($parts[$changing[1]] - 1) == 0) { // don't let them go under 1
            ++$continnue_counter;
            // sometime one element get everything and others even out on 1
            // just throw away everything you got so far and start over
            if ($continnue_counter > 10) {
                $parts = setup($sum, $part_no);
                $continnue_counter = 0;
            }
            continue;
        }
        $continnue_counter = 0;
        $signum   = mt_rand(0, 100) % 2 ? 1 : -1;
        $delta    = $signum * mt_rand(1, min($parts[$changing[0]] - 1, $parts[$changing[1]] - 1)); // -1 to make sure they don't go under 0
        $parts[$changing[0]] += $delta;
        $parts[$changing[1]] -= $delta;
    }
    return $parts;
}
function setup($sum, $part_no) {
    $parts = array_fill(0, $part_no, (int)($sum / $part_no));
    // acount for the reminder of (int) cast
    $reminder = $sum - array_sum($parts);
    while ($reminder) {
        $parts[array_rand($parts)] += 1;
        --$reminder;
    }
    return $parts;
}
$part_no = 5;
$sum = 42;
$parts = randomize($sum, setup($sum, $part_no));
var_export($parts);
print array_sum($parts)

更新:

我添加了一个引入更多熵的版本。

更新2:

更随机的倾向于将所有内容减少到 1,除了一部分,添加显式检测来处理这个问题。它背后的算法仍然具有未知的终止时间。