Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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