Cleanup (and apparently performance improvements)

This commit is contained in:
Sijmen 2018-12-03 00:08:01 +01:00
parent 5d158006b1
commit c2974f8fd2

View file

@ -1,25 +1,25 @@
{-# LANGUAGE TupleSections #-} {-# LANGUAGE TupleSections #-}
module Day2B where module Day2B where
import Data.List (find) import Data.Maybe (mapMaybe)
import qualified Data.Sequence as S import Data.Foldable (toList)
import qualified Data.Foldable as F import qualified Data.Sequence as Seq
dist' :: Int -> (S.Seq Char) -> String -> String -> (Int, String) distance' :: Int -> (Seq.Seq Char) -> String -> String -> Maybe String
dist' n common (a:x) (b:y) distance' n common (a:x) (b:y)
| a == b = dist' n (common S.|> a) x y | a == b = distance' n (common Seq.|> a) x y
| otherwise = dist' (n + 1) common x y | otherwise = distance' (n + 1) common x y
dist' n common _ _ = (n, F.toList common) distance' 1 common "" "" = Just(toList common)
distance' _ _ _ _ = Nothing
dist :: String -> String -> (Int, String) distance :: (String, String) -> Maybe String
dist = dist' 0 S.empty distance (a, b) = distance' 0 Seq.empty a b
distances :: [(String, String)] -> String
distances xs = head $ mapMaybe distance xs
combinations :: [String] -> [(String, String)] combinations :: [String] -> [(String, String)]
combinations (x:xs) = map (x,) xs ++ combinations xs combinations (x:xs) = map (x,) xs ++ combinations xs
combinations [] = [] combinations [] = []
distances :: [(String, String)] -> String
distances xs = result
where Just(_, result) = find (\(x, _) -> x == 1) $ map (uncurry dist) xs
main :: IO () main :: IO ()
main = interact $ distances . combinations . lines main = interact $ distances . combinations . lines