0

I can’t seem to understand this loop.

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

It is part of a larger code. nums[i] is an array of 1-49 filled with their respective index numbers, then it is run through this for loop and filled with random numbers.

I don’t understand why the temp variable is created, how the nums[rand]=temp; line of code works and what does it do, and why is it not even initialized without the var keyword.

Can someone explain how this loop works?

Paul D. Waite
  • 96,640
  • 56
  • 199
  • 270
dotmax
  • 21
  • 2
  • 4
  • 2
    Regardless of the solution, this is a [naïve random sort](http://www.codinghorror.com/blog/2007/12/the-danger-of-naivete.html) and isn't actually as random as you think it is. – Gareth Jul 09 '12 at 09:30
  • Read this regarding var vs no var -> http://stackoverflow.com/questions/1470488/difference-between-using-var-and-not-using-var-in-javascript – Manse Jul 09 '12 at 09:31

2 Answers2

1

What the code attempts to do is to shuffle the array. It works by going through the array, and for each position, store the value in a temp variable, pick another position in the array and swap the values with the other position.
The temp variable is required as this is the most simple way to swap the values of the variables.

Variant
  • 17,279
  • 4
  • 40
  • 65
1

It's just randomly swapping two values in the nums array. Although ignoring the very first one; javascript arrays start at 0, but the loop only starts at 1, so it only starts from the 2nd array element.

So stepping through the code, every time it goes round the loop it does something like this:

nums = [a, b, c];  // just mocking some data

rand = 0..2;  // lets say it = 2
temp = nums[1]; // = 'b', the 2nd array element
nums[1] = temp;  // so nums[1] goes from 'b' to 'c'
nums[temp] = temp; // and nums[2] goes from 'c' to 'b'

overall it's pretty bad code. If it's working with an array it should use array.length instead of hardcoding 50 for the upper limit of the loop.

duncan
  • 31,401
  • 13
  • 78
  • 99
  • but why do you need to store the old value when generating random numbers cant you just throw the ordered numbers out and fill it with random number why do you need to store the old value in temp? – dotmax Jul 09 '12 at 09:55
  • well it all depends on what is in the nums[] array. Is it just full of 50 random numbers? Because all this code does is swap the array values around – duncan Jul 09 '12 at 10:57