2017-04-25 27 views
0

我正在尝试编写一个函数,它可以在给定范围内生成四个不相等的随机数,但该函数目前在while (selection[i] in selection.slice().splice(i)行失败。此行应检查当前(i'th)值是否由任何其他随机值共享,但目前看起来什么都不做 - 可能我错误地使用了in?任何帮助,将不胜感激。Javascript - 多个不等随机数生成器

function getRandomInt(min, max) { 
    min = Math.ceil(min); 
    max = Math.floor(max); 
    return Math.floor(Math.random() * (max - min)) + min; 
} 

所以:

function contains(a, obj) { 
    for (var i = 0; i < a.length; i++) { 
    if (a[i] === obj) { 
    return true; 
    } 
    } 
    return false; 
} 

selected=[]; 

function randomSelection() { 

    var notselected=[]; 
    for (var i=0; i<25; i++) { 
    if(!contains(selected, i)) { 
     notselected.push(i); 
    } 
    } 
    var selection=[notselected[Math.floor(Math.random() * notselected.length)], 
          notselected[Math.floor(Math.random() * notselected.length)], 
          notselected[Math.floor(Math.random() * notselected.length)], 
          notselected[Math.floor(Math.random() * notselected.length)]]; 

    for (var i=0; i<selection.length; i++) { 
    while (selection[i] in selection.slice().splice(i)) { 
     alert('Hello!') 
     selection[i] = notselected[Math.floor(Math.random() * notselected.length)]; 
    } 
    } 
    for (var i=0; i<selection.length; i++) { 
    selected.pop(selection[i]); 
    } 
} 

回答

2

您可以使用下面的方法

function getRandomArbitrary(min, max) { 
    return Math.floor(Math.random() * (max - min)) + min; 
} 

如果该值必须是整数,你可以使用下面的方法来获得两个数字之间的随机值,假设你需要4个不同的随机整数值,你可以做类似的事情

var randoms = []; 
while(randoms.length < 4) { 

    var random = getRandomInt(0, 25); 

    if(randoms.indexOf(random) === -1) { 
    randoms.push(random); 
    } 
} 
0

,随机混合(在这种情况下的数字)的一组物体

var values = [0,1,2,3,4,5,6]; 
 
    function shuffle(arr){ 
 
     var temp = [...arr]; 
 
     arr.length = 0; 
 
     while(temp.length > 0){ 
 
      arr.push(temp.splice(Math.floor(Math.random() * temp.length),1)[0]); 
 
     } 
 
     return arr; 
 
    } 
 
    console.log("pre shuffle : [" + values.join(", ") + "]"); 
 
    shuffle(values); 
 
    console.log("post shuffle : [" + values.join(", ") + "]");