Skip to content

Instantly share code, notes, and snippets.

@patforna
Last active August 29, 2015 14:09
Show Gist options
  • Save patforna/2cf0ffb46a1c0b93084d to your computer and use it in GitHub Desktop.
Save patforna/2cf0ffb46a1c0b93084d to your computer and use it in GitHub Desktop.
(ns cracking.p_02_05
(:require [clojure.test :refer :all]))
(defn different? [[a b]] (not (= a b)))
(defn first-elem [[a b]] a)
; This is a solution using "Floyd's cycle-finding algorithm"
(defn detect-loop [coll]
(let [tortoise (drop 1 coll)
hare (drop 2 coll)
steps (map vector tortoise (take-nth 2 hare))
met (drop-while different? steps)
reset (map vector coll (map first-elem met))]
(first-elem (first (drop-while different? reset)))))
(def circular (concat [\a \b] (cycle [\c \d \e])))
(deftest a-test
(testing
(is (= (detect-loop circular) \c))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment