I'm trying to make a list of unique, random integers of a certain length.
end_list = for x <- 0..10, do: :rand.uniform(50)
> [41, 9, 8, 50, 49, 1, 1, 7, 7, 47, 20]
What can I write to convey an "if not already present" condition in the do:
block?
I was offered this one-liner using Stream.repeatedly/1
from somewhere else:
Stream.repeatedly(fn -> :rand.uniform(50) end) |> Stream.uniq |> Enum.take(10)
You could use MapSet for it, which will add an element only if it doesn't exist. Then, in the end, you could transform the MapSet to list.
Something like this would work:
ms = for x <- 0..10, into: MapSet.new(), do: :rand.uniform(50)
end_list = MapSet.to_list(ms)
[2, 10, 15, 16, 19, 28, 34, 43, 48]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With