有没有一种有效的方法可以将整数解包为随机的唯一数字?
我想10
成为3 4 6 1 0 2 5 7 8 9
。
我想这...但推值到阵列中去循环之前疯狂,我想或许有更好的办法。
编辑:
这是我的新功能和新功能:
function uniqueDigits(x){
y = [];
z = [];
while(x > 0) {
y.push(x);
x--;
}
while(y.length > 0){
var r = Math.floor(Math.random()*y.length);
var u = y[r]
y.splice(r, 1);
z.push(u-1);
}
return z;
}
uniqueDigits(4) //['2', '3', '0', '1']
编辑:
还有另一个选择:
function uniqueNum(x){
z = y = x;
var r = Math.ceil(Math.random() * x);
while ( x%r%2 == 0 ) {
r = Math.ceil(Math.random() * x);
}
while( x>0 ){
y = y - r
if(y<0){
var n = y;
y = z + n
}
$('p').append(y);
x--
}
} uniqueNum(4);//['2', '3', '0', '1']
或这一个太
好了,我完成了。
由于您要查找范围内的所有数字,请尝试
var x = 10,
array = [];
for (var y = 0; y < x; y++) {
array.push(y);
}
while (array.length) {
var random = Math.floor(Math.random() * array.length);
$('p').append(array.splice(random, 1));
}
演示:小提琴
使用数组的另一种方法是
var x = 10,
array = [];
//used for counting the loop for performance testing - remove it
var counter = 0;
for (var y = 0; y < x;) {
var random = Math.floor(Math.random() * x);
if ($.inArray(random, array) == -1) {
$('p').append(random);
array.push(random);
y++;
}
//for test
counter++;
}
console.log(counter)
演示:小提琴-但循环执行太多次
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句