DEV Community

loading...

Discussion on: Daily Challenge #166 - Cat and Mouse

Collapse
amcmillan01 profile image
Andrei McMillan • Edited

javascript

function cat_mouse(str, max_jump) {
  var has_animals = /(c|m|d)/i.test(str);
  if (!has_animals) {
    console.log('boring without all three');
  } else {
    var str_lower = str.toLowerCase();
    var cat_position = str_lower.indexOf('c');
    var dog_position = str_lower.indexOf('d');
    var mouse_position = str_lower.indexOf('m');
    var min = Math.min(cat_position, mouse_position);
    var max = Math.max(cat_position, mouse_position);

    // is the dog between the cat and mouse
    if (min < dog_position && dog_position < max) {
      console.log('Protected!');
    } else {
      var distance = Math.abs(cat_position - mouse_position);
      if (distance > max_jump) {
        console.log('Escaped!');
      } else {
        console.log('Caught!');
      }
    }

  }
}


// ----- test 

cat_mouse('..j.....h.', 5);
cat_mouse('..c.....m.', 5);
cat_mouse('..c....m.', 5);
cat_mouse('d..m.......c.', 10);
cat_mouse('d..m.......c.', 5);
cat_mouse('..m....d...c.', 5);
cat_mouse('...m.........C...D', 10);

python

import re
import math


def cat_mouse(str_input, max_jump):
    str_lower = str_input.lower()
    has_animal = re.search("c|m|d", str_lower)

    if has_animal is None:
        print('boring without all three')
    else:
        cat_position = str_lower.find("c")
        dog_position = str_lower.find("d")
        mouse_position = str_lower.find("m")
        min_pos = min(cat_position, mouse_position)
        max_pos = max(cat_position, mouse_position)

        # is the dog between the cat and mouse
        if min_pos < dog_position < max_pos:
            print('Protected!')
        else:
            distance = math.fabs(cat_position - mouse_position)
            if distance > max_jump:
                print('Escaped!')
            else:
                print('Caught!')


# // -- test
cat_mouse('..j.....h.', 5)
cat_mouse('..c.....m.', 5)
cat_mouse('..c....m.', 5)
cat_mouse('d..m.......c.', 10)
cat_mouse('d..m.......c.', 5)
cat_mouse('..m....d...c.', 5)
cat_mouse('...m.........C...D', 10)

Forem Open with the Forem app