我在这里找到了这个很好的旧算法PHP:从Oezis的给定数量的数字列表中找到两个或多个数字。
它工作得很好,但要使用它,我需要尽可能修改它。现在我输入普通数字并接收可能组合的新数组。
相反,我需要用它们的键输入数字,并用可能的组合保留这些键。
提前感谢您的想法。
BR米勒克
现在:
// Inputs OLD - no keys
$n = array(11, 18, 24, 24, 10, 9, 2);
// RESULT OLD - new array with no keys (no association to old indexes)
$ret = array(0 => 11,1 => 18,2 => 24,3 => 9);
目标:
// Inputs NEW - with keys to be preserved with the result
$n = array('21400'=>11, '10800'=>18, '91380'=>24, '91380'=>24, '21600'=>10, '70600'=>9, '71561'=>2);
// RESULT NEW - new array with old keys (associated with old keys)
$ret = array('21400'=>11, '10800'=>18, '91380'=>24, '70600'=>9);
算法 - PHP:从Oezis的给定数量加起来的数字列表中找到两个或多个数字
function array_sum_parts($n,$t,$all=false){
$count_n = count($n); // how much fields are in that array?
$count = pow(2,$count_n); // we need to do 2^fields calculations to test all possibilities
# now i want to look at every number from 1 to $count, where the number is representing
# the array and add up all array-elements which are at positions where my actual number
# has a 1-bit
# EXAMPLE:
# $i = 1 in binary mode 1 = 01 i'll use ony the first array-element
for($i=1;$i<=$count;$i++){ // start calculating all possibilities
$total=0; // sum of this try
$anzahl=0; // counter for 1-bits in this try
$k = $i; // store $i to another variable which can be changed during the loop
for($j=0;$j<$count_n;$j++){ // loop trough array-elemnts
$total+=($k%2)*$n[$j]; // add up if the corresponding bit of $i is 1
$anzahl+=($k%2); // add up the number of 1-bits
$k=$k>>1; //bit-shift to the left for looking at the next bit in the next loop
}
if($total==$t){
$loesung[$i] = $anzahl; // if sum of this try is the sum we are looking for, save this to an array (whith the number of 1-bits for sorting)
if(!$all){
break; // if we're not looking for all solutions, make a break because the first one was found
}
}
}
asort($loesung); // sort all solutions by the amount of numbers used
// formating the solutions to getting back the original array-keys (which shoud be the return-value)
foreach($loesung as $val=>$anzahl){
$bit = strrev(decbin($val));
$total=0;
$ret_this = array();
for($j=0;$j<=strlen($bit);$j++){
if($bit[$j]=='1'){
$ret_this[] = $j;
}
}
$ret[]=$ret_this;
}
return $ret;
}
// Target
$t=62;