From 786ed4980808b85cf8bdc5a9cb71859f1fc367ea Mon Sep 17 00:00:00 2001 From: Daniel Flanagan Date: Thu, 15 Dec 2022 00:29:44 -0600 Subject: [PATCH] Day 10 part 2 --- 2022/rust/src/common.rs | 10 +++++----- 2022/rust/src/day10.rs | 41 +++++++++++++++++++---------------------- 2 files changed, 24 insertions(+), 27 deletions(-) diff --git a/2022/rust/src/common.rs b/2022/rust/src/common.rs index be40a80..da01a3d 100644 --- a/2022/rust/src/common.rs +++ b/2022/rust/src/common.rs @@ -1,5 +1,5 @@ use std::env::var as envvar; -use std::fmt::Debug; +use std::fmt::Display; use std::fs; use std::path::Path; @@ -20,12 +20,12 @@ pub fn day_input(day: u8) -> String { } #[allow(dead_code)] -pub fn show_answers(answer1: &impl Debug, answer2: &impl Debug) { - println!("Part 1: {:?}", answer1); - println!("Part 2: {:?}", answer2); +pub fn show_answers(answer1: &impl Display, answer2: &impl Display) { + println!("Part 1: {}", answer1); + println!("Part 2: {}", answer2); } #[allow(dead_code)] -pub fn show_both_answers((a, b): &(impl Debug, impl Debug)) { +pub fn show_both_answers((a, b): &(impl Display, impl Display)) { show_answers(a, b) } diff --git a/2022/rust/src/day10.rs b/2022/rust/src/day10.rs index fc69743..d20ec5a 100644 --- a/2022/rust/src/day10.rs +++ b/2022/rust/src/day10.rs @@ -53,36 +53,32 @@ fn part2(input: &Input) -> Answer2 { let w = 40; let mut crt = String::new(); let mut x = 1; - let mut cycles = 0; - for i in input { - println!("{:?}", i); - let now_x = x.clone(); - cycles += match i { - Instruction::Noop => 1, - Instruction::AddX(n) => { - x += n; - 2 - } - }; - - let mut pixel = '.'; + let mut draw_pixel = |now_x| { + let mut pixel = ' '; if ((crt.len() % w) as i32).abs_diff(now_x) <= 1 { pixel = '#'; } crt.push(pixel); - crt.push('#'); + }; + for i in input { + println!("{:?}", i); + let now_x = x.clone(); + match i { + Instruction::Noop => draw_pixel(now_x), + Instruction::AddX(n) => { + draw_pixel(now_x); + draw_pixel(now_x); + x += n; + } + }; } crt.chars() .enumerate() .flat_map(|(i, c)| { - if i > 0 && i % w == 0 { - Some('\n') - } else { - None - } - .into_iter() - .chain(std::iter::once(c)) + if i % w == 0 { Some('\n') } else { None } + .into_iter() + .chain(std::iter::once(c)) }) .collect::() } @@ -256,12 +252,13 @@ noop"; assert_eq!(part1(&input), 13140); assert_eq!( part2(&input), - "##..##..##..##..##..##..##..##..##..##.. + "\n##..##..##..##..##..##..##..##..##..##.. ###...###...###...###...###...###...###. ####....####....####....####....####.... #####.....#####.....#####.....#####..... ######......######......######......#### #######.......#######.......#######....." + .replace('.', " ") ); // assert_eq!(both_parts(&input), (0, 0)); }