Skip to content

Instantly share code, notes, and snippets.

@icholy
Created September 21, 2015 20:12
Show Gist options
  • Save icholy/38e307758ca9f4cb4d07 to your computer and use it in GitHub Desktop.
Save icholy/38e307758ca9f4cb4d07 to your computer and use it in GitHub Desktop.
function shuffle<T>(o: T[]): T[] {
for(var j, x, i = o.length; i; j = Math.floor(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
return o;
}
enum Door {
Zonk,
Prize
}
class Game {
private doors: Door[];
private selectedDoor: number;
private openedDoor: number;
constructor() {
this.doors = shuffle([
Door.Zonk,
Door.Zonk,
Door.Prize
]);
}
choose(door: number): void {
this.selectedDoor = door;
for (let i = 0; i < 3; i++) {
if (i !== door && this.doors[i] == Door.Zonk) {
this.openedDoor = i;
break;
}
}
}
switch(): void {
for (let i = 0; i < 3; i++) {
if (i !== this.selectedDoor && i !== this.openedDoor) {
this.selectedDoor = i;
break;
}
}
}
won(): boolean {
return this.doors[this.selectedDoor] === Door.Prize;
}
}
let wins = 0;
let losses = 0;
for (let i = 0; i < 10000; i++) {
let game = new Game();
let randDoor = Math.floor(Math.random() * 3);
game.choose(randDoor);
game.switch();
if (game.won()) {
wins++;
} else {
losses++;
}
}
console.log("wins:", wins, "losses:", losses);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment