Skip to content

Instantly share code, notes, and snippets.

@d3ep4k
Last active August 29, 2015 14:15
Show Gist options
  • Save d3ep4k/0f9f13cd0367bf1b79fd to your computer and use it in GitHub Desktop.
Save d3ep4k/0f9f13cd0367bf1b79fd to your computer and use it in GitHub Desktop.
Biased coin toss converted to unbiased coin toss.
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;
/**
*
* @author deepak
*/
public class BiasedCoin {
public final static int HEAD = 1;
public final static int TAIL = 0;
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
List<Integer> l = new ArrayList();
for (int i = 0; i < 1000000; i++) {
l.add(getTossResult());
}
System.out.println("Heads baised: " + Collections.frequency(l, HEAD));
l.clear();
for (int i = 0; i < 1000000; i++) {
l.add(getUnbaisedTossResult());
}
System.out.println("Heads unbaised: " + Collections.frequency(l, HEAD));
}
//Biased toss
public static int getTossResult() {
Random r = new Random();
//60-40 chance
if (r.nextInt(100) > 59) {
return HEAD;
} else {
return TAIL;
}
}
//Unbiased toss
public static int getUnbaisedTossResult() {
int x, y;
do {
x = getTossResult();
y = getTossResult();
} while (x == y);
//Break loop when not same 50-50 chance
return x;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment