[rs] Simplify 2022_10
This commit is contained in:
parent
1b2128d709
commit
715def2e35
1 changed files with 13 additions and 40 deletions
|
|
@ -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) {
|
||||
let mut run = Run::new();
|
||||
let mut history = vec![];
|
||||
let mut reg_x = 1;
|
||||
|
||||
for line in input.lines() {
|
||||
if line == "noop" {
|
||||
run.noop();
|
||||
history.push(reg_x);
|
||||
} 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 {
|
||||
panic!("Unknown instruction");
|
||||
}
|
||||
|
|
@ -41,18 +16,16 @@ pub fn solve(input: String) {
|
|||
|
||||
let part1 = [20, 60, 100, 140, 180, 220]
|
||||
.into_iter()
|
||||
.map(|i| run.history[i - 1].x * i as i32)
|
||||
.map(|i| history[i - 1] * i as i32)
|
||||
.sum::<i32>();
|
||||
println!("Part 1: {part1}");
|
||||
|
||||
println!("Part 2:");
|
||||
for chunk in run.history.chunks(40) {
|
||||
for (x, state) in chunk.iter().enumerate() {
|
||||
if (x as i32).abs_diff(state.x) <= 1 {
|
||||
print!("#");
|
||||
} else {
|
||||
print!(".");
|
||||
}
|
||||
for chunk in history.chunks(40) {
|
||||
for (x, reg_x) in chunk.iter().enumerate() {
|
||||
let visible = (x as i32).abs_diff(*reg_x) <= 1;
|
||||
let pixel = if visible { '#' } else { '.' };
|
||||
print!("{pixel}");
|
||||
}
|
||||
println!();
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue