Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript

Zsolt Stegena
Zsolt Stegena
5,719 Points

How to implement random generator to my quiz

I have the code below, it's quite similar to Dave's one. I would like to make it works like choosing the questions randomly. I only know that I need to use Math.floor( Math.random()) function, but I don't know how. Because if I target the [i][0] element of the array with teh random function, how can I target the connecting answer? I need an assistance. Thanks for your answer in advance.

function print(message) { document.write(message); }

var questQ = [ [" 4x1",4], [" 4x2",8], [" 4x3",12], [" 4x4",06], [" 4x5",20], [" 4x6",24], [" 4x7",28], [" 4x8",32], [" 4x9",36], [" 4x10",40] ]; var correctAns =0; var goodOnes = []; var wrongOnes = [];

for (var i=0; questQ.length>i; i+=1){ var question = parseInt(prompt(questQ[i][0])); var answer = parseInt(questQ[i][1]); if (answer === question){ correctAns +=1; goodOnes.push(i + ". " + questQ[i][0]); } else { wrongOnes.push(i + ". " + questQ[i][0]); } }

var html = "Out of ten question " + correctAns + " were good" + "<br></br>"; print(html);

print("Good ones: " + "<br></br>" + goodOnes + "<br></br>"); print("Wrong ones: " + "<br></br>" + wrongOnes);

1 Answer

Steven Parker
Steven Parker
221,938 Points

Just like you are doing now by picking the indexes in sequence, you just pick an index using random and then use that same index for both the question and the answer.

To ask 10 random questions, instead of:

for (var i=0; questQ.length>i; i+=1) {

...do something like:

for (var c=0; c<10; c++) {
    i = Math.floor(Math.random() * 10);

Of course, there's no guarantee that every question will be different this way.

Oh, and 4x4 is not 6. :grin: