Home > OS >  how to sum consecutive numbers of array until remaining only one
how to sum consecutive numbers of array until remaining only one

Time:01-20

I want to sum the numbers of array in javascript, and create others rows of this sum, until it get only one I want to generate new rows as result of the previous sum. it is only for training algorithms

EX: [1,2,3,4,5,6,7,8] 
     [3,7,11,15]
      [10,26]
       [36]
function retsum(x) {
    for(let i = 0; i < x.length - 1; i  ) {
        console.log(x[i]   x[i   1] )
    }
}
retsum([2,3,5,6,10,20])

this is my code. I dont know how to generate other loop or other solution, to keep doing this sum, until remaining only one number if you can help me, thanks

CodePudding user response:

You can use while loop check if array size is above 1

function retsum(x) {
    const result = [];
    for(let i = 0; i < x.length - 1; i  ) {
        console.log(x[i]   x[i   1] )
        result.push(x[i]   x[i   1] )
    }
     return result
}
let arr = [2,3,5,6,10,20];
while (arr.length > 1) { 
    arr = retsum(arr)
    console.log(arr)
}

CodePudding user response:

You could take a recursive approach and return a single value at the end of recursion.

function sum(numbers) {
    console.log(...numbers);
    if (numbers.length === 1) return numbers[0];
    const result = [];
    for (let i = 0; i < numbers.length; i  = 2) {
        result.push(numbers[i]   (numbers[i   1] || 0));
    }
    return sum(result);
}

console.log(sum([1, 2, 3, 4, 5, 6, 7, 8]));

CodePudding user response:

If you want to sum pairs of numbers in an array, you have to decide if you are doing it left-to-right, or right-to-left. Depending on the route you go, all the intermittent arrays between the initial input and the final result will vary. Take note of the output of each snippet below.

Recursion would be the easiest way to tackle this. It all comes down to how your increment/decrement your for-loop.

Left-to-right (increment)

const print = (arr) => console.log(...arr.map(JSON.stringify));

const recursiveSums = (numbers, result = [numbers]) => {
  if (numbers == null || numbers.length === 0) throw new Error('array length less than 1');
  if (numbers.length === 1) return result;
  const subResult = [];
  for (let i = 0; i < numbers.length; i  = 2) {
    subResult.push(numbers[i]   (numbers[i 1] ?? 0));
  };
  result.push(subResult);
  return recursiveSums(subResult, result);
};

print(recursiveSums([1, 2, 3, 4, 5, 6, 7, 8])); // even
print(recursiveSums([5, 3, 8, 4, 1]));          // odd

try { recursiveSums([]) }                       // error!
catch (e) { console.log(e.message); }
.as-console-wrapper { top: 0; max-height: 100% !important; }

Output

[1,2,3,4,5,6,7,8] [3,7,11,15] [10,26] [36]
[5,3,8,4,1] [8,12,1] [20,1] [21]
array length less than 1

Right-to-left (decrement)

const print = (arr) => console.log(...arr.map(JSON.stringify));

const recursiveSums = (numbers, result = [numbers]) => {
  if (numbers == null || numbers.length === 0) throw new Error('array length less than 1');
  if (numbers.length === 1) return result;
  const subResult = [];
  for (let i = numbers.length - 1; i >= 0; i -= 2) {
    subResult.unshift((numbers[i-1] ?? 0)   numbers[i]);
  };
  result.push(subResult);
  return recursiveSums(subResult, result);
};

print(recursiveSums([1, 2, 3, 4, 5, 6, 7, 8])); // even
print(recursiveSums([5, 3, 8, 4, 1]));          // odd

try { recursiveSums([]) }                       // error!
catch (e) { console.log(e.message); }
.as-console-wrapper { top: 0; max-height: 100% !important; }

Output

[1,2,3,4,5,6,7,8] [3,7,11,15] [10,26] [36]
[5,3,8,4,1] [5,11,5] [5,16] [21]
array length less than 1

CodePudding user response:

Here's what I came up with using reduce. It covers empty or odd-numbered input arrays.

function addPairs(nums,left_to_right)
{
  nums=nums.length>0?nums:[0]
  const evenNumberOfItems=[...(nums.length%2===0?nums:left_to_right?[...nums,0]:[0,...nums])]
  const pairs=evenNumberOfItems.reduce((previous,current,index,array)=>{
    if(index%2===0)
      previous.push([current,array[index 1]])
    return previous
  },[])
  const addedPairs=pairs.reduce((previous,current)=>{    
    previous.push(current[0] current[1])
    return previous
  },[]);
  console.log(addedPairs)
  return addedPairs.length===1?addedPairs[0]:addPairs(addedPairs);
}
console.log(addPairs([]))
console.log(addPairs([2,3,5,6,10,20,13],true))
console.log(addPairs([2,3,5,6,10,20,13],false))
  • Related