Day 3 Part 1... WOW!!!
This commit is contained in:
@@ -1,3 +1,5 @@
|
||||
use std::collections::HashMap;
|
||||
|
||||
use super::Solution;
|
||||
|
||||
pub struct Day03 {}
|
||||
@@ -5,9 +7,17 @@ pub struct Day03 {}
|
||||
impl Solution for Day03 {
|
||||
fn part1(
|
||||
&self,
|
||||
_input: &mut Vec<String>,
|
||||
input: &mut Vec<String>,
|
||||
) -> Result<Box<dyn std::fmt::Display>, Box<dyn std::error::Error>> {
|
||||
Ok(Box::new("Ready"))
|
||||
// Get data into a byte array
|
||||
let lines = input.iter().map(|s| s.as_bytes()).collect::<Vec<_>>();
|
||||
let mut symbols: HashMap<(usize, usize, char), Vec<usize>> = HashMap::new();
|
||||
|
||||
// Get the valid numbers from the input
|
||||
self.map_valid_nums(&lines, &mut symbols)?;
|
||||
|
||||
let ans: usize = symbols.values().flat_map(|v| v).sum();
|
||||
Ok(Box::new(ans))
|
||||
}
|
||||
|
||||
fn part2(
|
||||
@@ -22,7 +32,60 @@ impl Solution for Day03 {
|
||||
}
|
||||
}
|
||||
|
||||
impl Day03 {}
|
||||
impl Day03 {
|
||||
fn map_valid_nums(
|
||||
&self,
|
||||
lines: &Vec<&[u8]>,
|
||||
symbols: &mut HashMap<(usize, usize, char), Vec<usize>>,
|
||||
) -> Result<(), Box<dyn std::error::Error>> {
|
||||
for (i, line) in lines.iter().enumerate() {
|
||||
let mut c = 0;
|
||||
|
||||
while c < line.len() {
|
||||
let (start, mut symbol) = (c, None);
|
||||
|
||||
while c < line.len() && line[c].is_ascii_digit() {
|
||||
// Coordinate deltas for adjacent checks
|
||||
for (drow, dcol) in [
|
||||
(-1, -1),
|
||||
(-1, 0),
|
||||
(-1, 1),
|
||||
(0, -1),
|
||||
(0, 1),
|
||||
(1, -1),
|
||||
(1, 0),
|
||||
(1, 1),
|
||||
] {
|
||||
let (row, column) =
|
||||
((i as i32 + drow) as usize, (c as i32 + dcol) as usize);
|
||||
|
||||
// Get symbol at adjacent row
|
||||
let Some(&s) = lines.get(row).and_then(|l| l.get(column)) else {
|
||||
continue;
|
||||
};
|
||||
|
||||
if s != b'.' && !s.is_ascii_digit() {
|
||||
symbol = Some((column, row, s as char));
|
||||
break;
|
||||
}
|
||||
}
|
||||
c += 1;
|
||||
}
|
||||
|
||||
if start < c {
|
||||
if let Some(symbol) = symbol {
|
||||
let num = line[start..c]
|
||||
.iter()
|
||||
.fold(0, |n, c| n * 10 + (c - b'0') as usize);
|
||||
symbols.entry(symbol).or_insert(Vec::new()).push(num)
|
||||
}
|
||||
}
|
||||
c += 1;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Test from puzzle input
|
||||
#[cfg(test)]
|
||||
@@ -44,7 +107,7 @@ mod test {
|
||||
.unwrap()
|
||||
.to_string();
|
||||
|
||||
assert_eq!(answer, "Ready");
|
||||
assert_eq!(answer, "4361");
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
Reference in New Issue
Block a user