aboutsummaryrefslogtreecommitdiff
path: root/2015/src/day24.cpp
diff options
context:
space:
mode:
authorThomas Schmucker <ts@its1.de>2025-01-06 12:33:11 +0100
committerThomas Schmucker <ts@its1.de>2025-01-06 12:33:11 +0100
commit21afde1f9f9e5869775c7c0b0b9e6ceb2d889ef9 (patch)
tree054d21e1de4da22347127e5068e50139c8da78ba /2015/src/day24.cpp
parent43394ea57b4f492b51e8d3492ffe841f1bc0ecc6 (diff)
downloadadvent-of-code-21afde1f9f9e5869775c7c0b0b9e6ceb2d889ef9.tar.gz
advent-of-code-21afde1f9f9e5869775c7c0b0b9e6ceb2d889ef9.tar.bz2
advent-of-code-21afde1f9f9e5869775c7c0b0b9e6ceb2d889ef9.zip
aoc 2015, day 24
Diffstat (limited to '2015/src/day24.cpp')
-rw-r--r--2015/src/day24.cpp76
1 files changed, 76 insertions, 0 deletions
diff --git a/2015/src/day24.cpp b/2015/src/day24.cpp
new file mode 100644
index 0000000..e9966bb
--- /dev/null
+++ b/2015/src/day24.cpp
@@ -0,0 +1,76 @@
1#include <fstream>
2#include <iostream>
3#include <numeric>
4#include <vector>
5using namespace std;
6
7vector<long>
8read_file(string_view filename)
9{
10 fstream input{ filename };
11 return { istream_iterator<long>{ input }, {} };
12}
13
14template<typename Process>
15void
16combination(const vector<long>& values, size_t r, Process process)
17{
18 vector<bool> marker(values.size());
19
20 fill(marker.end() - ptrdiff_t(r), marker.end(), true);
21
22 vector<long> subset(r);
23
24 do {
25 subset.clear();
26 for ( size_t i = 0; i != values.size(); ++i ) {
27 if ( marker[i] ) {
28 subset.emplace_back(values[i]);
29 }
30 }
31 process(subset);
32 } while ( std::next_permutation(marker.begin(), marker.end()) );
33}
34
35void
36solve(const vector<long>& weights, long num)
37{
38 auto totalWeight = accumulate(weights.begin(), weights.end(), 0L);
39 auto groupWeight = totalWeight / num;
40
41 auto min_so_far = numeric_limits<long>::max();
42
43 for ( size_t i = 1; i < weights.size(); ++i ) {
44 combination(weights, i, [&](const vector<long>& subset) {
45 auto subWeight = accumulate(subset.begin(), subset.end(), 0L);
46 if ( subWeight == groupWeight ) {
47 auto product = accumulate(subset.begin(), subset.end(), 1L, multiplies<>());
48 min_so_far = min(min_so_far, product);
49 }
50 });
51 if ( min_so_far != numeric_limits<long>::max() ) {
52 cout << min_so_far << endl;
53 return;
54 }
55 }
56}
57
58void
59part1(const vector<long>& weights)
60{
61 solve(weights, 3);
62}
63
64void
65part2(const vector<long>& weights)
66{
67 solve(weights, 4);
68}
69
70int
71main()
72{
73 auto weights = read_file("data/day24.txt");
74 part1(weights);
75 part2(weights);
76}