day8_part2.carbon 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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/8
  5. import Core library "io";
  6. import library "day8_common";
  7. import library "io_utils";
  8. fn MarkAndCount(marks: [[bool; 50]; 50]*, x: i32, y: i32) -> i32 {
  9. if (not (*marks)[x][y]) {
  10. (*marks)[x][y] = true;
  11. return 1;
  12. }
  13. return 0;
  14. }
  15. fn MarkAndCountAntinodesFor(grid: Grid, marks: [[bool; 50]; 50]*, ax: i32, ay: i32) -> i32 {
  16. var count: i32 = 0;
  17. var by: i32 = 0;
  18. while (by < 50) {
  19. var bx: i32 = 0;
  20. while (bx < 50) {
  21. let dx: i32 = bx - ax;
  22. let dy: i32 = by - ay;
  23. if (grid.data[bx][by] != grid.data[ax][ay] or (dx == 0 and dy == 0)) {
  24. ++bx;
  25. continue;
  26. }
  27. var x: i32 = bx;
  28. var y: i32 = by;
  29. while (x >= 0 and x < 50 and y >= 0 and y < 50) {
  30. count += MarkAndCount(marks, x, y);
  31. x += dx;
  32. y += dy;
  33. }
  34. ++bx;
  35. }
  36. ++by;
  37. }
  38. return count;
  39. }
  40. fn MarkAndCountAntinodes(grid: Grid, marks: [[bool; 50]; 50]*) -> i32 {
  41. var count: i32 = 0;
  42. var y: i32 = 0;
  43. while (y < 50) {
  44. var x: i32 = 0;
  45. while (x < 50) {
  46. if (grid.data[x][y] != 0x2E) {
  47. count += MarkAndCountAntinodesFor(grid, marks, x, y);
  48. }
  49. ++x;
  50. }
  51. ++y;
  52. }
  53. return count;
  54. }
  55. fn Run() {
  56. var marks: [[bool; 50]; 50];
  57. var y: i32 = 0;
  58. while (y < 50) {
  59. var x: i32 = 0;
  60. while (x < 50) {
  61. marks[x][y] = false;
  62. ++x;
  63. }
  64. ++y;
  65. }
  66. Core.Print(MarkAndCountAntinodes(Grid.Read(), &marks));
  67. }