-3
我有一個整數值的數組(超過4個鍵)。我必須選擇4個不同的值,以便這些數字的平均值等於給定的值,如果不可能,則爲假。 做什麼是最好的方法? (算法)PHP排序數組的平均數
我有一個整數值的數組(超過4個鍵)。我必須選擇4個不同的值,以便這些數字的平均值等於給定的值,如果不可能,則爲假。 做什麼是最好的方法? (算法)PHP排序數組的平均數
我將如何完成它是找到所有的給定長度的陣列的可能的子集,然後依次通過他們,並計算它們的平均值:
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)
@boomoto尋求家庭作業幫助沒有任何問題。 – Mike 2014-10-06 16:41:31
可能有很多方法可以做到這一點。你嘗試了哪些方法,以及哪種方法是最好的方法,爲什麼?在問題中顯示你的代碼和工作... – James 2014-10-06 16:44:12
對不起,它不是作業:D它適合我的工作..相當複雜的任務 – rokas 2014-10-06 16:44:41