Click here to Skip to main content
15,922,512 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello,


I am trying to understand what the random function does in this function. here is the original purpose of this function

This function returns an array that contains a scrambled list of values. There are exactly four pairs of numbers (1,2,3 and 4) and one unpaired number (5) in the array. The values in the array are scrambled by using the array.sort() method to sort the array in a pseudo random way.

JavaScript
function randomAnswers(){
    var answers = [1,1,2,2,3,3,4,4,5];
    answers.sort(function(item){
        return .5 - Math.random();
    })
    return answers;
}


What I have tried:

I know that random returns numbers between 0(included) to 1(not included). but I dont get .5 -Math.random(); in this function
Posted
Updated 27-Nov-17 14:44pm
v3

What's not to understand?

It's just math. Generate a random number between 0 and 1 (inclusive), subtract that from 0.5 and return the result to whatever code called this code.
 
Share this answer
 
If it works like .net's CompareTo, the Sort expects a comparison of two objects to return a value of...

=0 -- if the objects are "equal"
<0 -- if the first object is "less than" the second
>0 -- if the first object is "greater than" the second


The Sort can then arrange the objects according to their comparisons,
BUT! Here it receives a "random" value between -0.5 and +0.5 -- thereby resulting in an unpredictably arranged sequence of objects.
 
Share this answer
 
v3
Comments
mappleleaf 27-Nov-17 21:23pm    
Thank you so much Piebald for thelp. hmm So, .5 - Math.random(); is the same as Math.random() -.5 and that returns numbers between -.5 and +.5 right, but what is the purpose of passing an element in the function it it is not part of the random equation of '.5 - Math.random();'
PIEBALDconsult 27-Nov-17 21:33pm    
Just to satisfy the requirement I suspect.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900