Skip to content

Instantly share code, notes, and snippets.

@haraldkubota
Last active May 11, 2024 02:24
Show Gist options
  • Select an option

  • Save haraldkubota/460947df3d07ae44d3abfcc0eb887f2b to your computer and use it in GitHub Desktop.

Select an option

Save haraldkubota/460947df3d07ae44d3abfcc0eb887f2b to your computer and use it in GitHub Desktop.
import 'dart:math';
bool oneRun({bool stickToInitialChoice=true}) {
var doors = [false, false, false];
var winDoor = Random().nextInt(3);
doors[winDoor] = true;
// Player selected this door at the start of the game
var initialChoice = Random().nextInt(3);
// Game master will open a loser door, but not the one from the player
var openDoor = initialChoice;
while (openDoor == initialChoice) {
openDoor = Random().nextInt(3);
// Check if the door to open is a winner. If yes, pick another door.
if (doors[openDoor]) {
openDoor = initialChoice;
}
}
if (stickToInitialChoice) {
return doors[initialChoice];
} else {
if (initialChoice==0 && openDoor==1 || initialChoice==1 && openDoor==0) {
return doors[2];
}
if (initialChoice==0 && openDoor==2 || initialChoice==2 && openDoor==0) {
return doors[1];
}
// if (initialChoice==1 && openDoor==2 || initialChoice==2 && openDoor==1)
return doors[0];
}
}
class Result {
var win=0;
var lose=0;
}
Result runMany(int loops, {bool stickToInitialChoice=true}) {
var res=Result();
for (var i=0; i<loops; ++i) {
if (oneRun(stickToInitialChoice: stickToInitialChoice)) {
++res.win;
} else {
++res.lose;
}
}
return res;
}
void main() {
var result;
result=runMany(10000, stickToInitialChoice: true);
print("No Switch: win ${result.win}, lose ${result.lose}");
result=runMany(10000, stickToInitialChoice: false);
print("Always Switch: win ${result.win}, lose ${result.lose}");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment