day8_part2.carbon 1.6 KB

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