day10_part2.carbon 1.8 KB

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