-
Notifications
You must be signed in to change notification settings - Fork 0
/
day4.rs
95 lines (77 loc) · 2.17 KB
/
day4.rs
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
90
91
92
93
94
95
//! [Day 4: Scratchcards](https://adventofcode.com/2023/day/4)
use std::collections::HashSet;
struct Puzzle {
matching_cards: Vec<usize>,
}
impl Puzzle {
fn new() -> Puzzle {
Puzzle {
matching_cards: vec![],
}
}
/// Get the puzzle input.
fn configure(&mut self, path: &str) {
let data = std::fs::read_to_string(path).unwrap();
for line in data.lines() {
let line = line[line.find(':').unwrap() + 1..]
.split('|')
.collect::<Vec<_>>();
let winning = line[0]
.split_whitespace()
.map(|x| x.parse::<u32>().unwrap())
.collect::<HashSet<_>>();
let nums = line[1]
.split_whitespace()
.map(|x| x.parse::<u32>().unwrap())
.collect::<HashSet<_>>();
let result = winning.intersection(&nums).count();
self.matching_cards.push(result);
}
}
/// Solve part one.
fn part1(&self) -> usize {
let mut sum = 0;
for n in &self.matching_cards {
if n >= &1 {
sum += 2usize.pow(u32::try_from(*n).unwrap() - 1);
}
}
sum
}
/// Solve part two.
fn part2(&self) -> usize {
let mut copies = vec![0usize; self.matching_cards.len()];
for i in 0..self.matching_cards.len() {
copies[i] += 1;
let m = self.matching_cards[i];
for j in (i + 1)..(i + 1 + m) {
copies[j] += copies[i];
}
}
copies.iter().sum()
}
}
/// Test from puzzle input
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test01() {
let mut puzzle = Puzzle::new();
puzzle.configure("test.txt");
assert_eq!(puzzle.part1(), 13);
}
#[test]
fn test02() {
let mut puzzle = Puzzle::new();
puzzle.configure("test.txt");
assert_eq!(puzzle.part2(), 30);
}
}
fn main() {
let args = aoc::parse_args();
let mut puzzle = Puzzle::new();
puzzle.configure(args.path.as_str());
println!("{}", puzzle.part1());
println!("{}", puzzle.part2());
}