day7_common.carbon 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  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/7
  5. library "day7_common";
  6. import Core library "io";
  7. import library "io_utils";
  8. fn Concat(a_val: i64, b_val: i64) -> i64 {
  9. var a: i64 = a_val;
  10. var b: i64 = b_val;
  11. if (b == 0) {
  12. return a * 10;
  13. }
  14. while (b != 0) {
  15. a *= 10;
  16. b /= 10;
  17. }
  18. return a + b_val;
  19. }
  20. class Equation {
  21. impl as Core.UnformedInit {}
  22. fn Read() -> Equation {
  23. returned var me: Equation;
  24. me.num_operands = 0;
  25. ReadInt(ref me.result);
  26. ConsumeChar(':');
  27. while (ConsumeChar(' ')) {
  28. ReadInt(ref me.operands[me.num_operands]);
  29. ++me.num_operands;
  30. }
  31. while (SkipNewline()) {}
  32. return var;
  33. }
  34. fn SolveFrom[self: Self](start: i32, value: i64, concat: bool) -> bool {
  35. if (value > self.result) {
  36. return false;
  37. }
  38. if (start == self.num_operands) {
  39. return value == self.result;
  40. }
  41. return self.SolveFrom(start + 1, value + self.operands[start], concat) or
  42. self.SolveFrom(start + 1, value * self.operands[start], concat) or
  43. (concat and self.SolveFrom(start + 1, Concat(value, self.operands[start]), true));
  44. }
  45. fn Solve[self: Self](concat: bool) -> bool {
  46. return self.SolveFrom(1, self.operands[0], concat);
  47. }
  48. var operands: array(i64, 16);
  49. var num_operands: i32;
  50. var result: i64;
  51. }