Skip to content

Commit ad63a58

Browse files
committed
Refactored line reading, refs #4
1 parent f37b6b8 commit ad63a58

File tree

1 file changed

+32
-28
lines changed

1 file changed

+32
-28
lines changed

day_03_part_2/src/main.rs

Lines changed: 32 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -12,39 +12,43 @@ fn main() -> io::Result<()> {
1212
let mut lines = reader.lines();
1313
let mut found_char = 'X';
1414

15-
while let Some(Ok(line1)) = lines.next() {
16-
if let Some(Ok(line2)) = lines.next() {
17-
if let Some(Ok(line3)) = lines.next() {
18-
// What character is present in all three lines?
19-
let mut found = false;
20-
for c1 in line1.chars() {
21-
for c2 in line2.chars() {
22-
for c3 in line3.chars() {
23-
if c1 == c2 && c2 == c3 {
24-
found = true;
25-
found_char = c1;
26-
}
27-
}
28-
if found {
29-
break;
30-
}
31-
}
32-
if found {
33-
break;
15+
loop {
16+
// Try this but break if it is an error:
17+
let line1 = match lines.next() {
18+
Some(Ok(line)) => line,
19+
_ => break,
20+
};
21+
let line2 = lines.next().unwrap()?;
22+
let line3 = lines.next().unwrap()?;
23+
24+
// What character is present in all three lines?
25+
let mut found = false;
26+
for c1 in line1.chars() {
27+
for c2 in line2.chars() {
28+
for c3 in line3.chars() {
29+
if c1 == c2 && c2 == c3 {
30+
found = true;
31+
found_char = c1;
3432
}
3533
}
3634
if found {
37-
let priority = match found_char {
38-
'a'..='z' => found_char as u8 - 'a' as u8 + 1,
39-
'A'..='Z' => found_char as u8 - 'A' as u8 + 27,
40-
_ => 0,
41-
} as i32;
42-
score += priority;
43-
} else {
44-
// Quit with error
45-
panic!("No character found that was in all 3 lines");
35+
break;
4636
}
4737
}
38+
if found {
39+
break;
40+
}
41+
}
42+
if found {
43+
let priority = match found_char {
44+
'a'..='z' => found_char as u8 - 'a' as u8 + 1,
45+
'A'..='Z' => found_char as u8 - 'A' as u8 + 27,
46+
_ => 0,
47+
} as i32;
48+
score += priority;
49+
} else {
50+
// Quit with error
51+
panic!("No character found that was in all 3 lines");
4852
}
4953
}
5054
println!("{}", score);

0 commit comments

Comments
 (0)