[Rust Programming] Advent of Code 2023 - Day 3 - Gear Ratios

preview_player
Показать описание
My Rust solution for Day 3 of Advent of Code 2023.

0:00 Problem Description
3:15 Parsing
16:40 Part 1
21:00 Part 1 but Functional
25:40 Part 2

#aoc #adventofcode #adventofcode2023 #rust #rustlang #aoc2023
Рекомендации по теме
Комментарии
Автор

iterators in rust are often faster than loops, especially, if indices are involved in loops (as index checking kicks in most of the time). And variables calculated by iterators can remain immutable. Less explicit local variables are involved. That's why I prefer e.g. a fold operation over a loop any time. Iterators are more easy to reason about, as each iterator step can be discussed separately, there is only one straight forward flow of control through the pipeline.

Not all things may be expressed as iterator pipelines though. Example is the parsing loop: it produces two data collections at once. There is an unzip method that allows this, but it requires to produce a value to add to each collection on every cycle, which isn't the case here. Although the one-pass production hurts the separation of concerns, it's likely more efficient to do it this way (otherwise you would need to iterate over a line of input twice). The only improvement here may be using line.char_indices(), which delivers the same as line.chars().enumerate().

Note that the use of BTreeSet instead of HashSet doubles the execution speed in this case. Hashing is an expensive operation and HashSet's and HashMap's are non-zero-cost-abstractions. BTreeMap's and BTreeSet's less so, although they are not always the better solution (it is depending on the nature of keys resp. values).

And as coordinates are convention, there is no need to worry about negative coordinates. Treat the first line and char as (1, 1) und you are all set.

olafschluter
Автор

i got hung up on placing the let mut cur_number: Option<PartNumber> = None; on the wrong line,
Now it suggests that a number is continous over lines, would that be an edge case? so


234....2

would be 123234, 2 i dont see this specifyed

jimmylarsson
welcome to shbcf.ru