I need to traverse a list and do some calculations with every element and the elements excluding that element. For example, having a list (1 2 3 1), I need pairs (1) (2 3 1), (2) (1 3 1), (3) (1 2 1) and (1) (2 3 1).
I need to traverse a list and do some calculations with every element and
Share
With every element sounds like a
map. Excluding that element sounds like afilter. Let’s start with the latter.Great. Now let’s try to map it over all elements.
Creating actual pairs is left as an exercise for the reader. Hint: modify the closure used in
map.Keep in mind that the solution suggested above should work fine for short lists but it has a complexity of O(n²). Another issue is the fact that collections with duplicates aren’t handled correctly.
Let’s take a recursive approach instead. We’ll base the recursion on
loopandrecur.A trivial example:
A vector with duplicates: