Tuesday, 10 March 2015

JS; Random Question generator.

My approach to solving this problem may be different from the approach you will adopt to solving the same problem. But in all, it generates and prints random questions at every web-browser refresh from a list of pre-registered questions.


For this solution, I will be working with a data-type called array. The reason for this should be quite obvious. Array variables hold loads of values.. and our values? You got it, will be the questions.

Let us start therefore by defining an array variable to hold 7 questions.


var questions = new Array(7);

There, we just created an array variable "questions" with a length of 7. We now need to put in the questions into the array.

questions[0] = "What is your name?"
questions[1] = "How old are you?"
questions[2] = "Your primary school name is?"
questions[3] = "Your mother's maiden name"
questions[4] = "Your first dog is of what breed?"
questions[5] = "You have just how many toes?"
questions[6] = "Your favourite meal will be?"

You get the drift yes? Array index values begin at zero. Take this as a rule of thumb; 


Maximum index value of an array = length of the array - 1

So an array of length 20 has its maximum index value at 19 since index count begins from zero i.e 0,1,2,3,...19.

Great! Now to display our questions stored in this array at random, we invoke a Math.random() function.

The random() method of a Math class is really a weak method. It merely outputs floating point values between zero and one. Values such as 0.2342533. 


We actually want the javascript interpreter to deduce integer values from 0 - 6 which should serve as our index value for our questions array when the time is right. 

//Generating the numbers from 0 - 6 randomly.
var randNumb = Math.floor(Math.random() * 7 );

Math.floor - Rounds down the floating point value in its brackets to an integer.
Math.random() * 7 - generates a random floating point value between 0 and 1.

document.write(questions[randNumb]);

The JS statement above print out random questions from 0 - 6. 

//The script in its full form 

document.write("Welcome to my random question generator script");
var questions = new Array(7);
questions[0] = "What is your name?"
questions[1] = "How old are you?"
questions[2] = "Your primary school name is?"
questions[3] = "Your mother's maiden name"
questions[4] = "Your first dog is of what breed?"
questions[5] = "You have just how many toes?"
questions[6] = "Your favourite meal will be?"
var randNumb = Math.floor(Math.random() * 7 );
document.write(questions[randNumb]);

//End of script

Enjoy.
Joseph Kayode Agbede

1 comment: