Skip to content

Instantly share code, notes, and snippets.

@Alexei-B Alexei-B/dice.js
Last active Jan 20, 2017

Embed
What would you like to do?
dice thing
var Dice = {
B: [0, 0, 0, 0, 1, 1],
A: [0, 0, 0, 0, 1, 1, 1, 2],
P: [0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 2, 2],
S: [0, 0, 0, 0, -1, -1],
D: [0, 0, 0, 0, 0, -1, -1, -2],
C: [0, 0, 0, 0, 0, -1, -1, -1, -1, -1, -2, -2]
};
function applyToEach (set, func) {
for (var item in set) {
if (set.hasOwnProperty(item)) {
func(item);
}
}
}
function mapProbability (die) {
var prob = {};
applyToEach(die, function (i) {
if (prob[die[i]] == null) {
prob[die[i]] = 0;
}
prob[die[i]]++;
});
return prob;
}
function addProbability (setA, setB) {
var result = {};
applyToEach(setA, function (ia) {
applyToEach(setB, function (ib) {
if (result[~~ia + ~~ib] == null) {
result[~~ia + ~~ib] = 0;
}
result[~~ia + ~~ib] += setA[ia] * setB[ib];
});
});
return result;
}
function buildProbability (diceString) {
var probability = mapProbability(Dice[diceString[0]]);
for (var i = 1; i < diceString.length; ++i) {
probability = addProbability(probability, mapProbability(Dice[diceString[i]]));
}
return probability;
}
function calcProbability (set, test) {
var frequency = 0;
var total = 0;
applyToEach(set, function (i) {
total += set[i];
if (test(i)) {
frequency += set[i];
}
});
return (frequency / total) * 100;
}
function success (input) {
return calcProbability(buildProbability(input), function (i) {
return (~~i) > 0;
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.