Created
December 27, 2016 04:23
-
-
Save jcttrll/719a1875e8e38fbb5e2f3b3086c9e776 to your computer and use it in GitHub Desktop.
Standalone experimentation with rolling n dice with s sides.
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.Map; | |
import java.util.SortedMap; | |
import java.util.TreeMap; | |
public class Dice { | |
public static void main(String[] args) { | |
SortedMap<Long, Long> zeroSixSidedDice = sumOccurrencesOfDiceRoll(6, 0); | |
SortedMap<Long, Long> singleSixSidedDie = sumOccurrencesOfDiceRoll(6, 1); | |
SortedMap<Long, Long> twoSixSidedDice = sumOccurrencesOfDiceRoll(6, 2); | |
SortedMap<Long, Long> threeSixSidedDice = sumOccurrencesOfDiceRoll(6, 3); | |
assert zeroSixSidedDice.values().stream().mapToLong(Long::longValue).sum() == 1; | |
assert singleSixSidedDie.values().stream().mapToLong(Long::longValue).sum() == 6; | |
assert twoSixSidedDice.values().stream().mapToLong(Long::longValue).sum() == 6 * 6; | |
assert threeSixSidedDice.values().stream().mapToLong(Long::longValue).sum() == 6 * 6 * 6; | |
} | |
private static SortedMap<Long, Long> sumOccurrencesOfDiceRoll(long sides, long dice) { | |
if (dice < 0) throw new IllegalArgumentException("Must have 0 or more dice"); | |
if (sides < 1) throw new IllegalArgumentException("Dice must have at least one side"); | |
SortedMap<Long, Long> sums = new TreeMap<>(); | |
if (dice == 0) { | |
sums.put(0L, 1L); | |
return sums; | |
} | |
for (long i = 1; i <= sides; i++) { | |
sums.put(i, 1L); | |
} | |
for (long i = 2; i <= dice; i++) { | |
SortedMap<Long, Long> next = new TreeMap<>(); | |
for (Map.Entry<Long, Long> entry : sums.entrySet()) { | |
long sum = entry.getKey(); | |
long occurrences = entry.getValue(); | |
for (long possibleRoll = 1; possibleRoll <= sides; possibleRoll++) { | |
next.compute(sum + possibleRoll, (key, old) -> { | |
if (old == null) return occurrences; | |
return old + occurrences; | |
}); | |
} | |
} | |
sums = next; | |
} | |
return sums; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment