Elixir Today: Create a Hollow Triangle Pattern using Elixir

Photo by Shapelined on Unsplash

Elixir Today: Create a Hollow Triangle Pattern using Elixir

Pau Riosa's photo
Pau Riosa
·May 8, 2022·

1 min read

Subscribe to my newsletter and never miss my upcoming articles

Process

  • create a file named hollow_triangle.ex
  • write the code
hollow_triangle = fn number ->
  for i <- 1..number do
    for j when j < i <- 0..i do
      if i == number do
        "*"
      else
        if j == 0 || j == i - 1 do
          "*"
        else
          " "
        end
      end
    end
  end
  |> Enum.into("", fn string ->
    string = Enum.join(string)
    "#{string}\n"
  end)
end

IO.puts(hollow_triangle.(10))
IO.puts(hollow_triangle.(5))
  • run elixir hollow_triangle.ex

Result

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

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

Happy Coding!

 
Share this