首頁 > 後端開發 > Python教學 > AoC &#- Day 仔細考慮(C# 和 Python)

AoC &#- Day 仔細考慮(C# 和 Python)

Linda Hamilton
發布: 2024-12-10 11:42:11
原創
735 人瀏覽過

AoC

仔細考慮一下

今天的挑戰我第一次看到Regex時就尖叫起來,主要是因為每當我看到「提取該字串的一部分」時,Regex就是我的首選;

基本概念與要求

所以我們需要找到所有 mul(number1, number2) 並將它們相乘,但忽略所有其他字元。

所以我們需要找到一個機制來找出所有有效的 mul() 函數宣告。

第1部分

為此,我們可以利用正規表示式的強大功能,使用以下模式

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];
}
登入後複製

第2部分

這增加了稍微複雜的指令,加入了 do() 和 dont() 短語將啟用或停用 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 來幫助學習和提高我現有的 Python 技能 - 因此所有解決方案都將包括 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 &#- Day 仔細考慮(C# 和 Python)的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:dev.to
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板