2022 day10/rust: cleanup

This commit is contained in:
Xiretza 2022-12-10 06:38:47 +01:00
parent e0ff12f770
commit 135a5017f7

View file

@ -2,11 +2,10 @@
use std::{ use std::{
io::{stdin, Read}, io::{stdin, Read},
iter,
str::FromStr, str::FromStr,
}; };
use aoc::*;
enum Instruction { enum Instruction {
Noop, Noop,
Addx(i32), Addx(i32),
@ -17,10 +16,10 @@ impl FromStr for Instruction {
fn from_str(s: &str) -> Result<Self, Self::Err> { fn from_str(s: &str) -> Result<Self, Self::Err> {
let mut args = s.split_whitespace(); let mut args = s.split_whitespace();
match args.next().unwrap() { match args.next().ok_or(())? {
"noop" => Ok(Self::Noop), "noop" => Ok(Self::Noop),
"addx" => { "addx" => {
let i = args.next().unwrap().parse().unwrap(); let i = args.next().ok_or(())?.parse().map_err(|_| ())?;
Ok(Self::Addx(i)) Ok(Self::Addx(i))
} }
_ => Err(()), _ => Err(()),
@ -43,27 +42,25 @@ fn main() {
*acc += i; *acc += i;
Some(*acc) Some(*acc)
}); });
let values = [1, 1] let values = iter::once(1)
.into_iter()
.chain(values) .chain(values)
.enumerate() .enumerate()
.map(|(i, x)| (i32::try_from(i).unwrap(), x)); .map(|(i, x)| (i32::try_from(i).unwrap() + 1, x));
let sum: i32 = values let sum: i32 = values
.clone() .clone()
.skip(20) .skip(20 - 1)
.step_by(40) .step_by(40)
.map(|(i, x)| i * x) .map(|(i, x)| i * x)
.sum(); .sum();
println!("{:?}", sum);
let crt: Vec<_> = values let crt: Vec<_> = values
.skip(1) .map(|(i, x)| ((i - 1) % 40).abs_diff(x) < 2)
.map(|(i, x)| ((i - 1) % 40 - x).abs() < 2)
.map(|x| if x { '#' } else { '.' }) .map(|x| if x { '#' } else { '.' })
.collect(); .collect();
let (_, crt) = crt.split_last().unwrap();
println!("{:?}", sum); for line in crt.chunks_exact(40) {
for line in crt.chunks(40) {
println!("{}", line.iter().collect::<String>()); println!("{}", line.iter().collect::<String>());
} }
} }