lundi 2 octobre 2017

Divide / Hand out random amount

Lets say I have 8 people and 5000 apples.
I want to hand out all the apples to all 8 people so i have no apples left.
But everyone should get a different amount

What would be the best way to give them all out?

I started of with this:

let people = 8
let apples = 5000

function getRandomInt(min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min
}

while (people--) {
  // last person get the rest
  let x = people ? getRandomInt(0, apples) : apples

  // subtract how many apples i got left
  apples -= x 

  console.log(`Giving person ${people + 1} ${x} apples (got ${apples} left)`)
}

But the thing I don't like about this is that the last person get very few apples (sometimes less then 5 apples) and the first person gets way more then the others




Aucun commentaire:

Enregistrer un commentaire