Skip to content

Commit

Permalink
Day 1 (Part 2)
Browse files Browse the repository at this point in the history
  • Loading branch information
MartinZikmund committed Dec 1, 2023
1 parent d78e572 commit dfef78c
Show file tree
Hide file tree
Showing 5 changed files with 1,083 additions and 0 deletions.
20 changes: 20 additions & 0 deletions Day01_2/Day01_2.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net7.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>

<ItemGroup>
<None Remove="input.txt" />
</ItemGroup>

<ItemGroup>
<Content Include="input.txt">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
</ItemGroup>

</Project>
54 changes: 54 additions & 0 deletions Day01_2/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
var allDigits = new Dictionary<string, int>()
{
{ "one", 1 },
{ "two", 2 },
{ "three", 3 },
{ "four", 4 },
{ "five", 5 },
{ "six", 6 },
{ "seven", 7 },
{ "eight", 8 },
{ "nine", 9 },
};

for (int i = 1; i < 10; i++)
{
allDigits.Add(i.ToString(), i);
}

long total = 0;
while (Console.ReadLine() is { } line)
{
var firstIndex = line.Length;
var lastIndex = -1;
var firstValue = 0;
var lastValue = 0;

foreach (var digit in allDigits)
{
var index = line.IndexOf(digit.Key);
if (index == -1)
{
continue;
}

if (index < firstIndex)
{
firstIndex = index;
firstValue = digit.Value;
}

index = line.LastIndexOf(digit.Key);

if (index > lastIndex)
{
lastIndex = index;
lastValue = digit.Value;
}
}

var fullNumber = firstValue * 10 + lastValue;
total += fullNumber;
}

Console.WriteLine(total);
8 changes: 8 additions & 0 deletions Day01_2/Properties/launchSettings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"profiles": {
"Run": {
"commandName": "Project",
"commandLineArgs": "< input.txt > output.txt"
}
}
}
Loading

0 comments on commit dfef78c

Please sign in to comment.