AoC Day Red-Nosed Reports (C# and Python)
Today Solution was slighty more complex than the previous day warranting a little more code, but nevertheless was pretty straight forward.
Basic concepts of solution:
In order to be valid, the following conditions for Part 1 must be met:
We need to decide if the numbers are all increasing, or decreasing from one to the next.
the gap between the numbers can't be more than 3
Part 1
var reports = File.ReadAllLines("./input1.txt") .Select(x => x.Split(" ")) .ToList(); Part1(reports); void Part1(List<string[]> input) { var validReports = input .Select(report => report.Select(int.Parse).ToList()) .Count(IsValidReport); Console.WriteLine(validReports); } bool IsValidReport(List<int> levels) { // We don't care about the numbers, just wether going up or down, not both var isIncreasing = IsIncreasing(levels); var isDecreasing = IsDecreasing(levels); if (!isIncreasing && !isDecreasing) return false; // Check that all adjacent levels differ by at least 1 and at most 3 for (var i = 0; i < levels.Count - 1; i++) { var diff = Math.Abs(levels[i + 1] - levels[i]); if (diff is < 1 or > 3) { return false; } } return true; } bool IsIncreasing(List<int> numbers) { for (var i = 1; i < numbers.Count; i++) { if (numbers[i] < numbers[i - 1]) return false; } return true; } bool IsDecreasing(List<int> numbers) { for (var i = 1; i < numbers.Count; i++) { if (numbers[i] > numbers[i - 1]) return false; } return true; }
A simple explanation, is that we use LINQ parse the string numbers to integers before passing the report to our helper IsValidReport() method.
This method checks if all the numbers are either increasing or decreasing. This is done by comparing the ids with an ordered list, that will prove all the numbers are all going in one direction.
Once we know they're all in one direction (not the band) we can check if each number is within 3 numbers of each other. Using the Math.Abs() method, which returns the absolute number, helping us account for minus figures.
Note: an absolute number, is the number between the number and zero, i.e -5 and 5 would both return 5;
Part 2
For Part 2 we had an either slightly more complex instructions, but it sounds harder than it is.
The second part introduces the caveat of human error, with the basic concept that you need to know if you can remove any 1 item from the report and it will still be deemed a valid report.
void Part2(List<string[]> input) { var validReports = 0; foreach (var ints in input.Select(report => report.Select(int.Parse).ToList())) { // If valid as-is, count it if (IsValidReport(ints)) { validReports++; continue; } // Check if removing any single level makes it valid if (ints.Select((t, i) => ints.Where((_, index) => index != i).ToList()) .Any(IsValidReport)) { validReports++; } } Console.WriteLine(validReports); }
Here we're maximising the power of LINQ, parsing the string reports, as well as using it to modify the ints array. We modify by looping through the array and removing the current item at index, thus modifying the array of ints.
Once modified, we run the modified report through the validator. This can be done all in one go using the LINQ Select() method, combined with the Any() which will short circuit as soon as the condition is met (i.e as soon as a modified report is valid).
Why only check for a single valid modified report?
This is because it states if any one item can be removed then the report can be deemed valid. It doesn't say a particular item, so as soon as we find a matching item that when removed means the report is valid, we can stop looking at all the others.
We then increment the validReports counter, to keep track of our reports which are valid.
Here's my attempt at converting this to Python:
def main(): # Read the input file and split each line into a list of strings with open("./input1.txt") as file: reports = [line.split() for line in file] part1(reports) part2(reports) def part1(reports): # Count valid reports using a list comprehension and the IsValidReport function valid_reports = 0 for report in reports: levels = list(map(int, report)) if is_valid_report(levels): valid_reports += 1 print(valid_reports) def part2(reports): valid_reports = 0 for report in reports: ints = list(map(int, report)) # If valid as-is, count it if is_valid_report(ints): valid_reports += 1 continue # Check if removing any single level makes it valid valid_with_dampener = False # Iterate over each element in ints for i in range(len(ints)): # Create a new list without the element at index i modified_report = [x for j, x in enumerate(ints) if j != i] # Check if the modified report is valid if is_valid_report(modified_report): valid_with_dampener = True break if valid_with_dampener: valid_reports += 1 print(valid_reports) def is_valid_report(levels): # Check if the sequence is either all increasing or all decreasing is_increasing = is_increasing_sequence(levels) is_decreasing = is_decreasing_sequence(levels) if not is_increasing and not is_decreasing: return False # Check that all adjacent levels differ by at least 1 and at most 3 for i in range(len(levels) - 1): diff = abs(levels[i + 1] - levels[i]) if diff < 1 or diff > 3: return False return True def is_increasing_sequence(numbers): for i in range(1, len(numbers)): if numbers[i] < numbers[i - 1]: return False return True def is_decreasing_sequence(numbers): for i in range(1, len(numbers)): if numbers[i] > numbers[i - 1]: return False return True if __name__ == "__main__": main()
For a less verbose solution we could replace the Part 2 inner for loop with the modification and checking , like we did with LINQ in the C# solution, like so:
var reports = File.ReadAllLines("./input1.txt") .Select(x => x.Split(" ")) .ToList(); Part1(reports); void Part1(List<string[]> input) { var validReports = input .Select(report => report.Select(int.Parse).ToList()) .Count(IsValidReport); Console.WriteLine(validReports); } bool IsValidReport(List<int> levels) { // We don't care about the numbers, just wether going up or down, not both var isIncreasing = IsIncreasing(levels); var isDecreasing = IsDecreasing(levels); if (!isIncreasing && !isDecreasing) return false; // Check that all adjacent levels differ by at least 1 and at most 3 for (var i = 0; i < levels.Count - 1; i++) { var diff = Math.Abs(levels[i + 1] - levels[i]); if (diff is < 1 or > 3) { return false; } } return true; } bool IsIncreasing(List<int> numbers) { for (var i = 1; i < numbers.Count; i++) { if (numbers[i] < numbers[i - 1]) return false; } return true; } bool IsDecreasing(List<int> numbers) { for (var i = 1; i < numbers.Count; i++) { if (numbers[i] > numbers[i - 1]) return false; } return true; }
But I think you can agree, the verbose method with nicer named variables is much more readable.
Thanks for reading, join me again tomorrow, and as always drop me a follow on twitter
The above is the detailed content of AoC Day Red-Nosed Reports (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 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.

Is it enough to learn Python for two hours a day? It depends on your goals and learning methods. 1) Develop a clear learning plan, 2) Select appropriate learning resources and methods, 3) Practice and review and consolidate hands-on practice and review and consolidate, and you can gradually master the basic knowledge and advanced functions of Python during this period.

Python is better than C in development efficiency, but C is higher in execution performance. 1. Python's concise syntax and rich libraries improve development efficiency. 2.C's compilation-type characteristics and hardware control improve execution performance. When making a choice, you need to weigh the development speed and execution efficiency based on project needs.

Python and C each have their own advantages, and the choice should be based on project requirements. 1) Python is suitable for rapid development and data processing due to its concise syntax and dynamic typing. 2)C is suitable for high performance and system programming due to its static typing and manual memory management.

Pythonlistsarepartofthestandardlibrary,whilearraysarenot.Listsarebuilt-in,versatile,andusedforstoringcollections,whereasarraysareprovidedbythearraymoduleandlesscommonlyusedduetolimitedfunctionality.

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.

Python's applications in scientific computing include data analysis, machine learning, numerical simulation and visualization. 1.Numpy provides efficient multi-dimensional arrays and mathematical functions. 2. SciPy extends Numpy functionality and provides optimization and linear algebra tools. 3. Pandas is used for data processing and analysis. 4.Matplotlib is used to generate various graphs and visual results.

Key applications of Python in web development include the use of Django and Flask frameworks, API development, data analysis and visualization, machine learning and AI, and performance optimization. 1. Django and Flask framework: Django is suitable for rapid development of complex applications, and Flask is suitable for small or highly customized projects. 2. API development: Use Flask or DjangoRESTFramework to build RESTfulAPI. 3. Data analysis and visualization: Use Python to process data and display it through the web interface. 4. Machine Learning and AI: Python is used to build intelligent web applications. 5. Performance optimization: optimized through asynchronous programming, caching and code
