Skip to content

Instantly share code, notes, and snippets.

@rexim
Created August 7, 2014 18:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rexim/5f623b0c183aa0503079 to your computer and use it in GitHub Desktop.
Save rexim/5f623b0c183aa0503079 to your computer and use it in GitHub Desktop.
Tortoise-and-hare algorithm
import Data.Array
type LinkedList = Array Int Int
-- Tests ------------------------------
makeTest :: [Int] -> LinkedList
makeTest xs = array (1, n) $ zip [1 .. n] xs
where n = length xs
test1 :: LinkedList
test1 = makeTest ([2 .. 10] ++ [0])
test2 :: LinkedList
test2 = makeTest ([2, 3, 1])
test3 :: LinkedList
test3 = makeTest [2, 1]
-- Implementation ------------------------------
next :: LinkedList -> Int -> Int
next xs 0 = 0
next xs i = xs ! i
nextTH :: LinkedList -> (Int, Int) -> (Int, Int)
nextTH xs (t, h) = (next xs t, next xs $ next xs h)
stop :: (Int, Int) -> Bool
stop (t, h) = t == h
(|>) :: a -> (a -> b) -> b
x |> f = f x
containsCycle :: LinkedList -> Bool
containsCycle xs = (1, 1)
|> iterate (nextTH xs)
|> tail
|> dropWhile (not . stop)
|> head
|> fst
|> (/= 0)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment