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.)
Trending in Questions
Other Trending Topics
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #channels
- #elixirconf
- #exunit
- #discussion
- #code-sync
- #javascript
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixir-ls
- #phoenix_html
- #iex
- #blog-post
- #graphql
- #genstage
- #ai
- #elixirconf-us
- #websockets
- #supervisor
- #advent-of-code
- #distillery
- #processes
- #api
- #forms
- #metaprogramming
- #hex
- #performance










First 10 of 11 Posts
APB9785
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:
This way the function will go through each possibility one-by-one, and immediately stop when a match is found.
dimitarvp
As an aside: filtering is supported out of the box by Elixir’s
forcomprehension:dimitarvp
You can insert one
Stream.takecall in the pipe to enforce a hard limit, like so?dimitarvp
Even though @APB9785’s code is sound and does what it says it does, I am still not sure I understand your requirements. Can you share some more of them? Or ideally a small GitHub projects where you show where are you at currently?
stevensonmt
@APB9785’s solution is a great illustration of what I’m trying to do. I’m trying to check each combination as they’re created and short circuit at the first correct combination. I had it in my head that it should be possible to do with a
Streamof some sort but that recursive approach is fine. The importance of short circuiting is that the set of elements has no predefined boundaries, so there could be up to 3,628,800 possible permutations. Generating those permutations is potentially the bottleneck in the problem as applying the criteria is trivial.This is great, except I cannot know ahead of time that there are only 3 elements in each permutation. So I think I can start with
gen_perms(Enum.take(0..9, perm_len), criteria)and try to make it work. I’ll have to think on it some more.stevensonmt
This is the code I came up with for that approach, but it turns out to actually be slower than generating all the combinations and turning them into a stream for the criteria checks. I’m not sure why.
al2o3cr
Here’s a fully-lazy approach:
This produces results in order of length: all the length-1 permutations, all the length-2, etc
The maximum length of a result in the output is bounded by the length of the input alphabet, since the values cannot appear more than once. The
Stream.take(length(alphabet))makes sure that the calculation terminates; otherwise,all_exactlywill return[]for too-largenand theStream.concatwill iterate forever.thepeoplesbourgeois
You’ll generate the permutations faster with a map
stevensonmt
Thanks for that tip. Because I’m generating permutations of N length from a set of M items I had to change the terminating case from a map size of zero to map size of M - N. It’s about 30% faster than my original version. I also threw in a
Enum.shuffle(M)when generating the permutations. This randomness occasionally leads to another big increase in speed, though it could equally likely lead to a longer search as well. Thanks!Will try to implement this and see how it goes. Thanks for your help!
stevensonmt
I can’t seem to get this to work. The problem is that I don’t want any permutations of the wrong length, so I’d have to introduce a filtering step after generating them all, which seems terribly inefficient. For some reason I’m finding it very difficult to follow how your code works so I don’t know how to adjust it to only return permutations of the desired length.