-
Notifications
You must be signed in to change notification settings - Fork 10
/
Day24.cs
95 lines (82 loc) · 2.58 KB
/
Day24.cs
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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
using AdventOfCode.CSharp.Common;
using System;
using System.Collections.Generic;
using System.Numerics;
namespace AdventOfCode.CSharp.Y2015.Solvers;
public class Day24 : ISolver
{
public static void Solve(ReadOnlySpan<byte> input, Solution solution)
{
var weightList = new List<int>();
int totalWeight = 0;
var reader = new SpanReader(input);
while (!reader.Done)
{
int weight = reader.ReadPosIntUntil('\n');
weightList.Add(weight);
totalWeight += weight;
}
int[] weightArr = [.. weightList];
Array.Sort(weightArr);
solution.SubmitPart1(Solve(weightArr, totalWeight / 3));
solution.SubmitPart2(Solve(weightArr, totalWeight / 4));
}
private static BigInteger Solve(int[] weights, int targetWeight)
{
for (int count = 1; count < weights.Length; count++)
{
// Algorithm adapted from the python itertools.combinations documentation
// https://docs.python.org/3/library/itertools.html#itertools.combinations
int[] indices = new int[count];
for (int i = 0; i < count; i++)
{
indices[i] = i;
}
BigInteger? minQE = null;
while (true)
{
bool hasFinished = true;
int i;
for (i = count - 1; i >= 0; i--)
{
if (indices[i] != i + weights.Length - count)
{
hasFinished = false;
break;
}
}
if (hasFinished)
{
break;
}
indices[i]++;
for (int j = i + 1; j < count; j++)
{
indices[j] = indices[j - 1] + 1;
}
int totalWeight = 0;
foreach (int index in indices)
{
totalWeight += weights[index];
}
if (totalWeight == targetWeight)
{
BigInteger qe = 1;
foreach (int index in indices)
{
qe *= weights[index];
}
if (minQE == null || qe < minQE)
{
minQE = qe;
}
}
}
if (minQE != null)
{
return minQE.Value;
}
}
return 0;
}
}