day6_part2.carbon 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. // Part of the Carbon Language project, under the Apache License v2.0 with LLVM
  2. // Exceptions. See /LICENSE for license information.
  3. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  4. // https://adventofcode.com/2024/day/6
  5. import Core library "io";
  6. import library "day6_common";
  7. class LoopDetector {
  8. fn Make() -> LoopDetector {
  9. return {.last = ((-1, -1), (-1, -1)), .steps = 1, .next_steps = 1};
  10. }
  11. fn Check[ref self: Self](next: ((i32, i32), (i32, i32))) -> bool {
  12. // TODO: if (next == self.last) {
  13. if (next.0.0 == self.last.0.0 and next.0.1 == self.last.0.1 and
  14. next.1.0 == self.last.1.0 and next.1.1 == self.last.1.1) {
  15. return true;
  16. }
  17. --self.steps;
  18. if (self.steps == 0) {
  19. self.steps = self.next_steps;
  20. self.next_steps <<= 1;
  21. self.last = next;
  22. }
  23. return false;
  24. }
  25. var last: ((i32, i32), (i32, i32));
  26. var steps: i32;
  27. var next_steps: i32;
  28. }
  29. fn AddingObstacleMakesALoop(position: Maze) -> bool {
  30. var maze: Maze = position.Copy();
  31. var loop: LoopDetector = LoopDetector.Make();
  32. if (not maze.AddObstacle()) {
  33. return false;
  34. }
  35. while (maze.Step()) {
  36. if (loop.Check((maze.loc, maze.dir))) {
  37. return true;
  38. }
  39. }
  40. return false;
  41. }
  42. fn Run() {
  43. var maze: Maze = Maze.Read();
  44. var loops: i32 = 0;
  45. while (true) {
  46. if (AddingObstacleMakesALoop(maze)) {
  47. ++loops;
  48. }
  49. if (not maze.Step()) {
  50. break;
  51. }
  52. }
  53. Core.Print(loops);
  54. }