Lexicographic Permutation Algorithm in Ruby
A simple algorithm coded in Ruby to find the next lexicographic permutation explained in detail.
What is a Lexicographic Permutation?
A permutation of a string or integer refers to the possible arrangements of the characters or numerals within the set. For example, “ab” has two permutations: “ab” and “ba.” A lexicographic permutation is a list of all possible permutations of a set in increasing numeric or alphabetical order. The integer 123 has six possible permutations:
123
132
213
232
312
321
The number of permutations that a string or integer has can be determined by counting the amount of characters or digits and finding the factorial of that number. For the “ab” example, there are only two characters. The mathematical way to present the factorial of a number is to add “!” after the number. Two factorial would be written 2!
and is a short way of expressing the equation of the factorial: 2! = 2 * 1 = 2
. For the 123 example, there are three digits, therefore: 3! = 3 * 2 * 1 = 6
combinations (permutations) can be created with the digits 123 (or any set of three elements).
A lexicographic permutation of a string or integer is the next possible permutation of the current string/integer in increasing order…