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);
|
|
|
|
|
|
|
|
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);
|
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
|
|
|
}
|
|
|
|
|