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;
'outer: for (a, b) in DIRS.iter() {
let x = i as i32 + a;

View File

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