aoc22/day10/src/main.rs

51 lines
1.3 KiB
Rust
Raw Normal View History

2024-03-12 11:21:21 -05:00
use std::num;
2024-03-12 02:59:44 -05:00
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);
2024-03-12 11:21:21 -05:00
impl From<num::ParseIntError> for ParseError {
fn from(e: num::ParseIntError) -> Self {
ParseError(e.to_string())
}
}
2024-03-12 02:59:44 -05:00
fn parse_line(line: String) -> Result<Inst, ParseError> {
match &line[..4] {
"noop" => Ok(Inst::Noop),
2024-03-12 11:21:21 -05:00
"addx" => Ok(Inst::AddX(line[5..].parse::<i64>()?)),
2024-03-12 02:59:44 -05:00
_ => Err(ParseError(String::from("bad instruction"))),
}
}
fn main() {
let file = File::open(&env::args().nth(1).unwrap()).unwrap();
let reader = io::BufReader::new(file);
2024-03-12 03:25:51 -05:00
let mut xs: Vec<i64> = vec![1];
2024-03-12 02:59:44 -05:00
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) },
}
}
2024-03-12 03:25:51 -05:00
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>());
}
2024-03-12 02:59:44 -05:00
}