0

ここでこの古き良きアルゴリズムを見つけましたPHP: find two or more numbers from a list of numbers that to add up to a given amount by 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 によって合計される数値のリストから 2 つ以上の数値を見つけます。

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;
4

0 に答える 0