• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

A probability problem

 
Amil Mehmedagic
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 12101
30
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic