AOC2021/AOC2021/Models/Day10/ChunkReader.cs
Alexander Sigler 78ab98234c
All checks were successful
continuous-integration/drone/push Build is passing
Added Day 10 and 11 with test cases
2022-01-31 13:28:15 -08:00

89 lines
2.5 KiB
C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace AOC2021.Models.Day10
{
public class ChunkReader
{
private Stack<char> _stack;
private string _inputLine;
public ChunkReader(string line)
{
this._inputLine = line;
this._stack = new Stack<char>();
}
public ChunkReaderResult Process()
{
var result = new ChunkReaderResult() { Line = this._inputLine };
foreach (char c in this._inputLine)
{
//Implies its an opening char so we sent to stack
if (isOpeningChar(c))
{
_stack.Push(c);
continue;
}
if (_stack.Peek() == GetCorrespondingChar(c))
{
_stack.Pop();
}
else
{
result.CorruptedChar = c;
result.ExpectedChar = GetCorrespondingChar(_stack.Peek());
result.isCorrupted = true;
break;
}
}
if (!result.isCorrupted)
{
if (this._stack.Count == 0)
result.isValid = true;
else
{
result.isIncomplete = true;
while (_stack.Count() > 0)
{
result.CompletionString += GetCorrespondingChar(_stack.Pop());
}
}
}
return result;
}
private bool isOpeningChar(char c)
{
if (c == '(' || c == '[' || c == '{' || c == '<')
return true;
return false;
}
private char GetCorrespondingChar(char c)
{
switch (c)
{
case '(':
return ')';
case '[':
return ']';
case '{':
return '}';
case '<':
return '>';
case ')':
return '(';
case ']':
return '[';
case '}':
return '{';
case '>':
return '<';
}
throw new Exception("Invalid char given, no corresponing char found for: " + c);
}
}
}