-
Notifications
You must be signed in to change notification settings - Fork 0
/
solution_2019_13.rs
83 lines (72 loc) · 2.25 KB
/
solution_2019_13.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
use advent_of_code_2019::intcode::{Process, parse_machine_code};
use num_derive::FromPrimitive;
use num_traits::{FromPrimitive, signum};
#[repr(u8)]
#[derive(PartialEq, Eq, FromPrimitive, Debug)]
enum Tile {
Empty = 0, // No game object appears in this tile.
Wall = 1, // Walls are indestructible barriers.
Block = 2, // Blocks can be broken by the ball.
HorizontalPaddle = 3, // The paddle is indestructible.
Ball = 4, // 4 is a ball tile. The ball moves diagonally and bounces off objects.
}
fn solve_1() {
let mut program = Process::from_string(include_str!("../../resources/13.txt"));
program.run_to_halt();
let results = program.read_output();
let chunked: Vec<_> = results.chunks_exact(3).collect();
let tiles: Vec<Tile> = chunked
.iter()
.map(|arr| Tile::from_i128(arr[2]).unwrap())
.collect();
let result = tiles.iter().filter(|x| **x == Tile::Block).count();
println!("Part 1: {result:?}");
}
fn solve_2() {
let mut machine_code = parse_machine_code(include_str!("../../resources/13.txt"));
machine_code[0] = 2;
let mut program = Process::new(&machine_code);
let mut score = 0;
let mut ball_x = 0;
let mut paddle_x = 0;
loop {
while program.unsatisfied_input() {
let input = signum(ball_x - paddle_x);
program.provide_input(input);
}
let halted = program.run_next_op();
if halted {
break;
} else if program.output_len() >= 3 {
let a = program.next_output_unsafe();
let b = program.next_output_unsafe();
let c = program.next_output_unsafe();
if a == -1 && b == 0 {
score = c;
} else if Tile::from_i128(c).unwrap() == Tile::Ball {
ball_x = a;
} else if Tile::from_i128(c).unwrap() == Tile::HorizontalPaddle {
paddle_x = a;
}
}
}
println!("Part 2: {score}");
assert_eq!(score, 18371);
}
fn main() {
solve_1();
solve_2();
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_solve_1() {
solve_1();
}
#[test]
#[ignore]
fn test_solve_2() {
solve_2();
}
}