day11_part2.carbon 2.1 KB

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