Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit afb60c1

Browse files
committed
day07
1 parent 33e3b03 commit afb60c1

File tree

3 files changed

+79
-0
lines changed

3 files changed

+79
-0
lines changed

day07/one.hs

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
import Data.Char
2+
import Data.List
3+
import Text.Parsec
4+
import Parsing
5+
6+
main :: IO ()
7+
main = optimisticInteract readD solve
8+
9+
readD :: Parser [(String, Integer)]
10+
readD = readHand `sepEndBy` newline
11+
where
12+
readHand = do
13+
cards <- many1 (oneOf "AKQJT98765432")
14+
many1 space
15+
bid <- number
16+
return (cards, bid)
17+
18+
19+
solve hands = unlines [
20+
show sorted
21+
, show scores
22+
, show answer
23+
]
24+
where
25+
answer = sum scores
26+
sorted = sortOn (scoreHand . fst) hands
27+
scores = zipWith (*) [1..] . map snd $ sorted
28+
29+
scoreHand cards = foldl (\acc s -> acc*100 + scoreCard s) typeScore cards
30+
where
31+
groups = reverse . sort . map length . groupBy (==) . sort $ cards
32+
33+
countsMatch = and . zipWith (==) groups
34+
typeScore = fst . head . filter (countsMatch . snd) $ zip [7,6..1] [[5], [4], [3,2], [3], [2,2], [2], []]
35+
36+
scoreCard c = fst . head . filter ((==c) . snd) $ zip [1..] "23456789TJQKA"

day07/test.txt

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
32T3K 765
2+
T55J5 684
3+
KK677 28
4+
KTJJT 220
5+
QQQJA 483

day07/two.hs

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
import Data.Char
2+
import Data.List
3+
import Text.Parsec
4+
import Parsing
5+
6+
main :: IO ()
7+
main = optimisticInteract readD solve
8+
9+
readD :: Parser [(String, Integer)]
10+
readD = readHand `sepEndBy` newline
11+
where
12+
readHand = do
13+
cards <- many1 (oneOf "AKQJT98765432")
14+
many1 space
15+
bid <- number
16+
return (cards, bid)
17+
18+
19+
solve hands = unlines [
20+
show sorted
21+
, show scores
22+
, show answer
23+
]
24+
where
25+
answer = sum scores
26+
sorted = sortOn (scoreHand . fst) hands
27+
scores = zipWith (*) [1..] . map snd $ sorted
28+
29+
scoreHand cards = foldl (\acc s -> acc*100 + scoreCard s) typeScore cards
30+
where
31+
noJgroups = reverse . sort . map length . groupBy (==) . sort . filter (/='J') $ cards
32+
js = length . filter (=='J') $ cards
33+
groups = zipWith (+) (js:repeat 0) (noJgroups++[0]) -- Add a 0 to handle the case of all cards being J
34+
35+
countsMatch = and . zipWith (==) groups
36+
typeScore = fst . head . filter (countsMatch . snd) $ zip [7,6..1] [[5], [4], [3,2], [3], [2,2], [2], []]
37+
38+
scoreCard c = fst . head . filter ((==c) . snd) $ zip [1..] "J23456789TQKA"

0 commit comments

Comments
 (0)