I am writing some JS and I can't seem to figure out how to write a function that will give a true or false statement back.
The way I want to write it is:
Any help is appreciated.
This is what I have tried, in terms of getting the probability
function prob(n) {
var old = n - 1;
var val = (n += 1);
return Math.floor(Math.random() * val) == old;
}
console.log(prob(2));
I generally use these helper functions if I need random
const chance = (percentage) => Math.random() * 100 < percentage;
const getRandomInt = (min, max) =>
Math.floor(Math.random() * (max - min + 1)) + min;
const getRandomArbitrary = (min, max) =>
Math.random() * (max - min) + min;
console.log(chance(50));
console.log(getRandomInt(1, 10));
console.log(getRandomArbitrary(0, 5));
// Full code
const prizes = [{
name: 'Bear',
probability: 5,
},
{
name: 'Car',
probability: 0.02,
},
{
name: 'Poster',
probability: 90,
},
];
let count = 5;
while (count--) {
const prize = prizes[getRandomInt(0, prizes.length - 1)];
const win = chance(prize.probability);
console.log(`Prize: ${prize.name} - Won: ${win}`);
}