There we go
This commit is contained in:
59
app/3.hs
59
app/3.hs
@ -7,51 +7,32 @@ import Data.Char (digitToInt)
|
|||||||
import Control.Applicative
|
import Control.Applicative
|
||||||
import Data.Maybe
|
import Data.Maybe
|
||||||
import Data.Function (on)
|
import Data.Function (on)
|
||||||
import Debug.Trace (trace)
|
|
||||||
import Data.Ord
|
import Data.Ord
|
||||||
|
|
||||||
|
|
||||||
parse :: String -> [[Int]]
|
parse :: String -> [[Int]]
|
||||||
parse = map (digitToInt <$>) . lines
|
parse = map (digitToInt <$>) . lines
|
||||||
|
|
||||||
solve1 :: [[Int]] -> Int
|
solve :: Int -> [[Int]] -> Int
|
||||||
solve1 = sum . map go
|
solve n = sum . mapMaybe (\xs -> go n [] xs xs)
|
||||||
where
|
where
|
||||||
go :: [Int] -> Int
|
go :: Int -> [(Int,Int)] -> [Int] -> [Int] -> Maybe Int
|
||||||
go xs = let m = maximum xs
|
go 0 acc _ _ =
|
||||||
(Just mi) = elemIndex m xs
|
pure . foldl (\a b -> a * 10 + b) 0 . map snd $ sortBy (compare `on` fst) acc
|
||||||
xsafter = drop (mi+1) xs
|
go (n+1) acc ys xs
|
||||||
mafter = maximum xsafter
|
| length xs < n+1 = Nothing
|
||||||
m2 = maximum (delete m xs)
|
| otherwise =
|
||||||
in if xsafter /= [] then
|
let snMax = sortBy (comparing Down) . fst $ foldl (\(a,s) _ ->
|
||||||
m * 10 + mafter else
|
let curr = maximum s in
|
||||||
m2 * 10 + m
|
(curr:a,delete curr s)) ([],xs) [1..n+1]
|
||||||
|
in
|
||||||
solve2 :: [[Int]] -> Int
|
asum (map (\m ->
|
||||||
solve2 = sum . mapMaybe (go)
|
let (Just mi) = elemIndex m xs
|
||||||
where
|
xsafter = drop (mi+1) xs
|
||||||
go :: [Int] -> Maybe Int
|
(Just mio) = elemIndex m ys in
|
||||||
go ys = go' 12 [] ys
|
go n ((mio,m):acc) (replicate (mio + 1) 0 ++ drop (mio + 1) ys) xsafter)
|
||||||
where
|
snMax)
|
||||||
go' :: Int -> [(Int,Int)] -> [Int] -> Maybe Int
|
|
||||||
go' 0 acc _ =
|
|
||||||
(pure . foldl ((\a b -> a * 10 + b)) 0 . map snd $ sortBy (compare `on` fst) acc)
|
|
||||||
go' (n+1) acc xs
|
|
||||||
| length xs < n+1 = Nothing
|
|
||||||
| otherwise =
|
|
||||||
let
|
|
||||||
snMax = sortBy (comparing Down) . fst $ foldl (\(a,s) _ ->
|
|
||||||
let curr = maximum s in
|
|
||||||
(curr:a,delete curr s)) ([],xs) [1..n+1]
|
|
||||||
in
|
|
||||||
asum (map (\m ->
|
|
||||||
let (Just mi) = elemIndex m xs
|
|
||||||
xsafter = drop (mi+1) xs
|
|
||||||
(Just mio) = elemIndex m ys in
|
|
||||||
go' n ((mio,m):acc) xsafter)
|
|
||||||
snMax)
|
|
||||||
|
|
||||||
main :: IO ()
|
main :: IO ()
|
||||||
main = readFile "inputs/3" <&> parse >>= \i ->
|
main = readFile "inputs/3" <&> parse >>= \i ->
|
||||||
print (solve1 i) >>
|
print (solve 2 i) >>
|
||||||
print (solve2 i)
|
print (solve 12 i)
|
||||||
|
|||||||
Reference in New Issue
Block a user