View Full Version : Random selection, !=-1 question

protiss

01-26-2012, 05:16 PM

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:

while (that.src.indexOf(myImages[newImgNumber]) != -1)

The other code is irrelevant.

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.

jmrker

01-26-2012, 05:38 PM

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:

while (that.src.indexOf(myImages[newImgNumber]) != -1)

The other code is irrelevant.

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.

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"! :eek:

protiss

01-26-2012, 05:47 PM

Thank you for your reply and my apologies. This is from a textbook for school. The total code is:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"

"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.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 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.

I'm pretty sure you answered the question with (I don't see a quote button so I'm going to assume here)..

If the substring is NOT found, then the function always returns -1, which is the answer to the question you posed at the start.

Thank you for the reply, I clicked the "thanks" or whatever button for you.

jmrker

01-26-2012, 11:07 PM

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.

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.

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:

newImgNumber = Math.round(Math.random() * 3);

When you multiply by 3 the results can only fall in the range of 0, 1, 2

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:

newImgNumber = Math.round(Math.random() * myImages.length);

That way you can alter the number of images without changing the base code.

Try it. It's the best way to learn what happens (or doesn't happen) in coding a program.

:)

Old Pedant

01-27-2012, 03:46 AM

To correct this problem, make the following change at both statements:

newImgNumber = Math.round(Math.random() * myImages.length);

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

newImgNumber = Math.round(Math.random() * ( myImages.length -1 ) );

Okay, so now you will be multiplying the Math.random() result by 2. And so you will get numbers between

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()!!!

newImgNumber = Math.floor(Math.random() * myImages.length );

So, again, multiplying the random 0 through 1 value by 3 gives you numbers from

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:

function getRandomInteger( LOW, HIGH )

{

return LOW + Math.floor( Math.random() * ( HIGH - LOW + 1 ) );

}

That formula should be ingrained into any teacher--and especially any book--that teaches ANY computer language. The syntax might be slightly different in different languages, but the operations performed must match that formula.

**************

YOUR TEXTBOOK FROM SCHOOL IS TEACHING YOU THE WRONG THING!

It makes me wonder how many other idiocies it might be pushing on you.

Old Pedant

01-27-2012, 03:49 AM

The problem is here:

newImgNumber = Math.round(Math.random() * 3);

When you multiply by 3 the results can only fall in the range of 0, 1, 2

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.

jmrker

01-27-2012, 04:08 PM

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.

Spot on ... I seldom use Math.round(), but that's just me. :thumbsup:

I was too busy looking at the *3 compared to the 4 images in the array. :o

Old Pedant

01-27-2012, 09:24 PM

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.

felgall

01-27-2012, 10:14 PM

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.

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.

Old Pedant

01-27-2012, 10:20 PM

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.

felgall

01-27-2012, 10:32 PM

You are assuming there is an errata available for that book.

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.

Powered by vBulletin® Version 4.2.2 Copyright © 2015 vBulletin Solutions, Inc. All rights reserved.