我有一个整数值的数组(超过4个键)。我必须选择4个不同的值,这样这些数字的平均值将等于给定一个或如果不可能则为假。 最好的方法是什么? (算法)
答案 0 :(得分:0)
如何实现它是找到给定长度的数组的所有可能子集,然后遍历它们并计算它们的平均值:
function get_subset_with_average($average, Array $data, $length) {
// Make sure we can calculate the subsets
if (count($data) < $length) {
throw new Exception("The subset length is more than the size of the array");
}
$a = $b = 0;
$subset = [];
$subsets = [];
// Loop through the data and get all subset combinations
while ($a < count($data)) {
$current = $data[$a++];
$subset[] = $current;
if (count($subset) == $length) {
$subsets[] = $subset;
array_pop($subset);
}
if ($a == count($data)) {
$a = ++$b;
$subset = [];
}
}
// Loop through the subsets and check if the average equals the desired average
foreach ($subsets as $set) {
if (array_sum($set) / count($set) == $average) {
return $set;
}
}
return false;
}
$data = array(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15);
var_dump(get_subset_with_average(2.5, $data, 4));
var_dump(get_subset_with_average(5.75, $data, 4));
var_dump(get_subset_with_average(9.3, $data, 4));
var_dump(get_subset_with_average(13, $data, 4));
这将输出:
array(4) {
[0]=>
int(1)
[1]=>
int(2)
[2]=>
int(3)
[3]=>
int(4)
}
array(4) {
[0]=>
int(2)
[1]=>
int(3)
[2]=>
int(4)
[3]=>
int(14)
}
bool(false)
bool(false)