[rs] Solve 2022_10 part 1

This commit is contained in:
Joscha 2022-12-10 15:11:19 +01:00
parent 87103940eb
commit 745a205492
7 changed files with 344 additions and 2 deletions

View file

@ -41,8 +41,11 @@ macro_rules! days {
impl Day {
fn from_path(path: &Path) -> Option<Self> {
let day = &path.file_stem()?.as_bytes()[..7];
let day = String::from_utf8_lossy(day);
let bytes = path.file_stem()?.as_bytes();
if bytes.len() < 7 {
return None;
}
let day = String::from_utf8_lossy(&bytes[..7]);
Self::from_str(&day).ok()
}
}
@ -57,6 +60,7 @@ days! {
Y2022D07: "2022_07" => y2022::d07::solve,
Y2022D08: "2022_08" => y2022::d08::solve,
Y2022D09: "2022_09" => y2022::d09::solve,
Y2022D10: "2022_10" => y2022::d10::solve,
}
#[derive(Parser)]

View file

@ -7,3 +7,4 @@ pub mod d06;
pub mod d07;
pub mod d08;
pub mod d09;
pub mod d10;

47
rs/src/y2022/d10.rs Normal file
View file

@ -0,0 +1,47 @@
#[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();
for line in input.lines() {
if line == "noop" {
run.noop();
} else if let Some(arg) = line.strip_prefix("addx ") {
run.addx(arg.parse().unwrap());
} else {
panic!("Unknown instruction");
}
}
let part1 = [20, 60, 100, 140, 180, 220]
.into_iter()
.map(|i| run.history[i - 1].x * i as i32)
.sum::<i32>();
println!("Part 1: {part1}");
}