never executed always true always false
1 {-|
2 Module: Y2015.D08
3 Description: Advent of Code Day 08 Solutions.
4 License: MIT
5 Maintainer: @tylerjl
6
7 Solutions to the day 08 set of problems for <adventofcode.com>.
8 -}
9
10 module Y2015.D08 (difference, encoded) where
11
12 body :: [a] -> [a]
13 body [] = []
14 body [_] = []
15 body xs = tail $ init xs
16
17 hexChars :: String
18 hexChars = "0123456789abcdef"
19
20 escape :: String -> String
21 escape [] = []
22 escape [x] = [x]
23 escape (v:w:x:y:zs) | [v,w] == "\\x" && hex = '.' : escape zs
24 where hex = all (`elem` hexChars) [x,y]
25 escape (x:y:zs) | [x,y] == "\\\"" = '"' : escape zs
26 | [x,y] == "\\\\" = '\\' : escape zs
27 | otherwise = x : escape (y:zs)
28
29 encode :: String -> String
30 encode = (++) "\"" . (:) '"' . encode'
31
32 encode' :: String -> String
33 encode' [] = []
34 encode' (x:xs) | x == '"' = '\\' : '"' : encode' xs
35 | x == '\\' = "\\\\" ++ encode' xs
36 | otherwise = x : encode' xs
37
38 squish :: String -> String
39 squish = filter (/= '\n')
40
41 solve :: (Int -> Int -> Int) -> (String -> String) -> String -> Int
42 solve g f s = g (original s) (new s)
43 where original = length . squish
44 new = length . squish . unlines . map f . lines
45
46 -- |Finds the length difference between escaped and unescaped string
47 difference :: String -- ^ Input string with escapes
48 -> Int -- ^ Unescaped length difference
49 difference = solve (-) (escape . body)
50
51 -- |Same as 'encoded', but different
52 encoded :: String -- ^ Input string with escapes
53 -> Int -- ^ Length difference to encoded string
54 encoded = solve (flip (-)) encode