php - Split an array into three similar Sum
问题描述
I would like to split an array into three array that have similar sums - as close as possible
I have array
$arr = [1,2,4,7,1,6,2,8];
Desire output for example:
a = 8,2 // as sum is 10
b = 7,2,1 // as sum is 10
c = 6,4,1 // as sum is 10
Thanks
解决方案
您可以使用以下算法:
- 将输入数组从大到小排序
- 创建输出数组
- 对于输入中的每个元素 - 插入到输出数组中的最小总和。
考虑以下代码:
$arr = [1,2,4,7,1,6,2,8];
sort($arr);
$arr = array_reverse($arr); // big to small
$out = array(array(),array(),array()); // output array
for($i = 0; $i < 8; $i++) {
$sums = array_map("array_sum" ,$out); // get all current sums of the array
$index = array_keys($sums, min($sums))[0]; // get the min sum
$out[$index][] = $arr[$i]; // add the element to the array with the lowest sum
}
echo print_r($out, true);
现在你会得到:
array:
[0]: array:
[0] => 8
[1] => 2
[2] => 1
[1]: array:
[0] => 7
[1] => 2
[2] => 1
[2]: array:
[0] => 6
[1] => 4
推荐阅读
- javascript - 复选框值根据用户输入的数据反转,JavaScript 需要知道它何时被选中
- csv - 插值列数据
- reactjs - 在 React 中将输入字段的值传递给父组件
- video - 使用 FFmpeg 从 mjpeg 转换为 mp4 (libx264)
- html - 如何消除 CSS 网格第二列中的间隙?
- sparql - 为什么使用 SPARQL 在我的查询结果中出现 URL?
- ios - AVFoundation 切换相机慢(连接到采样缓冲区)
- python - 如何将县名转换为 fips 代码?(将县名映射到他们的 fips)
- r - R中Tune函数中“分散”的含义
- express - Express 会话 ID 未保存在 cookie 中(graphql)