Skip to content

Commit 7332c65

Browse files
committed
try to do part2 cleverly but failed
1 parent 506c5cd commit 7332c65

File tree

1 file changed

+14
-15
lines changed

1 file changed

+14
-15
lines changed

2024/day6/src/main.rs

Lines changed: 14 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -32,8 +32,8 @@ fn part1(input: &str) -> usize {
3232
.count()
3333
}
3434

35-
// try to do it without bruteforce
36-
fn _part2_clever(input: &str) -> usize {
35+
// try to do it without bruteforce, but is wrong. gives 2019 instead of 2008
36+
fn part2_clever(input: &str) -> usize {
3737
let directions = [(N, '^'), (E, '>'), (S, 'v'), (W, '<')];
3838
let get_direction = |char: char| directions.iter().find(|(_, c)| char == *c).unwrap().0;
3939
let get_next_direction =
@@ -56,32 +56,24 @@ fn _part2_clever(input: &str) -> usize {
5656
} else {
5757
m[newpos] = m[pos];
5858
pos = newpos;
59-
// if putting a obstruction at the new tile will make the guard join a path he already took
6059
let next_next_direction = get_next_direction(next_direction.1);
6160
for tile in m.in_direction(pos, get_next_direction(m[pos]).0) {
62-
if m[tile] == next_direction.1
63-
|| (m[tile] == next_next_direction.1
64-
&& m[m.move_in_direction(tile, next_direction.0).unwrap()] == '#')
61+
if m[tile] == next_next_direction.1
62+
&& m[m.move_in_direction(tile, next_direction.0).unwrap()] == '#'
6563
{
6664
let move_in_direction = m.move_in_direction(pos, direction).unwrap();
67-
if move_in_direction != start {
65+
if move_in_direction != start && m[move_in_direction] != '#' {
6866
possible_obstructions.insert(move_in_direction);
6967
}
7068
break;
7169
}
7270
}
7371
}
7472
}
75-
for pos in possible_obstructions.iter() {
76-
m[*pos] = 'O'
77-
}
78-
for row in m.iter() {
79-
println!("{}", row.iter().collect::<String>());
80-
}
8173
possible_obstructions.len()
8274
}
8375

84-
// bruteforce but thanks to rayon its still ~250ms to run
76+
// bruteforce but thanks to rayon its still really fast
8577
fn part2(input: &str) -> usize {
8678
let directions = [(N, '^'), (E, '>'), (S, 'v'), (W, '<')];
8779
let get_direction = |char: char| directions.iter().find(|(_, c)| char == *c).unwrap().0;
@@ -129,7 +121,10 @@ fn part2(input: &str) -> usize {
129121
fn main() {
130122
let input = include_str!("../input.txt");
131123
println!("Part 1: {}", part1(input));
132-
println!("Part 2: {}", part2(input));
124+
let p2 = part2(input);
125+
println!("Part 2: {p2}");
126+
assert_eq!(p2, 2008);
127+
assert_eq!(p2, part2_clever(input));
133128
}
134129

135130
#[cfg(test)]
@@ -153,4 +148,8 @@ mod tests {
153148
fn part2() {
154149
assert_eq!(super::part2(INPUT), 6);
155150
}
151+
#[test]
152+
fn part2_clever() {
153+
assert_eq!(super::part2(INPUT), 6);
154+
}
156155
}

0 commit comments

Comments
 (0)