Created
December 9, 2012 12:52
-
-
Save muuki88/4244719 to your computer and use it in GitHub Desktop.
CoinFlip
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
package de.mukis; | |
import java.text.DecimalFormat; | |
import java.text.NumberFormat; | |
/** | |
* Generates all possibilities for a coinflip. | |
* | |
* @author muki | |
* | |
*/ | |
public class CoinFlip { | |
private final NumberFormat formatter = DecimalFormat.getIntegerInstance(); | |
/** | |
* Prints all possible outcomes of a coinflip for n trials | |
* @param n | |
*/ | |
public void printPermutations(int n) { | |
formatter.setMinimumIntegerDigits(toBinaryString(n).length()); | |
int possibilities = (int) Math.pow(2, n); | |
for (int i = 0; i < possibilities; i++) { | |
System.out.println(formatPermutation(i)); | |
} | |
} | |
/** | |
* | |
* @param i | |
* @return a formatted string for one permutation step | |
*/ | |
private String formatPermutation(int i) { | |
return i + "\t " + formatter.format(toBinary(i)); | |
} | |
/** | |
* | |
* @param decimal | |
* @return an binary integer (contains only 0 and 1) | |
*/ | |
private long toBinary(int decimal) { | |
return Integer.valueOf(toBinaryString(decimal)); | |
} | |
/** | |
* | |
* @param decimal | |
* @return a binary representation of the decimal value as string | |
*/ | |
private String toBinaryString(int decimal) { | |
return Integer.toBinaryString(decimal); | |
} | |
/** | |
* @param args | |
*/ | |
public static void main(String[] args) { | |
CoinFlip coinFlip = new CoinFlip(); | |
coinFlip.printPermutations(5); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment