1
0
Fork 0
mirror of https://gitlab.com/mfocko/CodeWars.git synced 2024-09-19 14:16:55 +02:00
CodeWars/5kyu/pick_peaks/solution.hs

31 lines
1.1 KiB
Haskell
Raw Normal View History

module PickPeak.JorgeVS.Kata where
data PickedPeaks = PickedPeaks { pos :: [Int], peaks :: [Int] } deriving (Eq, Show)
windowed :: Int -> [a] -> [[a]]
windowed n xs
| null xs || length window < n = []
| otherwise = window : (windowed n $ tail xs)
where window = take n xs
addIfPeak :: PickedPeaks -> [(Int, Int)] -> PickedPeaks
addIfPeak ps [l, mid, r]
| (snd mid > snd l) && (snd mid > snd r) = PickedPeaks { pos = fst mid : pos ps, peaks = snd mid : peaks ps }
| otherwise = ps
addIfPeak _ _ = error "Invalid state"
removeConsecutiveDuplicates :: [(Int, Int)] -> [(Int, Int)]
removeConsecutiveDuplicates = foldr addIfNotDuplicate []
where addIfNotDuplicate :: (Int, Int) -> [(Int, Int)] -> [(Int, Int)]
addIfNotDuplicate pair [] = [pair]
addIfNotDuplicate pair@(i, x) pairs
| x == (snd . head) pairs = pair : tail pairs
| otherwise = pair : pairs
pickPeaks :: [Int] -> PickedPeaks
pickPeaks = foldl addIfPeak PickedPeaks { pos = [], peaks = [] }
. windowed 3
. reverse
. removeConsecutiveDuplicates
. zip [0..]