Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Day 9 Advent of Code 2020
using System;
using System.Collections.Generic;
using System.Linq;
using AdventOfCode.Library;
namespace AdventOfCode
{
// Day 9
internal static class Program
{
private static long _xmasKey;
public static void Main()
{
var data = TextUtility.ReadLines(removeBlank: true);
data.Process(true, 1, Solver1);
data.Process(true, 2, Solver2);
}
private static string Solver1(List<string> arg1)
{
var numbers = arg1.Select(a => Convert.ToInt64(a)).ToList();
for (int i = 25; i < arg1.Count; i++)
{
var slice = numbers.Skip(i - 25).Take(25).ToList();
var valid = GetKeys(slice);
if (!valid.Contains(numbers[i]))
{
_xmasKey = numbers[i];
return numbers[i].ToString();
}
}
return "-S1";
}
private static string Solver2(List<string> arg1)
{
var numbers = arg1.Select(a => Convert.ToInt64(a)).ToList();
for (int i = 0; i < numbers.Count; i++)
{
for (int k = 0; k < numbers.Count - i-2; k++)
{
var subset = numbers.Skip(k).Take(i).ToList();
if (_xmasKey == subset.Sum() && subset.Count()>1)
{
var result = subset.Min() + subset.Max();
return $"{result}";
}
}
}
return "-S2";
}
private static HashSet<long> GetKeys(IEnumerable<long> keys)
{
var values = keys.ToList();
var result = new HashSet<long>();
for (int i = 0; i < values.Count; i++)
{
for (int k = 0; k < values.Count; k++)
{
if (i != k)
{
result.Add(values[i] + values[k]);
}
}
}
return result;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment