Skip to content

Instantly share code, notes, and snippets.

@amacgregor
Created September 28, 2019 17:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save amacgregor/279e8bc290e4d7987f968c0dbca3919d to your computer and use it in GitHub Desktop.
Save amacgregor/279e8bc290e4d7987f968c0dbca3919d to your computer and use it in GitHub Desktop.
defmodule UniqueStrings do
@moduledoc """
Combinatronics exercise
reference: https://www.codewars.com/kata/586c7cd3b98de02ef60001ab/train/elixir
Goal: Calculate permutations without repetition
Formula: P(n,r)=n!(n−r)!
"""
def uniq_count(string) do
string = String.upcase(string)
factorial_of(s_length(string)) / c_dupe_factorial(string)
end
def factorial_of(0), do: 1
def factorial_of(n) when n > 0 do
n * factorial_of(n-1)
end
def s_length(string), do: String.codepoints(string) |> length
def c_dupe_factorial(string) do
String.codepoints(string)
|> count_letters()
|> Enum.reduce(1,fn({_, x},acc) -> factorial_of(x) * acc end)
end
def count_letters(string) do
increment = fn(word, map) ->
Map.put(map, word, (map[word] || 0) + 1)
end
string |> Enum.reduce(%{}, increment) |> IO.inspect
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment