2013-02-11 74 views
1

我想匹配具有特定數字的數組中值的不同組合。將數組中的值與數值匹配

例如:

number = 10 

Array (2, 6, 5, 3, 4) 

比賽將返回:6 + 4 = 102 + 3 + 5 = 10

我可以遍歷所有可能的組合,但是否有任何更快,更容易的方式來解決我的問題?

+3

有沒有內置的功能,要做到這一點,所以你需要循環....你可以做的唯一的事情來減少循環過濾出數組中的任何值大於你的目標數字,儘管這不適用於你的例子 – 2013-02-11 09:34:48

+0

謝謝!然後我會嘗試通過刪除不必要的值來優化數組。 – hgerdin 2013-02-11 09:38:15

回答

0

沒有與答案一個小問題,它返回的所有組合,即2,3,5和-3,2,5-等。

<?php 

$array = array(2, 6, 5, 3, 4); 

function depth_picker($arr, $temp_string, &$collect) { 
    if ($temp_string != "") 
     $collect []= $temp_string; 

    for ($i=0; $i<sizeof($arr);$i++) { 
     $arrcopy = $arr; 
     $elem = array_splice($arrcopy, $i, 1); // removes and returns the i'th element 
     if (sizeof($arrcopy) > 0) { 
      depth_picker($arrcopy, $temp_string ."," . $elem[0], $collect); 
     } else { 
      $collect []= $temp_string. "," . $elem[0]; 
     } 
    } 
} 

$collect = array(); 
depth_picker($array, "", $collect); 
foreach($collect as $val) 
{ 
    $sum = array_sum(explode(",",$val)); 
    if($sum == 10){ 
     print_r($val); 
     echo "<br>"; 
    } 
} 

?>