Skip to content

Instantly share code, notes, and snippets.

@loschtreality
Created January 27, 2017 20:08
Show Gist options
  • Save loschtreality/23e056251f6ccb0271539ebbdba6b028 to your computer and use it in GitHub Desktop.
Save loschtreality/23e056251f6ccb0271539ebbdba6b028 to your computer and use it in GitHub Desktop.
Permutations in JS & Ruby
// Given a string, write a function that uses recursion to output a list of all the possible permutations of that string.
// For example, given s='abc' the function should return ['abc', 'acb', 'bac', 'bca', 'cab', 'cba']
// Note: If a character is repeated, treat each occurence as distinct,
// for example an input of 'xxx' would return a list with 6 "versions" of 'xxx'
const permutations = (string) => {
let output = []
if (string.length === 1) {
output = [string]
}
for (let i = 0; i < string.length; i++) {
const letter = string[i]
// Slice from the start of the string up to the current index (left)
// Concat first slice with the remaining letters after the index (right)
const left = string.substring(0, i)
const right = string.substring(i + 1)
const permString = left + right
// Recursively create permutations
const single_permutation = permutations(permString)
for (let j = 0; j < single_permutation.length; j++) {
const perm_letter = single_permutation[j]
// Loop through permutations and concat each current letter (from outer scope)
// with the current permutation set
// push string combination to output
output.push(letter + perm_letter)
}
}
return output
}
console.log(permutations("abc")) // ['abc', 'acb', 'bac', 'bca', 'cab', 'cba']
@loschtreality
Copy link
Author

         def permutations(string)
          output = []

          return [string] if string.size == 1

          string.each_char.with_index do |letter, idx|
            # Slice from the start of the string up to the current index (left)
            # Concat first slice with the remaining letters after the index (right)

            left = string[0...idx] # 3 dots - exclude index
            right = string[(idx + 1)..-1] # 2 dots - include everything up to the end of the string (-1)
            permString = left + right


            # Recursively create permutations
            single_permutation = permutations(permString)

            single_permutation.each do |perm_letter|
              # Loop through permutations and concat each current letter (from outer scope)
                # with the current permutation set
              # push string combination to output

              output << letter + perm_letter
            end

          end

          return output
        end

        p permutations("abc") # ['abc', 'acb', 'bac', 'bca', 'cab', 'cba']

@zzz6519003
Copy link

ruby has permutations

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment