[rs] Simplify 2022_10

This commit is contained in:
Joscha 2022-12-10 15:23:14 +01:00
parent 1b2128d709
commit 715def2e35

View file

@ -1,39 +1,14 @@
#[derive(Clone, Copy)]
struct State {
x: i32,
}
struct Run {
history: Vec<State>,
now: State,
}
impl Run {
fn new() -> Self {
Self {
history: vec![],
now: State { x: 1 },
}
}
fn noop(&mut self) {
self.history.push(self.now);
}
fn addx(&mut self, arg: i32) {
self.noop();
self.noop();
self.now.x += arg;
}
}
pub fn solve(input: String) { pub fn solve(input: String) {
let mut run = Run::new(); let mut history = vec![];
let mut reg_x = 1;
for line in input.lines() { for line in input.lines() {
if line == "noop" { if line == "noop" {
run.noop(); history.push(reg_x);
} else if let Some(arg) = line.strip_prefix("addx ") { } else if let Some(arg) = line.strip_prefix("addx ") {
run.addx(arg.parse().unwrap()); history.push(reg_x);
history.push(reg_x);
reg_x += arg.parse::<i32>().unwrap();
} else { } else {
panic!("Unknown instruction"); panic!("Unknown instruction");
} }
@ -41,18 +16,16 @@ pub fn solve(input: String) {
let part1 = [20, 60, 100, 140, 180, 220] let part1 = [20, 60, 100, 140, 180, 220]
.into_iter() .into_iter()
.map(|i| run.history[i - 1].x * i as i32) .map(|i| history[i - 1] * i as i32)
.sum::<i32>(); .sum::<i32>();
println!("Part 1: {part1}"); println!("Part 1: {part1}");
println!("Part 2:"); println!("Part 2:");
for chunk in run.history.chunks(40) { for chunk in history.chunks(40) {
for (x, state) in chunk.iter().enumerate() { for (x, reg_x) in chunk.iter().enumerate() {
if (x as i32).abs_diff(state.x) <= 1 { let visible = (x as i32).abs_diff(*reg_x) <= 1;
print!("#"); let pixel = if visible { '#' } else { '.' };
} else { print!("{pixel}");
print!(".");
}
} }
println!(); println!();
} }