Sha256: 05668a8a4d11140785096b7783adf79a53e5ec37e346d10f9e62f2f2633a90e8

Contents?: true

Size: 748 Bytes

Versions: 69

Compression:

Stored size: 748 Bytes

Contents

defmodule Palindromes do
  @doc """
  Generates all palindrome products from an optionally given min factor (or 1) to a given max factor.
  """
  @spec generate(non_neg_integer) :: map
  @spec generate(non_neg_integer, non_neg_integer) :: map
  def generate(max_factor, min_factor \\ 1) do
    Enum.reduce(min_factor..max_factor, %{}, fn x, map ->
      Enum.reduce(x..max_factor, map, fn y, products ->
        if palindrome?(x * y), do: add_factor(products, x, y), else: products
      end)
    end)
  end

  defp palindrome?(number) do
    String.reverse(to_string(number)) == to_string(number)
  end

  defp add_factor(map, x, y) do
    product = x * y
    Map.update(map, product, [[x, y]], fn val -> Enum.concat(val, [[x, y]]) end)
  end
end

Version data entries

69 entries across 69 versions & 1 rubygems

Version Path
trackler-2.2.1.180 tracks/elixir/exercises/palindrome-products/example.exs
trackler-2.2.1.179 tracks/elixir/exercises/palindrome-products/example.exs
trackler-2.2.1.178 tracks/elixir/exercises/palindrome-products/example.exs
trackler-2.2.1.177 tracks/elixir/exercises/palindrome-products/example.exs
trackler-2.2.1.176 tracks/elixir/exercises/palindrome-products/example.exs
trackler-2.2.1.175 tracks/elixir/exercises/palindrome-products/example.exs
trackler-2.2.1.174 tracks/elixir/exercises/palindrome-products/example.exs
trackler-2.2.1.173 tracks/elixir/exercises/palindrome-products/example.exs
trackler-2.2.1.172 tracks/elixir/exercises/palindrome-products/example.exs
trackler-2.2.1.171 tracks/elixir/exercises/palindrome-products/example.exs
trackler-2.2.1.170 tracks/elixir/exercises/palindrome-products/example.exs
trackler-2.2.1.169 tracks/elixir/exercises/palindrome-products/example.exs
trackler-2.2.1.167 tracks/elixir/exercises/palindrome-products/example.exs
trackler-2.2.1.166 tracks/elixir/exercises/palindrome-products/example.exs
trackler-2.2.1.165 tracks/elixir/exercises/palindrome-products/example.exs
trackler-2.2.1.164 tracks/elixir/exercises/palindrome-products/example.exs
trackler-2.2.1.163 tracks/elixir/exercises/palindrome-products/example.exs
trackler-2.2.1.162 tracks/elixir/exercises/palindrome-products/example.exs
trackler-2.2.1.161 tracks/elixir/exercises/palindrome-products/example.exs
trackler-2.2.1.160 tracks/elixir/exercises/palindrome-products/example.exs