A
A
Alexander Verbitsky2019-10-31 07:05:54
PHP
Alexander Verbitsky, 2019-10-31 07:05:54

How to add elements of an array in different variations?

For example, there is an array And you need to add these numbers in different variations 1+2 1+3 ​​1+4 1+2+4 3+2+5 , etc. The point is that there is a large list of prices, and I need to find out which items add up to a certain value. Those. if the sum of these elements, for example, is equal to 20, we stop the search and show what is included in this sum. I’ll think of the last condition myself, but the enumeration of variations for adding numbers is something not for my mind ...
$array = [1, 2, 3, 4, 5]

Answer the question

In order to leave comments, you need to log in

2 answer(s)
W
wisgest, 2019-10-31
@VerbAlexVlad

Blunt viewing of all possible subsets of the set of indices (the subset is given by a binary number: 1 - there is an element, 0 - there is no element). Without recursion. Without optimization.

<?php
$array = [1, 2, 3, 4, 5];
$SUM = 7;

$LIMIT = 1 << count($array);
for ($set = 0; $set < $LIMIT; $set++) {
  $s = 0;
  for ($i = 0; $i < count($array); $i++)
    if ((1 << $i) & $set) $s += $array[$i];
  if ($s == $SUM) {
    echo 'Индексы элементов массива, составляющих сумму: ';
    for ($i = 0; $i < count($array); $i++)
      if ((1 << $i) & $set) echo $i, ' ';
    break;
  }
}

D
Dmitry, 2019-10-31
@Compolomus

https://www.php.net/manual/ru/function.array-sum.php
Another option

$stop = 42;

$items = range(1, 100);

$sum = 0;

$i = 0;

while($sum <= $stop) {
    $sum += $items[$i];
    $i++;
}
echo $sum;

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question