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

91
Vistas
Change Size of Integer Array But Retain Array Sum Javascript - Probability Distribution

I think this is more conceptual than anything and my use case is very niche.

I am trying to create an array of probabilites to pass to an RNG function. The array of probabilites can vary in size so it can't have a static length. I am creating the array of probabilities based on a single integer 0-100. I know this sounds confusing but bear with me.

For example.

const range = 5
const weight = 30
const weights = new Array(10).fill(0)
const middleIndex = Math.floor(weight / 10)

weights[middleIndex] = 100

const add = 10 - middleIndex

let counter = 2
for (let i = middleIndex + 1; i < add + middleIndex; i++) {
    weights[i] = 100 / counter
    counter += 1
}

counter = 2
for (let i = middleIndex - 1; i >= 0; i--) {
    weights[i] = 100 / counter
    counter += 1
}

console.log(weights) // [ 25, 33.336, 50, 100, 50, 33.3336, 25, 20, 16.668, 14.285 ]

See that the output array is in the form length 10, but I need the same distribution of probabilities in length 5 to pass to my RNG function such that:

const cleanWeights = compressWeights(weights, range) 
// This is my required function, it should output an array of length range and share the exact same distribution of probabilties with the input weights array.

const rand = weightedRandom(weights) 
// Returns an int from range 0 to weights.length. Likely to equal ~2 - as distribution of probability (30/100) leans to lower end of range 0, 5

If there is a better approach all together for this please let me know, if you also spot any optimization opportunities I'd love to hear them.

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