Last active
December 3, 2021 04:59
-
-
Save ggmichaelgo/40e0d8532845b275c3f93e64738b1e23 to your computer and use it in GitHub Desktop.
rabbit.rb
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$holes = Array.new(100, false) | |
answer = rand($holes.count) | |
$holes[answer] = true | |
puts "Bunny is at index: #{answer}" | |
def move_bunny | |
bunny_index = $holes.index(true) | |
$holes[bunny_index] = false | |
new_bunny_index = bunny_index | |
if bunny_index == 0 | |
# bunny can only go to right | |
new_bunny_index = bunny_index + 1 | |
elsif bunny_index == $holes.count - 1 | |
# bunny can only go to left | |
new_bunny_index = bunny_index - 1 | |
elsif rand(2) == 0 | |
# go to left | |
new_bunny_index = bunny_index - 1 | |
else | |
# go to right | |
new_bunny_index = bunny_index + 1 | |
end | |
$holes[new_bunny_index] = true | |
puts "Bunny moved to index: #{bunny_index} => #{new_bunny_index}" | |
end | |
i = 0 | |
2.times do | |
(0...($holes.count - 1)).step(1) do |_i| | |
# by checking twice, the bunny will be always in even or odd hole | |
# let's assume bunny is in even holes | |
i = _i | |
puts "Check index: #{i}" | |
break if $holes[i] | |
move_bunny | |
puts "Check index: #{i}" | |
break if $holes[i] | |
move_bunny | |
end | |
if $holes.index(true) == i | |
puts "Bunny is at index: #{i}" | |
exit | |
elsif | |
# we didn't find the bunny, it must has been in odd holes | |
# make a dummy check, this will force rabbit to be in even holes | |
puts "DUMMY Check index: #{i}" | |
move_bunny | |
end | |
end | |
puts "Failed to find the bunny" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment