Skip to content

Instantly share code, notes, and snippets.

@hauntedhost
Created October 28, 2013 19:34
Show Gist options
  • Save hauntedhost/7203132 to your computer and use it in GitHub Desktop.
Save hauntedhost/7203132 to your computer and use it in GitHub Desktop.
# Write a function which takes a number N of cats and outputs which cats have
# hats. Initially, none of the cats have hats. You walk down the line of cats,
# stopping at every cat, taking off its hat if it has one or putting on a hat
# if it doesn't have one. On the second round, you only stop at every second
# cat [eg #2, #4, #6], on the third round you stop at every third cat [eg #3,
# #6, #9...]. You continue this until you've done as many round as there are
# cats. Your function should output an array containing booleans indicating
# whether each cat has a hat or not by the end.
def cats_in_hats(num_cats)
cats = []
1.upto(num_cats) do |m|
1.upto(num_cats) do |n|
idx = (m * n) - 1
next if idx > num_cats
cats[idx] = cats[idx] ? false : true
end
end
cats
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment