Skip to content

Instantly share code, notes, and snippets.

@alcalyn
Last active August 29, 2015 14:09
Show Gist options
  • Save alcalyn/e80e75f1a3a004663283 to your computer and use it in GitHub Desktop.
Save alcalyn/e80e75f1a3a004663283 to your computer and use it in GitHub Desktop.
Can you create an algorithm that guesses the next random value ?
var RandomBot =
{
/**
* Returns random boolean
*
* @returns {Boolean}
*/
rand: function ()
{
return Math.random() < 0.5;
},
/**
* Returns true if boolean is same as bot just said
*
* @param {Boolean} boolean
*
* @returns {Boolean}
*/
guess: function (boolean)
{
return !(RandomBot.rand() ^ boolean);
},
/**
* Return percentage of good guesses made by guesser algorithm
*
* @param {Object} guesser with a 'guess' function which take the last random value as argument
* @param {integer} times default 1000
*
* @returns {float}
*/
algorithmGuess: function (guesser, times)
{
guesser.init && guesser.init();
times = times || 1000;
var good = 0;
var last = RandomBot.rand();
var percentModulo = Math.floor(times / 10);
for (iteration = 0; iteration < times; iteration++) {
var guesserValue = guesser.guess(last);
var botValue = RandomBot.rand();
if (!(guesserValue ^ botValue)) {
good++;
}
last = botValue;
if (0 === (iteration % percentModulo)) {
console.log((100 * iteration) / times + '% ...');
}
}
console.log('100% done!');
return good / times;
}
};
/*
* Guesser examples
*/
var RandomGuesser =
{
/**
* Guess algorithm from last bot random value
*
* @param {Boolean} lastValue
*
* @returns {Boolean}
*/
guess: function (lastValue)
{
return Math.random() < 0.5;
}
};
// Run a guesser:
var success = RandomBot.algorithmGuess(RandomGuesser);
// If success is near than 0.5, try another algorithm!
/**
* Try to say true or false depending on the n-last random value:
* if there is more true than false, the say false,
* if there is more false, then say true.
* In other words, try to equilibrate true and false.
*
* Sure, that do not work.
*/
var EquilibratorGuess =
{
lastest: [],
lastestMax: 40,
init: function ()
{
EquilibratorGuess.lastest = [];
},
guess: function (last)
{
EquilibratorGuess.lastest.push(last);
if (EquilibratorGuess.lastest.length < EquilibratorGuess.lastestMax) {
return false;
}
var nbTrue = 0;
for (i = 0; i < EquilibratorGuess.lastest.length; i++) {
if (EquilibratorGuess.lastest[i]) {
nbTrue++;
}
}
EquilibratorGuess.lastest.shift();
return (nbTrue > (EquilibratorGuess.lastestMax / 2));
}
};
var MaybeItIsTheNegativeBooleanOfTheLastRandomBooleanGuesser =
{
guess: function (lastValue)
{
return !lastValue;
}
};
var IAmAStupidLotoPlayerAndIPlayTheSameLastRandomValueGuesser =
{
guess: function (lastValue)
{
return lastValue;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment