猿问

将数组拆分为相等的部分,每个数组最多 6 个项目

我试图将一组项目拆分为多个相等的部分,每个数组最多 6 个项目


例如:


5 items in original array --> result: 1 array with 5 items

12 items in original array --> result: 2 arrays with 6 items

7 items in original array --> result: 2 arrays with 3 and 4 items

13 items in original array --> result: 3 arrays with 5,4,4 items

我完全不知道如何开始


白衣染霜花
浏览 204回答 2
2回答

守着星空守着你

我想这就是你要找的。不完全漂亮,但工作:<?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++) {&nbsp; &nbsp; $output[] =&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; $i == 0 ?&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; array_slice($input, $i * $chunk, $chunk + $bonus) :&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; array_slice($input, $i * $chunk + $bonus, $chunk);}print_r($output);这$size是数组$step的大小,是从该数组中切割的块的大小。您可以使用这些值。具有上述设置的示例输出将是:Array(&nbsp; &nbsp; [0] => Array&nbsp; &nbsp; &nbsp; &nbsp; (&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [0] => 0&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [1] => 1&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [2] => 2&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [3] => 3&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [4] => 4&nbsp; &nbsp; &nbsp; &nbsp; )&nbsp; &nbsp; [1] => Array&nbsp; &nbsp; &nbsp; &nbsp; (&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [0] => 5&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [1] => 6&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [2] => 7&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [3] => 8&nbsp; &nbsp; &nbsp; &nbsp; )&nbsp; &nbsp; [2] => Array&nbsp; &nbsp; &nbsp; &nbsp; (&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [0] => 9&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [1] => 10&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [2] => 11&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [3] => 12&nbsp; &nbsp; &nbsp; &nbsp; ))

慕容708150

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