DEV Community

Discussion on: Daily Challenge #136 - The Deaf Rats of Hamelin

Collapse
 
hyftar profile image
Simon Landry

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