Skip to content

Commit

Permalink
complete day 10 part 2
Browse files Browse the repository at this point in the history
  • Loading branch information
Lawrence Niu committed Dec 14, 2022
1 parent 0b852aa commit 65a6301
Showing 1 changed file with 26 additions and 12 deletions.
38 changes: 26 additions & 12 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,19 +3,18 @@ use std::io::{BufRead, BufReader};

const FILENAME: &str = "data/input.txt";

fn process_lines(reader: impl BufRead) -> anyhow::Result<i64> {
let mut register = 1_i64;
fn process_lines(reader: impl BufRead) -> anyhow::Result<()> {
let mut sprite_column = 1_i64;
let mut cycle = 0_usize;
let cycle_query = [19_usize, 59, 99, 139, 179, 219];
let mut signal_sum = 0;
let mut is_pixel_bright = [false; 240];
for line_result in reader.lines() {
let line = line_result?;
let cost = if "noop" == line { 1 } else { 2 };

for i_cycle in cycle..(cycle + cost) {
if cycle_query.binary_search(&i_cycle).is_ok() {
signal_sum += (1 + i_cycle as i64) * register;
}
is_pixel_bright[i_cycle] = (-1..=1)
.map(|i_sprite| i_sprite + sprite_column)
.any(|i_sprite| (i_cycle as i64 % 40) == i_sprite);
}

cycle += cost;
Expand All @@ -25,11 +24,28 @@ fn process_lines(reader: impl BufRead) -> anyhow::Result<i64> {
.next()
.and_then(|add_str| add_str.parse().ok())
.ok_or_else(|| anyhow::Error::msg("failed to read addend."))?;
register += addend;
sprite_column += addend;
}
}

Ok(signal_sum)
let display_buffer: Vec<char> = is_pixel_bright
.into_iter()
.map(|is_bright| if is_bright { '#' } else { '.' })
.collect();
(0usize..6)
.map(|i_row| {
let i_start = i_row * 40;
let i_end = i_start + 40;
i_start..i_end
})
.for_each(|line_indices| {
println!(
"{}",
display_buffer[line_indices].iter().collect::<String>()
);
});

Ok(())
}

fn main() {
Expand All @@ -38,9 +54,7 @@ fn main() {
Err(err) => {
eprintln!("Could not process file {}:\n {}", FILENAME, err);
}
Ok(n) => {
println!("{}", n);
}
Ok(_n) => {}
},
Err(err) => {
eprintln!("Error opening file {}:\n {}", FILENAME, err);
Expand Down

0 comments on commit 65a6301

Please sign in to comment.