diff options
author | kaiwu <kaiwu2004@gmail.com> | 2022-05-06 16:43:10 +0800 |
---|---|---|
committer | kaiwu <kaiwu2004@gmail.com> | 2022-05-06 16:43:10 +0800 |
commit | 79a25bdb20f0a9fb958f1edcd6fa525a1a3cfd62 (patch) | |
tree | 6904e508375d130a6e9cd0b4d80a12b293adb85e /src/2021/day7/aoc.cpp | |
parent | 591f81258727537ce8a7a74df5e1de377d85519a (diff) | |
download | advent-of-code-79a25bdb20f0a9fb958f1edcd6fa525a1a3cfd62.tar.gz advent-of-code-79a25bdb20f0a9fb958f1edcd6fa525a1a3cfd62.zip |
2021 day7 part1
Diffstat (limited to 'src/2021/day7/aoc.cpp')
-rw-r--r-- | src/2021/day7/aoc.cpp | 50 |
1 files changed, 50 insertions, 0 deletions
diff --git a/src/2021/day7/aoc.cpp b/src/2021/day7/aoc.cpp index f01daef..6ba7c29 100644 --- a/src/2021/day7/aoc.cpp +++ b/src/2021/day7/aoc.cpp @@ -1,4 +1,54 @@ #include "aoc.h" +#include <map> namespace aoc2021 { +static void get_number(const char** pp, int* d) { + const char* p = *pp; + *d = 0; + while (*p >= '0' && *p <= '9') { + *d = *d * 10 + *p - '0'; + p++; + } + *pp = p; } + +int fuel(int a, const std::map<int, int>& is) { + int total{0}; + for (auto& kv : is) { + if (kv.first != a) { + total += std::abs(a - kv.first) * kv.second; + } + } + return total; +} + +int day7(line_view file) { + std::map<int, int> is; + const char* p1 = file.line; + const char* p2 = p1 + file.length; + int mi{INT32_MAX}; + int mx{INT32_MIN}; + while (p1 < p2) { + if (*p1 >= '0' && *p1 <= '9') { + int d{0}; + get_number(&p1, &d); + mi = std::min(mi, d); + mx = std::max(mx, d); + is[d] += 1; + } + p1++; + } + + int min{INT32_MAX}; + for (int i = mi; i <= mx; i++) { + int f = fuel(i, is); + // printf("%d -> %d\n", i, f); + if (f < min) { + min = f; + } + } + + return min; +} + +} // namespace aoc2021 |