skip to Main Content

For example, there is an array:

[3, 8, 9, 2, 7, 5, 6, 5, 3, 11, 9, 17, 6, 5, 8, 4, 2, 7, 9, 12, 5, 16, 4]

Algorithm:

let arr = []

3 + 8 + 9 + 2 > 20 (do not sum)
3 + 8 + 9 = 20 (sum and push to arr)
next
9 + 2 + 7 + 5 > 20 (do not sum)
9 + 2 + 7 < 20 (sum and push to arr)
next
5 + 6 + 5 + 3 + 11 > 20 (do not sum)
5 + 6 + 5 + 3 < 20 (sum and push to arr)
...

The point is that there are files in the array with a certain weight in MB, and I need to merge them one by one, not exceeding 20MB, and make a new array from the merged ones.

I tried to do this with the following code, but I don’t understand how to set my condition.

var sum = (array) => (array.length === 0) ? 0 : array[0] + sum(array.slice(1));

2

Answers


  1. function addValuesUntilSumLessThan20(arr) {
      let sum = 0;
      let resultArray = [];
    
      for (let i = 0; i < arr.length; i++) {
        if (sum + arr[i] <= 20) {
          sum += arr[i];
          resultArray.push(arr[i]);
        } else {
          break;
        }
      }
    
      return resultArray;
    }
    
    const inputArray = [3, 8, 9, 2, 7, 5, 6, 5, 3, 11, 9, 17, 6, 5, 8, 4, 2, 7, 9, 12, 5, 16, 4];
    const result = addValuesUntilSumLessThan20(inputArray);
    
    console.log(result); // Output: [3, 8, 9]
    Login or Signup to reply.
  2. You could group by having a look to subset sum.

    Less Than

    const
        add = (a, b) => a + b,
        lessThan = value => (r, v, i) => {
            if (!i || r.at(-1).reduce(add) + v >= value) r.push([v]);
            else r.at(-1).push(v);
            return r;
        },
        data = [3, 8, 9, 2, 7, 5, 6, 5, 3, 11, 9, 17, 6, 5, 8, 4, 2, 7, 9, 12, 5, 16, 4],
        result = data.reduce(lessThan(20), []);
    
    console.log(result);
    .as-console-wrapper { max-height: 100% !important; top: 0; }

    Up to

    const
        add = (a, b) => a + b,
        upTo = value => (r, v, i) => {
            if (!i || r.at(-1).reduce(add) + v > value) r.push([v]);
            else r.at(-1).push(v);
            return r;
        },
        data = [3, 8, 9, 2, 7, 5, 6, 5, 3, 11, 9, 17, 6, 5, 8, 4, 2, 7, 9, 12, 5, 16, 4],
        result = data.reduce(upTo(20), []);
    
    console.log(result);
    .as-console-wrapper { max-height: 100% !important; top: 0; }
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search