Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- var input = await File.ReadAllLinesAsync("input.txt");
- var parsedInput = input
- .Select(line => line.Trim().Split(' ', StringSplitOptions.RemoveEmptyEntries))
- .ToArray();
- var columns = new List<Column>();
- for (var i = 0; i < parsedInput[0].Length; i++)
- {
- var values = parsedInput[..^1].Select((line, idx) => line[i]).ToArray();
- var operation = parsedInput[^1][i][0];
- columns.Add(new Column(values, operation));
- }
- Console.WriteLine($"Part 1: {columns.Sum(col => col.Compute())}");
- columns.Clear();
- var lineLength = input[0].Length;
- var caret = 0;
- var lineCount = input.Length - 1;
- while (caret < lineLength)
- {
- var values = new string[lineCount];
- var segmentLength = 0;
- var endReached = false;
- var isSpace = false;
- //Calculate segment length from bottom row
- while (!endReached)
- {
- if (caret + segmentLength >= lineLength)
- {
- // End of line reached - add one more to align with previous segments
- segmentLength++;
- break;
- }
- var currentChar = input[lineCount][caret + segmentLength];
- if (isSpace && currentChar != ' ')
- {
- endReached = true;
- continue;
- }
- segmentLength++;
- isSpace = currentChar == ' ';
- }
- // Extract segments from each line
- for (var line = 0; line < lineCount; line++)
- {
- values[line] = input[line].Substring(caret, segmentLength - 1);
- }
- var operation = input[lineCount][caret];
- columns.Add(new Column(values, operation));
- caret += segmentLength;
- }
- Console.WriteLine($"Part 2: {columns.Sum(col => col.ComputeRtl())}");
- record struct Column(string[] Values, char Operation)
- {
- public readonly long Compute() => Operation switch
- {
- '+' => Values.Sum(long.Parse),
- '*' => Values.Aggregate(1L, (a, b) => a * long.Parse(b)),
- _ => throw new InvalidOperationException($"Unknown operation: {Operation}")
- };
- public readonly long ComputeRtl()
- {
- var parsedValues = new string[Values[0].Length];
- for (var col = 0; col < Values[0].Length; col++)
- {
- var sb = new System.Text.StringBuilder();
- for (var row = 0; row < Values.Length; row++)
- {
- sb.Append(Values[row][col]);
- }
- parsedValues[col] = sb.ToString().Trim();
- }
- return Operation switch
- {
- '+' => parsedValues.Sum(long.Parse),
- '*' => parsedValues.Aggregate(1L, (a, b) => a * long.Parse(b)),
- _ => throw new InvalidOperationException($"Unknown operation: {Operation}")
- };
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment