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 it assigns the value of i (which will be between 1 and 49) to each each i-th element of the nums array. So I guess it's 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 it runs a standard loop from 1 to 49, and for each of the 49 iterations, it:
assigns a random number between 1 and 49 to "rand"
assigns the i-th value of the 'nums' list (which will still be just i, right?) to temp (why?)
assigns the random number to the i-th element of the "nums" array, so presumably if it's at i=1, nums[i] = 1, and now instead of 1 it's the random number.
Then it assigns temp (which was the original value, which was i anyway) 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 it just picks 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 ) ;