Skip to content

Instantly share code, notes, and snippets.

@allansideas
Created February 27, 2017 16:21
Show Gist options
  • Save allansideas/ef0a628f39ef192b548220f7a7c00452 to your computer and use it in GitHub Desktop.
Save allansideas/ef0a628f39ef192b548220f7a7c00452 to your computer and use it in GitHub Desktop.
defmodule Pyramid.Plans do
defstruct height: nil, layers: nil
end
defmodule Pyramid do
@moduledoc """
Mario's Pyramid problem solution
"""
def main(height) do
#How to validate that input is > 0 without if?
plans = %Pyramid.Plans{height: height}
plans
|> build_layers
|> print_out
end
def print_out(%Pyramid.Plans{layers: layers}) do
# Say I didn't want a newline at the very end, would the best way be to just
# delete the last element of the flattened list?
# List.flatten(layers)
# |> Enum.join("")
# |> IO.puts
IO.puts(layers)
end
@doc """
Builds a list consisting of the carachters needed for the layer of the Pyramid
`blocks` is the number of blocks in the layer
`height` is used to calculate the left padding
## Examples
iex> Pyramid.build_layer(3, 5)
[" ", " ", "#", "#", "#", "\\n"]
"""
def build_layer(blocks, height) do
# Cleaner
Enum.map(1..height + 1, fn
x when x <= (height - blocks) -> ' '
x when x > height -> '\n'
_ -> '#'
end)
# Messier
# left_pad = height - blocks
# padding = Enum.map(0..left_pad, fn(pos)-> " " end)
# padding_plus_blocks = padding ++ Enum.map(1..blocks, fn()-> "#" end)
# trimmed = List.delete_at(padding_plus_blocks, 0)
# trimmed ++ ["\n"]
end
@doc """
Builds a List of lists with each layer's representation in strings i.e.
[[" ", "#", "\n"], ["#", "#", "\n"]]
"""
def build_layers(%Pyramid.Plans{height: height} = plans) do
layers =
1..height
# Can I do an (&build_layer/2) with args here instead of the full fn inside
# the map?, should this somehow be done with recursion?
|> Enum.map(fn(blocks_in_layer)-> build_layer(blocks_in_layer, height) end)
%Pyramid.Plans{plans | layers: layers}
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment