Build a random string of n lengths from a list using Elixir

I have a list of strings that I want to use to build a new length string n. How can I randomly select items from a list and add them to a string until I reach the desired length?

parts = ["hello", "world", "foo bar", "baz"]
n = 25
# Example: "foo bar hello world baz baz"
+4
source share
2 answers

You need to use the module Streamto create an infinity sequence. One way to do this is to:

Stream.repeatedly(fn -> Enum.random(["hello", "world", "foo bar", "baz"]) end)
|> Enum.take(25)

This is an elixir 1.1 due Enum.random/1. Take a look at the module documentation Stream.

UPDATE 1:

take characters with the 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 character stripe after n.

+6

, :

defmodule TakeN do
    def take(list, n) do
        if length(list) == 0 do
            :error
        else
            do_take(list, n, [])
        end
    end

    defp do_take(_, n, current_list) when n < 0 do
        Enum.join(current_list, " ")
    end

    defp do_take(list, n, current_list) do
        random = Enum.random(list)

        # deduct the length of the random element from the remaining length (+ 1 to account for the space)
        do_take(list, n - (String.length(random) + 1), [random|current_list])
    end
end

:

iex > TakeN.take(["hello", "world", "foo bar", "baz"], 25)
"foo bar baz baz hello hello"
+4

Source: https://habr.com/ru/post/1615908/


All Articles