day 18
continuous-integration/drone/push Build is passing
Details
continuous-integration/drone/push Build is passing
Details
This commit is contained in:
parent
433959aae4
commit
8571af616b
|
@ -24,8 +24,8 @@ namespace aoc2020.test
|
|||
[DataRow(typeof(Day14), "17481577045893", "4160009892257")]
|
||||
[DataRow(typeof(Day15), "257", "8546398")]
|
||||
[DataRow(typeof(Day16), "19093", "5311123569883")]
|
||||
[DataRow(typeof(Day18), "", "")]
|
||||
// [DataRow(typeof(Day17), "293", "1816")]
|
||||
[DataRow(typeof(Day18), "12918250417632", "171259538712010")]
|
||||
[DataRow(typeof(Day19), "", "")]
|
||||
[DataRow(typeof(Day20), "", "")]
|
||||
[DataRow(typeof(Day21), "", "")]
|
||||
|
|
|
@ -1,5 +1,7 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
|
||||
namespace aoc2020
|
||||
{
|
||||
|
@ -8,18 +10,72 @@ namespace aoc2020
|
|||
/// </summary>
|
||||
public sealed class Day18 : Day
|
||||
{
|
||||
private readonly List<string> _expressions;
|
||||
|
||||
public Day18() : base(18, "Operation Order")
|
||||
{
|
||||
_expressions = Input.Select(line => line.Replace(" ", "")).ToList();
|
||||
}
|
||||
|
||||
private static long Calculate(string expr, Func<char, int> precedence)
|
||||
{
|
||||
var postfixNotation = new StringBuilder();
|
||||
var postfixStack = new Stack<char>();
|
||||
|
||||
foreach (var c in expr)
|
||||
if (char.IsDigit(c))
|
||||
{
|
||||
postfixNotation.Append(c);
|
||||
}
|
||||
else if (c == '(')
|
||||
{
|
||||
postfixStack.Push(c);
|
||||
}
|
||||
else if (c == ')')
|
||||
{
|
||||
while (postfixStack.Count > 0 && postfixStack.Peek() != '(')
|
||||
postfixNotation.Append(postfixStack.Pop());
|
||||
|
||||
postfixStack.TryPop(out _);
|
||||
}
|
||||
else
|
||||
{
|
||||
while (postfixStack.Count > 0 && precedence(c) <= precedence(postfixStack.Peek()))
|
||||
postfixNotation.Append(postfixStack.Pop());
|
||||
|
||||
postfixStack.Push(c);
|
||||
}
|
||||
|
||||
while (postfixStack.Count > 0)
|
||||
postfixNotation.Append(postfixStack.Pop());
|
||||
|
||||
var expressionStack = new Stack<long>();
|
||||
|
||||
foreach (var c in postfixNotation.ToString())
|
||||
if (char.IsDigit(c))
|
||||
{
|
||||
expressionStack.Push((long) char.GetNumericValue(c));
|
||||
}
|
||||
else
|
||||
{
|
||||
var a = expressionStack.Pop();
|
||||
var b = expressionStack.Pop();
|
||||
|
||||
if (c == '+') expressionStack.Push(a + b);
|
||||
if (c == '*') expressionStack.Push(a * b);
|
||||
}
|
||||
|
||||
return expressionStack.Pop();
|
||||
}
|
||||
|
||||
public override string Part1()
|
||||
{
|
||||
return "";
|
||||
return $"{_expressions.Sum(expr => Calculate(expr, c => c == '+' || c == '*' ? 1 : 0))}";
|
||||
}
|
||||
|
||||
public override string Part2()
|
||||
{
|
||||
return "";
|
||||
return $"{_expressions.Sum(expr => Calculate(expr, c => c switch {'+' => 2, '*' => 1, _ => 0}))}";
|
||||
}
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue