From 0ddcf2d424434e65bef7f2e93e59bf0a9e5079fd Mon Sep 17 00:00:00 2001 From: Grzegorz Kucmierz Date: Sun, 1 Dec 2019 13:13:51 +0100 Subject: [PATCH] The Deaf Rats of Hamelin --- the-deaf-rats-of-hamelin/index.js | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 the-deaf-rats-of-hamelin/index.js diff --git a/the-deaf-rats-of-hamelin/index.js b/the-deaf-rats-of-hamelin/index.js new file mode 100644 index 0000000..da11bfa --- /dev/null +++ b/the-deaf-rats-of-hamelin/index.js @@ -0,0 +1,27 @@ +// https://www.codewars.com/kata/the-deaf-rats-of-hamelin/javascript + +const countDeafRats = function(town) { + const [l, r] = town.split('P'); + const cnt = s => { + const c = [0, 0]; + const p = ['O~', '~O']; + while (1) { + let idx = p.map(p => s.indexOf(p)); + let min = Math.min(...idx); + let max = Math.max(...idx); + let sidx; + if (0 <= min) { + sidx = min; + } else if (0 <= max) { + sidx = max; + } else { + break; + } + const sp = s.slice(sidx, sidx+2); + s = s.replace(sp, ''); + ++c[p.indexOf(sp)]; + } + return c; + }; + return cnt(l)[0] + cnt(r)[1]; +};