Add day 10

This commit is contained in:
2022-12-11 09:32:36 +01:00
parent e76573b78c
commit c447b7fc71
4 changed files with 418 additions and 0 deletions

131
src/day10/main.rs Normal file
View File

@ -0,0 +1,131 @@
use base::read_file;
struct CRT {
display: [[char; 40]; 6],
row_idx: usize,
col_idx: usize,
}
impl CRT {
fn new() -> Self {
Self {
display: [['\0'; 40]; 6],
col_idx: 0,
row_idx: 0,
}
}
fn clock(&mut self, register: i32) {
if self.col_idx >= 6 || self.row_idx >= 40 {
return;
}
let range = ((register - 1).max(0))..=((register + 1).min(39));
self.display[self.col_idx][self.row_idx] = if range.contains(&(self.row_idx as i32)) { '⭐' } else { '🌲' };
self.row_idx += 1;
if self.row_idx % 40 == 0 {
self.row_idx = 0;
self.col_idx += 1;
};
}
fn display(&self) {
for col in 0..6 {
for row in 0..40 {
print!("{}", self.display[col][row]);
}
println!();
}
}
}
#[derive(Debug, Copy, Clone)]
enum Op {
NOOP,
ADD {
amount: i32
},
}
struct Machine {
program: Vec<Op>,
register: i32,
register_next: i32,
instruction_counter: usize,
instruction_left_counter: u32,
current_option: Option<Op>,
}
impl Machine {
fn new(program: Vec<Op>) -> Self {
Self {
program,
register: 1,
register_next: 1,
instruction_counter: 0,
instruction_left_counter: 0,
current_option: None,
}
}
fn clock(&mut self, crt: &mut CRT) {
self.register = self.register_next;
crt.clock(self.register);
if self.instruction_left_counter == 0 {
if self.instruction_counter >= self.program.len() {
self.current_option = None;
self.instruction_left_counter = 0;
return;
}
let next_op = self.program[self.instruction_counter];
self.instruction_counter += 1;
match next_op {
Op::NOOP => {
self.instruction_left_counter = 0;
}
Op::ADD { .. } => {
self.instruction_left_counter = 1;
}
}
self.current_option = Some(next_op);
} else {
if let Some(current_op) = self.current_option {
match current_op {
Op::NOOP => {}
Op::ADD { amount } => { self.register_next = self.register + amount; }
}
}
self.instruction_left_counter -= 1;
}
}
}
fn main() {
let lines = read_file("day10.txt");
let mut ops = vec![];
for line in lines {
if line.starts_with("noop") { ops.push(Op::NOOP); } else if line.starts_with("addx") {
let amount = line.split_whitespace().collect::<Vec<_>>()[1].parse::<i32>().unwrap();
ops.push(Op::ADD { amount });
}
}
let mut crt = CRT::new();
let mut machine = Machine::new(ops);
let mut signals = vec![];
for cycle in 0..2220 {
machine.clock(&mut crt);
let cycle = cycle + 1;
match cycle {
20 | 60 | 100 | 140 | 180 | 220 => {
signals.push(cycle * machine.register);
}
_ => {}
}
}
println!("Sum: {}", signals.iter().sum::<i32>());
crt.display();
}