Created
August 7, 2014 18:24
-
-
Save rexim/5f623b0c183aa0503079 to your computer and use it in GitHub Desktop.
Tortoise-and-hare algorithm
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
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