day7_common.carbon 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  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 = a * 10;
  16. b = b / 10;
  17. }
  18. return a + b_val;
  19. }
  20. class Equation {
  21. fn Read() -> Equation {
  22. returned var me: Equation;
  23. me.num_operands = 0;
  24. ReadInt64(&me.result);
  25. ConsumeChar(0x3A);
  26. while (ConsumeChar(0x20)) {
  27. ReadInt64(&me.operands[me.num_operands]);
  28. ++me.num_operands;
  29. }
  30. while (SkipNewline()) {}
  31. return var;
  32. }
  33. fn SolveFrom[self: Self](start: i32, value: i64, concat: bool) -> bool {
  34. if (value > self.result) {
  35. return false;
  36. }
  37. if (start == self.num_operands) {
  38. return value == self.result;
  39. }
  40. return self.SolveFrom(start + 1, value + self.operands[start], concat) or
  41. self.SolveFrom(start + 1, value * self.operands[start], concat) or
  42. (concat and self.SolveFrom(start + 1, Concat(value, self.operands[start]), true));
  43. }
  44. fn Solve[self: Self](concat: bool) -> bool {
  45. return self.SolveFrom(1, self.operands[0], concat);
  46. }
  47. var operands: [i64; 16];
  48. var num_operands: i32;
  49. var result: i64;
  50. }