day10_part1.carbon 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  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. impl as Core.UnformedInit {}
  23. fn Make(terrain: Terrain) -> Reachable {
  24. returned var me: Reachable;
  25. var next: u256 = 1;
  26. for (y: i32 in Core.Range(43)) {
  27. for (x: i32 in Core.Range(43)) {
  28. if (terrain.height[x][y] == 0) {
  29. me.trailheads[x][y] = next;
  30. next <<= 1;
  31. }
  32. }
  33. }
  34. return var;
  35. }
  36. fn AddLevel[ref self: Self](terrain: Terrain, level: i32) {
  37. let adj: array((i32, i32), 4) = ((-1, 0), (0, -1), (1, 0), (0, 1));
  38. for (y: i32 in Core.Range(43)) {
  39. for (x: i32 in Core.Range(43)) {
  40. if (terrain.height[x][y] == level) {
  41. var reach: u256 = 0;
  42. var i: i32 = 0;
  43. while (i < 4) {
  44. let adj_x: i32 = x + adj[i].0;
  45. let adj_y: i32 = y + adj[i].1;
  46. if (adj_x >= 0 and adj_x < 43 and
  47. adj_y >= 0 and adj_y < 43 and
  48. terrain.height[adj_x][adj_y] == level - 1) {
  49. reach = reach | self.trailheads[adj_x][adj_y];
  50. }
  51. ++i;
  52. }
  53. self.trailheads[x][y] = reach;
  54. }
  55. }
  56. }
  57. }
  58. fn Count[self: Self](terrain: Terrain, level: i32) -> i32 {
  59. var total: i32 = 0;
  60. for (y: i32 in Core.Range(43)) {
  61. for (x: i32 in Core.Range(43)) {
  62. if (terrain.height[x][y] == level) {
  63. total += PopCount(self.trailheads[x][y]);
  64. }
  65. }
  66. }
  67. return total;
  68. }
  69. var trailheads: array(array(u256, 43), 43);
  70. }
  71. fn Run() {
  72. var terrain: Terrain = Terrain.Read();
  73. var reachable: Reachable = Reachable.Make(terrain);
  74. for (i: i32 in Core.InclusiveRange(1, 9)) {
  75. reachable.AddLevel(terrain, i);
  76. }
  77. Core.Print(reachable.Count(terrain, 9));
  78. }