DEV Community

Pau Riosa
Pau Riosa

Posted on • Originally published at paugramming.com

4 3

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).

Image of Stellar post

🚀 Stellar Dev Diaries Series: Episode 1 is LIVE!

Ever wondered what it takes to build a web3 startup from scratch? In the Stellar Dev Diaries series, we follow the journey of a team of developers building on the Stellar Network as they go from hackathon win to getting funded and launching on mainnet.

Read more

👋 Kindness is contagious

Explore a trove of insights in this engaging article, celebrated within our welcoming DEV Community. Developers from every background are invited to join and enhance our shared wisdom.

A genuine "thank you" can truly uplift someone’s day. Feel free to express your gratitude in the comments below!

On DEV, our collective exchange of knowledge lightens the road ahead and strengthens our community bonds. Found something valuable here? A small thank you to the author can make a big difference.

Okay