...

View Full Version : A very simple question



laland
10-20-2006, 11:57 AM
Hey,
I have a very simple question abt the Rabbit Jumping problem.

If a rabbit need to across the river, there are number of stones positioned at different distance between the two opposite side of a river, the rabbit can only hop at most 50 centimetres far. I suppose to write out a program to calculate the minimum number of jumps it needs to take to reach the other side of the river.

But I stuck at the algorithm of calculating the min jumps.... Can anyone give me some ideas. Thanks in advance.

Kor
10-20-2006, 12:08 PM
You may use the modulo operator (I guess in fact that was the intention of you teacher):

<script type="text/javascript">
var riverWidth=13.4;
var maxJump=0.5;
var d=parseInt(riverWidth/maxJump);
var minJumps=riverWidth%maxJump==0?d:d+1;
alert(minJumps);
</script>

laland
10-20-2006, 12:35 PM
Em... but how to use array to store the number of stones between the river?

AND what does this " 0?d:d+1 " mean?

Thanks

Kor
10-20-2006, 12:59 PM
The stones number is, obviousely, the min jumps-1.

condition?statement1:statement2
is a ternary operator. It is the shorthand notation for

if(condition){
statement1
}
else{
statement2
}

laland
10-20-2006, 01:54 PM
Hey, thanks
I almost done... but I have a problem...
For example: if the user enter the distance measured from one side of the river like this : 5 10 15 20 25 100 , it is impossible for the rabbit to jump from the 2nd last stone(which is positioned at 25cm measured from the starting side of the river) to 100, right?
OR if the user entered 40 70 150 160 180, it is also impossible for the rabbit to jump from 70 to 150, thus the rabbit cannot jump across the river...

How do we check huh?
Do we have to write a loop to check the difference between every stones?

Kor
10-20-2006, 01:59 PM
I don't understand your problem.

For me, the logical analysis is like that:

- I have the width of the river and the max witdh of rabbits jump
- I need to find the number of the stones.

To find that, I find as a first step the number of minimum jumps the rabbit must do (I have shown you the code). Now I substract 1 from that number (but only if modulo between Riverwidth/maxWidhOfAJump is different from 0) and here's the result, the number of the stones.

laland
10-20-2006, 02:45 PM
Sorry 4 not explaining clearly...
but thanks, I finally get it.

laland
10-20-2006, 02:49 PM
hey,
I've nominated u 4 ur help,
Thanx~~



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum