day10_part1.carbon 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  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/10
  5. import Core library "io";
  6. import Core library "range";
  7. import library "day10_common";
  8. import library "io_utils";
  9. // TODO: Add this to the prelude.
  10. fn PopCount(n: u256) -> i32 {
  11. var bit: u256 = 1;
  12. var total: i32 = 0;
  13. while (bit != 0) {
  14. if (n & bit != 0) {
  15. ++total;
  16. }
  17. bit <<= 1;
  18. }
  19. return total;
  20. }
  21. class Reachable {
  22. fn Make(terrain: Terrain) -> Reachable {
  23. returned var me: Reachable;
  24. var next: u256 = 1;
  25. for (y: i32 in Core.Range(43)) {
  26. for (x: i32 in Core.Range(43)) {
  27. if (terrain.height[x][y] == 0) {
  28. me.trailheads[x][y] = next;
  29. next <<= 1;
  30. }
  31. }
  32. }
  33. return var;
  34. }
  35. fn AddLevel[ref self: Self](terrain: Terrain, level: i32) {
  36. let adj: array((i32, i32), 4) = ((-1, 0), (0, -1), (1, 0), (0, 1));
  37. for (y: i32 in Core.Range(43)) {
  38. for (x: i32 in Core.Range(43)) {
  39. if (terrain.height[x][y] == level) {
  40. var reach: u256 = 0;
  41. var i: i32 = 0;
  42. while (i < 4) {
  43. let adj_x: i32 = x + adj[i].0;
  44. let adj_y: i32 = y + adj[i].1;
  45. if (adj_x >= 0 and adj_x < 43 and
  46. adj_y >= 0 and adj_y < 43 and
  47. terrain.height[adj_x][adj_y] == level - 1) {
  48. reach = reach | self.trailheads[adj_x][adj_y];
  49. }
  50. ++i;
  51. }
  52. self.trailheads[x][y] = reach;
  53. }
  54. }
  55. }
  56. }
  57. fn Count[self: Self](terrain: Terrain, level: i32) -> i32 {
  58. var total: i32 = 0;
  59. for (y: i32 in Core.Range(43)) {
  60. for (x: i32 in Core.Range(43)) {
  61. if (terrain.height[x][y] == level) {
  62. total += PopCount(self.trailheads[x][y]);
  63. }
  64. }
  65. }
  66. return total;
  67. }
  68. var trailheads: array(array(u256, 43), 43);
  69. }
  70. fn Run() {
  71. var terrain: Terrain = Terrain.Read();
  72. var reachable: Reachable = Reachable.Make(terrain);
  73. for (i: i32 in Core.InclusiveRange(1, 9)) {
  74. reachable.AddLevel(terrain, i);
  75. }
  76. Core.Print(reachable.Count(terrain, 9));
  77. }