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.139 tracks/elixir/exercises/palindrome-products/example.exs
trackler-2.2.1.138 tracks/elixir/exercises/palindrome-products/example.exs
trackler-2.2.1.137 tracks/elixir/exercises/palindrome-products/example.exs
trackler-2.2.1.136 tracks/elixir/exercises/palindrome-products/example.exs
trackler-2.2.1.135 tracks/elixir/exercises/palindrome-products/example.exs
trackler-2.2.1.134 tracks/elixir/exercises/palindrome-products/example.exs
trackler-2.2.1.133 tracks/elixir/exercises/palindrome-products/example.exs
trackler-2.2.1.132 tracks/elixir/exercises/palindrome-products/example.exs
trackler-2.2.1.131 tracks/elixir/exercises/palindrome-products/example.exs
trackler-2.2.1.130 tracks/elixir/exercises/palindrome-products/example.exs
trackler-2.2.1.129 tracks/elixir/exercises/palindrome-products/example.exs
trackler-2.2.1.128 tracks/elixir/exercises/palindrome-products/example.exs
trackler-2.2.1.127 tracks/elixir/exercises/palindrome-products/example.exs
trackler-2.2.1.126 tracks/elixir/exercises/palindrome-products/example.exs
trackler-2.2.1.125 tracks/elixir/exercises/palindrome-products/example.exs
trackler-2.2.1.124 tracks/elixir/exercises/palindrome-products/example.exs
trackler-2.2.1.123 tracks/elixir/exercises/palindrome-products/example.exs
trackler-2.2.1.122 tracks/elixir/exercises/palindrome-products/example.exs
trackler-2.2.1.121 tracks/elixir/exercises/palindrome-products/example.exs
trackler-2.2.1.120 tracks/elixir/exercises/palindrome-products/example.exs