Lucas016
Lucas016

Reputation: 117

minimum of list to maximum of value in Javascript

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.

Upvotes: 0

Views: 52

Answers (1)

Tushar Wasson
Tushar Wasson

Reputation: 556

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);
}

Upvotes: 1

Related Questions