[TWEAK] Day 3 performance
This commit is contained in:
15
src/day3.rs
15
src/day3.rs
@@ -64,7 +64,7 @@ impl Day3 {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn has_adjacent_symbol(&self, pos: &Coord<usize>, n: &u32) -> bool {
|
fn has_adjacent_symbol(&self, pos: &Coord<usize>, n: u32) -> bool {
|
||||||
let n_len = Self::number_length(n);
|
let n_len = Self::number_length(n);
|
||||||
for y in pos.y.checked_sub(1).unwrap_or(0)..pos.y + 2 {
|
for y in pos.y.checked_sub(1).unwrap_or(0)..pos.y + 2 {
|
||||||
for x in pos.x.checked_sub(1).unwrap_or(0)..pos.x + n_len + 1 {
|
for x in pos.x.checked_sub(1).unwrap_or(0)..pos.x + n_len + 1 {
|
||||||
@@ -86,12 +86,17 @@ impl Day3 {
|
|||||||
|
|
||||||
fn is_adjacent(&self, pos: &Coord<usize>, number: &(Coord<usize>, u32)) -> bool {
|
fn is_adjacent(&self, pos: &Coord<usize>, number: &(Coord<usize>, u32)) -> bool {
|
||||||
|
|
||||||
return pos.x >= number.0.x.checked_sub(1).unwrap_or(0) && pos.x <= number.0.x + Self::number_length(&number.1) &&
|
return pos.x >= number.0.x.checked_sub(1).unwrap_or(0) && pos.x <= number.0.x + Self::number_length(number.1) &&
|
||||||
pos.y >= number.0.y.checked_sub(1).unwrap_or(0) && pos.y <= number.0.y + 1
|
pos.y >= number.0.y.checked_sub(1).unwrap_or(0) && pos.y <= number.0.y + 1
|
||||||
}
|
}
|
||||||
|
|
||||||
fn number_length(n: &u32) -> usize {
|
fn number_length(n: u32) -> usize {
|
||||||
n.to_string().len()
|
if n < 10 { 1 }
|
||||||
|
else if n < 100 { 2 }
|
||||||
|
else if n < 1000 { 3 }
|
||||||
|
else if n < 10000 { 4 }
|
||||||
|
else if n < 100000 { 5 }
|
||||||
|
else { n.to_string().len() }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -102,7 +107,7 @@ impl DaySolver for Day3 {
|
|||||||
// println!("{:?}", self);
|
// println!("{:?}", self);
|
||||||
let mut sum = 0u32;
|
let mut sum = 0u32;
|
||||||
for (pos, n) in &self.numbers {
|
for (pos, n) in &self.numbers {
|
||||||
if self.has_adjacent_symbol(&pos, n) {
|
if self.has_adjacent_symbol(&pos, n.to_owned()) {
|
||||||
sum += n;
|
sum += n;
|
||||||
// } else {
|
// } else {
|
||||||
// println!("No adjacent symbol for {}", n);
|
// println!("No adjacent symbol for {}", n);
|
||||||
|
|||||||
Reference in New Issue
Block a user