Skip to content

Commit 845d760

Browse files
committed
refactor: revert back to the original approach - but only insert the prefix and suffix of IDs into the hashset
1 parent f6c50ce commit 845d760

File tree

1 file changed

+17
-23
lines changed

1 file changed

+17
-23
lines changed

src/year2018/day02.rs

Lines changed: 17 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
//! # Inventory Management System
22
3+
use crate::util::hash::*;
4+
35
pub fn parse(input: &str) -> Vec<&[u8]> {
46
input.lines().map(str::as_bytes).collect()
57
}
@@ -43,33 +45,25 @@ pub fn part1(input: &[&[u8]]) -> u32 {
4345
}
4446

4547
pub fn part2(input: &[&[u8]]) -> String {
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];
48+
let width = input[0].len();
5149

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-
}
50+
let mut seen = FastSet::with_capacity(input.len());
6251

63-
if diff {
64-
// Build the string of characters which are the same between both IDs
65-
return id1
66-
.iter()
67-
.zip(id2)
68-
.filter(|&(a, b)| a == b)
69-
.map(|(a, _)| char::from(*a))
70-
.collect();
52+
// Use a set to check for duplicates by comparing the prefix and suffix of IDs excluding one
53+
// column at a time.
54+
for column in 0..width {
55+
for &id in input {
56+
let prefix = &id[..column];
57+
let suffix = &id[column + 1..];
58+
59+
if !seen.insert([prefix, suffix]) {
60+
// Convert to String
61+
return prefix.iter().chain(suffix).cloned().map(char::from).collect();
7162
}
7263
}
64+
65+
seen.clear();
7366
}
67+
7468
unreachable!()
7569
}

0 commit comments

Comments
 (0)