range-v3
range-v3 copied to clipboard
views::zip_longest Request
I've been trying to learn range-v3 by going through project Euler problems.
I found that I needed a zip_longest view, and managed to steal some code from this blog post https://m-peko.github.io/craft-cpp/posts/zipping-by-the-longest-range/
Therefore, unlike std::transform and Boost library, ranges::v3::view::zip function does not lead us into an Undefined Behavior if input ranges are of different lengths.
So, basically ranges-v3 library solves pretty much all the problems we had with the previous two approaches. But… there might be something missing here… What about zipping by the longest input range?
For example, Python’s itertools module provides such functionality with zip_longest function which makes an iterator that aggregates elements from each of the ranges. If the ranges are of uneven length, missing values are filled-in with the value specified on a function call and iteration continues until the longest range is exhausted. Pretty cool 😎, right?
The specific problem was about computing least common multiples (problem 5)
2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.
What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?
You compute a range of the powers of the prime factorization for each number, and then recursively zip_with std::max
and then accumulate with std::multiplies
.
Feel free to close this, I'm just showing my appreciation, although I do feel a zip_longest view would be very useful.
https://stackoverflow.com/questions/66230792/how-to-emulate-haskells-data-list-transpose-in-c-with-range-v3