Skip to content

Instantly share code, notes, and snippets.

@pap
Created April 24, 2014 14:12
Show Gist options
  • Select an option

  • Save pap/11256028 to your computer and use it in GitHub Desktop.

Select an option

Save pap/11256028 to your computer and use it in GitHub Desktop.
Codewars perfect square ruby kata implemented in elixir
# The ruby kata was:
# Given an array of numbers, which are perfect squares?
# get_squares(1..16) # => [1, 4, 9, 16]
# get_squares(1..100) # => [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
#
# This version accepts lists an ranges
defmodule ElixirKatas do
def get_squares(numbers) do
cond do
Range.range?(numbers) ->
for n <- numbers, is_sqrt_natural?(n), do: n
Kernel.is_list(numbers) ->
for n <- numbers, is_sqrt_natural?(n), do: n
true ->
IO.puts "Arg must be a list or a range !"
end
end
defp is_sqrt_natural?(n) when is_integer(n) do
:math.sqrt(n) |> :erlang.trunc |> :math.pow(2) == n
end
defp is_sqrt_natural?(_n) do
false
end
end
iex(25)> ElixirKatas.get_squares [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]
[1, 4, 9, 16]
iex(26)> ElixirKatas.get_squares 1..16
[1, 4, 9, 16]
iex(27)> ElixirKatas.get_squares 1..1
[1]
iex(28)> ElixirKatas.get_squares 1
Arg must be a list or a range !
:ok
iex(29)> ElixirKatas.get_squares ["a", :ok]
[]
iex(30)>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment