Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Solution to prisoner's dilema
- # http://www.cartalk.com/content/prison-switcharoo-0?question
- # https://news.ycombinator.com/item?id=7286279
- $TOTAL_NUM_PRISONERS = 23
- $switch_a = rand() > 0.5
- $switch_b = rand() > 0.5
- $prisoners_who_have_visited = [false] * $TOTAL_NUM_PRISONERS
- $cycles = 0
- def we_have_all_visited()
- if $prisoners_who_have_visited.any?{|pr| pr==false}
- puts "\nYou will all be fed to the aligators now... (after #{$cycles} visits)"
- else
- puts "\nCongratualtions, you may all go free (took #{$cycles} visits)"
- end
- exit
- end
- class Prisoner
- def initialize(name)
- @name = name
- @i_have_previously_touched_a = false
- end
- def name
- return @name
- end
- def i_have_previously_touched_a
- return @i_have_previously_touched_a
- end
- def inspect
- return "Prisoner<#{@name}, #{@i_have_previously_touched_a}>"
- end
- def to_s
- return inspect
- end
- def switch_time(a_state, b_state)
- if a_state == false and !@i_have_previously_touched_a then
- @i_have_previously_touched_a = true
- return 'A'
- else
- return 'B'
- end
- end
- end
- class Watchkeeper < Prisoner
- def initialize
- @name = "Watchkeeper"
- @i_have_previously_touched_a = false
- @num_prisoners_touched_a = 0
- end
- def switch_time(a_state, b_state)
- if a_state == true
- @num_prisoners_touched_a += 1
- @i_have_previously_touched_a = true
- puts "Number of people who have switched 'A' is #{@num_prisoners_touched_a}"
- if @num_prisoners_touched_a == ($TOTAL_NUM_PRISONERS-1)
- puts "I declare we have all visited this room!"
- we_have_all_visited()
- end
- return 'A'
- else
- return 'B'
- end
- end
- end
- # Throw prisoners in jail
- prisoners = Array.new
- for i in 1 .. $TOTAL_NUM_PRISONERS-1
- prisoners.push(Prisoner.new("Prisoner #{i}"))
- end
- prisoners.push(Watchkeeper.new)
- puts "Welcome to the prisoner's dilema"
- puts "================================\n\n"
- while true
- next_prisoner = rand(0 .. $TOTAL_NUM_PRISONERS-1)
- pr = prisoners[next_prisoner]
- puts "Current state of the switches: A=#{$switch_a}, B=#{$switch_b}"
- puts "#{pr.name}, you're up!"
- puts "#{pr.name}, have you previously touched A? #{pr.i_have_previously_touched_a}"
- choice = pr.switch_time($switch_a, $switch_b)
- puts "#{pr.name} chose #{choice}\n\n"
- if choice == 'A'
- $switch_a = !$switch_a
- else
- $switch_b = !$switch_b
- end
- $prisoners_who_have_visited[next_prisoner] = true
- $cycles += 1
- #gets
- end
Advertisement
Add Comment
Please, Sign In to add comment