use std::num; 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); impl From for ParseError { fn from(e: num::ParseIntError) -> Self { ParseError(e.to_string()) } } fn parse_line(line: String) -> Result { match &line[..4] { "noop" => Ok(Inst::Noop), "addx" => Ok(Inst::AddX(line[5..].parse::()?)), _ => 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![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 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::()); } }