Can any one Explain how this Math.random here?


#1

var rand = Math.floor(Math.random() * (index - 1)) + 1;

that’s the code for the math.random
but I still do what to learn some of this code below on how it work?

`function populateRoundAnswers(gameQuestionIndexes, correctAnswerIndex, correctAnswerTargetLocation) {
// Get the answers for a given question, and place the correct answer at the spot marked by the
// correctAnswerTargetLocation variable. Note that you can have as many answers as you want but
// only ANSWER_COUNT will be selected.
var answers = [],
answersCopy = questions[gameQuestionIndexes[correctAnswerIndex]][Object.keys(questions[gameQuestionIndexes[correctAnswerIndex]])[0]],
temp, i;

var index = answersCopy.length;

if (index < ANSWER_COUNT){
    throw "Not enough answers for question.";
}

// Shuffle the answers, excluding the first element.
for (var j = 1; j < answersCopy.length; j++){
    var rand = Math.floor(Math.random() * (index - 1)) + 1;
    index -= 1;

//also this one here Can anyone elaborate what are they actually trying to accomplish here? Much love and thank you *****************************************************************
var temp = answersCopy[index];
answersCopy[index] = answersCopy[rand];
answersCopy[rand] = temp;
}

// Swap the correct answer into the target location
for (i = 0; i < ANSWER_COUNT; i++) {
    answers[i] = answersCopy[i];
}
temp = answers[0];
answers[0] = answers[correctAnswerTargetLocation];
answers[correctAnswerTargetLocation] = temp;
return answers;

}


#2

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.