Skip to content

Instantly share code, notes, and snippets.

@chipbell4
Created January 16, 2016 05:11
Show Gist options
  • Save chipbell4/586cab4ccacdec7633e1 to your computer and use it in GitHub Desktop.
Save chipbell4/586cab4ccacdec7633e1 to your computer and use it in GitHub Desktop.
CLR Simulation (Interesting results...)
var _ = require('lodash');
var chiSquaredTest = require('chi-squared-test');
var seedrandom = require('seedrandom');
var rng = seedrandom('hello.');
function rollDie(sides) {
var index = Math.floor(rng() * sides.length);
return sides[index];
}
function doTurn(seats, roller) {
var leftNeighbor = (roller + seats.length - 1) % seats.length;
var rightNeighbor = (roller + 1) % seats.length;
// Roll only as many dice as the player has tokens
var diceToRoll = Math.min(3, seats[roller]);
_.range(diceToRoll).forEach(function() {
var die = ['.', '.', '.', 'C', 'L', 'R'];
var diceRollResult = rollDie(die);
// If they got a dot, they're safe
if(diceRollResult == '.') {
return;
}
// otherwise, they'll lose a token
seats[roller] -= 1;
// L and R move the money left to right. C just makes the money go away...
if(diceRollResult == 'L') {
seats[leftNeighbor] += 1;
} else if(diceRollResult == 'R') {
seats[rightNeighbor] += 1;
}
});
}
function getWinner(seats) {
// map the seats to a list of players with index and number of "tokens" left
var remainingPlayers = seats.map(function(seat, index) {
return {
tokens: seat,
index: index
};
}).filter(function(seat) {
return seat.tokens > 0;
});
if(remainingPlayers.length == 1) {
return remainingPlayers[0].index;
}
}
function doTest(N) {
// initialize the seats
var seats = _.range(N).map(function() { return 3; });
var currentPlayer = 0;
while(getWinner(seats) === undefined) {
doTurn(seats, currentPlayer);
currentPlayer = (currentPlayer + 1) % N;
}
return getWinner(seats);
}
var N = 5;
var bins = _.range(N).map(function() { return 0; });
var sampleCount = 100000;
_.range(sampleCount).forEach(function() {
var winner = doTest(N);
bins[winner] += 1;
});
console.log(bins);
// Chi-squared test it! We expect uniform distribution
var expected = _.range(N).map(function() {
return sampleCount / N;
});
var reduction = 1;
var probability = chiSquaredTest(bins, expected, reduction);
console.log('Probability of uniform?', probability);
{
"name": "JUNK",
"version": "1.0.0",
"description": "",
"main": "clr.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"chi-squared-test": "^1.1.0",
"lodash": "^4.0.0",
"seedrandom": "^2.4.2"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment