使用没有冗余数组值的Fisher Yates

时间:2017-01-06 17:11:39

标签: javascript arrays

我使用fisher yates shuffle随机化将使用哪些数组值但是当我在我的完整脚本中使用它时,它有时使用相同的数组值我需要一个函数来防止它使用相同的数组值两次

这是使用嵌套数组

的shuffle
Array.prototype.shuffle =
function(){
        var i = this.length, j , temp;
        while (--i> 0){
            j= Math.floor(Math.random() * (i+1));
            temp= this[j];
            this[i]= temp;
        }return this;

}
var rans = [
    [ "What is 10 + 4?", "12", "14", "16", "B" ],
    [ "What is 20 - 9?", "7", "13", "11", "C" ],
    [ "What is 7 x 3?", "21", "24", "25", "A" ],
    [ "What is 8 / 2?", "10", "2", "4", "C" ]
];
var questions = rans.shuffle();

这是使用数组

的脚本
var pos = 0, test, test_status, question, choice, choices, chA, chB, chC, correct = 0;

function _(x){
return document.getElementById(x);
}
// this function renders the test results
function renderQuestion(){
test = _("test");
if(pos >= questions.length){
    test.innerHTML = "<h2>You got "+correct+" of "+questions.length+"    questions correct</h2>";
    _("test_status").innerHTML = "Test Completed";
        pos = 0;
    correct = 0;
    return false;
}
_("test_status").innerHTML = "Question "+(pos+1)+" of "+questions.length;
question = questions[pos][0];
chA = questions[pos][1];
chB = questions[pos][2];
chC = questions[pos][3];
test.innerHTML = "<h3>"+question+"</h3>";
test.innerHTML += "<input type='radio' name='choices' value='A'> "+chA+"<br>";
test.innerHTML += "<input type='radio' name='choices' value='B'> "+chB+"<br>";
test.innerHTML += "<input type='radio' name='choices' value='C'> "+chC+"<br><br>";
test.innerHTML += "<button onclick='checkAnswer()'>Submit Answer</button>";
}
 function checkAnswer(){
choices = document.getElementsByName("choices");
for(var i=0; i<choices.length; i++){
    if(choices[i].checked){
        choice = choices[i].value;
    }
}
if(choice == questions[pos][4]){
    correct++;
}
pos++;
renderQuestion();
}
window.addEventListener("load", renderQuestion, false);

0 个答案:

没有答案