Last active
July 27, 2017 19:49
-
-
Save NCrashed/d1b30a603b705eb9ac2b02b7b4ec418f to your computer and use it in GitHub Desktop.
This file contains 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
{-# LANGUAGE OverloadedLists #-} | |
module Main where | |
import Data.Vector.Unboxed (Vector(..), fromList, (!?)) | |
import Data.List | |
import Data.Maybe (isJust) | |
import qualified Data.Vector.Unboxed as V | |
hasCycle1 :: (V.Unbox a, Eq a) => Vector a -> Bool | |
hasCycle1 l = isJust $ V.find (uncurry (==)) $ V.zip l $ every 2 l | |
where | |
every n xs = let | |
xs' = V.drop (n-1) xs | |
in if V.null xs' then V.empty else V.head xs' `V.cons` every n (V.tail xs') | |
hasCycle2 :: (V.Unbox a, Eq a, Show a) => Vector a -> Bool | |
hasCycle2 l = V.any check . V.indexed . V.take (V.length l `div` 2) $ l | |
where | |
check (i, a) = a == l V.! (2*i+1) | |
{-# INLINE check #-} | |
calculateJumps :: Vector Int -> Maybe Int | |
calculateJumps l | |
| V.null l = Nothing | |
| hasCycle2 indexes = Nothing | |
| otherwise = Just $ V.length indexes | |
where | |
indexes = generateIndexes l | |
generateIndexes :: Vector Int -> Vector Int | |
generateIndexes vec = V.unfoldr gen (vec,0) | |
where gen (v,i) = case v !? i of | |
Just i' -> Just (i+i',(v,i+i')) | |
Nothing -> Nothing | |
main :: IO () | |
main = print $ calculateJumps $ V.replicate 100000 1 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment