samedi 8 août 2015

"lottery" in javascript - sort algorithm?

I'm trying to understand the code example that's at the end of my post and I need help. So this is supposed to be a "lottery". So here's what I see:

for( i = 1 ; i < 50 ; i++ ){ nums[ i ] = i ; }

Here we assign the value of i (which will be between 1 and 49) to each each i-th element of the nums array. So I guess we're just making an array that contains the numbers 1 to 49. I don't see the point of this whole line, actually, given the code that follows.

for( i = 1 ; i < 50 ; i++ )
 {
   rand = Math.ceil( Math.random() * 49 ) ;
   temp = nums[ i ] ;
   nums[ i ] = nums[ rand ] ;
   nums[ rand ] =temp ;
 }


Here I get confused. So, once again we run a standard loop from 1 to 49, and for each of the 49 iterations, we 1) assign a random number between 1 and 49 to "rand"

2) assign the i-th value of the 'nums' list (which will still be just i, right?) to temp (why?)

3) assign our random number to the i-th element of the "nums" array, so presumably if we are at i=1, nums[i] = 1, and now instead of 1 it's our random number.

4) Then we assign temp (which was the original value, which was i anyways) back to the value that's in the rand-th position of the nums array.

So what am I misunderstanding here? I don't get the point of this. Where is this leading? Am I reading it correctly? Presumably at the end of this, the numbers inside the array are jumbled up, and then at the end we just pick the first six, which are 6 "random" numbers. But why not just do something like:

var nums=[];
for(i=0; i<6; i++) {
  nums[i] == Math.ceil(Math.random() * 49);
} 

along with a test to ensure the random numbers weren't the same?


Here's the code example in whole:

function init()
{
 var panel = document.getElementById( "panel" ) ;
 var i , rand , temp , str , nums = [] ;
 for( i = 1 ; i < 50 ; i++ ){ nums[ i ] = i ; }
 for( i = 1 ; i < 50 ; i++ )
 {
   rand = Math.ceil( Math.random() * 49 ) ;
   temp = nums[ i ] ;
   nums[ i ] = nums[ rand ] ;
   nums[ rand ] =temp ;
 }
 str = "Your Six Lucky Numbers:<br>" ;
 for( i = 1 ; i < 7 ; i++ )
 {
   str += nums[ i ] ;
   if( i !== 6 ) { str += " - " ; }
 }
 panel.innerHTML = str;
}
document.addEventListener( "DOMContentLoaded" , init , false ) ;




Aucun commentaire:

Enregistrer un commentaire