Skip to content

Instantly share code, notes, and snippets.

@joriki
Created November 27, 2012 00:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joriki/4151520 to your computer and use it in GitHub Desktop.
Save joriki/4151520 to your computer and use it in GitHub Desktop.
Simulate a certain random walk; see http://math.stackexchange.com/questions/245122
import java.util.Random;
public class Question245122 {
final static Random random = new Random ();
public static void main (String [] args) {
int N = Integer.parseInt (args [0]);
int ntrials = Integer.parseInt (args [1]);
int count = 0;
for (int n = 0;n < ntrials;n++) {
int pos = 0;
do {
int d = (random.nextBoolean () ? 1 : -1) * (random.nextBoolean () ? 1 : 2);
pos += d;
if (pos == N)
count++;
} while (pos < N);
}
System.out.println (count / (double) ntrials);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment