How to generate nested random list?

I am trying to generate nested random list.
For example

[
  [3, 14],
  [15, 92]
]

I am able to generate a random list of size n using

n = 5
1..n |> Enum.map(fn _ -> Enum.random(1..100) end)
[41, 43, 3, 94, 25]

When I tried an extended version of the above I got the
same element per row

n = 5
List.duplicate(n, n) |> Enum.map(fn n -> List.duplicate(Enum.random(1..100), n) end) 
[
  [25, 25, 25, 25, 25],
  [3, 3, 3, 3, 3],
  [16, 16, 16, 16, 16],
  [1, 1, 1, 1, 1], 
  [18, 18, 18, 18, 18]
]

In ruby I will do this by wrapping the generation of the outer list and the inner in two blocks.
For instance

Array.new(5) { Array.new(5) { rand(1..100) } }
[
  [48, 22, 31, 92, 28],
  [89, 20, 53, 50, 24],
  [52, 10, 7, 44, 55],
  [81, 47, 85, 76, 77],
  [57, 77, 83, 89, 93]
] 

Can I do the same thing in elixir?
Thanks!

Here’s something. Don’t count on me for the min/max calculations to be correct, though. :smiley:

y = 7; # Rows
x = 10; # Columns
max = 20; # Max integer value
min = -45; # Min integer value

1..y |> Enum.map(fn _ ->
  1..x |> Enum.map(fn _ ->
    (:rand.uniform() * (max - min) + min) |> Float.round(0) |> trunc()
  end)
end)

Prints something like:

[[-32, -29, 5, -4, -17, 12, -43, -16, -12, -35],
 [17, -8, 6, -8, -22, -42, 3, 15, -43, -28],
 [-41, -43, -32, -38, 14, -33, 13, 11, 4, -27],
 [-28, 0, -10, -15, -10, -37, 8, -30, -16, -40],
 [-42, -35, 9, -22, -4, -44, 17, 13, -7, -35],
 [-34, -34, -11, -32, -4, -28, 1, 13, -11, 3],
 [-34, -25, 17, -31, -16, 12, 11, -41, 4, -12]]
3 Likes

@Nicd Exactly the idea that I was missing. Thanks!

Please mark as solved. :slight_smile:

2 Likes