1 import Data.List.Split (chunksOf)
3 import Text.Printf (printf)
10 part1 key = sum rowCounts
11 where hashes = map knotHash $ rowSpecs key
12 rowCounts = map (countSetBits . binify) hashes
14 rowSpecs :: String -> [String]
15 rowSpecs key = map (((key ++ "-") ++) . show) [0..127]
17 countSetBits :: String -> Int
18 countSetBits = length . filter (== '1')
21 knotHash :: String -> [Int]
22 knotHash input = densify tied
23 where (tied, _, _) = foldl step ([0..255], 0, 0) hashTerms
24 hashTerms = mkHashTerms input
26 step :: ([Int], Int, Int) -> Int -> ([Int], Int, Int)
27 step (original, start, skip) len = (replaced, start', skip + 1)
28 where replaced = tie original start len
29 start' = (start + len + skip) `mod` (length original)
31 tie :: [a] -> Int -> Int -> [a]
32 tie original start len = replace original replacement start
33 where replacement = reverse $ extract original start len
35 extract :: [a] -> Int -> Int -> [a]
36 extract items from len = take len $ drop from $ items ++ items
38 replace :: [a] -> [a] -> Int -> [a]
39 replace original replacement from = take (length original) (start ++ replacement ++ remainder)
40 where excess = drop (length original - from) replacement
41 stub = drop (length excess) original
42 start = take from (excess ++ stub)
43 remainder = drop (length $ start ++ replacement) original
46 mkHashTerms :: String -> [Int]
47 mkHashTerms text = take (length chunk * 64) $ cycle chunk
48 where chunk = map ord text ++ [17, 31, 73, 47, 23]
50 hexify :: [Int] -> String
51 hexify = concatMap (printf "%02x")
53 binify :: [Int] -> String
54 binify = concatMap (printf "%08b")
56 densify :: [Int] -> [Int]
58 where chunks = chunksOf 16 ns
60 codes = map compress chunks