From 2cbcc69ff300390eb7299eb45f65e66bb7d1ed29 Mon Sep 17 00:00:00 2001 From: Dory Date: Tue, 12 Mar 2024 01:25:51 -0700 Subject: [PATCH] d10p2 --- day10/src/main.rs | 14 ++++++++------ day10/src/main1.rs | 45 +++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 53 insertions(+), 6 deletions(-) create mode 100644 day10/src/main1.rs diff --git a/day10/src/main.rs b/day10/src/main.rs index 78bcd3f..ef65e00 100644 --- a/day10/src/main.rs +++ b/day10/src/main.rs @@ -26,7 +26,7 @@ fn parse_line(line: String) -> Result { fn main() { let file = File::open(&env::args().nth(1).unwrap()).unwrap(); let reader = io::BufReader::new(file); - let mut xs: Vec = vec![0, 1]; + let mut xs: Vec = vec![1]; for line in reader.lines().flatten() { let last_x = *xs.last().unwrap(); @@ -36,10 +36,12 @@ fn main() { Err(e) => { eprintln!("error: {:?}", e); process::exit(1) }, } } - let res: i64 = xs.iter().enumerate() - .skip(20).step_by(40) - .map(|(i, &x)| (i as i64)*x) - .sum(); - println!("{:?}", res); + + let screen: Vec<_> = xs.iter().enumerate() + .map(|(i, &x)| if ((i as i64) % 40 - x).abs() <= 1 { '#' } else { '.' }) + .collect(); + for i in 0..6 { + println!("{}", screen[(i*40)..((i+1)*40)].iter().collect::()); + } } diff --git a/day10/src/main1.rs b/day10/src/main1.rs new file mode 100644 index 0000000..78bcd3f --- /dev/null +++ b/day10/src/main1.rs @@ -0,0 +1,45 @@ +use std::env; +use std::process; +use std::fs::File; +use std::io::{self, BufRead}; + +#[derive(Debug)] +enum Inst{ + AddX(i64), + Noop, +} + +#[derive(Debug)] +struct ParseError(String); + +fn parse_line(line: String) -> Result { + match &line[..4] { + "noop" => Ok(Inst::Noop), + "addx" => match line[5..].parse::() { + Ok(operand) => Ok(Inst::AddX(operand)), + Err(e) => Err(ParseError(e.to_string())), + }, + _ => Err(ParseError(String::from("bad instruction"))), + } +} + +fn main() { + let file = File::open(&env::args().nth(1).unwrap()).unwrap(); + let reader = io::BufReader::new(file); + let mut xs: Vec = vec![0, 1]; + + for line in reader.lines().flatten() { + let last_x = *xs.last().unwrap(); + match parse_line(line) { + Ok(Inst::Noop) => { xs.push(last_x) }, + Ok(Inst::AddX(x)) => { xs.push(last_x); xs.push(last_x + x) }, + Err(e) => { eprintln!("error: {:?}", e); process::exit(1) }, + } + } + let res: i64 = xs.iter().enumerate() + .skip(20).step_by(40) + .map(|(i, &x)| (i as i64)*x) + .sum(); + println!("{:?}", res); +} +