Skip to content

Commit cf7450f

Browse files
committed
speedup
1 parent c6a2c93 commit cf7450f

File tree

1 file changed

+14
-15
lines changed

1 file changed

+14
-15
lines changed

2015/Day24/Solution.cs

Lines changed: 14 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
using System;
2+
using System.Collections.Immutable;
23
using System.Collections.Generic;
34
using System.Linq;
45

@@ -15,36 +16,34 @@ int[] Parse(string input) =>
1516
input.Split("\n").Select(int.Parse).ToArray();
1617

1718
long Solve(int[] nums, int groups) {
18-
var minLength = int.MaxValue;
19-
var min = long.MaxValue;
20-
foreach (var part in Pick(nums, 0, nums.Sum() / groups)) {
21-
if (part.c < minLength) {
22-
minLength = part.c;
23-
min = part.mul;
24-
} else if (part.c == minLength) {
25-
min = Math.Min(min, part.mul);
19+
var mul = (ImmutableList<int> l) => l.Aggregate(1L, (m, x) => m*x);
20+
21+
for(var i =0;i<nums.Length;i++) {
22+
var parts = Pick(nums, i, 0, nums.Sum() / groups);
23+
if (parts.Any()){
24+
return parts.Select(mul).Min();
2625
}
2726
}
28-
return min;
27+
throw new Exception();
2928
}
3029

31-
IEnumerable<(int c, long mul)> Pick(int[] nums, int i, int sum) {
30+
IEnumerable<ImmutableList<int>> Pick(int[] nums, int count, int i, int sum) {
3231
if (sum == 0) {
33-
yield return (0, 1);
32+
yield return ImmutableList.Create<int>();
3433
yield break;
3534
}
3635

37-
if (sum < 0 || i >= nums.Length){
36+
if (count < 0 || sum < 0 || i >= nums.Length) {
3837
yield break;
3938
}
4039

4140
if (nums[i] <= sum) {
42-
foreach (var x in Pick(nums, i + 1, sum - nums[i])) {
43-
yield return (x.c + 1, x.mul * nums[i]);
41+
foreach (var x in Pick(nums, count-1, i + 1, sum - nums[i])) {
42+
yield return x.Add(nums[i]);
4443
}
4544
}
4645

47-
foreach (var x in Pick(nums, i + 1, sum)) {
46+
foreach (var x in Pick(nums, count, i + 1, sum)) {
4847
yield return x;
4948
}
5049
}

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy