This commit is contained in:
Dory 2024-03-12 01:25:51 -07:00
parent 176149a167
commit 2cbcc69ff3
2 changed files with 53 additions and 6 deletions

View File

@ -26,7 +26,7 @@ fn parse_line(line: String) -> Result<Inst, ParseError> {
fn main() {
let file = File::open(&env::args().nth(1).unwrap()).unwrap();
let reader = io::BufReader::new(file);
let mut xs: Vec<i64> = vec![0, 1];
let mut xs: Vec<i64> = 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::<String>());
}
}

45
day10/src/main1.rs Normal file
View File

@ -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<Inst, ParseError> {
match &line[..4] {
"noop" => Ok(Inst::Noop),
"addx" => match line[5..].parse::<i64>() {
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<i64> = 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);
}