summaryrefslogtreecommitdiffstats
path: root/day01/solution.cpp
blob: 86d4efb189691e15575f10f160d3ef9b385ff704 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
#include <print>
#include <vector>
#include <iostream>
#include <algorithm>
#include <ranges>
#include <map>
#include <print>
#include <iostream>
#include <utility>

namespace ranges = std::ranges;
namespace views = std::views;

const auto parse_input() {
  std::pair<std::vector<int>, std::vector<int>> result;

  for (int a, b; std::cin >> a >> b;) {
    result.first.push_back(a);
    result.second.push_back(b);
  }

  return result;
}

void part1(auto input) {
  auto &[A, B] = input;

  ranges::sort(A);
  ranges::sort(B);

  int sum = 0;
  for (const auto& [a, b] : views::zip(A, B)) {
    sum += std::abs(a - b);
  }

  std::println("{}", sum);
}

void part2(auto input) {
  auto &[A, B] = input;
  std::map<int, int> freq_A, freq_B;

  for (auto a : A) {
    freq_A[a]++;
  }
  for (auto b : B) {
    freq_B[b]++;
  }

  int sum = 0;
  for (const auto& [a, b] : freq_A) {
    sum += a * b * freq_B[a];
  }

  std::println("{}", sum);
}

int main() {
  const auto input = parse_input();

#ifndef NO_PART1
  part1(input);
#endif

#ifndef NO_PART2
  part2(input);
#endif
  return 0;
}