-
Notifications
You must be signed in to change notification settings - Fork 0
/
day10.rs
103 lines (91 loc) · 2.56 KB
/
day10.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
96
97
98
99
100
101
102
103
//! [Day 10: Cathode-Ray Tube](https://adventofcode.com/2022/day/10)
use aoc::ocr::scan_5x6;
struct Puzzle {
/// Value of X during the `index+1` cycle
cycles: Vec<i32>,
}
impl Puzzle {
fn new() -> Self {
Self { cycles: vec![] }
}
/// Loads data from input (one line)
fn configure(&mut self, path: &str) {
let data = std::fs::read_to_string(path).unwrap();
let lines = data.split('\n').collect::<Vec<_>>();
#[allow(non_snake_case)]
let mut X = 1;
self.cycles.push(X); // value of X during the first cycle
for line in lines {
if line == "noop" {
self.cycles.push(X);
} else if let Some(v) = line.strip_prefix("addx ") {
self.cycles.push(X);
X += v.parse::<i32>().unwrap();
self.cycles.push(X);
}
}
}
// Solves part one
fn part1(&self) -> i32 {
let mut signal_strength = 0;
for (i, x) in self.cycles.iter().enumerate() {
let cycle = (i + 1) as i32;
if (cycle + 20) % 40 == 0 {
signal_strength += cycle * (*x);
}
}
signal_strength
}
// Solve part two
fn part2(&self) -> String {
let mut iter_x = self.cycles.iter();
let mut crt = String::new();
for _ in 1..=6 {
for pixel in 1..=40 {
let sprite = *iter_x.next().unwrap();
if sprite <= pixel && pixel < sprite + 3 {
crt.push('#');
} else {
crt.push('.');
}
}
crt.push('\n');
}
crt
}
}
/// main function
fn main() {
let args = aoc::parse_args();
let mut puzzle = Puzzle::new();
puzzle.configure(&args.path);
println!("{}", puzzle.part1());
// println!("{}", puzzle.part2());
println!("{}", scan_5x6(&puzzle.part2()));
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_part1() {
let mut puzzle = Puzzle::new();
puzzle.configure("test.txt");
assert_eq!(puzzle.part1(), 13140);
}
#[test]
fn test_part2() {
let mut puzzle = Puzzle::new();
puzzle.configure("test.txt");
assert_eq!(
puzzle.part2(),
"\
##..##..##..##..##..##..##..##..##..##..
###...###...###...###...###...###...###.
####....####....####....####....####....
#####.....#####.....#####.....#####.....
######......######......######......####
#######.......#######.......#######.....
"
);
}
}