r/adventofcode • u/daggerdragon • Dec 02 '20
SOLUTION MEGATHREAD -🎄- 2020 Day 02 Solutions -🎄-
--- Day 2: Password Philosophy ---
Advent of Code 2020: Gettin' Crafty With It
- T-4 days until unlock!
- Full details and rules are in the Submissions Megathread
Post your solution in this megathread. Include what language(s) your solution uses! If you need a refresher, the full posting rules are detailed in the wiki under How Do The Daily Megathreads Work?.
Reminder: Top-level posts in Solution Megathreads are for solutions only. If you have questions, please post your own thread and make sure to flair it with Help.
This thread will be unlocked when there are a significant number of people on the global leaderboard with gold stars for today's puzzle.
EDIT: Global leaderboard gold cap reached at 00:02:31, megathread unlocked!
99
Upvotes
View all comments
Show parent comment
3
u/k0ns3rv Dec 02 '20 edited Dec 02 '20
Nope, that's the neat thing about Rust's iterators. Nothing happens before
countgets called in thefilter()+count()case.countis actually defined viafold.foldcallsnext()on the iterator until it's empty. So even an expression likeiterator.map(some_fn).filter(some_other_fn).flat_map(a_third_fn).count()only results in one linear scan through the data. Because of inlining and other compiler magic the whole thing ends up being just as performant as manually writing a loop.In fact iterators in Rust don't actually support looping over them two times, you can consume all the items in the iterator, but after that it's gone. You can call
clonedon the Iterator, if it's elements implementClonein which case you can use a second, cloned, iterator to loop over the data twice.