Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

151
Views
How do I write a probability function in JS

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:

  • Loop function 5 times
  • on each loop give 1 of 8 random prizes
  • then check the probability of getting the prize, e.g 1 out of 10,000.
  • One of the loops has to provide with 1 as true

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

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!