I currently have a list in Javascript:
let x = [1.0, 2.5, 5.0, 20.0, 50.0, 100.0, 500.0, 2000.0, 5000.0] where each value of this is a dollar coin.
My problem is the following, I need some equation for Javascript to choose the smallest possible number of coins to reach the maximum in the desired value.
I'll give an example:
I need as few coins as possible to max out at 5.5USD. I would use a coin of 2.5USD and 3 coins of 1.0USD to arrive at 5.5USD.
Restriction: The value obtained cannot exceed the desired value.
What math function would I use for this? Or does anyone know a technical name given to this type of equation for me to look up? Well, there was never anything like it.
CodePudding user response:
You have to write logic , no inbuilt function as such can be done easily by reduce !
let a = [1.0, 2.5, 5.0, 20.0, 50.0, 100.0, 500.0, 2000.0, 5000.0];
let query = 80.0;
while (query > 0) {
//find closest maximum number
const output = a.filter(t => t <= query).reduce((prev, curr) => Math.abs(curr - query) < Math.abs(prev - query) ? curr : prev);
query = query - output;
console.log(output);
}
CodePudding user response:
Sounds like a homework problem.
It's a little similar to this leetcode problem: https://leetcode.com/problems/combination-sum/
Check the discussion tab for various approaches.