In imperative languages, if one wants to compare every element in an array with the other they can use nested loops where the inner loop starts from the iterator of the outer loop. This avoids comparing elements with each other twice.
E.g.
int best = 0
for (int i = 0; i < a.length; i++) {
for (int k = i + 1; k < a.length; k++) {
best = max(best, compare(a[i], a[k]))
}
}
In Elixir, say I wanted to compare every value in a list with the others and find the best score (according to some arbritrary comparison) I could do something like
Enum.reduce(big_list_of_things, 0, fn
a, best ->
max(
best,
Enum.reduce(big_list_of_things, fn b, inner_best -> max(inner_best, compare(a, b)) end)
)
end)
This works, but involves iterating more times than needed (On^2). How might one refactor this so the inner iteration only reduces over what’s left?
The problem here is about finding best score from all combinations of 2 items in list (nc2) - @LostKobrakai’s Post -#3 and Post 4 are generating these combinations of 2.