ホームページ >バックエンド開発 >Python チュートリアル >AoC - 検討する日 (C# と Python)
今日の課題は、最初に Regex を見たときに叫びました。主な理由は、「この文字列の一部を抽出」を見るたびに、Regex が私にとって最適だからです。
基本概念と要件
したがって、すべての mul(number1, number2) を見つけてこれらを乗算する必要がありますが、他の文字はすべて無視します。
したがって、有効な mul() 関数宣言をすべて見つけるメカニズムを見つける必要があります。
これを行うには、次のパターンを使用して正規表現の機能を活用できます
mul([0-9]{1,3},[0-9]{1,3})"
これは、 mul( 0-9 の任意の数値、1 の数値 > 3 回の右括弧に一致します。
mul() の一致を取得したら、再度正規表現を利用して数値を取り出し、解析して合計に加算します。
非常にシンプルで簡単な解決策です。
void Part1() { const string regex = @"mul\([0-9]{1,3},[0-9]{1,3}\)"; var matches = Regex.Matches(input, regex); var total = 0; foreach (Match match in matches) { var numbers = GetNumbers(match); total += numbers[0] * numbers[1]; } } int[] GetNumbers(Match match) { var numbers = Regex.Matches(match.Value, "\d{1,3}"); var a = int.Parse(numbers[0].Value); var b = int.Parse(numbers[1].Value); return [a, b]; }
これにより、少し複雑な命令が追加され、do() および don't() 句によって mil() 関数が有効または無効になるという注意が追加されました。
これに対処する最善の方法は、簡単に思えますが、 do() dont() または mul(number,number
を考慮して正規表現パターンを更新することです。正規表現は、 | を使用して、これらのフレーズのいずれかを検索します。オペレーター。
これらをループし、switch ステートメントを使用して、do、dont、または mil() の一致を調べ、それに応じて有効なフラグを更新します。
次に、乗算して合計に加算する前に、それが mul() であり、isEnabled が True であるかどうかを簡単にチェックします。
以下の両方のソリューションの完全なコード
using System.Text.RegularExpressions; var input = File.ReadAllText("./input1.txt"); // var input = @"xmul(2,4)&mul[3,7]!^don't()_mul(5,5)+mul(32,64](mul(11,8)undo()?mul(8,5))"; Part1(); Part2(); return; void Part1() { const string regex = @"mul\([0-9]{1,3},[0-9]{1,3}\)"; var matches = Regex.Matches(input, regex); var total = 0; foreach (Match match in matches) { var numbers = GetNumbers(match); total += numbers[0] * numbers[1]; } Console.WriteLine("Total: " + total); } void Part2() { const string regex = @"do\(\)|don't\(\)|mul\([0-9]{1,3},[0-9]{1,3}\)"; var matches = Regex.Matches(input, regex); // At the start, mul instructions are enabled var isEnabled = true; var total = 0; // loop over the matches (e.g do(), dont() or mul(x, y) foreach (Match match in matches) { switch (match.Value) { case "do()": isEnabled = true; break; case "don't()": isEnabled = false; break; default: { if (match.Value.StartsWith("mul") && isEnabled) { var numbers = GetNumbers(match); total += numbers[0] * numbers[1]; } break; } } } Console.WriteLine("Total: " + total); } int[] GetNumbers(Match match) { var numbers = Regex.Matches(match.Value, "\d{1,3}"); var a = int.Parse(numbers[0].Value); var b = int.Parse(numbers[1].Value); return [a, b]; }
私のシリーズを初めてご覧になる方のために、繰り返しますが、私は既存の Python スキルの学習と向上を支援するために AoC '24 を使用しています。そのため、すべてのソリューションには C# と Python の両方の試みが含まれます。
同様の概念を使用できますが、Python の言語と関数を活用できます。
import re # Read input from file with open("./input1.txt", "r") as file: input_text = file.read() # Part 1 def part1(): regex = r"mul\(\d{1,3},\d{1,3}\)" matches = re.findall(regex, input_text) total = 0 for match in matches: a, b = get_numbers(match) total += a * b print(f"Total: {total}") # Part 2 def part2(): regex = r"do\(\)|don't\(\)|mul\(\d{1,3},\d{1,3}\)" matches = re.findall(regex, input_text) is_enabled = True # At the start, mul instructions are enabled total = 0 for match in matches: if match == "do()": is_enabled = True elif match == "don't()": is_enabled = False elif match.startswith("mul") and is_enabled: a, b = get_numbers(match) total += a * b print(f"Total: {total}") # Helper function to extract numbers from a match def get_numbers(match): numbers = re.findall(r"\d{1,3}", match) return int(numbers[0]), int(numbers[1]) # Execute parts part1() part2()
いつものように、Twitter で私をフォローするか、Github でその他のソリューションのリポジトリ全体をご覧ください。
以上がAoC - 検討する日 (C# と Python)の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。