/* Find the nth permutation (Code golf) in Picat. https://codegolf.stackexchange.com/questions/114883/i-give-you-nth-permutation-you-give-me-n """ I give you Nth permutation, you give me N Input: a sequence of uppercase letters (ASCII [65;90]) which is the Nth* lexicographical permutation of the multiset of its characters *permutations are numbered from 0 or 1 upwards Output: base-10 integer N Rulez There might be duplicates (that's how this challenge differs from this one) The characters are ordered by their ASCII value In case of an input of length less than or equal to 1, the input is the first permutation and the result is 0 or 1 respectively First permutation is that in which the leftmost character has the lowest value, the rightmost character has the highest value, and the sequence of characters between the first and the last character is the first permutation of the multiset of its characters (recursive definition!) Shortest entry wins Example Input AAB produces output 0 Input ABA produces output 1 Input BAA produces output 2 Input ZZZ produces output 0 Input DCBA produces output 23 EDIT Extra kudos to the one who can come up with a solution which doesn't produce all permutations and then search for the input. That's some challenge. """ This program was created by Hakan Kjellerstrand, hakank@gmail.com See also my Picat page: http://www.hakank.org/picat/ */ import util. % Don't forget to count this! 12 chars main => go. go ?=> Tests = ["AAB", "ABA", "BAA", "ZZZ", "DCBA"], foreach(T in Tests) % 74 chars + 12 (for "import util.") = total 86 chars % P=permutations(T).sort_remove_dups,[I-1:I in 1..P.len,P[I]==T].min.println, % Ungolfed % P=permutations(T).sort.remove_dups, % [I-1:I in 1..P.len,P[I]==T].min.println % Or as 1-based: total 84 chars % P=permutations(T).sort_remove_dups,[I:I in 1..P.len,P[I]==T].min.println % Shorter using find_first_of/2: 58 chars + 12 chars = 70 chars % Or without println/1: 49 + 12 = 61 chars permutations(T).sort_remove_dups.find_first_of(T).println, end, nl. go => true.