Using Ruby and Regex
def count_deaf_rats(input) deaf_count = 0 while input =~ /~O|O~/ if input =~ /~O\s*P|P\s*O~/ input = input.gsub(/~O\s*P|P\s*O~/, 'P') end if input =~ /O~\s*P|P\s*~O/ input = input.gsub(/O~\s*P|P\s*~O/, 'P') deaf_count += 1 end end deaf_count end examples = [ '~O~O~O~O P', 'P O~ O~ ~O O~', '~O~O~O~OP~O~OO~' ] examples.each_with_index do |ex, idx| puts "ex#{idx + 1} #{ex} has #{count_deaf_rats(ex)} deaf rats" end
Output:
ex1 ~O~O~O~O P has 0 deaf rats ex2 P O~ O~ ~O O~ has 1 deaf rats ex3 ~O~O~O~OP~O~OO~ has 2 deaf rats
Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink.
Hide child comments as well
Confirm
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
Using Ruby and Regex
Output: