I have a list of strings that I want to use construct a new string of n
length. How would I go about randomly selecting an elements from the list, and appending them to the string until I've reached the desired length?
parts = ["hello", "world", "foo bar", "baz"]
n = 25
# Example: "foo bar hello world baz baz"
You need to use Stream
module to generate infinity sequence. One way to do it can be:
Stream.repeatedly(fn -> Enum.random(["hello", "world", "foo bar", "baz"]) end)
|> Enum.take(25)
This is elixir 1.1 due Enum.random/1
. Take a look at Stream
module documentation.
UPDATE 1:
to take chars with same approach:
defmodule CustomEnum do
def take_chars_from_list(list, chars) do
Stream.repeatedly(fn -> Enum.random(list) end)
|> Enum.reduce_while([], fn(next, acc) ->
if String.length(Enum.join(acc, " ")) < chars do
{:cont, [next | acc]}
else
{:halt, Enum.join(acc, " ")}
end
end)
|> String.split_at(chars)
|> elem(0)
end
end
This one strip chars after n
.
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