Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Construct a random string of n length from a list using Elixir

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"
like image 1000
Kyle Decot Avatar asked Nov 14 '15 20:11

Kyle Decot


1 Answers

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.

like image 76
Igor Kapkov Avatar answered Nov 01 '22 20:11

Igor Kapkov