Created
October 12, 2015 20:07
-
-
Save allolex/5609be84fdf51393e673 to your computer and use it in GitHub Desktop.
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
| # 1: Remove all hats. All are 0. | |
| # 2: Every 2nd cat is switched to 1. [0, 1, 0, 1] | |
| # 3: Every 3rd cat is switched (toggled). [0, 1, 1, 1] | |
| # 4: [ 0, 1, 1, 0 ] | |
| max = 100 | |
| cats = Array.new(max, 1) | |
| p cats | |
| def toggle cat | |
| if cat == 0 | |
| 1 | |
| else | |
| 0 | |
| end | |
| end | |
| (1..max).each do |pass| | |
| cats.each_index do |index| | |
| remainder = (index + 1) % pass | |
| # puts "#{index + 1} has a remainder of #{remainder} when divided by #{pass}" | |
| if remainder == 0 | |
| # print "Cat: " | |
| # p cats[index] | |
| cats[index] = toggle cats[index] | |
| end | |
| end | |
| end | |
| cats.each_with_index do |cat, index| | |
| puts "Cat #{index + 1} has no hat." if cat == 0 | |
| end | |
| __END__ | |
| You have 100 cats in a row that are all wearing hats. You make 100 passes by the cats. The first time through, you visit every cat and remove its hat if it’s on, and put it on if it’s off. The second time you only visit every 2nd cat (cat #2, #4, #6, …). The third time, every 3rd cat (cat #3, #6, #9, …), etc, until you only visit the 100th cat. | |
| After the last pass, which cats aren’t wearing hats? | |
| Show the code you wrote to get this answer. | |
| __END__ | |
| cat in the hat | |
| pyramid |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment