Skip to content

Instantly share code, notes, and snippets.

@Alexei-B
Last active January 20, 2017 21:18
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 Alexei-B/f50aea93a5ae28b8520e4ecd3a586439 to your computer and use it in GitHub Desktop.
Save Alexei-B/f50aea93a5ae28b8520e4ecd3a586439 to your computer and use it in GitHub Desktop.
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