Random distribution

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);
}

function getRandomContributions(){

let boostAmount = 20;
let minPrice = 2;
let maxPrice = 20;
let randomContributions = [];

let left = boostAmount;

while(left > 0) {
	let currentAmount = left <= minPrice ? minPrice : Math.min(getRandomInt(minPrice, maxPrice), left);
	
  if (left <= minPrice){
  		currentAmount = minPrice;
  }
  
  if ((left - (getSum(randomContributions) + currentAmount) < minPrice)){
  	// currentAmount -= 1;
  }
  
	randomContributions.push(currentAmount);
  
  left -= currentAmount;
}

let correction = getSum(randomContributions) > boostAmount;

let j = 0;
while(correction > 0 || j > 100){
    randomContributions.map((c, i) => {
      // do not correct the first item
      if (i > 0 && c > (minPrice + 1)){
        console.log('lower', c);
        c -= 1;
        correction -= 1;
      }
    });
    
    j += 1;
  }
  
  return randomContributions;
}


for(let i = 0; i < 100; i++){
	// const cs = getRandomContributions();
  
  console.log(i);
}