Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

157
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda