Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- var timer = System.Diagnostics.Stopwatch.StartNew();
- var input = await File.ReadAllLinesAsync("input.txt");
- var equations = new List<(long Target, long[] Values)>();
- foreach (var line in input)
- {
- var split = line.Split(": ");
- var targetValue = long.Parse(split[0]);
- var values = split[1].Split(' ').Select(long.Parse).ToArray();
- equations.Add((targetValue, values));
- }
- Console.WriteLine($"Parsing done. ({timer.ElapsedMilliseconds}ms)");
- var part1 = equations.Where(equation => IsValid(equation.Target, 0, 0, equation.Values))
- .Sum(equation => equation.Target);
- Console.WriteLine($"Part 1: {part1} ({timer.ElapsedMilliseconds}ms)");
- var part2 = equations.Where(equation => IsValid(equation.Target, 0, 0, equation.Values, true))
- .Sum(equation => equation.Target);
- Console.WriteLine($"Part 2: {part2} ({timer.ElapsedMilliseconds}ms)");
- return;
- bool IsValid(long targetValue, long currentValue, int index, long[] values, bool isPart2 = false)
- {
- if (index == values.Length)
- {
- return currentValue == targetValue;
- }
- if (currentValue > targetValue)
- {
- return false;
- }
- var result = IsValid(targetValue, currentValue + values[index], index + 1, values, isPart2) ||
- IsValid(targetValue, currentValue * values[index], index + 1, values, isPart2);
- if (!isPart2 || result) return result;
- var concat = Concat(currentValue, values[index]);
- result = IsValid(targetValue, concat, index + 1, values, true);
- return result;
- }
- static long Concat(long a, long b)
- {
- var pow = (int)Math.Log10(b) + 1;
- return a * (long)Math.Pow(10, pow) + b;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement