2017-04-25 11 views
0

주어진 범위 내에서 4 개의 동일하지 않은 임의의 숫자를 생성하는 함수를 작성하려고하지만이 함수는 현재 while (selection[i] in selection.slice().splice(i) 행에서 실패하고 있습니다. 이 줄은 현재 (i) 값이 다른 임의의 값과 공유되는지를 확인해야하지만 현재 아무 것도하지 않는 것처럼 보입니다. 아마도 in을 잘못 사용했을 것입니다. 어떤 도움을 주시면 감사하겠습니다. 그래서자바 스크립트 - 여러 불균등 난수 생성기

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(", ") + "]");

셔플하려면