Last active
May 24, 2017 12:47
-
-
Save jozsefs/1b881010dd5a2aa0ec822b1530a6d95a to your computer and use it in GitHub Desktop.
cat-mouse.js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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