2 回答

TA贡献1799条经验 获得超8个赞
我想这就是你要找的。不完全漂亮,但工作:
<?php
$size = 13;
$step = 6;
$input = array_keys(array_fill(0, $size, null));
$count = ceil($size / $step);
$chunk = floor($size / $count);
$bonus = $size % $count;
for ($i = 0; $i < $count; $i++) {
$output[] =
$i == 0 ?
array_slice($input, $i * $chunk, $chunk + $bonus) :
array_slice($input, $i * $chunk + $bonus, $chunk);
}
print_r($output);
这$size是数组$step的大小,是从该数组中切割的块的大小。您可以使用这些值。
具有上述设置的示例输出将是:
Array
(
[0] => Array
(
[0] => 0
[1] => 1
[2] => 2
[3] => 3
[4] => 4
)
[1] => Array
(
[0] => 5
[1] => 6
[2] => 7
[3] => 8
)
[2] => Array
(
[0] => 9
[1] => 10
[2] => 11
[3] => 12
)
)

TA贡献1831条经验 获得超4个赞
好的,我用更动态的编程方式做到了这一点,其中我们计算较小子问题的分布,然后从6到1,查看$j代码中的当前分布是否适合之前的任何分布。
<?php
$arr = [];
$size = rand(1,150);
$range = range(1,$size);
$dist = [];
$dist[] = [];
for($i=1;$i<=$size;++$i){
if($i <= 6) $dist[] = [$i];
else{
for($j=6;$j>=1;--$j){
if(abs($j - $dist[$i-$j][0]) <= 1){
$dist[] = array_merge($dist[$i-$j],[$j]);
break;
}
}
}
}
// echo $size,PHP_EOL;
// print_r($dist[$size]); print the distribution if you want.
$result = [];
$curr_index = 0;
foreach($dist[$size] as $chunk_size){
$result[] = array_slice($range,$curr_index,$chunk_size);
$curr_index += $chunk_size;
}
echo $size,PHP_EOL;
print_r($result);
演示: https : //3v4l.org/gCWB2(请注意,每个版本的 PHP 输出不同,因为每次生成的数组大小随机数不同)。
更新:您可以针对这条粗线进一步优化上面的代码$dist[] = array_merge($dist[$i-$j],[$j]); ,但这是我留给你的练习(提示:只存储最小的开始计数)。
- 2 回答
- 0 关注
- 203 浏览
添加回答
举报