PHP Увеличение массива на 1 - PullRequest
0 голосов
/ 31 января 2020

У меня есть простой массив $iteration=[0,1,2,3,4], и я пытаюсь создать функцию, например, чтобы увеличить его до максимального значения $max=12, и я не могу повторно использовать одно и то же число для 2 клавиш. Но пока у меня очень мало успеха. Вот что у меня сейчас.

//$iteration is my array and $max is the maximum value a key can have.
IncrementIteration($iteration,$max){
    $count=count($iteration);
    while($count > 0){
        if( ($iteration[($count-1)] < $max) ){
            $iteration[($count-1)]++;
            break;
        }
        $count--;
    }
    return $iteration;
}

Но это никогда не сбрасывает ключи, следующие за инкрементной клавишей, и не учитывает, использовался ли уже номер.

Вот то, что я ищу в качестве примера результатов:

print_r(IncrementIteration([0,1,2],12))

Выход: Array ([0] => 0 [1] => 1 [ 2] => 3)

print_r(IncrementIteration([0,1,12],12))

Выход: Массив ([0] => 1 [1] => 2 [2] => 3)

print_r(IncrementIteration([0,11,12],12))

Выход: Массив ([0] => 1 [1] => 2 [2] => 3)

Это будет максимально возможное увеличение.

print_r(IncrementIteration([10,11,12],12))

Вывод: Array ([0] => 10 [1] => 11 [2] => 12)

Спасибо за любую помощь по этому коду.


Я добавляю другие функции, чтобы лучше понять назначение этой функции.

function ReverseSUM($value,$array){
    global $debug;
    $count=count($array);
    $count=3;
    $values=array();
    while($count > 0){
        //Init of While Iteration
        $iteration=GenerateIteration($count);
        //We iterate
        while(SumIteration($iteration,$array) != $value){
            if($iteration === IncrementIteration($iteration,(count($array)-1))){
                break;
            } else {
                $iteration=IncrementIteration($iteration,(count($array)-1));
            }
            //End of While Iteration
        }
        //End of While Iteration
        if(SumIteration($iteration,$array) == $value){
            array_push($values,$iteration);
        }
        unset($iteration);
        if($debug){echo "</div>";};
        $count--;
    }
    return $values;
}
function GenerateIteration($number){
    $iteration=array();
    $count = 0;
    while($count < $number){
        array_push($iteration,$count);
        $count++;
    }
    return $iteration;
}
function IncrementIteration($iteration,$max){
    $count=count($iteration);
    while($count > 0){
        if( ($iteration[($count-1)] < $max) ){
            $iteration[($count-1)]++;
            break;
        }
        $count--;
    }
    return $iteration;
}
function SumIteration($iteration,$array){
    $result=array();
    foreach($iteration as $key){
        array_push($result,$array[$key]);
    }
    return array_sum($result);
}

Ответы [ 2 ]

0 голосов
/ 03 февраля 2020

Вот мой окончательный код для моей обратной суммы

function ReverseSUM($value,$array){
    ini_set('max_execution_time', 10);
    if (!function_exists('GenerateIteration')) {
        function GenerateIteration($number){
            global $debug;
            $iteration=array();
            $count = 0;
            while($count < $number){
                $count++;
                array_push($iteration,$count);
            }
            return $iteration;
        }
    }
    if (!function_exists('IncrementIteration')) {
        function IncrementIteration($iteration,$max){
            global $debug;
            $count=count($iteration);
            while($count > 0){
                if( $iteration[($count-1)] < $max ){
                    $iteration[($count-1)]++;
                    if($count != count($iteration)){
                        $count2=$count;
                        while($count2 <= count($iteration)){
                            if($count2 != count($iteration)){
                                // if( ($iteration[$count2] < $max) ){
                                    $iteration[$count2]=($iteration[($count2-1)]+1);
                                // }
                            }
                            $count2++;
                        }
                    }
                    break;
                }
                $max--;
                $count--;
            }
            return $iteration;
        }
    }
    if (!function_exists('SumIteration')) {
        function SumIteration($iteration,$array){
            global $debug;
            $result=array();
            foreach($iteration as $key){
                array_push($result,$array[$key]);
            }
            return array_sum($result);
        }
    }
    $count=count($array);
    $count=3;
    $values=array();
    while($count > 0){
        //Init of While Iteration
        $iteration=GenerateIteration($count);
        //We iterate
        while(SumIteration($iteration,$array) != $value){
            if($iteration === IncrementIteration($iteration,(count($array)-1))){
                break;
            } else {
                $iteration=IncrementIteration($iteration,(count($array)-1));
            }
            //End of While Iteration
        }
        //End of While Iteration
        if(SumIteration($iteration,$array) == $value){
            array_push($values,$iteration);
        }
        unset($iteration);
        $count--;
    }
    return $values;
}

И вот как я отображаю результаты:

<?php foreach($recap as $line => $value){ ?>
    <?php if($line<2){?>
    <table border="1">
        <tr>
            <th colspan="2" style="text-align:left;">Line <?=$line?> - <?=$value?></th>
        </tr>
        <tr>
            <th>Iteration</th>
            <th>Values</th>
        </tr>
        <?php foreach(ReverseSUM($value,$invoice) as $iteration => $values){?>
            <tr>
                <td><?=$iteration?></td>
                <td>
                    <?php foreach($values as $array){?>
                        <?=($array +1)?><br />
                    <?php } ?>
                </td>
            </tr>
        <?php } ?>
    </table>
    <?php } ?>
<?php } ?>

Массив $ recap просто содержит итоговые значения, которые мы имеем ищу. И массив $ invoice содержит все суммы строк счетов.

Код, доступный на GitHub: https://github.com/LouisOuellet/ReverseSUM

Sheers

0 голосов
/ 31 января 2020

Может быть что-то подобное может помочь,

  function unique_keys_array($array) {
    $temp_array = array();
    $i = 0;
    $key_array = array();

    foreach($array as $key) {
        if (!in_array($key, $key_array)) {
            $key_array[$i] = $key;
            $temp_array[$i] = $key;
        }
        $i++;
    }
    return $temp_array;
}


print_r(unique_keys_array([1,2,2,3,4,5,6,7,8,8,9,9]));

returns Array
(
    [0] => 1
    [1] => 2
    [3] => 3
    [4] => 4
    [5] => 5
    [6] => 6
    [7] => 7
    [8] => 8
    [10] => 9
)
...