46 lines
1.2 KiB
Rust
46 lines
1.2 KiB
Rust
|
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);
|
||
|
}
|
||
|
|