在数组中随机取三个数字,但上下左右不相邻的数字(数组交叉随机数)
这是我的代码,如何优化(更均匀地获取数字)?
感谢〜
阵列
var a = [
[0, 1],
[2, 3],
[4, 5],
[6, 7]
];
function select() {
var a = [
[0, 1],
[2, 3],
[4, 5],
[6, 7]
];
var lastSelect = -1;
for (var i = 0; i < a.length; i++) {
var index = getRandomNumber(lastSelect, a[i].length);
console.log(a[i][index]);
lastSelect = index;
}
}
function getRandomNumber(lastSelect, max) {
var random = Math.floor(Math.random() * max);
if (random == lastSelect) return getRandomNumber(lastSelect, max);
else return random;
}
select();
答案 0 :(得分:0)
Javascript有一个modulus operator %,可以找到除法的剩余部分。
var a = [
[0, 1],
[2, 3],
[4, 5],
[6, 7]
];
function select() {
//generating random 0 or 1
var random = Math.round(Math.random());
for (var i = 0; i < a.length; i++) {
console.log(a[i][(i+random)%2]);// 0 or 1
}
console.log("-----------");
}
//test
for(var j=0;j<5;j+=1){
select();
}