Harrygr

Harrygr

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?

Showing Posts 1 to 6

kartheek

kartheek

You are trying to find the max from a list?

Below code achieves the same thing

[first | rest] = big_list_of_things
Enum.reduce(rest, first, fn x, acc ->
  case x > acc do
    true ->
      x
    false ->
      acc
  end
end)

Enum.max/2 and Enum.max_by/4 can do the same.


Edit: Sorry, I got it all wrong.

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.

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 · GitHub

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}]
benwilson512

benwilson512

Author of Craft GraphQL APIs in Elixir with Absinthe

That is beautiful.

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))
eksperimental

eksperimental

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

— All posts loaded —

Where Next? Top

Trending in Questions Top

RSP87
I’m working on a project that simulates the bumbl example in the programming phoenix book. It acts almost like an email client. We have a...
New
nseaSeb
Hello, I know there is an approach for handling lists that allows for optimized traversal, but I can’t recall the specific method (somet...
New
RemyXRenard
I’m seeing that a list inside a Kino.DataTable will be interpreted as a charlist, even if the Kino.configure() is set to charlists: :as_l...
New
velrest
So my question is quite simple and i have found no conclusive answer on forum, google or AI. Should we use :erlang.float for Integer to ...
New
brecabral
Documentation While reading the Scoped Routes section, I noticed that the documentation currently refers to a problem without explainin...
New
samoloth
Hi, I’ve just set up an application with ash_authentication. There is only magic link strategy for now, so there is no confirmation add o...
New
FlyingNoodle
If a change or preparation module uses Ash.Changeset.get_argument/2 or Ash.Query.get_argument/2 (or any of the other get_argument functio...
New

Other Trending Topics Top

mudasobwa
I am happy to introduce the very α version of the new programming language compiled to BEAM. Welcome Cure. It has literally three kille...
New
marciok
Hi there! We created Gust: A task orchestrator inspired by Airflow. For those who have never heard about Aiflow, it’s a Python-based wor...
New
jimsynz
Beam Bots (or just BB for short) is a framework for building fault-tolerant robotics applications in Elixir using familiar OTP patterns. ...
New
Dmk
Xamal is a deployment tool for Elixir apps that deploys native releases to bare metal servers over SSH. It’s a port of GitHub - basecamp/...
New
netoum
Corex is an accessible, unstyled UI component library for Phoenix that integrates Zag.js state machines using Vanilla JavaScript and Live...
New
webofbits
With AI doing more of the implementation work, I’ve been wondering how much coding I should deliberately keep doing myself. My main conc...
#ai
New

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews