Skip to content

Instantly share code, notes, and snippets.

@ggmichaelgo
Last active December 3, 2021 04:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ggmichaelgo/40e0d8532845b275c3f93e64738b1e23 to your computer and use it in GitHub Desktop.
Save ggmichaelgo/40e0d8532845b275c3f93e64738b1e23 to your computer and use it in GitHub Desktop.
rabbit.rb
$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