随机数、列和行..PHP


Random Numbers, Column and Row. PHP

请原谅我,因为这是我的第一篇文章,我对任何类型的编程都相当陌生。我希望我的问题很清楚,我正在使用 Excel 参考,因为我认为这解释了我最擅长的事情。

我正在尝试为池生成随机数。我有 8 行数字,每行包含 10 个点,从 0 到 9。我想在每一行都有一个随机数,并确保该数字不会在每一行中重复。

示例网格 - 8 列宽 x 10 行长。

我正在为每一列重复此 scrip,但我得到的行数相同,我想确保不会发生这种情况。

for ($i=1; $i<=10; $i++) {
            while (1) {
                $duplicate = 0;
                $num=rand(0,9);     
                for ($x=1; $x<$i; $x++) {
                    if ($NFC1[$x]==$num) { $duplicate = 1; }
                }
                if ($duplicate==0) {
                    $NFC1[$i]=$num;
                    break;
                }
            }
        }

这是结果,如您所见,我有随机数是每一列,但不在每一行中。

"4";"8";"5";"5";"0";"4";"2";"7"
"5";"9";"4";"3";"9";"9";"9";"0"
"9";"5";"1";"1";"5";"8";"6";"1"
"7";"4";"6";"2";"6";"7";"3";"3"
"2";"6";"8";"4";"7";"2";"7";"5"
"0";"1";"0";"7";"2";"1";"4";"6"
"1";"7";"9";"9";"4";"3";"0";"4"
"3";"0";"3";"0";"3";"5";"5";"9"
"8";"2";"7";"8";"1";"6";"8";"2"
"6";"3";"2";"6";"8";"0";"1";"8"

从这里添加到非平方数组的答案可能如下所示:

$rows = 10;    // Number of rows
$columns = 8;  // Number of columns
$row = range(0, $columns-1);
$column = range(0, $rows-1);
shuffle($row);
shuffle($column);
// Create an array
foreach ($row as $x => $value)
    foreach ($column as $y)
        $array[$y][$x] = $value++ % max($rows, $columns);

如果您想查看结果:

foreach($array as $r) {
    foreach($r as $number) {
        echo $number.' ';
    }
    echo "<br/>";
}