1 import Data.List.Split (chunksOf)
3 import Text.Printf (printf)
5 import qualified Data.Map.Strict as M
6 import qualified Data.Graph as G
8 type CellMap = M.Map (Int, Int) Bool
10 puzzleKey = "xlqgujun"
14 print $ part1 puzzleKey
15 print $ part2 puzzleKey
18 part1 :: String -> Int
19 part1 key = sum rowCounts
20 where binHashes = map binHash $ rowSpecs key
21 rowCounts = map countSetBits binHashes
24 part2 :: String -> Int
25 part2 key = length $ cellEdges cells
26 where binHashes = map binHash $ rowSpecs key
27 cells = presentCells binHashes
29 binHash :: String -> String
30 binHash = binify . knotHash
32 numKey :: (Int, Int) -> Int
33 numKey (r, c) = 128 * r + c
36 presentCells :: [String] -> CellMap
37 presentCells binHashes = M.fromList [((r, c), True) | r <- [0..127], c <- [0..127], (binHashes!!r)!!c == '1']
39 adjacentCells :: CellMap -> (Int, Int) -> [(Int, Int)]
40 adjacentCells cells (r, c) = filter (\k -> M.member k cells) possibles
41 where possibles = [(r, c - 1), (r, c + 1), (r - 1, c), (r + 1, c)]
44 cellEdges :: CellMap -> [G.SCC (Int, Int)]
45 cellEdges cells = G.stronglyConnComp [(k, numKey k, map numKey $ adjacentCells cells k) | k <- M.keys cells]
47 rowSpecs :: String -> [String]
48 rowSpecs key = map (((key ++ "-") ++) . show) ([0..127] :: [Integer])
50 countSetBits :: String -> Int
51 countSetBits = length . filter (== '1')
55 knotHash :: String -> [Int]
56 knotHash input = densify tied
57 where (tied, _, _) = foldl step ([0..255], 0, 0) hashTerms
58 hashTerms = mkHashTerms input
60 step :: ([Int], Int, Int) -> Int -> ([Int], Int, Int)
61 step (original, start, skip) len = (replaced, start', skip + 1)
62 where replaced = tie original start len
63 start' = (start + len + skip) `mod` (length original)
65 tie :: [a] -> Int -> Int -> [a]
66 tie original start len = replace original replacement start
67 where replacement = reverse $ extract original start len
69 extract :: [a] -> Int -> Int -> [a]
70 extract items from len = take len $ drop from $ items ++ items
72 replace :: [a] -> [a] -> Int -> [a]
73 replace original replacement from = take (length original) (start ++ replacement ++ remainder)
74 where excess = drop (length original - from) replacement
75 stub = drop (length excess) original
76 start = take from (excess ++ stub)
77 remainder = drop (length $ start ++ replacement) original
80 mkHashTerms :: String -> [Int]
81 mkHashTerms text = take (length chunk * 64) $ cycle chunk
82 where chunk = map ord text ++ [17, 31, 73, 47, 23]
84 -- hexify :: [Int] -> String
85 -- hexify = concatMap (printf "%02x")
87 binify :: [Int] -> String
88 binify = concatMap (printf "%08b")
90 densify :: [Int] -> [Int]
92 where chunks = chunksOf 16 ns
94 codes = map compress chunks