KamaKAzii
6/20/2011 - 9:54 AM

## gistfile1.js

``````var G = {

// Input
data: [
{w: 0, b: 1},
{w: 2, b: 3},
{w: 3, b: 0}
],

pickTwo: function(array) {
var choiceFirstIndex = Math.floor(Math.random() * (array.length));

if (choiceFirstIndex == (array.length - 1)) {
choiceFirst = array[choiceFirstIndex];
choiceSecond = array[0];
array.splice(choiceFirstIndex, 1);
array.splice(0, 1);
}
else {
choiceSecondIndex = choiceFirstIndex + 1;
choiceFirst = array[choiceFirstIndex];
choiceSecond = array[choiceSecondIndex];
array.splice(choiceFirstIndex, 2);
}

return [choiceFirst, choiceSecond, array];
},

analyse: function(ballsTotal) {

// Check if there's only one ball...
if (ballsTotal.length > 1) {
result = G.pickTwo(ballsTotal);
ballsTotal = result[2];
ballOne = result[0];
ballTwo = result[1];

// Check if either of the chosen balls are "b"...
// If it is, then we can assume last ball will be "b"
if ((ballOne == "b") || (ballTwo == "b")) {
return "b";
}
else {

// By this point we can assume we have chosen "w" "w"
// ... if there is still more than one ball in the hat, then put a "w" back and analyse again...
// ... otherwise assume that the final ball is "w"
if (ballsTotal.length > 0) {
ballsTotal.push("w");
G.analyse(ballsTotal);
}
else {
return "w";
}
}
}
else {
return ballsTotal[0];
}
}

};

\$(function() {

for (i=0; i<G.data.length; i++) {

ballsTotal = [];
// push to balls using G.data
for (j=0; j<G.data[i]["w"]; j++) { ballsTotal.push("w"); };
for (j=0; j<G.data[i]["b"]; j++) { ballsTotal.push("b"); };

finalBall = G.analyseTwo(ballsTotal);

// Check the final ball...
console.log(finalBall);

}

// End codez

});
``````