Created
September 5, 2024 17:49
-
-
Save emadb/1aa4a26652e8da6c95a9584baa41bf1f to your computer and use it in GitHub Desktop.
Diamond kata in Elixir
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
defmodule Diamond do | |
def build(n) do | |
half = Enum.map(1..n, &build_line(&1, n)) | |
[_ | t] = Enum.reverse(half) | |
half ++ t | |
end | |
defp build_line(i, n) do | |
spaces(n - i) <> middle(i) <> spaces(n - i) | |
end | |
defp middle(1), do: letter(0) | |
defp middle(n) do | |
char = letter(n - 1) | |
char <> spaces(2 * n - 3) <> char | |
end | |
defp letter(n), do: <<n + 65>> | |
defp spaces(n), do: String.duplicate(" ", n) | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
defmodule DiamondTest do | |
use ExUnit.Case | |
test "1 Line" do | |
diamond = Diamond.build(1) | |
assert List.first(diamond) == "A" | |
end | |
test "2 Lines (first line)" do | |
diamond = Diamond.build(2) | |
assert List.first(diamond) == " A " | |
end | |
test "2 Lines (second line)" do | |
diamond = Diamond.build(2) | |
[_, s | _] = diamond | |
assert s == "B B" | |
end | |
test "3 (first line)" do | |
diamond = Diamond.build(3) | |
assert List.first(diamond) == " A " | |
end | |
test "3 (second line)" do | |
diamond = Diamond.build(3) | |
[_, s | _] = diamond | |
assert s == " B B " | |
end | |
test "3 (third line)" do | |
diamond = Diamond.build(3) | |
[_, _, s | _] = diamond | |
assert s == "C C" | |
end | |
test "2" do | |
assert Diamond.build(2) == [" A ", "B B", " A "] | |
end | |
test "3" do | |
assert Diamond.build(3) == [" A ", " B B ", "C C", " B B ", " A "] | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment