仔细考虑一下
今天的挑战我第一次看到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中文网其他相关文章!

theDifferenceBetweewneaforoopandawhileLoopInpythonisthataThataThataThataThataThataThataNumberoFiterationSiskNownInAdvance,而leleawhileLoopisusedWhenaconDitionNeedneedneedneedNeedStobeCheckedStobeCheckedStobeCheckedStobeCheckedStobeceDrepeTysepectients.peatsiveSectlyStheStobeCeptellyWithnumberofiterations.1)forloopsareAceareIdealForitoringercortersence

在Python中,for循环适用于已知迭代次数的情况,而while循环适合未知迭代次数且需要更多控制的情况。1)for循环适用于遍历序列,如列表、字符串等,代码简洁且Pythonic。2)while循环在需要根据条件控制循环或等待用户输入时更合适,但需注意避免无限循环。3)性能上,for循环略快,但差异通常不大。选择合适的循环类型可以提高代码的效率和可读性。

在Python中,可以通过五种方法合并列表:1)使用 运算符,简单直观,适用于小列表;2)使用extend()方法,直接修改原列表,适用于需要频繁更新的列表;3)使用列表解析式,简洁且可对元素进行操作;4)使用itertools.chain()函数,内存高效,适合大数据集;5)使用*运算符和zip()函数,适用于需要配对元素的场景。每种方法都有其特定用途和优缺点,选择时应考虑项目需求和性能。

foroopsare whenthenemberofiterationsisknown,而whileLoopsareUseduntilacTitionismet.1)ForloopSareIdealForeSequencesLikeLists,UsingSyntaxLike'forfruitinFruitinFruitinFruitIts:print(fruit)'。2)'

toConcateNateAlistofListsInpython,useextend,listComprehensions,itertools.Chain,orrecursiveFunctions.1)ExtendMethodStraightForwardButverBose.2)listComprechencomprechensionsareconconconciseandemandeconeandefforlargerdatasets.3)

Tomergelistsinpython,YouCanusethe操作员,estextMethod,ListComprehension,Oritertools

在Python3中,可以通过多种方法连接两个列表:1)使用 运算符,适用于小列表,但对大列表效率低;2)使用extend方法,适用于大列表,内存效率高,但会修改原列表;3)使用*运算符,适用于合并多个列表,不修改原列表;4)使用itertools.chain,适用于大数据集,内存效率高。

使用join()方法是Python中从列表连接字符串最有效的方法。1)使用join()方法高效且易读。2)循环使用 运算符对大列表效率低。3)列表推导式与join()结合适用于需要转换的场景。4)reduce()方法适用于其他类型归约,但对字符串连接效率低。完整句子结束。


热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

Video Face Swap
使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

安全考试浏览器
Safe Exam Browser是一个安全的浏览器环境,用于安全地进行在线考试。该软件将任何计算机变成一个安全的工作站。它控制对任何实用工具的访问,并防止学生使用未经授权的资源。

SublimeText3 英文版
推荐:为Win版本,支持代码提示!

MinGW - 适用于 Windows 的极简 GNU
这个项目正在迁移到osdn.net/projects/mingw的过程中,你可以继续在那里关注我们。MinGW:GNU编译器集合(GCC)的本地Windows移植版本,可自由分发的导入库和用于构建本地Windows应用程序的头文件;包括对MSVC运行时的扩展,以支持C99功能。MinGW的所有软件都可以在64位Windows平台上运行。

mPDF
mPDF是一个PHP库,可以从UTF-8编码的HTML生成PDF文件。原作者Ian Back编写mPDF以从他的网站上“即时”输出PDF文件,并处理不同的语言。与原始脚本如HTML2FPDF相比,它的速度较慢,并且在使用Unicode字体时生成的文件较大,但支持CSS样式等,并进行了大量增强。支持几乎所有语言,包括RTL(阿拉伯语和希伯来语)和CJK(中日韩)。支持嵌套的块级元素(如P、DIV),

Dreamweaver CS6
视觉化网页开发工具