Swifty
Swifty

Reputation: 23

Monty Hall simulation only 44%

I just created a simulation for the Monty Hall problem, but my result (even with 10,000,000 tests) is strange. For strategy 1 (keep) the hits are in 1/3, and strategy 2 (switch) in 44,44%. Is there a mistake in the code?

Thanks everybody!

var hits1 = 0
var hits2 = 0
let testsNumber = 1000

for i in 0..<testsNumber {

    var doors: [Int] = []

    for i in 0..<3 {
        doors.append(0) // Append closed door
    }

    doors[Int(arc4random_uniform(UInt32(doors.count)))] = 1 // Here's the car...        
    var selection = Int(arc4random_uniform(UInt32(doors.count))) // Select door


    if doors[selection] == 1 {
        hits1 += 1
    }

    // Open first closed door
    for i in 0..<doors.count {
        if doors[i] != 1 {
            doors[i] = -1 // Open door
            break
        }
    }

    // Switch to next closed door
    repeat {
        selection = (selection + 1) % doors.count 
    } while(doors[selection] == -1)

    if doors[selection] == 1 {
        hits2 += 1
    }

}

print("Hits: \(hits1), quote: \((Double) (hits1) / (Double) (testsNumber))")
print("Hits: \(hits2), quote: \((Double) (hits2) / (Double) (testsNumber))")

Upvotes: 1

Views: 164

Answers (1)

Rob
Rob

Reputation: 437977

The Monty Hall problem says "pick a door; before I open it, I'll show what's behind one of the other doors (one that doesn't have a car) and let you stay with your initial selection or switch to the other closed door".

But consider:

for i in 0 ..< doors.count {
    if doors[i] != 1 {
        doors[i] = -1 // Open door
        break
    }
}

That effectively says "show the contestant what's behind the first door that doesn't have a car".

But, you're not considering the possibility that this door might be the one that the contestant already picked. That's changing the parameters of the game.

You meant to say "open a door that does not have a car and is not the door the contestant picked."

for i in 0 ..< doors.count {
    if doors[i] != 1 && i != selection {
        doors[i] = -1 // Open door
        break
    }
}

When you do that, your odds by always changing your selection (having been shown one of the other two doors that didn't have a car) goes up to 2/3rds.

Upvotes: 2

Related Questions