stevensonmt

stevensonmt

Lazily generate permutations

I know how to use comprehensions to generate combinations/permutations:

(for a <- 0..9,
b <- 0..9 |> Enum.reject(&Kernel.==(&1, a)),
c <- 0..9 |> Enum.reject(fn i -> i == a or i == b end),
do:
[a,b,c])
|> apply_criteria()

How would I do this lazily so that I stop generating permutations once I find the one that fulfills some criteria? I tried using Stream.repeatedly:

Stream.repeatedly(Enum.random(0..9))
|> Stream.chunk_every(3)
|> Stream.filter(fn combo -> Enum.uniq(combo) == combo end)
|> apply_criteria()

But this only works in the cases for which there is a permutation that satisfies the criteria. If there is no match it will just go infinitely. In this example I’m using permutations of 3 items, but in the real problem the length of the permutations is variable. The best non lazy approach I’ve come up with generating permutations of variable length is recursive:

def gen_perms(0, combos), do: combos
def gen_perms(len, []) do 
  gen_perms(len - 1, Enum.map(0..9, fn i -> [i] end))
end
def gen_perms(len, combos) do 
  new_combos = 
    for combo <- combos,
      n <- 0..9 |> Enum.filter(fn i -> not Enum.member?(combo, i) end),
    do: [n | combo]

  gen_perms(len - 1, new_combos)
end

(As an aside, in the Stream approach I used the random function to pick the starting digit because there is no reason to suspect that sequential order is going to be the most efficient path, even if in the worst case the randomness leads to never getting all permutations. I have not yet decided if that is a good tradeoff.)

Most Liked

dimitarvp

dimitarvp

As an aside: filtering is supported out of the box by Elixir’s for comprehension:

(for a <- 0..9, b <- 0..9, c <- 0..9, a != b and b != c, do: [a,b,c])
al2o3cr

al2o3cr

If you know the length of the permutation you want, then RecursiveStream.all is doing more computation than you need.

RecursiveStream.all_exactly(alphabet, desired_permutation_length) gives a stream of permutations of a specific length; RecursiveStream.all concatenates those streams for all possible lengths.

APB9785

APB9785

Creator of ECSx

I think you need to go in order, otherwise you won’t know when you have exhausted all possibilities. I would use the recursive approach like such:

def gen_perms(criteria), do: gen_perms({0, 0, 0}, criteria)

def gen_perms({_, _, 10}, criteria), do: {:no_match, criteria}
def gen_perms({a, 10, c}, criteria), do: gen_perms({a, 0, c+1}, criteria)
def gen_perms({10, b, c}, criteria), do: gen_perms({0, b+1, c}, criteria)
def gen_perms({a, b, c}, criteria) do
  if criteria_match?({a, b, c}, criteria) do
    {:ok, {a, b, c}, criteria}
  else
    gen_perms({a+1, b, c}, criteria)
  end
end

This way the function will go through each possibility one-by-one, and immediately stop when a match is found.

Where Next?

Popular in Questions Top

siddhant3030
Hi, I have to write a raw query for one of my project. But till now I have used ecto queries and don’t have much experience writing raw ...
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
myronmarston
The Elixir Typespec docs show the following syntax for keyword lists in typespecs: # ... | [key: type] # keyword lists...
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
shahryarjb
Hello, I have map which I want to convert it to string like this: the map: %{last_name: "tavakkoli", name: "shahryar"} the string I ne...
New
shahryarjb
Hello, I get Persian date from my client and convert it to normal calendar like this: def jalali_string_to_miladi_english_number(persi...
New
jerry
Good day to you all. I have been struggling to get a query involving like and ilike to work. Can anyone assist me on this, please? pro...
New
hariharasudhan94
lets say i have a sample like a = 20; b = 10; if (a &gt; b) do {:ok, "a"} end if (a &lt; b) do {:ok, b} end if (a == b) do {:ok, "equa...
New
aalberti333
As the title describes, I’m trying to run Enum.map() over a list of key/value pairs, where the value is a map. My data looks like this: ...
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

Other popular topics Top

AstonJ
Posting this to see if we can make things easier for people to get into Neovim. If you use Neovim and have a favourite distro please let ...
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
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
hariharasudhan94
lets say i have a sample like a = 20; b = 10; if (a &gt; b) do {:ok, "a"} end if (a &lt; b) do {:ok, b} end if (a == b) do {:ok, "equa...
New
AngeloChecked
What learn first? Rust or Elixir Hi Elixir community! I’m here because i want learn a new language. I’m a junior developer and mainly i ...
New
Emily
I have VueJS GUIs with the project generated using Webpack. I have Elixir modules that will need to be used by the VueJS GUIs. I forese...
New
vonH
When I run the Plug and I recompile I wind up having to use Ctrl C to quit iex and start again. Witht the help of rlwrap I can use the cu...
New
gausby
I asked this very same question on twitter and got some interesting feedback, but I thought it would be a good question to ask here as we...
1207 39297 209
New
dblack
I’ve got an issue with an app and I’ve no idea of how to troubleshoot it. I’m hoping someone here might have seen something similar. I p...
New
jononomo
For some reason my phoenix channels are working for me in my local dev environment, but as soon as I deploy via Docker, I get a 403 error...
New

We're in Beta

About us Mission Statement