Day 3 part 2

This commit is contained in:
tarneo 2023-12-03 19:34:51 +01:00
parent b7dafd5996
commit 106920df3d
Signed by: tarneo
GPG Key ID: BA924E53D0EB3FCC
1 changed files with 50 additions and 4 deletions

View File

@ -1,6 +1,5 @@
#![feature(let_chains)]
use core::slice;
use std::char;
fn main() {
@ -33,8 +32,8 @@ fn main() {
})
.flatten()
.collect();
let symbols = get_matching_coordinates(|c| c.to_digit(10).is_none() && *c != '.');
let mut symbol_coordinates: Vec<_> = symbols
let symbol_chars = get_matching_coordinates(|c| c.to_digit(10).is_none() && *c != '.');
let mut symbol_coordinates: Vec<_> = symbol_chars
.iter()
.map(|(y, chars)| (y, chars.iter().map(|(x, _)| x).collect::<Vec<_>>()))
.map(|(y, x_s)| x_s.into_iter().map(|x| (y, x)).collect::<Vec<_>>())
@ -54,7 +53,6 @@ fn main() {
})
.flatten()
.collect();
println!("l: {}, c: {}, allowed: {:?}", y, x, allowed_positions);
for p in allowed_positions {
let p: &(&usize, &usize) = &(&p.0, &p.1);
if symbol_coordinates.binary_search(&p).is_ok() {
@ -66,6 +64,54 @@ fn main() {
.map(|(_, _, _, v)| *v)
.collect();
println!("sum: {}", filtered_numbers.iter().sum::<u32>());
let gear_chars = get_matching_coordinates(|c| *c == '*');
let gear_positions: Vec<_> = gear_chars
.iter()
.map(|(y, numbers)| numbers.into_iter().map(|(x, _)| (y, x)).collect::<Vec<_>>())
.flatten()
.collect();
let filtered_gears: Vec<_> = gear_positions
.iter()
.filter_map(|(y, x)| {
let allowed_positions: Vec<_> = (0..3)
.map(|w| {
(0..3)
.map(|v| ((*y + w).checked_sub(1), (*x + v).checked_sub(1)))
.filter(|(y, x)| y.is_some() && x.is_some())
.map(|(y, x)| (y.unwrap(), x.unwrap()))
.collect::<Vec<_>>()
})
.flatten()
.collect();
let mut my_numbers = numbers.clone();
let numbers: Vec<_> = allowed_positions
.iter()
.filter_map(|p| {
let my_numbers_cloned = my_numbers.clone();
let mut rv: Option<u32> = None;
for (i, (ny, nx, nl, nv)) in my_numbers_cloned.iter().enumerate() {
if **ny == p.0 && *nx <= p.1 && nx + nl > p.1 {
my_numbers.remove(i);
rv = Some(*nv);
break;
}
}
rv
})
.collect();
if numbers.len() == 2 {
return Some(numbers);
} else {
return None;
}
})
.collect();
let gear_ratios: Vec<_> = filtered_gears
.iter()
.map(|ab| ab.first().unwrap() * ab.last().unwrap())
.collect();
println!("gear ratio sum: {:?}", gear_ratios.iter().sum::<u32>())
}
fn combine_consecutive(items: &Vec<(usize, String)>) -> Vec<(usize, String)> {