Untitled
unknown
java
a year ago
1.3 kB
10
Indexable
package frog;
public class Frog {
public static void main(String[] args) {
FrogSimulation sim = new FrogSimulation(50,10);
double proportion = sim.runSimulation(10);
System.out.println(proportion);
}
}
class FrogSimulation {
private int goalDistance;
private int maxHops;
public FrogSimulation(int dist,int numHops) {
goalDistance = dist;
maxHops = numHops;
}
private int hopDistance() {
return ((int)(Math.random()*30-10));
}
public boolean simulate() {
// a)
int position = 0;
for (int i = 0; i < maxHops; i++) {
position += hopDistance();
if (position >= goalDistance) {
return true; // Frog reached goal
}
if (position < 0) {
return false; // Frog reached negative position
}
}
return false;
}
public double runSimulation(int num) {
int successfullSimulations = 0;
for (int i = 0; i < num; i++) {
if (simulate()) {
successfullSimulations++;
}
}
// b)
return (double) successfullSimulations / num;
}
}
Editor is loading...
Leave a Comment