Skip to content

Instantly share code, notes, and snippets.

@jozsefs
Last active May 24, 2017 12:47
Show Gist options
  • Select an option

  • Save jozsefs/1b881010dd5a2aa0ec822b1530a6d95a to your computer and use it in GitHub Desktop.

Select an option

Save jozsefs/1b881010dd5a2aa0ec822b1530a6d95a to your computer and use it in GitHub Desktop.
cat-mouse.js
function catMouse(map, maxMoves){
const pos = map.split('\n').reduce((acc, row, idx) => {
const catIndex = row.indexOf('C');
const mouseIndex = row.indexOf('m');
if (catIndex > -1) {
acc.cat = [idx, catIndex];
}
if (mouseIndex > -1) {
acc.mouse = [idx, mouseIndex];
}
return acc;
}, {cat: [], mouse: []});
if (!pos.cat.length || !pos.mouse.length) {
return 'boring without two animals';
}
const distance = Math.abs(pos.cat[0] - pos.mouse[0]) + Math.abs(pos.cat[1] - pos.mouse[1]);
return distance <= maxMoves ? 'Caught!' : 'Escaped!';
}
// tests
let map=
`..C......
.........
....m....`
console.log(assertSimilar(catMouse(map,5),'Caught!'))
map =
`.C.......
.........
......m..`
console.log(assertSimilar(catMouse(map,5),'Escaped!'))
map =
`..C......
.........
.........`
console.log(assertSimilar(catMouse(map,5),'boring without two animals'))
function assertSimilar(a,b) {
return a === b ? 'Passed' : 'Failed';
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment