Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
First solution in Clear category for [old] Pearls in the Box by mortonfox
"use strict";
function treeProb(black, white, step) {
return step == 1 ? white / (black + white) :
(black > 0 ? black / (black + white) * treeProb(black - 1, white + 1, step - 1) : 0) +
(white > 0 ? white / (black + white) * treeProb(black + 1, white - 1, step - 1) : 0);
}
function boxProbability(marbles, step) {
var counts = { 'b' : 0, 'w' : 0 };
for (var marble of marbles) counts[marble]++;
return Math.round(treeProb(counts['b'], counts['w'], step) * 100) / 100;
}
var assert = require('assert');
if (!global.is_checking) {
assert.equal(boxProbability('bbw', 3), 0.48, "First");
assert.equal(boxProbability('wwb', 3), 0.52, "Second");
assert.equal(boxProbability('www', 3), 0.56, "Third");
assert.equal(boxProbability('bbbb', 1), 0, "Fifth");
assert.equal(boxProbability('wwbb', 4), 0.5, "Sixth");
assert.equal(boxProbability('bwbwbwb', 5), 0.48, "Seventh");
console.log("Coding complete? Click 'Check' to review your tests and earn cool rewards!");
}
Oct. 8, 2016