day11_part2.carbon 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  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/11
  5. import Core library "io";
  6. import Core library "range";
  7. import library "day11_common";
  8. import library "io_utils";
  9. class Digits {
  10. fn Make() -> Digits {
  11. returned var me: Digits;
  12. for (digit: i32 in Core.Range(10)) {
  13. for (depth: i32 in Core.Range(75)) {
  14. me.count[digit][depth] = 0;
  15. }
  16. }
  17. return var;
  18. }
  19. fn Print[self: Self](max_depth: i32) {
  20. for (digit: i32 in Core.Range(10)) {
  21. Core.PrintChar(digit + 0x30);
  22. Core.PrintChar(0x3A);
  23. for (depth: i32 in Core.Range(max_depth)) {
  24. Core.PrintChar(0x20);
  25. PrintInt64NoNewline(self.count[digit][depth]);
  26. }
  27. Core.PrintChar(0x0A);
  28. }
  29. Core.PrintChar(0x0A);
  30. }
  31. var count: array(array(i64, 75), 10);
  32. }
  33. fn ReduceToDigits(n: i64, depth: i32, multiplicity: i64, digits: Digits*) -> i64 {
  34. if (n == -1) { return 0; }
  35. if (depth == 0) { return multiplicity; }
  36. if (n < 10) {
  37. let count: i64* = &digits->count[n as i32][depth - 1];
  38. *count += multiplicity;
  39. return 0;
  40. }
  41. let next: (i64, i64) = Next(n);
  42. return ReduceToDigits(next.0, depth - 1, multiplicity, digits) +
  43. ReduceToDigits(next.1, depth - 1, multiplicity, digits);
  44. }
  45. fn Run() {
  46. let max_depth: i32 = 75;
  47. var total: i64 = 0;
  48. var digits: Digits = Digits.Make();
  49. var n: i64;
  50. while (ReadInt64(&n)) {
  51. total += ReduceToDigits(n, max_depth, 1, &digits);
  52. PrintInt64(total);
  53. digits.Print(max_depth - 1);
  54. SkipSpaces();
  55. }
  56. var depth: i32 = max_depth - 1;
  57. while (depth >= 0) {
  58. PrintInt64(total);
  59. digits.Print(depth);
  60. for (digit: i32 in Core.Range(10)) {
  61. let m: i64 = digits.count[digit][depth];
  62. if (m > 0) {
  63. let next: (i64, i64) = Next(digit as i64);
  64. total += ReduceToDigits(next.0, depth, m, &digits) +
  65. ReduceToDigits(next.1, depth, m, &digits);
  66. }
  67. }
  68. --depth;
  69. }
  70. PrintInt64(total);
  71. }