Skip to content

Instantly share code, notes, and snippets.

@muuki88
Created December 9, 2012 12:52
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 muuki88/4244719 to your computer and use it in GitHub Desktop.
Save muuki88/4244719 to your computer and use it in GitHub Desktop.
CoinFlip
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