-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path3b.hs
89 lines (75 loc) · 2.07 KB
/
3b.hs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
{-
Advent of Code
Mark Hegreberg
3b - gather diagnostic data about O2 and CO2 from binary data
-}
sampleData = [00100,
11110,
10110,
10111,
10101,
01111,
00111,
11100,
10000,
11001,
00010,
01010]
:: [Int]
-- 10111
-- [3,-2,5,2,-1]
-- [2,-2,4,2,-2]
---1
--2
--5
---2
--3
common :: [Int] -> Int
common [] = 0
common [x]
| x ==1 = 1
| x ==0 = -1
common (x:xs)
| x == 1 = common xs + 1
| x == 0 = common xs - 1
main = do
contents <- readFile "./3.input"
let input = lines contents
input' = map (read::String->Int) input
-- print $ toDec' (filterOx 12 input')
print $ solution 12 input'
solution width x = toDec' (filterOx width x) * toDec' (filterCO2 width x)
filterOx :: Int -> [Int] -> [Int]
filterOx 0 x = x
filterOx _ [x] = [x]
filterOx width x
| com >= 0 = filterOx (width-1) (filter (isPlace place 1) x)
| otherwise = filterOx (width-1) (filter (isPlace place 0) x)
where
place = 10 ^ (width-1)
com = common $ getPlaces place x
filterCO2 :: Int -> [Int] -> [Int]
filterCO2 0 x = x
filterCO2 _ [x] = [x]
filterCO2 width x
| com >= 0 = filterCO2 (width-1) (filter (isPlace place 0) x)
| otherwise = filterCO2 (width-1) (filter (isPlace place 1) x)
where
place = 10 ^ (width-1)
com = common $ getPlaces place x
getPlace :: (Eq a, Num a, Integral a) => a -> a -> a
getPlace place x
| place == 1 = mod (x - mod x place) place'
| otherwise = mod (x - mod x place) place' `div` place
where
place' = place * 10
getPlaces :: (Integral a) => a -> [a] -> [a]
getPlaces place = map (getPlace place)
isPlace place val x
| getPlace place x == val = True
| otherwise = False
toDec :: Integral a => a -> a
toDec 0 = 0
toDec x = 2 * toDec (div x 10) + mod x 10
toDec' :: Integral a => [a] -> a
toDec' [x] = toDec x