day12_part2.carbon 1.8 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/12
  5. import Core library "io";
  6. import Core library "range";
  7. import library "day12_common";
  8. import library "io_utils";
  9. fn CountExtensions(map: Map, regions: DisjointSetForest*) -> array(i32, 140 * 140) {
  10. returned var extensions: array(i32, 140 * 140);
  11. for (i: i32 in Core.Range(140 * 140)) {
  12. extensions[i] = 0;
  13. }
  14. var ext: array({.same: (i32, i32), .adj: (i32, i32)}, 4) = (
  15. {.same = (-1, 0), .adj = (0, -1)},
  16. {.same = (-1, 0), .adj = (0, 1)},
  17. {.same = (0, -1), .adj = (-1, 0)},
  18. {.same = (0, -1), .adj = (1, 0)},
  19. );
  20. for (x: i32 in Core.Range(140)) {
  21. for (y: i32 in Core.Range(140)) {
  22. let kind: i32 = map.At(x, y);
  23. for (e: i32 in Core.Range(4)) {
  24. if (map.At(x + ext[e].same.0, y + ext[e].same.1) == kind and
  25. map.At(x + ext[e].adj.0, y + ext[e].adj.1) != kind and
  26. map.At(x + ext[e].same.0 + ext[e].adj.0,
  27. y + ext[e].same.1 + ext[e].adj.1) != kind) {
  28. ++extensions[regions->Lookup(y * 140 + x)];
  29. }
  30. }
  31. }
  32. }
  33. return var;
  34. }
  35. fn Run() {
  36. var map: Map = Map.Read();
  37. var regions: DisjointSetForest = MakeRegions(map);
  38. var ext: array(i32, 140 * 140) = CountExtensions(map, &regions);
  39. var total: i32 = 0;
  40. for (i: i32 in Core.Range(140 * 140)) {
  41. if (regions.Lookup(i) == i) {
  42. let area: i32 = regions.Weight(i);
  43. let internal_edges: i32 = regions.Unions(i);
  44. let extensions: i32 = ext[i];
  45. let perimeter: i32 = area * 4 - internal_edges * 2 - extensions;
  46. total += area * perimeter;
  47. }
  48. }
  49. Core.Print(total);
  50. }