day10_part2.carbon 1.8 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/10
  5. import Core library "io";
  6. import Core library "range";
  7. import library "day10_common";
  8. import library "io_utils";
  9. class PathsToTop {
  10. impl as Core.UnformedInit {}
  11. fn Make(terrain: Terrain) -> PathsToTop {
  12. returned var me: PathsToTop;
  13. for (y: i32 in Core.Range(43)) {
  14. for (x: i32 in Core.Range(43)) {
  15. // TODO: We shouldn't need an explicit cast here.
  16. me.paths[x][y] =
  17. if terrain.height[x][y] == 9 then 1 as i64 else 0;
  18. }
  19. }
  20. return var;
  21. }
  22. fn AddLevel[ref self: Self](terrain: Terrain, level: i32) -> i64 {
  23. var total: i64 = 0;
  24. let adj: array((i32, i32), 4) = ((-1, 0), (0, -1), (1, 0), (0, 1));
  25. for (y: i32 in Core.Range(43)) {
  26. for (x: i32 in Core.Range(43)) {
  27. if (terrain.height[x][y] == level) {
  28. var paths: i64 = 0;
  29. // TODO: for ((adj_x: i32, adj_y: i32) in adj) {
  30. for (i: i32 in Core.Range(4)) {
  31. let adj_x: i32 = x + adj[i].0;
  32. let adj_y: i32 = y + adj[i].1;
  33. if (adj_x >= 0 and adj_x < 43 and
  34. adj_y >= 0 and adj_y < 43 and
  35. terrain.height[adj_x][adj_y] == level + 1) {
  36. paths += self.paths[adj_x][adj_y];
  37. }
  38. }
  39. self.paths[x][y] = paths;
  40. total += paths;
  41. }
  42. }
  43. }
  44. return total;
  45. }
  46. var paths: array(array(i64, 43), 43);
  47. }
  48. fn Run() {
  49. var terrain: Terrain = Terrain.Read();
  50. var paths: PathsToTop = PathsToTop.Make(terrain);
  51. var total: i64;
  52. for (i: i32 in Core.InclusiveRange(0, 8)) {
  53. total = paths.AddLevel(terrain, 8 - i);
  54. }
  55. PrintInt(total);
  56. }