【问题标题】:php sort array by the average of numbers [closed]php按数字的平均值对数组进行排序[关闭]
【发布时间】:2014-10-06 16:37:40
【问题描述】:

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

【问题讨论】:

  • @boomoto 寻求家庭作业的帮助并没有错。
  • 可能有很多方法可以做到这一点。您尝试过哪些方法,您认为哪种方法最好,为什么?在问题中显示您的代码和工作原理...
  • 对不起,这不是家庭作业:D 它是我的工作.. 相当复杂的任务
  • 相当复杂?听起来并不那么复杂。尝试一下先生,我们很乐意帮助您使用 foreach 循环对每个元素求和,然后将其除以数组元素的数量,检查它是否等于所需的平均值.. Ooooooooos,就是这样.. 不管事实正如迈克所说,要找到一个与循环完全相同的非常精确的平均值将非常困难。

标签: php average


【解决方案1】:

我将如何实现它是找到给定长度的数组的所有可能子集,然后遍历它们并计算它们的平均值:

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)

【讨论】:

    猜你喜欢
    • 2023-04-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多