patternjavaModerate
Random walk with equal probability
Viewed 0 times
randomequalwithwalkprobability
Problem
This method randomly increments or decrements (with equal probability) until either -3 or 3 are reached. I'd like to maintain printing the value of
pos on each iteration, and printing the largest positive number max reached at the end of the loop. How can I improve this method using the Random() function? I know this sounds pretty ambiguous, but I'd like to know if I can make rand.nextInt(2) == 0 an easier condition to understand? Any suggestions/improvements are welcome!public static void randomWalk() {
Random rand = new Random();
int pos = 0;
int max = 0;
System.out.println("position = " + pos);
while (pos > -3 && pos 0) {
max = pos;
}
} else {
pos--;
}
System.out.println("position = " + (int) pos);
}
System.out.println("max position = " + max);
}Solution
There's a minor bug there:
should test
Use
to make it shorter.
I'd like to know if I can make rand.nextInt(2) == 0 an easier condition to understand?
Use
For other probabilities, you can use
Another possibility is simply
or
or
without any conditionals. You may consider it tricky, but it isn't. Obviously, my last solution shouldn't be used for such a simple case.
Concerning the computation of
if (pos > 0) {
max = pos;
}should test
pos > max instead.Use
max = Math.max(max, pos)to make it shorter.
I'd like to know if I can make rand.nextInt(2) == 0 an easier condition to understand?
Use
rand.nextBoolean(). For a probability of exactly 50%, it's perfect.For other probabilities, you can use
rand.nextDouble() < probabilityAnother possibility is simply
pos += 2 * rand.nextInt(2) - 1;
max = Math.max(max, pos);or
pos += rand.nextBoolean() ? 1 : -1;
max = Math.max(max, pos);or
private static final int[] DELTAS = {+1, -1};
pos += DELTAS[rand.nextInt(DELTAS.length)];
max = Math.max(max, pos);without any conditionals. You may consider it tricky, but it isn't. Obviously, my last solution shouldn't be used for such a simple case.
Concerning the computation of
max it may be slightly less efficient since it gets executed even if the value decreases. But this doesn't matter unless you need to optimize heavily (your print is many orders of magnitude slower than this).Code Snippets
if (pos > 0) {
max = pos;
}max = Math.max(max, pos)rand.nextDouble() < probabilitypos += 2 * rand.nextInt(2) - 1;
max = Math.max(max, pos);pos += rand.nextBoolean() ? 1 : -1;
max = Math.max(max, pos);Context
StackExchange Code Review Q#94916, answer score: 12
Revisions (0)
No revisions yet.