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

153
Vistas
Choosing a random element from an array with weights

I'm currently trying to create a random weighted index picker.

My goal is to randomly pick an element from an array. However, its not just as simple as doing this. Certain elements have a boosted chance of winning. This can be viewed as a sort of lottery

The data structure is as follows:

const users = [
 {userId: 1, multiplier: 0},
 {userId: 2, multiplier: 25}
 {userId: 3, multiplier: 0}
 {userId: 4, multiplier: 25}
 {userId: 5, multiplier: 15}
 {userId: 6, multiplier: 30}
 {userId: 7, multiplier: 35}
 {userId: 8, multiplier: 2}
 {userId: 8, multiplier: 7}
]

Each element of the array counts as one entry. However, the multipliers allow the user to have a higher chance of winning.

A solution which I came up with was view the multipliers as number of tickets so if a user had a multiplier of 25 then they would have 25 tickets.

However, this is very inefficient because when there are 10s of thousands of entries with many multipliers the array size grows at an incredible rate.

I'm not sure how I can make this more efficient.

My solution can be viewed here:

const users = [
 {userId: 1, multiplier: 0},
 {userId: 2, multiplier: 25}
 {userId: 3, multiplier: 0}
 {userId: 4, multiplier: 25}
 {userId: 5, multiplier: 15}
 {userId: 6, multiplier: 30}
 {userId: 7, multiplier: 35}
 {userId: 8, multiplier: 2}
 {userId: 8, multiplier: 7}
]

const potentialWinners = []

users.map((user) => {
    for(let i=0; i < user.multiplier; i++) {
        potentialWinners.push(user.userId)
    }
})

Other solutions which I have viewed seemed quite complicated and I am not great at Math so I had a hard time understanding what was happening.

They also all seem to work based off of percentages, and mine doesn't I'm not entirely sure how I can rework the multiplier system to take into account a multiplied chance of winning.

about 4 years ago · Juan Pablo Isaza
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