JSFiddle - React, Tailwind, and code Playground
by coktopus
JavaScript
// cons - need extra logic to divide the non-divisible values like 222, 543
// pros - consistent result even on small samples(100 not 1000)
let arr = [];
let a = 0;
let distribution = 1000/100; // change this to 100/100
let x = 1;
let tempArray = []
let distributedArray = []
while(a<=1000){
arr.push(a)
if(x === 10){
x = 1
tempArray.push(a)
distributedArray.push(tempArray);
tempArray = [];
}else{
tempArray.push(a);
x++
}
a++
};
const targetValue = 10;
let closestValue = null
let closestValueIndex = -1
distributedArray.map((x, index)=>{
const closest = x.reduce((a, b) => {
return Math.abs(b - targetValue) < Math.abs(a - targetValue) ? b : a;
});
if(closestValue === null) {
closestValue = closest
closestValueIndex = index
}else{
closestValue = [closest, closestValue].reduce((a, b) => {
return Math.abs(b - targetValue) < Math.abs(a - targetValue) ? b : a;
});
if (closestValue === closest){
closestValueIndex = index
}
}
})
console.log('prob. to exceed =>', 100-closestValueIndex)