Skip to content

Instantly share code, notes, and snippets.

@joelhinz
Created November 5, 2016 11:07
Show Gist options
  • Save joelhinz/6c805828f11f60deaaeec0ac40eb333c to your computer and use it in GitHub Desktop.
Save joelhinz/6c805828f11f60deaaeec0ac40eb333c to your computer and use it in GitHub Desktop.
The twelve prisoners, OOP
var _ = require('lodash');
class Card {
constructor(value) {
this.value = value;
}
}
class Deck {
fill() {
this.cards = _.range(52).map(
i => new Card(Math.floor(i/4))
)
return this;
}
shuffle() {
this.cards = _.shuffle(this.cards);
return this;
}
pile() {
this.piles = _.chunk(this.cards, 4)
return this;
}
run() {
var hold = this.piles[0].shift();
return this.iterate(hold);
}
iterate(hold) {
if (this.gameWon()) return true;
if (this.gameOver(hold)) return false;
hold = this.piles[hold.value].shift();
return this.iterate(hold);
}
gameOver(hold) {
return this.piles[0].length == 0
&& hold.value === 0;
}
gameWon() {
return _.range(1, 13).every(
i => this.piles[i].length === 0
);
}
}
class Solitaire {
constructor() {
this.wins = 0;
this.losses = 0;
}
run(n) {
_.range(n).forEach(this.solitaire, this);
this.print(n);
}
solitaire() {
var result = new Deck()
.fill()
.shuffle()
.pile()
.run();
result ? this.wins++ : this.losses++;
}
print(n) {
var pct = this.wins / n * 100;
console.log(`W: ${this.wins}`);
console.log(`L: ${this.losses}`);
console.log(`%: ${pct.toFixed(2)}%`);
}
}
new Solitaire().run(1000000);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment