day 9 part 2
continuous-integration/drone/push Build is passing Details

This commit is contained in:
Ben Harris 2020-12-09 00:57:16 -05:00
parent 3c0cc14d45
commit 298ac825fd
Signed by: ben
GPG Key ID: 4E0AF802FFF7960C
3 changed files with 23 additions and 11 deletions

View File

@ -17,7 +17,7 @@ namespace aoc.tests
[DataRow(typeof(Day06), "6273", "3254")]
[DataRow(typeof(Day07), "169", "82372")]
[DataRow(typeof(Day08), "1654", "833")]
[DataRow(typeof(Day09), "", "")]
[DataRow(typeof(Day09), "138879426", "23761694")]
public void CheckAllDays(Type dayType, string part1, string part2)
{
// create day instance

View File

@ -1,4 +1,3 @@
using System.Collections.Generic;
using System.Linq;
namespace aoc2020
@ -9,6 +8,7 @@ namespace aoc2020
public sealed class Day09 : Day
{
private readonly long[] _list;
private long _part1;
public Day09() : base(9)
{
@ -18,16 +18,27 @@ namespace aoc2020
public override string Part1()
{
var i = 25;
while (_list.Skip(i - 25).Take(25).DifferentCombinations(2).Select(c => c.Sum()).Contains(_list[i]))
{
i++;
}
while (_list.Skip(i - 25).Take(25).Combinations(2).Select(c => c.Sum()).Contains(_list[i])) i++;
_part1 = _list[i];
return $"{_list[i]}";
}
public override string Part2()
{
for (var i = 0; i < _list.Length - 1; i++)
{
var offset = 1;
while (_list.Skip(i).Take(offset).Sum() < _part1) offset++;
var subset = _list.Skip(i).Take(offset).ToArray();
if (subset.Sum() != _part1) continue;
var min = subset.Min();
var max = subset.Max();
return $"{min + max}";
}
return "";
}
}
}
}

View File

@ -14,12 +14,13 @@ namespace aoc2020
: source.Remove(source.LastIndexOf(value, StringComparison.Ordinal));
}
public static IEnumerable<IEnumerable<T>> DifferentCombinations<T>(this IEnumerable<T> elements, int k)
public static IEnumerable<IEnumerable<T>> Combinations<T>(this IEnumerable<T> elements, int k)
{
var enumerable = elements as T[] ?? elements.ToArray();
return k == 0 ? new[] { Array.Empty<T>() } :
enumerable.SelectMany((e, i) =>
enumerable.Skip(i + 1).DifferentCombinations(k - 1).Select(c => (new[] {e}).Concat(c)));
return k == 0
? new[] {Array.Empty<T>()}
: enumerable.SelectMany((e, i) =>
enumerable.Skip(i + 1).Combinations(k - 1).Select(c => new[] {e}.Concat(c)));
}
/// <summary>