The Deaf Rats of Hamelin

The Deaf Rats of Hamelin

Approach

find pattern

Count the rats who looking in the opposite direction of Pied Piper

solve the problem

  1. split based on 'P' as 'left', 'right'

  2. remove empty space of 'left', 'right'

  3. split left and right side every 2 characters through RegExp for distinguishing rats

  4. check left side who seeing left side because 'left side' means pied piper's 'left side' which means rats must-see 'pide piper' and the one who does not look right side that's the target

  5. check right side who seeing right side because 'right side' means pied piper's 'right side' which means rats must-see 'pide piper' and the one who does not look left side that's the target

  6. return process-4 plus process-5 result

Solution

// the-deaf-rats-of-hamelin
// The Deaf Rats of Hamelin
// https://www.codewars.com/kata/598106cb34e205e074000031

const countDeafRats = (town) => {
  const [left, right] = town.replace(/\s/g, '').split('P');
  return (left.match(/.{2}/gm) || []).filter((v) => v === 'O~').length
    + (right.match(/.{2}/gm) || []).filter((v) => v === '~O').length;
};


// test code
console.log(countDeafRats("~O~O~O~O P"), 0);
console.log(countDeafRats("P O~ O~ ~O O~"), 1);
console.log(countDeafRats("~O~O~O~OP~O~OO~"), 2);

Last updated

Was this helpful?