Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

90
Visualizações
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 à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda