Harrygr

Harrygr

Iterating a list to compare all elements with each other

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?

Most Liked

LostKobrakai

LostKobrakai

You can do the same with recursion:

list = [1, 2, 3, 4]

defmodule Rec do
  def compare(list, acc \\ [])

  def compare([_], acc) do
    acc
    |> Enum.reverse()
    |> List.flatten()
  end

  def compare([cur | rest], acc) do
    compare(rest, [Enum.map(rest, &{cur, &1}) | acc])
  end
end

Rec.compare(list)
# [{1, 2}, {1, 3}, {1, 4}, {2, 3}, {2, 4}, {3, 4}]

And you can look at combinatorics: GitHub - tallakt/comb: Elixir combinatorics - permutations and combinations of lists

LostKobrakai

LostKobrakai

Another option are streams:

list = [1, 2, 3, 4]

stream = 
  Stream.transform(list, list, fn _, [cur | rest] -> 
    {Enum.map(rest, &{cur, &1}), rest}
  end)

Enum.into(stream, [])
# [{1, 2}, {1, 3}, {1, 4}, {2, 3}, {2, 4}, {3, 4}]
gregvaughn

gregvaughn

A for comprehension with two generators from the same source list and a filter can do the job

for x <- list, y <- list, x < y, reduce: 0, do: (best -> max(best, compare(x, y))
benwilson512

benwilson512

Author of Craft GraphQL APIs in Elixir with Absinthe

That is beautiful.

eksperimental

eksperimental

Probably not optimal, but by the look of it I would do:
list |> List.flatten() |> Enum.max_by(...)

Where Next?

Popular in Questions Top

dotdotdotPaul
Okay, I'm having a heck of a time trying to figure out how to best handle the validation of belongs_to associations in Ecto. I'm sure I'...
New
gshaw
What is the idiomatic way of matching for not nil in Elixir? E.g., First way: defp halt_if_not_signed_in(conn, signed_in_account) when...
New
albydarned
Hello all! I am typing this post from my new MacBook Pro with the M1 chip. I’m loving it so far, and will probably use it as my daily dr...
New
New
Harrisonl
We have an ECS cluster with 4 services, where each task joins a single cluster, via discovery ECS discovery service. Currently when I de...
New
Kagamiiiii
Student &amp; New to elixir. Nice language. I want to convert a english character, e.g. “a”, which is stored in a variable, to it’s asci...
New
ashish173
I am using Ecto timestamps with postgres, I can see the timestamps() use the :naive_dateime but for my use case I wanted to store the ti...
New
alice
Hey, Just curious what are the main benefits of Elixir compared to Clojure? When is Elixir more useful than Clojure and vice versa? Th...
New
kostonstyle
Hi all I want to have a unix time, from the current time plus 1 hour. DateTime.now + 1 hour How to get it in elixir? Thanks
New
chrisalley
ExUnit now has describe blocks which is a welcome addition coming from RSpec. In the docs, it states that nested hierarchies of describe ...
New

Other popular topics Top

sergio
In Ruby, I can go: User.find_by(email: "foobar@email.com").update(email: "hello@email.com") How can I do something similar in Elixir? ...
New
vonH
In asking this question I am more interested about the expressiveness of the language itself and less concerned about the availability of...
New
William
I would like to know that is there any online source for learning Phoenix Framework for building E-Commerce Store? Any advantage on build...
New
lessless
I believe there are people here who are dealing with CSV files import on the daily basis, and since Excel is a really popular tool there ...
New
axelson
This post is a wiki (feel free to hit the edit button near the bottom right of this post to add your own changes!) This post collects co...
239 45766 226
New
jononomo
I am trying to figure out how Mix knows whether the environment is test, dev, or prod -- where is this set? Thanks.
New
vertexbuffer
Hello, can anybody help here..? I have a list of players and I what to delete an element, but every for loop the list is reverting to ori...
New
freewebwithme
Using vs code and installed ElixirLS: support and debugger. And I got an error popped up on start up says Failed to run ‘elixir’ comma...
New
baxterw3b
Hi guys, i’m new in the Elixir world, and i have to say, that i love it! i’m having some problem to understand anonymous functions with ...
New
vrod
I am using the Starship cross-shell prompt – it seems pretty nice, but I get some errors: [WARN] - (starship::utils): Executing command ...
New

We're in Beta

About us Mission Statement