jumpstart 2 hw cats in hats
You have 100 cats. Your rules are simple:
whenever you visit a cat, you toggle it's hat status (if it already has a hat, you remove it... if it does not have a hat, you put one on). All of the cats start hat-less. You cycle through 100 rounds of visiting cats. In the 1st round, you visit every cat. In the second round, you visit every other cat. In the nth round, you visit every nth cat.. until the 100th round, in which you only visit the 100th cat.
At the end of 100 rounds, which cats have hats?
1. Using a counter hash to track (via incrementing the count) whether cats' hats are on or off (evens ~ hats off, odds ~ hats on):
def cats_in_hats
litter = Hash.new(0)
(1..100).each do |visit| # track visit number (100 in total)
count = visit
while count <= 100 # hatting corresponds to adding 1 to an even (unhatted) value (0 ~ even)
litter[count] += 1
count += visit # hatting frequency dependent on visit number
end
end
litter.select {|k, v| k if v % 2 != 0}.keys # if value is odd (hatted), get cat position (key)
end
2. Modifying the "hat" (true/false) values in an array:
def cats_in_hats
cats = Array.new(101) {false}
cats.each.with_index(1) do |_, out_idx|
count = out_idx
while count <= 100
if cats[count] == false
cats[count] = true
else
cats[count] = false
end
count += out_idx
end
end
cat_positions_with_hats = []
cats.each.with_index do |hat_status, idx|
cat_positions_with_hats << idx if hat_status == true
end
cat_positions_with_hats
end