Improved solution

This commit is contained in:
Dreaded_X 2022-12-03 21:09:11 +01:00
parent 0c0c5f183c
commit 1b70661986

View File

@ -49,8 +49,8 @@ impl aoc::Solver for Day {
input.lines() input.lines()
.map(|line| line.split_at(line.len()/2)) .map(|line| line.split_at(line.len()/2))
.map(|(a, b)| { .map(|(a, b)| {
// @NOTE This is not really ok if the string contains multi byte characters // @NOTE This is not really ok if the string contains multi byte characters, this
// @TODO Is there a better way to do this // is however not the case here
for c in a.as_bytes() { for c in a.as_bytes() {
// There is always one character in common between the two sides // There is always one character in common between the two sides
if b.contains(*c as char) { if b.contains(*c as char) {
@ -64,24 +64,23 @@ impl aoc::Solver for Day {
} }
fn part2(input: &str) -> u32 { fn part2(input: &str) -> u32 {
let mut lines = input.lines(); input.lines()
.collect::<Vec<_>>()
// @TODO Is there a beter way to do this conversion, this seems a bit messy .chunks(3)
let mut groups: Vec<(&str, &str, &str)> = Vec::new();
loop {
match (lines.next(), lines.next(), lines.next()) {
(Some(a), Some(b), Some(c)) => groups.push((a, b, c)),
(None, None, None) => break,
_ => panic!("Invalid input"),
}
}
groups.iter()
.map(|group| { .map(|group| {
for c in group.0.as_bytes() { if let [a, b, c] = group {
// There is always one character in common between the two sides (a, b, c)
if group.1.contains(*c as char) && group.2.contains(*c as char) { } else {
return c; panic!("Invalid input")
}
})
.map(|(a, b, c)| {
// @NOTE This is not really ok if the string contains multi byte characters, this
// is however not the case here
for l in a.as_bytes() {
// There is always one character in common between the three rucksacks
if b.contains(*l as char) && c.contains(*l as char) {
return l;
} }
} }
unreachable!("No characters in common, this should never happen") unreachable!("No characters in common, this should never happen")