day 9 part 2
continuous-integration/drone/push Build is passing
Details
continuous-integration/drone/push Build is passing
Details
This commit is contained in:
parent
3c0cc14d45
commit
298ac825fd
|
@ -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
|
||||
|
|
|
@ -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 "";
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
|
@ -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>
|
||||
|
|
Loading…
Reference in New Issue