From 06f01d2ef9635bb26d853e9b29ecbdf3f3786956 Mon Sep 17 00:00:00 2001 From: Grzegorz Kucmierz Date: Sat, 23 Nov 2019 23:43:02 +0100 Subject: [PATCH] Cycle Detection: Floyd's The Tortoise and the The Hare --- .../index.js | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 cycle-detection-floyds-the-tortoise-and-the-the-hare/index.js diff --git a/cycle-detection-floyds-the-tortoise-and-the-the-hare/index.js b/cycle-detection-floyds-the-tortoise-and-the-the-hare/index.js new file mode 100644 index 0000000..a66d72b --- /dev/null +++ b/cycle-detection-floyds-the-tortoise-and-the-the-hare/index.js @@ -0,0 +1,15 @@ +// https://www.codewars.com/kata/cycle-detection-floyds-the-tortoise-and-the-the-hare/javascript + +const floyd = function(f, x0) { + let x = x0; + let i = 0; + const map = new WeakMap(); + + while (1) { + map[x] = i++; + x = f(x); + if (x in map) break; + } + + return [map[x], i - map[x]]; +}