-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.cs
66 lines (56 loc) · 2.11 KB
/
Solution.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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reactive.Linq;
using System.Text.RegularExpressions;
using Combinatorics.Collections;
using Microsoft.VisualStudio.TestPlatform.ObjectModel;
namespace AdventOfCode2020.Day09
{
internal class Solution
{
private readonly int _preambleSize;
private readonly long[] _data;
private readonly Lazy<long> _invalidNumber;
public Solution(int preambleSize, IEnumerable<string> input)
{
_preambleSize = preambleSize;
_data = input.Select(line => Convert.ToInt64(line)).ToArray();
_invalidNumber = new Lazy<long>(FindInvalidNumber);
}
public long PartOne() => _invalidNumber.Value;
public long PartTwo()
{
var target = _invalidNumber.Value;
var targetIndex = Array.IndexOf(_data, target);
var result = Enumerable.Range(0, targetIndex)
.Select(n => _data.Skip(n))
.Select(values => SelectRangeWithSumNotExceedingTarget(values, target))
.First(values => values.Sum() == target)
.ToList();
return result.Min() + result.Max();
}
private long FindInvalidNumber()
{
var windowSize = _preambleSize + 1;
return _data
.ToObservable()
.Buffer(windowSize, 1)
.ToEnumerable()
.First(data =>
new Combinations<long>(data.SkipLast(1).ToList(), 2)
.All(pair => pair.Sum() != data.Last()))
.Last();
}
private static IEnumerable<long> SelectRangeWithSumNotExceedingTarget(IEnumerable<long> numbers, long target)
{
var rangeWithSum = numbers
.ToObservable()
.Scan(new {Value = 0L, Sum = 0L}, (acc, cur) => new {Value = cur, Sum = acc.Sum + cur});
return rangeWithSum
.TakeWhile(value => value.Sum <= target)
.Select(value => value.Value)
.ToEnumerable();
}
}
}