Skip to content

Instantly share code, notes, and snippets.

@gianugo
Created December 10, 2021 06:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gianugo/02741079539a71561344fb60bc48ea9f to your computer and use it in GitHub Desktop.
Save gianugo/02741079539a71561344fb60bc48ea9f to your computer and use it in GitHub Desktop.
using System;
using System.Linq;
using System.Collections.Generic;
namespace Day10
{
class Program
{
static void Main(string[] args)
{
List<char[]> Instructions = new List<char[]>();
List<int> ErrorScoresPart1 = new List<int>();
List<long> ErrorScoresPart2 = new List<long>();
Dictionary<char, char> Delimiters = new Dictionary<char, char>() {
{ '>', '<' },
{ ')', '(' },
{ ']', '[' },
{ '}', '{' }
};
foreach (String line in System.IO.File.ReadLines(@"c:\Temp\day10.txt"))
{
Instructions.Add(line.ToCharArray());
}
List<char[]> IncompleteLines = new List<char[]>();
foreach (char[] Instruction in Instructions)
{
Stack<char> InstructionStack = new Stack<char>();
bool isIncorrect = false;
foreach (char c in Instruction)
{
isIncorrect = false;
if (c == '(' || c == '[' || c == '{' || c == '<')
{
InstructionStack.Push(c);
}
else
{
if (InstructionStack.Peek() == Delimiters[c])
{
InstructionStack.Pop();
}
else
{
isIncorrect = true;
switch (c)
{
case ')':
ErrorScoresPart1.Add(3);
break;
case ']':
ErrorScoresPart1.Add(57);
break;
case '}':
ErrorScoresPart1.Add(1197);
break;
case '>':
ErrorScoresPart1.Add(25137);
break;
}
break;
}
}
}
if (!isIncorrect)
{
IncompleteLines.Add(Instruction);
}
}
foreach (char[] IncompleteInstruction in IncompleteLines)
{
Stack<char> InstructionStack = new Stack<char>();
long ErrorScore = 0;
foreach (char c in IncompleteInstruction)
{
if (c == '(' || c == '[' || c == '{' || c == '<')
{
InstructionStack.Push(c);
}
else
{
if (InstructionStack.Peek() == Delimiters[c])
{
InstructionStack.Pop();
}
}
}
while (InstructionStack.Count > 0)
{
char c1 = InstructionStack.Pop();
switch (c1)
{
case '(':
ErrorScore = (ErrorScore * 5) + 1;
break;
case '[':
ErrorScore = (ErrorScore * 5) + 2;
break;
case '{':
ErrorScore = (ErrorScore * 5) + 3;
break;
case '<':
ErrorScore = (ErrorScore * 5) + 4;
break;
}
}
ErrorScoresPart2.Add(ErrorScore);
}
Console.WriteLine(ErrorScoresPart1.Sum());
Console.WriteLine(ErrorScoresPart2
.OrderBy(x => x)
.ToList()
.ElementAt((int)ErrorScoresPart2.Count / 2));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment