获取 2D 数组 php 上随机播放范围的索引
Get index of Shuffle Range on 2D Array php
我想为遗传算法随机生成 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] 时,它的值与第 1 列第 1 行中的 table 不同。
有什么想法吗?
UPDATE!
这个问题的最佳解决方案是 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++;
}
我想为遗传算法随机生成 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] 时,它的值与第 1 列第 1 行中的 table 不同。
有什么想法吗?
UPDATE!
这个问题的最佳解决方案是 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++;
}