day1_part2.carbon 722 B

123456789101112131415161718192021222324252627282930313233
  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/1
  5. import Core library "io";
  6. import library "day1_common";
  7. import library "sort";
  8. fn Run() {
  9. var a: array(i32, 1000);
  10. var b: array(i32, 1000);
  11. let n: i32 = ReadInputs(ref a, ref b);
  12. Quicksort(ref a, 0, n);
  13. Quicksort(ref b, 0, n);
  14. var i: i32 = 0;
  15. var j: i32 = 0;
  16. var similarity: i32 = 0;
  17. while (i < n and j < n) {
  18. if (a[i] < b[j]) {
  19. ++i;
  20. } else {
  21. if (a[i] == b[j]) {
  22. similarity += b[j];
  23. }
  24. ++j;
  25. }
  26. }
  27. Core.Print(similarity);
  28. }