js 实现 总和为 1 的一组按比例随机分配的数字

243 阅读1分钟

 要求:第一个权重在65%-70%之间随机,第二个在15%-20%之间随机,第三个在5%-10%之间随机,第四个用100%减去前三个之和

预览地址

// Import stylesheets
import './style.css';

// Write Javascript code!
const appDiv = document.getElementById('app');
appDiv.innerHTML = `<h1></h1>`;
const numberCondition = [
  [65, 70],
  [15, 20],
  [5, 10],
];
const getRandInRange = (start, end) => {
  return start + Math.floor(Math.random() * (end - start));
};
const numberArray = numberCondition.map((condition) =>
  getRandInRange(condition[0], condition[1])
);
numberArray[3] = 100 - eval(numberArray.join('+'));
console.log(numberArray);
for (let number of numberArray) {
  appDiv.innerHTML += `<h1>${number / 100}</h1>`;
}
appDiv.innerHTML += `<h1>合计:${eval(numberArray.join('+')) / 100}</h1>`;