DEV Community

Pau Riosa
Pau Riosa

Posted on • Originally published at paugramming.com

Elixir Today: Create a Left Triangle Pattern using Elixir

Process

  • create a file named left_triangle.ex
  • write the code
left_triangle = fn n ->
  for i <- 0..n do
    for _ <- 0..i do
      "*"
    end
  end
  |> Enum.into("", fn string ->
    string = Enum.join(string)
    "#{string}\n"
  end)
end

IO.puts(left_triangle.(10))
IO.puts(left_triangle.(5))
Enter fullscreen mode Exit fullscreen mode
  • run elixir left_triangle.ex

Result

*
**
***
****
*****
******
*******
********
*********
**********
***********

*
**
***
****
*****
******

Enter fullscreen mode Exit fullscreen mode

Happy Coding!

Top comments (1)

Collapse
 
pyrsmk profile image
Aurélien Delogu

This code needs some optimization because you have a nested loop. Can't you directly output the number of * you need with a simple Elixir function? Internally it would still be a loop, but more optimized

Also, can't you pass an IO to your function so it's responsible of displaying things the right way? I mean, if you pass an IO, you can drop your last Enum loop and you avoid putting strings on the heap which is really inefficient (I don't know if it works like that in Elixir but it's the case in Rust, Crystal, and many other languages).