2014-10-06 158 views
-3

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

+1

@boomoto寻求家庭作业帮助没有任何问题。 – Mike 2014-10-06 16:41:31

+1

可能有很多方法可以做到这一点。你尝试了哪些方法,以及哪种方法是最好的方法,为什么?在问题中显示你的代码和工作... – James 2014-10-06 16:44:12

+0

对不起,它不是作业:D它适合我的工作..相当复杂的任务 – rokas 2014-10-06 16:44:41

回答

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)