如何使用JavaScript将值随机添加到数组中
How to add a value randomly to an array using JavaScript
我是JavaScript的新手,我正在执行一项任务,必须在12个负载之间随机分配输入值。另一方面,数组中的每个元素与下一个元素的差异不能超过一个。
例如,如果我有30头骆驼,我需要在12头骆驼之间分配这个数量。到目前为止,我已经写了下面的代码,但我正在按照要求使用TextPad,我不知道如何在同一行打印出结果。
var amount = 30;
var camels = [0,0,0,0,0,0,0,0,0,0,0,0]
var div = amount/12;
var mod = amount%12;
var x = mod / 12;
for(i=0;i<camels.length;i++){
WScript.echo(camels[i] + "|" + Math.floor(div) + "|" + mod + "|" + x)
}
如果您需要更多信息,请发表评论,谢谢
这是我的看法。注意,对于声明数组值不能与下一个值相差一个以上的要求,我认为数组是循环的,即最后一个值之后的值再次是第一个值。
var amount = 30;
var camels = [0,0,0,0,0,0,0,0,0,0,0,0];
while (amount > 0) {
var index = Math.floor(Math.random() * camels.length);
var previous = (camels.length + index - 1) % camels.length;
var next = (index + 1) % camels.length;
if (Math.abs(camels[index] + 1 - camels[previous]) <= 1
&& Math.abs(camels[index] + 1 - camels[next]) <= 1) {
camels[index]++;
amount--;
}
}
更新
根据OP的要求,这里有一个注释版本:
// the amount that needs to be distributed among the camels
var amount = 30;
// the actual values for all 12 camels, initially all zero
var camels = [0,0,0,0,0,0,0,0,0,0,0,0];
// as long as we have something to distribute
while (amount > 0) {
// get a random current index in the array, i.e. a value between 0 and 11
var index = Math.floor(Math.random() * camels.length);
// calculate the index previous to the current index;
// in case the current index is 0, the previous index will be 11
var previous = (camels.length + index - 1) % camels.length;
// calculate the index next to the current index;
// in case the current index is 11, the next index will be 0
var next = (index + 1) % camels.length;
// if adding 1 to the camel at the current index makes it so that
// the difference with the camel at the previous index is 1 or lower
// the difference with the camel at the next index is 1 or lower
if (Math.abs(camels[index] + 1 - camels[previous]) <= 1
&& Math.abs(camels[index] + 1 - camels[next]) <= 1) {
// go ahead and add 1 to that camel
camels[index]++;
// and decrement the amount accordingly
amount--;
}
}
通过添加外循环,您可以正确地添加金额的剩余部分。
while(amount > 0){
//add amount to camels
}
检查这个Fiddle是否是你想要实现的。
相关文章:
- 在函数中添加数组元素的数值
- 在Codrops的内容中添加数组元素展开缩略图网格预览
- 在javascript中动态添加数组数组
- 在 javascript 中添加数组到数组
- 如何使用推送在 JavaScript 中添加数组值
- 设置和添加数组值javascript时出现问题
- 使用 JavaScript 添加数组对象
- 将文件转换为数组并使用数据列表和选项标签为自动完成文本框添加数组元素
- 单击时将值推送到数组,然后循环添加数组值.Javascript
- 如何使用 JavaScript 更新或添加数组中的值
- 在窗体中动态添加数组文本框
- 在 javascript 中添加数组和对象会产生错误
- 如何在JavaScript中更新/添加数组的元素
- 在JavaScript中添加数组中的值
- 通过for循环添加数组值
- 如何在HTML中从Javascript添加数组的滚动列表
- Vaildate动态添加数组输入-jQuery Validate
- 在HighChart android中添加数组数据
- AngularJS:防止再次添加数组中已有的项
- 添加数组元素到现有的javascript数组