X-Git-Url: https://git.njae.me.uk/?a=blobdiff_plain;f=src%2Fadvent14%2Fadvent14.hs;h=698853c7bcd2c60b0a891598e0ee9b0bbcc9f41f;hb=fc23edeb0e66a61d640dfeaffd5a274a63acf8c8;hp=940fe7b4d9c6ed811589001b66ff34b075eb1821;hpb=0c672ee4c5d50a7e51b0408ae1b87f68c44534a7;p=advent-of-code-17.git diff --git a/src/advent14/advent14.hs b/src/advent14/advent14.hs index 940fe7b..698853c 100644 --- a/src/advent14/advent14.hs +++ b/src/advent14/advent14.hs @@ -2,22 +2,59 @@ import Data.List.Split (chunksOf) import Data.Char (ord) import Text.Printf (printf) import Data.Bits (xor) +import qualified Data.Set as S +import qualified Data.Graph as G +import Control.Parallel.Strategies (parMap, rpar) + +type CellSet = S.Set (Int, Int) puzzleKey = "xlqgujun" +main :: IO () +main = do + print $ part1 puzzleKey + print $ part2 puzzleKey + part1 :: String -> Int part1 key = sum rowCounts - where hashes = map knotHash $ rowSpecs key - rowCounts = map (countSetBits . binify) hashes + where rowCounts = parMap rpar countSetBits $ binHashes key + + +part2 :: String -> Int +part2 key = length $ cellEdges cells + where cells = presentCells $ binHashes key + +binHashes :: String -> [String] +binHashes key = parMap rpar binHash $ rowSpecs key + + +binHash :: String -> String +binHash = binify . knotHash + +numKey :: (Int, Int) -> Int +numKey (r, c) = 128 * r + c + + +presentCells :: [String] -> CellSet +presentCells bhs = S.fromList [(r, c) | r <- [0..127], c <- [0..127], (bhs!!r)!!c == '1'] + +adjacentCells :: CellSet -> (Int, Int) -> [(Int, Int)] +adjacentCells cells (r, c) = filter (\k -> S.member k cells) possibles + where possibles = [(r, c - 1), (r, c + 1), (r - 1, c), (r + 1, c)] + + +cellEdges :: CellSet -> [G.SCC (Int, Int)] +cellEdges cells = G.stronglyConnComp [(k, numKey k, map numKey $ adjacentCells cells k) | k <- S.elems cells] rowSpecs :: String -> [String] -rowSpecs key = map (((key ++ "-") ++) . show) [0..127] +rowSpecs key = map (((key ++ "-") ++) . show) ([0..127] :: [Integer]) countSetBits :: String -> Int countSetBits = length . filter (== '1') + knotHash :: String -> [Int] knotHash input = densify tied where (tied, _, _) = foldl step ([0..255], 0, 0) hashTerms @@ -47,8 +84,8 @@ mkHashTerms :: String -> [Int] mkHashTerms text = take (length chunk * 64) $ cycle chunk where chunk = map ord text ++ [17, 31, 73, 47, 23] -hexify :: [Int] -> String -hexify = concatMap (printf "%02x") +-- hexify :: [Int] -> String +-- hexify = concatMap (printf "%02x") binify :: [Int] -> String binify = concatMap (printf "%08b") @@ -57,4 +94,4 @@ densify :: [Int] -> [Int] densify ns = codes where chunks = chunksOf 16 ns compress = foldl1 xor - codes = map compress chunks \ No newline at end of file + codes = map compress chunks