【问题标题】:Get index of Shuffle Range on 2D Array php在 2D Array php 上获取 Shuffle Range 的索引
【发布时间】:2018-07-27 10:00:20
【问题描述】:

我想为遗传算法随机选择 80*13 位数字,其中 80 是 popsize,13 是 dna 大小。我试图在二维数组上获取范围值的索引。要从 1 到 13 随机生成一个不重复的整数,我的意思是 2d 表示 80 行和 13 列。像这样

$arr = [0][0]; //this is output will be same with the table value in row1 col1
$arr = [0][1]; //this is output will be same with the table value in row1 col2
...
$arr = [0][12]; //this is output will be same with the table value in row2 col1
$arr = [1][1]; //this is output will be same with the table value in row2 col2
..

我有这样的代码。

<?php
function randomGen($min, $max) {
    $numbers = range($min, $max);
    shuffle($numbers);
    return array_slice($numbers, 0);
}
?>

<table>
    <tr>
        <th rowspan="2">Kromosom ke-</th>
        <th colspan="13">Stasiun Kerja</th>
    </tr>
    <tr>
        <?php
        for ($i=1; $i <= 13; $i++) { 
        ?>
            <th>
                <?php echo $i;?>
            </th>
        <?php
        }
        ?>
    </tr>
    <tr>
<?php
    for($i = 0; $i < 80; $i++) {
        $no = 1;
        echo "<td> v".$no."</td>";
        $arr[$i] = randomGen(1,13);
        for ($j=0; $j <= 12; $j++) {
            $arr[$j] = randomGen(1,13);
            echo "<td>";
            echo $arr[$i][$j];
            echo "</td>";
        }
            echo "</td><tr>";
            $no++;

    }
    // print_r($arr[0][0].' '); // for see the value is same or not
    ?>

当我尝试打印 $arr[0][0] 时,该值与 row1 col1 中的表不同。

有什么想法吗?

更新!

这个问题的最佳解决方案是 Rainmx93 的回答,这对我有用。非常非常感谢你

【问题讨论】:

  • 为什么在第二个for循环中调用randomGen()?
  • 我认为这是数组的索引列,比如 $arr[0][$j] 它的意思是 $arr[0][$j] 其中 $j =0 -> 12,也许?
  • 不,您在第一个循环中已经有多维数组,只需删除第二个函数 randomGen() 调用,一切都会正常

标签: php arrays random range shuffle


【解决方案1】:

在第一个 for 循环中,您已经生成了多维数组,但现在在第二个循环中,您在每次迭代中覆盖所有数组元素,您需要删除第二个函数调用。 您的代码应如下所示:

for($i = 0; $i < 80; $i++) {
    $no = 1;
    echo "<td> v".$no."</td>";
    $arr[$i] = randomGen(1,13);
    for ($j=0; $j <= 12; $j++) {
        echo "<td>";
        echo $arr[$i][$j];
        echo "</td>";
    }
    echo "</td><tr>";
    $no++;

}

【讨论】:

  • 是的!这是我的工作,非常感谢,先生。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-09
  • 1970-01-01
  • 2011-08-12
  • 1970-01-01
  • 1970-01-01
  • 2013-09-26
相关资源
最近更新 更多