RosettaCode Monty Hall

Revision as of 16:15, 9 August 2012 by Peter gummer (Talk | contribs)


Reference

Statement of the Monty Hall problem on RosettaCode: here.
Deadline for adding to RosettaCode page: 31 Aug 2012; submitter:

Eiffel code

Here's an initial implementation, just to get things started. I just typed this straight into the wiki, so it might not even compile.

Please feel free to edit this in place, I won't be offended.

class MONTY_HALL
 
feature
 
	play
		local
			games: INTEGER
			random: RANDOM
			doors: ARRAYED_LIST [BOOLEAN]
			chosen, shown: INTEGER
			stayWins: INTEGER
		do
			games := 1000000
			create random.make
 
			across 1 |..| games as plays loop
				create doors.make_filled (3)	-- False is a goat, True is a car
				random.forth
				doors [random.item \\ 3 + 1] := True	-- Put a car behind a random door
 
				random.forth
				chosen := random.item \\ 3 + 1	-- Pick a door, any door
 
				from shown := chosen until shown /= chosen and not doors [shown] loop
					random.forth
					shown := random.item \\ 3 + 1
				end
 
				if doors [chosen] then	-- If you would have won by staying, count it
					stay_wins := stay_wins + 1
				end
			end
 
			out ("Staying wins " + stay_wins + " times.%N")
			out ("Switching wins " + games - stay_wins + " times.%N")
		end
 
end

Comments

Note that the implementations in many other languages maintain a separate variable to count the number of switch wins. They calculate whether switching wins at each step via some funky logic that relies on zero-based array indexing, which would be inconvenient in Eiffel. But we don't need to do that at all anyway, because calculating it at each step is completely redundant: we can just do a final subtraction at the end, right?