day3: optimized p2 and p1

This commit is contained in:
Ishan Jain 2023-12-03 14:21:15 +05:30
parent e54bdefa21
commit 159c41390c
Signed by: ishan
GPG Key ID: 0506DB2A1CC75C27
3 changed files with 21 additions and 20 deletions

View File

@ -43,7 +43,6 @@ fn process(data: &[u8]) -> u64 {
} }
let mut valid = false; let mut valid = false;
'outer: for (a, b) in DIRS.iter() { 'outer: for (a, b) in DIRS.iter() {
let x = i as i32 + a; let x = i as i32 + a;

View File

@ -1,6 +1,6 @@
#![feature(test)] #![feature(test)]
use std::collections::{HashMap, HashSet}; use std::collections::HashSet;
extern crate test; extern crate test;
const INPUTS: [&[u8]; 2] = [ const INPUTS: [&[u8]; 2] = [
@ -30,13 +30,10 @@ fn process(data: &[u8]) -> u64 {
let m = grid.len(); let m = grid.len();
let n = grid[0].len(); let n = grid[0].len();
let mut map = HashMap::with_capacity(200); let mut set = HashSet::with_capacity(2);
for i in 0..m { for i in 0..m {
for j in 0..n { for j in 0..n {
let c = grid[i][j]; if grid[i][j] != b'*' {
if c != b'*' {
continue; continue;
} }
@ -65,26 +62,31 @@ fn process(data: &[u8]) -> u64 {
ey += 1; ey += 1;
} }
let num = String::from_utf8_lossy(&grid[x][sy..ey]) // only insert valid parts in this
.parse::<u64>() if set.len() < 2 {
.unwrap(); set.insert((parse(&grid[x][sy..ey]), sy, ey, x));
}
}
map.entry((i, j)) if set.len() == 2 {
.or_insert_with(HashSet::new) total += set.drain().fold(1, |a, (x, _, _, _)| a * x);
.insert((num, x, sy, ey)); } else {
set.clear();
} }
} }
} }
for v in map.into_values() { total
if v.len() < 2 { }
continue;
}
total += v.into_iter().fold(1, |a, (b, _, _, _)| a * b); fn parse(b: &[u8]) -> u64 {
let mut output = 0;
for (i, v) in b.iter().enumerate() {
output += 10u64.pow(b.len() as u32 - i as u32 - 1) * ((v - b'0') as u64);
} }
total output
} }
fn main() { fn main() {