Let’s say we have an arbitrary integer, position that equals 1850
We also have an array of integers, components that equals [150, 200, 500]
We can reach the zero by:
- Subtract
components[2]
fromposition
three times (500*3), making it 350 - Subtract
components[1]
fromposition
, making it 150 - Subtract
components[0]
fromposition
, making it 0
So, using integers from the components array, I subtracted from position
until there was as little left as possible (0)
Coded example:
var components = [500, 750, 1000];
var position = 2250;
position -= components[1]; // goal is now 1500
position -= components[0] * 3; // goal is now 0
The question: is there an algorithm to determine the best way to reach zero from a number by subtracting only allowed numbers?
It would be highly preferrable that the algorithm uses the least number of components / subtractions possible.
I’ve tried a few naive methods like brute forcing, but that isn’t ideal as performance is quite important in my application.
2
Answers
You could take a backtracking and use an ordered array for having the largest values first.
technically this is a brute-force algorithm trying combinations but with some short circuiting. Like avoiding some pointless combinations and returning early when a combination is found with remainder: 0.
And it works backwards from highest to lowest value, trying to reduce the remainder as much as possible and then checking if there is a better result with a lower count for this value to ensure that when there are multiple possible results it finds the one with the lowest count first.