-3

I want a math algorithm for javascript

  • Input: random from 0.00 to 200.00
  • Output: 3 randomly-minimal numbers in banknotes (0.01,0.02,0.05,1,5,10,20,50,100,200)
  • (like paying at the shop)

Example input->output:

  • 0.15->0.2 or 0.5 or 1
  • 4-> 4 or 5 or 10
  • 9-> 10 or 15 or 20
  • 174 -> 175 or 180 or 200
martik78
  • 3
  • 5

1 Answers1

0

For the first step, you can multiple Math.random() with 200 (this link will explain more).

Then you can find what banknotes are greater than or equal to the random amount (Array.prototype.filter()).

Then you can use Math.random() again to pick 3 random valid banknotes (link).

This is the code that does the steps above:

const banknotes = [0.01, 0.02, 0.05, 1, 5, 10, 20, 50, 100, 200]

const handleClick = () => {
  const amountNeeded = Math.random() * 200
  const validBanknotes = banknotes.filter(value => value >= amountNeeded)
  const randomBanknotes = []
  for (let i = 0; i < 3; i++) {
    randomBanknotes.push(validBanknotes[Math.floor(
      Math.random() * validBanknotes.length)])
  }
  console.log(`Amount needed: ${amountNeeded}. Random banknotes: ${randomBanknotes}`)
}
<button onclick='handleClick()'>Click to generate random results</button>
programmerRaj
  • 1,810
  • 2
  • 9
  • 19