Skip to content

Commit 6977c03

Browse files
committed
perf: improve performance of 2018 day 2 part 2
1 parent 558e7a9 commit 6977c03

File tree

1 file changed

+20
-18
lines changed

1 file changed

+20
-18
lines changed

src/year2018/day02.rs

Lines changed: 20 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
//! # Inventory Management System
2-
use crate::util::hash::*;
32
43
pub fn parse(input: &str) -> Vec<&[u8]> {
54
input.lines().map(str::as_bytes).collect()
@@ -44,29 +43,32 @@ pub fn part1(input: &[&[u8]]) -> u32 {
4443
}
4544

4645
pub fn part2(input: &[&[u8]]) -> String {
47-
let width = input[0].len();
46+
// Manually compare all IDs, as it is faster than other methods considering there are so few total IDs
47+
for i in 0..input.len() {
48+
for ii in i + 1..input.len() {
49+
let id1 = input[i];
50+
let id2 = input[ii];
4851

49-
let mut seen = FastSet::with_capacity(input.len());
50-
let mut buffer = [0; 32];
51-
52-
// Use a set to check for duplicates after replacing a single character with '*' in each column.
53-
for column in 0..width {
54-
for &id in input {
55-
buffer[0..width].copy_from_slice(id);
56-
buffer[column] = b'*';
52+
let mut diff = false;
53+
for (a, b) in id1.iter().zip(id2) {
54+
if a != b {
55+
if diff {
56+
diff = false;
57+
break;
58+
}
59+
diff = true;
60+
}
61+
}
5762

58-
if !seen.insert(buffer) {
59-
// Convert to String
60-
return buffer
63+
if diff {
64+
// Build the string of characters which are the same between both IDs
65+
return id1
6166
.iter()
62-
.filter(|&&b| b.is_ascii_lowercase())
63-
.map(|&b| b as char)
67+
.zip(id2)
68+
.filter_map(|(a, b)| if a == b { Some(char::from(*a)) } else { None })
6469
.collect();
6570
}
6671
}
67-
68-
seen.clear();
6972
}
70-
7173
unreachable!()
7274
}

0 commit comments

Comments
 (0)