将数组分成相等或近似相等的数组一半 [英] Split array into half with equal or approximately equal array sum
本文介绍了将数组分成相等或近似相等的数组一半的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
问题:
带有数字值的数组需要分成大约相等的数组一半,或者如果可能的话,等于数组的总和.数组中元素的数量或顺序并不重要.
Array with numeric values needs to be split in half with approximately equal or if possible equal array sum. Number or order of elements in arrays is not important.
$probabilites = array(0.4, 0.15, 0.1, 0.1, 0.2, 0.2, 0.3); # 1.45
$probabilites[0] = array(0.4, 0.15, 0.1, 0.1); # 0.75
$probabilites[1] = array(0.2, 0.2, 0.3); # 0.7
有什么建议吗?
谢谢.
推荐答案
喜欢吗?
<?php
$in = array(0.4, 0.15, 0.1, 0.1, 0.2, 0.2, 0.3);
// Sort array decreasing
rsort($in, SORT_NUMERIC);
// Start with two empty arrays
$arr1 = $arr2 = array();
// Put the next value in the array in the array with the lowest sum
foreach ($in as $value)
if (array_sum($arr2) > array_sum($arr1)) $arr1[] = $value; else $arr2[] = $value;
// Wrap in array (as in question)
$out = array($arr1,$arr2);
这篇关于将数组分成相等或近似相等的数组一半的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文