1

好的,我想要做的是将一个数字($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'";
4

1 回答 1

2

这是我的看法:

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,添加了一个明确的检测来处理这个问题。其背后的算法仍然具有未知的终止时间。

于 2012-08-17T17:03:50.500 回答