129 lines
2.9 KiB
C#
129 lines
2.9 KiB
C#
// See https://aka.ms/new-console-template for more information
|
|
using AdventCommon;
|
|
|
|
/** P1 **/
|
|
var p1exampleSln = Part01(new AdventCommon.PuzzleInput("example-input.txt"));
|
|
var p1puzzleSln = Part01(new AdventCommon.PuzzleInput("puzzle-input.txt"));
|
|
|
|
Console.WriteLine("Part01 Example Sum: " + p1exampleSln);
|
|
Console.WriteLine("Part01 Puzzle Sum: " + p1puzzleSln);
|
|
|
|
/** P2 **/
|
|
var p2exampleSln = Part02(new AdventCommon.PuzzleInput("example-input-2.txt"));
|
|
var p2puzzleSln = Part02(new AdventCommon.PuzzleInput("puzzle-input.txt"));
|
|
|
|
Console.WriteLine("Part02 Example Sum: " + p2exampleSln);
|
|
Console.WriteLine("Part02 Puzzle Sum: " + p2puzzleSln);
|
|
|
|
int Part01(PuzzleInput input)
|
|
{
|
|
int sum = 0;
|
|
|
|
foreach (var line in input.Lines)
|
|
{
|
|
int num = 0;
|
|
|
|
// Left digit
|
|
for (int i = 0; i < line.Length; i++)
|
|
{
|
|
if (Char.IsDigit(line[i]))
|
|
{
|
|
num += 10 * (line[i] - '0');
|
|
break;
|
|
}
|
|
}
|
|
|
|
// Right digit
|
|
for (int i = line.Length-1; i >= 0; i--)
|
|
{
|
|
if (Char.IsDigit(line[i]))
|
|
{
|
|
num += line[i] - '0';
|
|
break;
|
|
}
|
|
}
|
|
|
|
sum += num;
|
|
}
|
|
|
|
return sum;
|
|
}
|
|
|
|
int Part02(PuzzleInput input)
|
|
{
|
|
int sum = 0;
|
|
|
|
foreach (var line in input.Lines)
|
|
{
|
|
int num = 0;
|
|
|
|
// Left digit
|
|
for (int i = 0; i < line.Length; i++)
|
|
{
|
|
var val = ReadInteger(line, i);
|
|
|
|
if (val != -1)
|
|
{
|
|
num += 10 * val;
|
|
break;
|
|
}
|
|
}
|
|
|
|
// Right digit
|
|
for (int i = line.Length - 1; i >= 0; i--)
|
|
{
|
|
var val = ReadInteger(line, i);
|
|
|
|
if (val != -1)
|
|
{
|
|
num += val;
|
|
break;
|
|
}
|
|
}
|
|
|
|
sum += num;
|
|
}
|
|
|
|
return sum;
|
|
}
|
|
|
|
int ReadInteger(string line, int index)
|
|
{
|
|
// If its a digit, we done
|
|
if (Char.IsDigit(line[index]))
|
|
{
|
|
return line[index] - '0';
|
|
}
|
|
else
|
|
{
|
|
// Ok read string
|
|
int number_index = 1;
|
|
var number = new string[] { "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" };
|
|
|
|
foreach (var num in number)
|
|
{
|
|
if (index + num.Length <= line.Length)
|
|
{
|
|
bool found = true;
|
|
|
|
for (int i = 0; i < num.Length && (index + i) < line.Length; i++)
|
|
{
|
|
if (num[i] != line[index + i])
|
|
{
|
|
found = false;
|
|
break;
|
|
}
|
|
}
|
|
|
|
if (found)
|
|
{
|
|
return number_index;
|
|
}
|
|
}
|
|
|
|
number_index++;
|
|
}
|
|
}
|
|
|
|
return -1;
|
|
} |