JSFiddle - React, Tailwind, and code Playground

by Lardpower

JavaScript

function getRandomInt(min, max) {
    min = Math.ceil(min);
    max = Math.floor(max);
    return Math.floor(Math.random() * (max - min + 1)) + min;
}

function getSum(numbers){
	return numbers.reduce((partialSum, a) => partialSum + a, 0);
}

let boostAmount = 35;
let minPrice = 2;
let maxPrice = 20;

function getRandomContributions(){
let randomContributions = [];

let left = boostAmount;
let currentSum = 0;

while(left > 0) {
    let currentAmount = left === minPrice ? minPrice : Math.min(getRandomInt(minPrice, maxPrice), left);

    if (left <= minPrice){
        currentAmount = minPrice;
    }
    
    const leftForNext = left - currentAmount;
    
    if (leftForNext < minPrice){
      currentAmount += leftForNext;
      left = 0;
    }

		currentSum += currentAmount;
    randomContributions.push(currentAmount);

    left -= currentAmount;
}
  
  return randomContributions;
}

let globalSum = 0;
for(let i = 0; i < 100; i++){
const cs = getRandomContributions();
  const sum = getSum(cs);
  
  console.log('i:', i, cs, sum);
  
  globalSum += sum;
  
	if (sum > boostAmount || sum < boostAmount){
  	console.log(i, cs, sum);
  }
}

console.log('stop', globalSum);