Last active
August 29, 2015 14:15
-
-
Save d3ep4k/0f9f13cd0367bf1b79fd to your computer and use it in GitHub Desktop.
Biased coin toss converted to unbiased coin toss.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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