Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create list with random and unique numbers

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?

like image 561
t56k Avatar asked Dec 14 '22 13:12

t56k


2 Answers

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)
like image 50
t56k Avatar answered Dec 24 '22 08:12

t56k


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]
like image 41
Paweł Dawczak Avatar answered Dec 24 '22 10:12

Paweł Dawczak