sandeshsoni

sandeshsoni

Elixir big comprehension-list optimisation - takes too long

Need help! need to optimize.
My terminal hangs when I run the code.

I have a list of 1_78_000 words i.e 178k words

I need pairs of words, such that when joined together, their length is exactly ten.

# this is how I get those 178k words from a file
# do I need to use streams here?
# Its just a txt file with one word per line
def all_words do
    {:ok, content} = File.read("assets/dictionary.txt")
    String.split(content, "\n", trim: true)
end

# Length of individial word must be 3 or more
# two words combined, their length must be exactly 10.
# example: moto + camera = motocamera
# I am sending `all_words` here.
def foo list
    for a <- list, b <-list,
      String.length(a) > 2 && String.length(b) > 2 && String.length(a <> b)==10,
      do: a <> b
end
# do I need to add :into ?

Most Liked

Ankhers

Ankhers

The reason this is taking so long is because you are traversing the list so many times (178,001 which is 31,684,178,000 elements to run through).

When you have that comprehension, you are basically doing the same as

Enum.map(all_words, fn a ->
  Enum.map(all_words, fn b ->
    ...
  end)
end)

So for each element in the list, you are actually traversing the entire list again.

What you may be able to do is reduce the list into a map with the key being the length of the word, and the values in a list. So you may end up with something like

%{
  3 => ["and", "bat"],
  5 => ["apple"]
}

Then you could just merge the numbers that equal 10. This should shrink your runtime a bit. There are probably ways to do this though.

NobbZ

NobbZ

This is how I mean it:

defmodule Glue do
  @list ~w[moto camera foo giraffe stupid thing word brat wurst]

  def pair(list \\ @list), do: list |> Enum.filter(&(String.length(&1) >= 3)) |> pair([])

  def pair([], acc), do: acc |> Enum.into([])
  def pair(list = [word|tail], acc) do
    len = 10 - String.length(word)

    acc = list
    |> Enum.filter(&(String.length(&1) === len))
    |> Enum.flat_map(fn
      other when other === word -> [other <> other]
      other -> [word <> other, other <> word]
    end)
    |> Stream.concat(acc)

    pair(tail, acc)
  end
end

IO.inspect(Glue.pair())

This is just a draft though, and still might have some room for optimisations, but at least it should be of O(n * log n) instead of O(n²).

Eiji

Eiji

Here is how I have generated 178_000 random “words” (just ~r/[a-zA-Z]{1,11}/) with random length from 1 to 11:

file = File.open!("words.txt", [:append])
list = Enum.to_list(?a..?z) ++ Enum.to_list(?A..?Z)

1..178_000 |> Flow.from_enumerable() |> Flow.each(fn _ ->
  length = Enum.random(1..11)
  data = Enum.map(1..length, fn _ -> Enum.random(list) end)
  IO.binwrite(file, data ++ '\n')
end) |> Flow.run()

File.close(file)

From this random input I have received 35_349_451 combinations in average 209 seconds.

Note: This time is much too big as I’m on my “standard” PC usage with web browser, code editor and video player. :slight_smile:

Here is my example code:

defmodule Example do
  require Integer

  @target_length 10

  def sample(path) do
    path
    |> File.stream!()
    |> Flow.from_enumerable()
    |> Flow.reduce(fn -> %{} end, &group/2)
    |> Enum.into(%{})
    |> do_sample()
  end

  defp group(line, acc) do
    word = String.trim(line)
    length = String.length(word)
    if length > @target_length, do: acc, else: Map.update(acc, length, [word], &[word | &1])
  end

  defp do_sample(acc) do
    target_words = Map.get(acc, @target_length) || []
    lengths = Map.keys(acc) -- [5, 10]
    keys = for a <- lengths, b = Enum.find(lengths, &(a + &1 == 10)), not is_nil(b), do: {a, b}
    keys_flow = keys |> Flow.from_enumerable() |> Flow.flat_map(&combine(&1, acc))
    target_words ++ combine_half(acc) ++ Enum.to_list(keys_flow)
  end

  defp combine_half(acc) when Integer.is_even(@target_length) do
    half_length = round(@target_length / 2)
    list = Map.get(acc, half_length) || []
    combine(list)
  end

  defp combine_half(_acc), do: []

  defp combine([]), do: []

  defp combine([head | tail]) do
    tail_flow = tail |> Flow.from_enumerable() |> Flow.map(&(head <> &1))
    Enum.to_list(tail_flow) ++ combine(tail)
  end

  defp combine({a, b}, acc) do
    flow1 = acc |> Map.get(a) |> Flow.from_enumerable()
    flow2 = acc |> Map.get(b) |> Flow.from_enumerable()
    flow1 |> Flow.flat_map(&do_combine(&1, flow2)) |> Enum.to_list()
  end

  defp do_combine(word, flow), do: flow |> Flow.map(&(word <> &1)) |> Enum.to_list()
end

Example.sample("words.txt")

I got previous clause warning, but it’s only because @target_length module attribute is set at compile time. Feel free to modify it as you wish. For sure I believe that it’s definitely possible to write better code - it’s just my typical “5 min” example as I don’t have much time now.

Let me know what do you think about it. :smiley:

Where Next?

Popular in Questions Top

9mm
I am constructing a JSON object (map) and I need to conditionally set a field. I’m trying to write proper elixir-way code… and I’m at a l...
New
senggen
Erlang/OTP 25 [erts-13.2.2] [source] [64-bit] [smp:8:8] [ds:8:8:10] [async-threads:1] 15:22:35.803 [error] gen_event {lager_file_backend...
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
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
fireproofsocks
I’m working on defining a simple Ecto schema for a table (in PostGres), but I don’t see where I can define a column as NOT NULL. Conside...
New
JulienCorb
I am trying to implement my new.html.eex file to create new posts on my website. new.html.eex: &lt;h1&gt;Create Post&lt;/h1&gt; &lt;%= ...
New
stefanchrobot
What’s the safe way to decode a JSON string into a struct? I want to avoid calling String.to_atom. Jason.decode can give me a map with st...
New
JDanielMartinez
Hi! May someone helps me, please! I have two apps into an umbrella project: the first one is Database, which manages queries, and the se...
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
chensan
I have a User schema with a :from_id field set to type :string: defmodule TweetBot.Repo.Migrations.CreateUsers do use Ecto.Migration ...
New

Other popular topics Top

New
mcarvalho
What is the difference between System.get_env and Application.get_env? For example, what are best practices to use one versus another.
New
skosch
To my knowledge, put_in, Map.update etc. all have the one limitation of not automatically creating intermediate keys when needed (for exa...
New
chrismccord
As promised, the first release candidate of Phoenix 1.3.0 is out! This release focuses on code generators with improved project structure...
New
Patoshizzle
After calling mix ecto.create I get this error: 17:00:32.162 [error] GenServer #PID&lt;0.412.0&gt; terminating ** (Postgrex.Error) FATAL...
New
johnnyicon
Hi all, I’ve just started learning Elixir and Phoenix Framework, so please pardon my n00bness at this stage. I’m trying to use Postgres...
New
Fl4m3Ph03n1x
About me? ( if you have nothing better to do than reading about some random guy in the internet :stuck_out_tongue: ) Hello all, this is ...
New
vegabook
I’m brand new to Phoenix and I have stripped one of the demo applications to the bone. I just want to get an svg up on the screen. Here i...
New
grych
Hi folks, Few months ago I have announced the proof-of-concept of the library to manipulate the browsers DOM objects directly from Elixi...
639 52341 488
New
RisingFromAshes
I’ve read in another post that it may be possible with a router helper - but I couldn’t find an appropriate one, and tbh, I’m still just ...
New

We're in Beta

About us Mission Statement