Skip to content

Commit 3f499d5

Browse files
committed
Parsing
1 parent dd20d32 commit 3f499d5

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed

day24_1.rkt

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
#lang racket
2+
3+
(struct units (count hit-points weaknesses immunities damage dtype initiative)
4+
#:transparent)
5+
6+
(define (parse-weaknesses inp)
7+
(define parsed (append (string-split inp "; ") (list "" "")))
8+
(define weaknesses (string-replace (if (string-contains? (first parsed) "weak") (first parsed) (second parsed)) "weak to " ""))
9+
(define immunities (string-replace (if (string-contains? (first parsed) "immune") (first parsed) (second parsed)) "immune to " ""))
10+
(cons (string-split weaknesses ", ") (string-split immunities ", ")))
11+
12+
(define (parse-line l)
13+
(define parsed (regexp-match #px"(\\d+) units each with (\\d+) hit points \\((.*)\\) with an attack that does (\\d+) (\\w+) damage at initiative (\\d+)" l))
14+
(define weaknesses-and-immunities (parse-weaknesses (fourth parsed)))
15+
(units (string->number (second parsed))
16+
(string->number (third parsed))
17+
(car weaknesses-and-immunities)
18+
(cdr weaknesses-and-immunities)
19+
(string->number (fifth parsed))
20+
(sixth parsed)
21+
(string->number (seventh parsed))))
22+
23+
(define (parse-lines lines)
24+
(map parse-line (rest lines)))
25+
26+
(define (parse-input inp)
27+
(define split-pos (index-of inp ""))
28+
(define immune-lines (take inp split-pos))
29+
(define infection-lines (drop inp (add1 split-pos)))
30+
(cons (parse-lines immune-lines) (parse-lines infection-lines)))
31+
32+
(define test-input
33+
(list "Immune System:"
34+
"17 units each with 5390 hit points (weak to radiation, bludgeoning) with an attack that does 4507 fire damage at initiative 2"
35+
"989 units each with 1274 hit points (immune to fire; weak to bludgeoning, slashing) with an attack that does 25 slashing damage at initiative 3"
36+
""
37+
"Infection:"
38+
"801 units each with 4706 hit points (weak to radiation) with an attack that does 116 bludgeoning damage at initiative 1"
39+
"4485 units each with 2961 hit points (immune to radiation; weak to fire, cold) with an attack that does 12 slashing damage at initiative 4"))

0 commit comments

Comments
 (0)