我想为遗传算法随机选择80*13个数字,其中80是popsize,13是dna大小。我试图在二维数组上得到范围值的索引。为了从1-13中随机生成一个不重复的int,我的意思是80行13列的2d。像这个
$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]时,该值与第1行col1中的表不相同。
有什么想法吗?
更新!
这个问题的伟大解决方案是Rainmx93的答案,这对我来说很好。非常感谢
在第一个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++;
}