0

I'm trying to grab 3 random answer from an array of answers and store them into a new array. So pretty much the new array which is selectedAnswers will have 3 random answers from the pool of answers, plus the correctAnswer. I think I some what got it, but the only problem is, I don't know how to make it skip if an array element is already used, and add a different one instead. So I end up having duplicates in my new array.

see the code here.

http://jsfiddle.net/oybojgzm/2/

var answerList = ["answer 1", "answer 2", "answer 3", "answer 4", "answer 5"];
var correctAnswer = "CORRECT!";
var selectedAnswers = [correctAnswer];
var randomNumber = 0;

function randomAnswer() {
    if (selectedAnswers.length < 4) {
        randomNumber = Math.floor((Math.random() * answerList.length) +
            1) - 1;

        for (i = 0; i < answerList.length; i++) {
            if (answerList[randomNumber] === answerList[i]) {
                randomNumber = Math.floor((Math.random() * answerList.length) +
            1) - 1;

                randomAnswer();

            } else {
                selectedAnswers.push(answerList[i]);
                console.log(selectedAnswers);
                randomNumber = Math.floor((Math.random() * answerList.length) +
            1) - 1;
                randomAnswer();
                break;
            }
        }
    }
}




randomAnswer();
1
  • Use selectedAnswers.indexOf(answerList[randomNumber]) to see if the answer is already in the array. Commented Sep 1, 2014 at 8:33

5 Answers 5

1

I would suggest using a shuffle function rather than selecting a random index from your array multiple times.

NB. This assumes that the maximumAnswers value will always be <= to answerList.length + 1

var answerList = ["answer 1", "answer 2", "answer 3", "answer 4", "answer 5"];
var correctAnswer = "CORRECT!";
var selectedAnswers = [];
var maximumAnswers = 4;

function generateAnswers() {
    var tempAnswerList = shuffle(answerList); // lets create a clone of the answerList so we dont effect the original, and shuffle it
    tempAnswerList = tempAnswerList.slice(0, maximumAnswers - 1); // - 1 cos we will be adding the correct answer
    tempAnswerList.push(correctAnswer); // add correct answer to the 
    tempAnswerList = shuffle(tempAnswerList); // shuffle again so our correct answer isnt always last
    console.log(tempAnswerList);
}


// from http://stackoverflow.com/questions/6274339/how-can-i-shuffle-an-array-in-javascript
function shuffle(o){ //v1.0
    for(var j, x, i = o.length; i; j = Math.floor(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
    return o;
};

generateAnswers();

JSFIDDLE DEMO

Sign up to request clarification or add additional context in comments.

Comments

0

I updated your code a litle, because I don't really understand why you are using such a big recursive function:

var answerList = ["answer 1","answer 2", "answer 3", "answer 4", "answer 5"];
var correctAnswer = "CORRECT!";
var selectedAnswers = [correctAnswer];

function wrong(answerList, number = 3) {
    //number means the number of answers you want as a return, I took the default as being 3
    var wrongAnswers = [];
    //While the wrongAnswer array is not filled as it should be:
    while (wrongAnswers.length < number && answerList.length > number) {
        //Take a new random value
        var random = Math.floor(Math.random() * answerList.length);
        //and add it to our array if it isn't already in there (indexOf)
        if (wrongAnswers.indexOf(answerList[random]) == -1) 
             wrongAnswers.push(answerList[random]);
    }
    //If the list of possible answers is shorter than the number of answers you need as a return, just return all the possible answers, else return the generated list
    if (answerList.length <= number) 
        return answerList; 
    else 
        return wrongAnswers;
}

console.log(wrong(answerList));

Fiddle: http://jsfiddle.net/oybojgzm/2/

Comments

0
/*
    Count: Number of answers to select
    answerPool: Array containing the possible answers
    selectedAnswers: Array that will be filled (possibly already containing elements)
*/
function selectRandomFromAndPushInto(count, answerPool, selectedAnswers) {
    //Copy answerPool in case you want to reuse it for another call
    answerPool = answerPool.slice();

    //Iterate count times to select the random answers
    for(var iteration = 0; iteration < count; iteration ++) {
        //Find a random index in range 0 .. (answerPool.length - 1)
        var index = Math.round(Math.random() * (answerPool.length - 1));
        //Take the element at this index and push it into selectedAnswers
        selectedAnswers.push(answerPool[index]);
        //Remove the answer from answerPool, so that you won't select it again
        answerPool.splice(index, 1);
    }

    //Return the resulting array
    return selectedAnswers;
}

var answerPool = ["answer 1", "answer 2", "answer 3", "answer 4", "answer 5"];
var selectedAnswers = ["CORRECT!"];
console.log(selectRandomFromAndPushInto(3, answerPool, selectedAnswers));

Yields something like (tested using node.js) :

[ 'CORRECT!', 'answer 3', 'answer 5', 'answer 4' ]

Comments

0

In a very short way:

var answerList = ["answer 1", "answer 2", "answer 3", "answer 4", "answer 5"];
var correctAnswer = "CORRECT!";
var selectedAnswers = [correctAnswer];
var randomNumber = 0;

function randomAnswer() {
while(selectedAnswers.length < 4){
    randomNumber = Math.floor(Math.random() * answerList.length);
    if(!(selectedAnswers.indexOf(answerList[randomNumber])>-1))
        selectedAnswers.push(answerList[randomNumber]);
    }
}

randomAnswer();

http://jsfiddle.net/oybojgzm/5/

Comments

0

Consider starting with an array you can test as you use it:

 var answerList = ["answer 1", "answer 2", "answer 3", "answer 4", "answer 5"];
 var correctAnswer = "CORRECT!";
 var selectedAnswers = [];
 var randomNumber, tmp, tm2, lng, i;

 function randomAnswer() {
   tmp=[];
   tm2=0; //number of elements currently in the tmp array
   lng=answerList.length; //save processing time by getting the length ONCE
   while(tm2<3) { //loop til we get 3 numbers in the tmp array
     randomNumber = Math.floor(Math.random() * lng); //array-index 0 thru (lng-1)
     for(i=0; i<tm2; i++) //first random number always is acceptable
       if(tmp[i]==randomNumber) //if array-index is in the tmp array
         break; //stop looping/looking; prevents i from equalling tm2
     if(i==tm2) //at end of UN-break'ed for loop, this would be true
       tmp[tm2++]=randomNumber; //only different indices saved in tmp array
   }//end of while loop, which gets another random number until 3 different ones are selected
   //now put the correct answer somewhere, randomly, in the final array
   randomNumber = Math.floor(Math.random() * 3); //array-index 0 thru 2
   for(i=0; i<3; i++) {  //we know there are 3 indices in the tmp array
     if(i==randomNumber) //if our counter equals the random location for the answer
       selectedAnswers.push(correctAnswer);  //put the real answer into the output
     selectedAnswers.push(answerList[tmp[i]]); //always put one of the other answers into the output
   }
   console.log(selectedAnswers);
 }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.