I require a method for taking in a string of varying length and content, returning the number of permutations without repetition. I have written the following to try to solve this problem
def permutations(n)
k = n.to_s.chars.uniq.length
e = n.to_s.length
m = (1..e).reduce(1, :*)
p = (1..k).reduce(1, :*)
l = m / p
case
when k == 1 then 1
when k < e then l
else m
end
end
The above is returning some results that I've been confused by for a couple of days which I've realised occur where there are more than 1 set of duplicate values for uniq
to check.
If I pass through bbbb789
I get 210
which is correct. However if I have a set with two duplicates such as 73839
the expected result is 60 but I reach 5
I realised yesterday where the issues were but I can't find a way to factor in the duplicates
Also my first method for solving this was to use
k = n.to_s.chars.uniq.length
m = n.to_s.chars.length
return 1 if k <= 1
n.to_s.chars.permutation(m)to_a.uniq.size
This also worked but takes an age to cycle through all permutations of longer sets