diff options
| author | Orfeas Chatzipanagiotis <csd4366@csd.uoc.gr> | 2022-12-08 05:45:14 +0200 |
|---|---|---|
| committer | Orfeas Chatzipanagiotis <csd4366@csd.uoc.gr> | 2022-12-09 11:57:39 +0200 |
| commit | 52123945a7bf2d627f3000add96d30f46c6f48b8 (patch) | |
| tree | bdf168e85a030b96fd610d11293039f4f1907bc3 /day4/solution.nim | |
| parent | Day 2 (diff) | |
| download | aoc22-52123945a7bf2d627f3000add96d30f46c6f48b8.tar.gz aoc22-52123945a7bf2d627f3000add96d30f46c6f48b8.zip | |
Day 3,4
Diffstat (limited to 'day4/solution.nim')
| -rw-r--r-- | day4/solution.nim | 56 |
1 files changed, 56 insertions, 0 deletions
diff --git a/day4/solution.nim b/day4/solution.nim new file mode 100644 index 0000000..36e90fb --- /dev/null +++ b/day4/solution.nim | |||
| @@ -0,0 +1,56 @@ | |||
| 1 | import std/strutils | ||
| 2 | import std/sequtils | ||
| 3 | |||
| 4 | type | ||
| 5 | # We use begin and length for Range representation to simplify calculations later | ||
| 6 | Range = tuple[begin: int, length: int] | ||
| 7 | Entry = tuple[first: Range, second: Range] | ||
| 8 | |||
| 9 | proc part1(entries: seq[Entry]): int = | ||
| 10 | var score = 0 | ||
| 11 | for e in entries: | ||
| 12 | var r: Entry | ||
| 13 | # Let first become the leftmost range. In case both ranges start at the same index, we consider the longest one to be first | ||
| 14 | if e.first.begin < e.second.begin or (e.first.begin == e.second.begin and e.first.length >= e.second.length): | ||
| 15 | r.first = e.first | ||
| 16 | r.second = e.second | ||
| 17 | else: | ||
| 18 | r.first = e.second | ||
| 19 | r.second = e.first | ||
| 20 | |||
| 21 | if r.first.length >= r.second.length + r.second.begin - r.first.begin: | ||
| 22 | score += 1 | ||
| 23 | |||
| 24 | return score | ||
| 25 | |||
| 26 | proc part2(entries: seq[Entry]): int = | ||
| 27 | var score = 0 | ||
| 28 | for e in entries: | ||
| 29 | var r: Entry | ||
| 30 | # Let first become the leftmost range. In case both ranges start at the same index, we consider the longest one to be first | ||
| 31 | if e.first.begin < e.second.begin or (e.first.begin == e.second.begin and e.first.length >= e.second.length): | ||
| 32 | r.first = e.first | ||
| 33 | r.second = e.second | ||
| 34 | else: | ||
| 35 | r.first = e.second | ||
| 36 | r.second = e.first | ||
| 37 | |||
| 38 | if r.first.begin + r.first.length - 1 >= r.second.begin: | ||
| 39 | score += 1 | ||
| 40 | |||
| 41 | return score | ||
| 42 | |||
| 43 | let | ||
| 44 | content = readFile("./input.txt").strip().splitLines() | ||
| 45 | entries = map( | ||
| 46 | content, | ||
| 47 | proc(line: string): Entry = | ||
| 48 | let tokens = map(line.split({',', '-'}), proc(token: string): int = token.parseInt()) | ||
| 49 | ( | ||
| 50 | (tokens[0], tokens[1] - tokens[0]+1), | ||
| 51 | (tokens[2], tokens[3] - tokens[2]+1) | ||
| 52 | ) | ||
| 53 | ) | ||
| 54 | |||
| 55 | echo part1(entries) | ||
| 56 | echo part2(entries) | ||
