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

98
Views
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
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!