Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/272.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
php根据数字的平均值对数组进行排序_Php_Average - Fatal编程技术网

php根据数字的平均值对数组进行排序

php根据数字的平均值对数组进行排序,php,average,Php,Average,我有一个超过4个整数值键的数组。我必须选择4个不同的值,这样这些数字的平均值将等于给定的1或false(如果不可能)。 最好的方法是什么?算法我将如何完成这一任务,即找到给定长度数组的所有可能子集,然后循环遍历它们并计算它们的平均值: function get_subset_with_average($average, Array $data, $length) { // Make sure we can calculate the subsets if (count($data

我有一个超过4个整数值键的数组。我必须选择4个不同的值,这样这些数字的平均值将等于给定的1或false(如果不可能)。
最好的方法是什么?算法

我将如何完成这一任务,即找到给定长度数组的所有可能子集,然后循环遍历它们并计算它们的平均值:

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));

@boomoto找人帮忙做作业没什么错,可能有很多方法。你试过哪些方法,你认为哪种方法最好,为什么?在问题中显示您的代码和工作方式…抱歉,这不是家庭作业:D是我的工作。。相当复杂的任务相当复杂?听起来没那么复杂。尝试一下,先生,我们很乐意为您提供foreach循环,对每个元素求和,并根据数组中的元素数进行细分,检查其是否等于所需的平均值。。哎哟,就是这样。。不管事实是什么,就像迈克说的,你很难找到一个真正精确的平均值,这个平均值与循环中的一个完全相同。
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)