【发布时间】:2020-05-28 09:33:18
【问题描述】:
我想创建一个数组 (indexes),该数组应填充从 0 到 length - 1 的随机数。
所以如果length = 3; 那么indexes 应该从0 延伸到2,例如它可能类似于:[0, 2, 1]。
我们应该遵循一个条件:(上帝,我怎么能用英语来描述呢:)
条件:我们不接受连续的数字。
所以我们不应该返回:
[0, 1, 2] => Because 0 and 1 and 2 are consecutive.
[2, 0, 1] => Because 0 and 1 are consecutive.
[2, 3, 1, 0] => Because 2 and 3 are consecutive.
好的,我知道可能有一个例外,最后一个元素可能是连续的,因为那时我们别无选择!
我写了一段代码,但不幸的是,由于 CPU 使用率高,它导致浏览器崩溃!
请帮忙,我和我的笔记本电脑都很困惑!
// generate number from 0 to max (max could include in the result)
function getRandom(max) {
return Math.floor(Math.random() * (max + 1));
};
// our array to be filled with unordered numbers
let indexes = [];
// we will fill the above array with 0, 1 ,2 ,3 I mean 0 to (length - 1)
let length = 4;
// loop through indexes so that it is filled with 4 elements
while( indexes.length <= length){
// get a number randomally from 0 to 3
let result = getRandom(length - 1);
// we don't want any repeated number so..
if(!indexes.includes(result)){
// finally here is our condition, we should
if( result !== indexes[indexes.length - 1] + 1 ){
indexes.push(result);
} else if(indexes.length == length){
// push the last element to the array despite the condition
indexes.push(result);
}
}
};
console.log(indexes);
【问题讨论】:
-
你的标题是错误的......“用随机连续数字填充数组”与你想要的相反。
-
对不起.. 感谢 VLAZ 的编辑...
-
只是对数组进行排序然后反转它?那么所有数字都将不连续?
-
[3, 2]有效吗? -
旁注,因为您现在有很多答案,但是您的原始代码正在崩溃,因为您的
while循环永远不会结束。将<=更改为<
标签: javascript arrays random numbers