aspose file tools*
The moose likes Beginning Java and the fly likes A probability problem Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "A probability problem" Watch "A probability problem" New topic
Author

A probability problem

Amil Mehmedagic
Greenhorn

Joined: Feb 27, 2004
Posts: 22
The problem requests the creation of a circle set at position (30,30).
It then needs to move at a rate of 5 pixels every 20 milliseconds to follow
a square perimeter of side 400 pixels in a clock-wise direction.
I managed to code this step, but now comes the tricky part.
At each move the circle must be capable of changing its direction with probability 0.01 (the probability of moving anti-clockwise)
This is my code:
import genesis.*;
import java.awt.*;
public class MovingCircle2 {

public static void main ( String [ ] args) {

/*Create a circle of radius 30 pixels at position(30,30).
Circle is to move at a rate of 5 pixels every 20 milliseconds to follow the perimeter of
the square (400 pixels).
Initially the circle is to move in a clockwise direction.
However at each move the circle must have a probability of 0.01 to change direction.
*/
CircleFigure.create();
CircleFigure.setRadius(30);
CircleFigure.moveTo(30,30);
int x = CircleFigure.getXCentre();
int y = CircleFigure.getYCentre();

while (x != 0) {while (x != 370) {

x = x + 5;
CircleFigure.moveRight(5);
Delay.milliseconds(20);
}


if (x == 370) {

while (y != 370) {
y = y + 5;
CircleFigure.moveDown(5);
Delay.milliseconds(20);
}
if (y == 370) {

while (x != 30) {
x = x - 5;
CircleFigure.moveLeft(5);
Delay.milliseconds(20);
}
}

if (x == 30) {

while (y != 30) {
y = y - 5;
CircleFigure.moveUp(5);
Delay.milliseconds(20);
}
}

}
}
}
}
How can I make sure that the circle changes direction with a probability of
0.01. I understand that a variable of type double, which stores the generated random number, needs to be created, but I am unable to pull that
section of code off!
Any help and advice on how to approach this problem would be greatly appreciated!
By the way, the class CircleFigure only has the following methods available: moveRight,moveLeft,moveUp,moveDown,moveTo,getXCentre,getYCentre.
fred rosenberger
lowercase baba
Bartender

Joined: Oct 02, 2003
Posts: 11412
    
  16

something like
double randomNumber = Math.random();
if (randomNumber < 0.01){
reverseDirection();
}

note: this is not tested in any way, it's just off the top of my head with no coffee this morning.


There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: A probability problem