AoC - Day Mull it Over (C# and Python)
Mull it Over
Today's challenge screamed Regex when I first saw it, mainly because whenever I see "extract parts of this string", Regex is my goto;
Basic Concept and Requirements
So we need to find all the mul(number1, number2) and multiply these together, but ignore all other characters.
So we need to find a mechanism to find all the valid mul() function declarations.
Part1
To do this, we can leverage the power of Regex, using the following pattern
mul([0-9]{1,3},[0-9]{1,3})"
Which will match on mul( any number between 0-9 , a number of 1 > 3 times closing bracket.
Once we've got the mul() matches, we can utilise regex again to pull out the numbers, parsing these and adding to the total.
Quite a simple and straightforward solution.
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]; }
Part 2
This added slightly more complicated instructions, adding the caveat that do() and don't() phrases will enable or disable the mil() functions.
The best way to handle this, seemed easy, update the Regex pattern to account for do() dont() or mul(number, number
The Regex will now look for any of these phrases, by using the | oprator.
We can then loop through these and using a switch statemnt decide if we're looking at a do, dont or mil() match, and update the enabled flag accordingly.
It's then a simple check of whether its a mul() and isEnabled is True, before multiplying and adding to the total.
Full Code for both solutions below
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 Solution Attempt
If you're new to my series, i'll re-iterate, I'm using AoC '24 to help learn and improve my existing Python skills - so all solutions will include both C# and Python attempts.
We can use the similar concepts but leverage Pythons language and functions:
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()
As always you can follow me on twitter or view the whole repo for more solutions on Github.
The above is the detailed content of AoC - Day Mull it Over (C# and Python). For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











Python is suitable for data science, web development and automation tasks, while C is suitable for system programming, game development and embedded systems. Python is known for its simplicity and powerful ecosystem, while C is known for its high performance and underlying control capabilities.

You can learn basic programming concepts and skills of Python within 2 hours. 1. Learn variables and data types, 2. Master control flow (conditional statements and loops), 3. Understand the definition and use of functions, 4. Quickly get started with Python programming through simple examples and code snippets.

Python excels in gaming and GUI development. 1) Game development uses Pygame, providing drawing, audio and other functions, which are suitable for creating 2D games. 2) GUI development can choose Tkinter or PyQt. Tkinter is simple and easy to use, PyQt has rich functions and is suitable for professional development.

You can learn the basics of Python within two hours. 1. Learn variables and data types, 2. Master control structures such as if statements and loops, 3. Understand the definition and use of functions. These will help you start writing simple Python programs.

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.

To maximize the efficiency of learning Python in a limited time, you can use Python's datetime, time, and schedule modules. 1. The datetime module is used to record and plan learning time. 2. The time module helps to set study and rest time. 3. The schedule module automatically arranges weekly learning tasks.

Python is widely used in the fields of web development, data science, machine learning, automation and scripting. 1) In web development, Django and Flask frameworks simplify the development process. 2) In the fields of data science and machine learning, NumPy, Pandas, Scikit-learn and TensorFlow libraries provide strong support. 3) In terms of automation and scripting, Python is suitable for tasks such as automated testing and system management.

Python excels in automation, scripting, and task management. 1) Automation: File backup is realized through standard libraries such as os and shutil. 2) Script writing: Use the psutil library to monitor system resources. 3) Task management: Use the schedule library to schedule tasks. Python's ease of use and rich library support makes it the preferred tool in these areas.
