Algorithm to remove items from an array

Tell us what’s happening:
I have manually spliced items from the array so that their sum becomes 10.
But is there any algorithmic way so that the code can do that for any random array.

``````
const arr = [2, 4, 5, 1, 7, 5, 2, 1];
// Only change code below this line
arr.splice(0, 1)
arr.splice(3)
// Only change code above this line
console.log(arr);

``````

Challenge: Remove Items Using splice()

Try this

``````arr.splice(1,4)
``````

You have not got my question.
You are saying about a different group of numbers that sums to 10.

I am asking a general method that can check for in any random array and returns array of numbers that will add up to 10, if possible, and everything else get spliced off.

If you want a way to handle any type of numerical array, as well with an arbitrary total value you can make a function to do that:

example:

``````function keepUntilSum(a, tot)  {
let counter = 0;
let finalArr = [];
for(let i = 0; i < a.length; i++) {
if(a[i] + counter <= tot) {
finalArr.push(a[i]);
counter += a[i];
}
}
return finalArr
}
``````
1 Like

I tried something like it. But the problem I am facing is starting from the initial index won’t always work.

For e.g.,

``````keepUntilSum([2, 4, 5, 1], 10)
``````

Here the desired output is [4, 5, 1]. But as per the function, the output is [2, 4, 1]

Simply because I haven’t accounted for all the possible permutations that gets me the “closes possible result” to total, I simply went from the first element and move forward until you reach or pass total.

If you want a functionality like the one describing, that’s a whole lot more complicated to achieve, but I hope you got the logic, so you can work on it

1 Like

Just for reference & to make it easier to Google, the general version of this is called the knapsack problem, and this specifically is called a subset sum problem. It’s a very common CS-related test question, it has many usecases in practice, and it’s quite hard to do efficiently. There is no [known] way to find a solution quickly for larger sets [bar throwing more computing power at it] regardless of the algorithm used because as the problem grows larger the time required to run the code expands rapidly.

1 Like

Indeed the term is of great help to search on my own. Thank you.

1 Like