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.