Enjoy an ad free experience by logging in. Not a member yet? Register.


Results 1 to 11 of 11
Thread: Random selection, !=1 question

01262012, 04:16 PM #1
 Join Date
 Jan 2012
 Posts
 2
 Thanks
 1
 Thanked 0 Times in 0 Posts
Random selection, !=1 question
Very, VERY new to javascript, hopefully this question isn't too bad..
So I'm looking at an example of randomly changing a picture through a function, I want to understand *why*, not simply know how.. The confusing code for me is:
Code:while (that.src.indexOf(myImages[newImgNumber]) != 1)
My question is, why would testing a current image with a new image result in 1 if they are the same? To me, it seems like it should be !=0?
I mean, if I tested if a number was the same as another number, I would expect a result of 0 by subtracting.
Is it not subtracting index position to find out if they're the same? Does it simply just return 1 if they are the same, and I'm over thinking it?
Thanks for any help.
01262012, 04:38 PM
#2
The problem with your question is that your statement: "The other code is irrelevant" is false.
I will make a few assumptions here since the other code is missing:
1. The 'that.src' portion to test with the '.indexOf()' function is a string, yes?
2. The 'myImages' is an array containing the source (src) names of the images to display, yes?
3. The 'newImageNumber' of the while function is initialize before the while and is incremented or decremented somewhere in the while loop, yes?
If all of the above is true, then the that.src string is being looked at by the indexOf function using the appropriate array element string.
If the array element string is found as a substring within the 'that.src' string,
then the position where the string is found is returned for the comparison.
The position starts at zero (0) and goes to the length of the 'that.src' string.
If the substring is NOT found, then the function always returns 1, which is the answer to the question you posed at the start.
Note also that unless you change the 'newImageNumber' somewhere in the while block,
you will enter into an infinite loop.
Therefore, never assume your "other code is irrelevent"!
Users who have thanked jmrker for this post:
protiss (01262012)
01262012, 04:47 PM
#3
 Join Date
 Jan 2012
 Posts
 2
 Thanks
 1
 Thanked 0 Times in 0 Posts
Thank you for your reply and my apologies. This is from a textbook for school. The total code is:
I guess my assumption was that the example was universal, and that no matter what you were comparing, you would put in !=1, as the book seems to point to that.Code:<!DOCTYPE html PUBLIC "//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Chapter 6: Example 5</title> <script type="text/javascript"> var myImages = new Array("usa.gif","canada.gif","jamaica.gif","mexico.gif"); function changeImg(that) { var newImgNumber = Math.round(Math.random() * 3); while (that.src.indexOf(myImages[newImgNumber]) != 1) { newImgNumber = Math.round(Math.random() * 3); } that.src = myImages[newImgNumber]; return false; } </script> </head> <body> <img name="img0" src="usa.gif" border="0" onclick="return changeImg(this)" /> <img name="img1" src="mexico.gif" border="0" onclick="return changeImg(this)" /> </body> </html>
I'm pretty sure you answered the question with (I don't see a quote button so I'm going to assume here)..
Thank you for the reply, I clicked the "thanks" or whatever button for you.If the substring is NOT found, then the function always returns 1, which is the answer to the question you posed at the start.
01262012, 10:07 PM
#4
No problem. You did say you were just a beginner.
However, one other problem you might have with the example is that
if you change the number of entries in the 'myImages' array,
either it will not work as expected or it will break!
The problem is here:
When you multiply by 3 the results can only fall in the range of 0, 1, 2Code:newImgNumber = Math.round(Math.random() * 3);
You have 4 images (numbered for a zero based array as 0,1,2,3)
Therefore, you calculation will never display the image for 'mexico.gif'
To correct this problem, make the following change at both statements:
That way you can alter the number of images without changing the base code.Code:newImgNumber = Math.round(Math.random() * myImages.length);
Try it. It's the best way to learn what happens (or doesn't happen) in coding a program.
01272012, 02:46 AM
#5
BAD ANSWER!
Math.random() returns a number between 0 and JUST LESS THAN 1.
That is, from 0.0000000000000000 to 0.9999999999999999 (approximately).
Let's say that myImages.length is 3. There are 3 images.
If you multiply that random number by 3, you will get a number between
0.0000000000000000 and 2.9999999999999997 (approximately)
If you then use Math.round() indeed you will get an integer number that is 0, 1, 2, or 3 !!!
So PART OF THE TIME, you will get the random number 3, and there IS NO myImages[3] element! KABLOOEY!
OUCH!!
Okay, you say, what about if I use
Okay, so now you will be multiplying the Math.random() result by 2. And so you will get numbers betweenCode:newImgNumber = Math.round(Math.random() * ( myImages.length 1 ) );
0.0000000000000000 and 1.9999999999999998 (approaximately)
And when you call Math.round(), you will indeed get integers 0,1,2. Perfect, right!
*NO*
The numbers 0 and 2 will occur HALF AS OFTEN as the number 1!!
That's easy to see:
Numbers from 0.0000 to 0.4999 round to 0
Numbers from 0.5000 to 1.4999 round to 1
Numbers from 1.5000 to 1.9999 round to 2
CLEARLY twice as many random numbers between 0 and 2 round to 1 as round to either 0 or 2.
*********************
The *CORRECT* answer is to use Math.floor() in place of Math.round()!!!
So, again, multiplying the random 0 through 1 value by 3 gives you numbers fromCode:newImgNumber = Math.floor(Math.random() * myImages.length );
0.0000000000000000 to 2.9999999999999997 (approximately)
But NOW, when you take Math.floor(), the ranges become:
0.0000 to 0.9999 becomes 0
1.0000 to 1.9999 becomes 1
2.0000 to 2.9999 becomes 2
Perfect distribution.
The general formula for evenly distributed numbers in the range LOW to HIGH is this:
That formula should be ingrained into any teacherand especially any bookthat teaches ANY computer language. The syntax might be slightly different in different languages, but the operations performed must match that formula.Code:function getRandomInteger( LOW, HIGH ) { return LOW + Math.floor( Math.random() * ( HIGH  LOW + 1 ) ); }
**************
YOUR TEXTBOOK FROM SCHOOL IS TEACHING YOU THE WRONG THING!
It makes me wonder how many other idiocies it might be pushing on you.
An optimist sees the glass as half full.
A pessimist sees the glass as half empty.
A realist drinks it no matter how much there is.
01272012, 02:49 AM
#6
As you can see from the above, jmrker is wrong. Because of the way Math.round() works, you *will* get resulst of 0,1,2,and 3. But, again, you will get 0 and 3 half as often as you will get 1 and 2.
We will be gentle and assume that jmrker didn't even notice that your idiot text book slipped in Math.round() when it should be Math.floor(). I'll bet jmrker uses Math.floor() so often he didn't even notice the slip up.
An optimist sees the glass as half full.
A pessimist sees the glass as half empty.
A realist drinks it no matter how much there is.
01272012, 03:08 PM
#7
01272012, 08:24 PM
#8
Isn't it amazing that true crap like that makes its way into a textbook that the poor students have to work with? I think he should demand his money back from the textbook publisher. He might also want to question the teacher's competence, given that apparently the teacher didn't tell them about the error in the book.
An optimist sees the glass as half full.
A pessimist sees the glass as half empty.
A realist drinks it no matter how much there is.
01272012, 09:14 PM
#9
 Join Date
 Sep 2005
 Location
 Sydney, Australia
 Posts
 6,482
 Thanks
 0
 Thanked 635 Times in 625 Posts
Where a mistake does find its way into a book the errata page on the corresponding web site should have it listed as soon as it is discovered. Someone teaching from that book should be expected to be completely familiar with all the corrections listed there so it can be brought to the students attention  so there's no excuse at all for the teacher to miss any of the errors in the book that someone has spotted and reported as that doesn't rely on their own ability to spot the error.
Even better would be where the teacher tells the students about the errata page that all books now have on the web so that they know that they can look up all the corrections to any book for themselves simply by finding the right web page.
Stephen
Learn Modern JavaScript  http://javascriptexample.net/
Helping others to solve their computer problem at http://www.felgall.com/
Don't forget to start your JavaScript code with"use strict";
which makes it easier to find errors in your code.
01272012, 09:20 PM
#10
You are assuming there is an errata available for that book. But yes, wholeheartedly agree. But the fact that the instructor doesn't catch that kind of mistake on his/her own shows that he/she is probably just one step ahead of the students.
An optimist sees the glass as half full.
A pessimist sees the glass as half empty.
A realist drinks it no matter how much there is.
01272012, 09:32 PM
#11
 Join Date
 Sep 2005
 Location
 Sydney, Australia
 Posts
 6,482
 Thanks
 0
 Thanked 635 Times in 625 Posts
All of the hundreds of computer books I have reviewed over the past eight years all have an errata page on their web site to list the errors. While not all books would necessarily have one it is fairly certain that any computer book that was published recently enough to be useful will certainly have one  even if there is nothing listed there.
All the computer book publishers I have ever received books from have the same setup on their web site for each book they publish and all include an errata page. So I am certain that the top dozen computer book publishers do have errata pages for all their books.
I agree that anyone teaching JavaScript should have spotted that error on their own even if it wasn't already listed in the errata.
Stephen
Learn Modern JavaScript  http://javascriptexample.net/
Helping others to solve their computer problem at http://www.felgall.com/
Don't forget to start your JavaScript code with"use strict";
which makes it easier to find errors in your code.