Advertisement
Lyuben_Andreev

AdventOfCode2023Part1Part2

Feb 15th, 2025
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.56 KB | Source Code | 0 0
  1. using System;
  2. using System.IO;
  3. using System.Linq;
  4. using System.Text.RegularExpressions;
  5.  
  6. namespace AdventOfCodeDay1
  7. {
  8.     class Solution
  9.     {
  10.         public object PartOne(string input) =>
  11.             Solve(input, @"\d");
  12.  
  13.         public object PartTwo(string input) =>
  14.             Solve(input, @"\d|one|two|three|four|five|six|seven|eight|nine");
  15.  
  16.         int Solve(string input, string rx) => (
  17.             from line in input.Split("\n")
  18.             let first = Regex.Match(line, rx)
  19.             let last = Regex.Match(line, rx, RegexOptions.RightToLeft)
  20.             select ParseMatch(first.Value) * 10 + ParseMatch(last.Value)
  21.         ).Sum();
  22.  
  23.         int ParseMatch(string st) => st switch
  24.         {
  25.             "one" => 1,
  26.             "two" => 2,
  27.             "three" => 3,
  28.             "four" => 4,
  29.             "five" => 5,
  30.             "six" => 6,
  31.             "seven" => 7,
  32.             "eight" => 8,
  33.             "nine" => 9,
  34.             var d => int.Parse(d)
  35.         };
  36.     }
  37.  
  38.     class Program
  39.     {
  40.         static void Main(string[] args)
  41.         {
  42.             string filePath = "input.txt";
  43.  
  44.             if (!File.Exists(filePath))
  45.             {
  46.                 Console.WriteLine("Файлът input.txt не е намерен!");
  47.                 return;
  48.             }
  49.  
  50.             string input = File.ReadAllText(filePath);
  51.             var solution = new Solution();
  52.  
  53.             Console.WriteLine($"Part One: {solution.PartOne(input)}");
  54.             Console.WriteLine($"Part Two: {solution.PartTwo(input)}");
  55.         }
  56.     }
  57. }
  58.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement