我想随机生成某人每天花在各种事件上的小时数。
我创建了一个对象,该对象将存储对象键(事件)、其值(小时)以及一个用于存储它们的数组。我还使用随机方法生成小时数,并确保每个初始值在随机生成下一个对象属性之前不超过 24 小时。但我需要总和为 24 小时的小时数。
let organised = new Object(),
pworks = null,
commutes = null,
fun = null,
work = false;
let arr= [];
if(!work){
organised.pworks = Math.floor(Math.random()*24)
if(organised.pworks < 24){
console.log('you spend ' + organised.pworks+'hrs' + ' on Primary Work' )
arr.push(organised.pworks)
organised.commutes = Math.floor(Math.random()*24)
if(organised.commutes + organised.pworks < 24){
arr.push(organised.commutes)
console.log('you spend ' + organised.commutes+'hrs' + ' on Commute' )
organised.fun = Math.floor(Math.random()*24)
if(organised.commutes + organised.pworks + organised.fun <= 24){
console.log('you spend ' + organised.fun+'hrs' + ' on having Fun' )
arr.push(organised.fun)
}
}
} }
您在主要工作上花费了 6 小时 您在通勤上花费了 10 小时 你花了 8 小时来享受乐趣
最佳答案
您需要在剩余时间内随机选择随机值,而不是完整的 24 小时。例如,这是不正确的:
organised.commutes = Math.floor(Math.random() * 24);
...因为它不允许 organized.pworks
占用的时间。所以:
organised.commutes = Math.floor(Math.random() * (24 - organized.pworks));
...下一个依此类推,它必须允许 organized.pworks
和 organized.commute
。保持运行记录可能会很方便,这样您就不必继续添加更多属性:
var remaining = 24;
organised.pworks = Math.floor(Math.random() * remaining);
remaining -= organised.pworks;
// ...
organised.commutes = Math.floor(Math.random() * remaining);
remaining -= organised.commutes;
// ...
那么您可能不需要最后一个随机值,您只需要剩余时间:
organised.fun = remaining;
关于javascript - 有没有办法让事件总时间始终为24小时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54079325/