r/dailyprogrammer • 1 2 • Jan 07 '13

[01/07/13] Challenge #116 [Easy] Permutation of a string

(Easy): Permutation of a string

Write a function that prints all of the permutatons of the unique characters of a given string. For example, permute("baz") would print:

baz
bza
abz
azb
zba
zab

Find all the permutations of daily.

Author: skeeto

Formal Inputs & Outputs

Input Description

Your function should accept a single string variable which is guaranteed to be at least 1 character long.

Output Description

Print all permutations of the given string variable.

Sample Inputs & Outputs

Sample Input

Let the string argument be "ab"

Sample Output

All permutations of "ab" would be ["ab", "ba"]

Challenge Input

Let the string argument be "abbccc"

Challenge Input Solution

abbccc abcbcc abccbc abcccb acbbcc acbcbc acbccb accbbc accbcb acccbb babccc bacbcc baccbc bacccb bbaccc bbcacc bbccac bbccca bcabcc bcacbc bcaccb bcbacc bcbcac bcbcca bccabc bccacb bccbac bccbca bcccab bcccba cabbcc cabcbc cabccb cacbbc cacbcb caccbb cbabcc cbacbc cbaccb cbbacc cbbcac cbbcca cbcabc cbcacb cbcbac cbcbca cbccab cbccba ccabbc ccabcb ccacbb ccbabc ccbacb ccbbac ccbbca ccbcab ccbcba cccabb cccbab cccbba

Note

  • Bonus 1: Instead of printing, be functional. Return a collection (array, etc.) of the permutations.

  • Bonus 2: Correctly handle the case when the input contains a character multiple times. That is, don't output repeats and ensure the output contains the same number of characters as the input. For example, there are three permutations of foo: foo, ofo, oof.

  • Note that this challenge is a near-duplicate of challenge #12, hence why there is the above "bonus" challenges

67 Upvotes

100 comments sorted by

View all comments

9

u/skeeto -9 8 Jan 07 '13

These all satisfy both bonuses. Removing an element from the middle of a sequence seems to be ugly in every language. slice slice append

Clojure,

(defn permute
  ([string]
     (permute string ""))
  ([string prefix]
     (if (empty? string)
       [prefix]
       (distinct
        (flatten
         (for [i (range (count string))]
           (permute (str (.substring string 0 i) (.substring string (inc i)))
                    (str prefix (get string i)))))))))

JavaScript,

function permute(string) {
    function recur(string, prefix) {
        if (string.length === 0) {
            return [prefix];
        } else {
            var out = [];
            for (var i = 0; i < string.length; i++) {
                var pre = string.substring(0, i);
                var post = string.substring(i + 1);
                out = out.concat(recur(pre + post, string[i] + prefix));
            }
            return out;
        }
    }
    var distinct = {};
    recur(string, "").forEach(function(result) {
        distinct[result] = true;
    });
    return Object.keys(distinct);
}

Common Lisp / Emacs Lisp,

(defun permute (string &optional (prefix ""))
  (if (string= "" string)
      (list prefix)
      (flet ((cat (a b) (concatenate 'string a b)))
        (loop for i below (length string)
           for new-string = (cat (subseq string 0 i) (subseq string (1+ i)))
           for new-prefix = (cat prefix (subseq string i (1+ i)))
           append (permute new-string new-prefix) into output
           finally (return (remove-duplicates output :test #'string=))))))

4

u/indivitalism Jan 08 '13

Hi, could you please comment and describe in detail your Clojure and JS code?

10

u/skeeto -9 8 Jan 08 '13

It's the same algorithm for all three, just expressed idiomatically for each language. The algorithm is generatively recursive, accumulating a prefix string, initially empty, as the second argument. Possibly the most important thing to pay attention to is the types of the inputs and outputs. The inputs are always strings and the output is always a collection of strings.

The prefix can be considered an arbitrary string that needs to be prepended to all permutations of the input string. In the case where the input string is empty -- the bottom of the recursion -- there is exactly one permutation: the empty string. Since this is appended to the prefix, all that we need to return is the prefix string stuffed into a collection.

If the input string is not empty, pick the first letter in the string (locking it in place), compute the permutations of the remainder (recurse), and prepend the selected letter to the results. This prepend is done by appending it to the prefix and passing it as the new prefix when recursing. Repeat for each letter in the input string.

Clojure

In the Clojure code the function has two arities, making for an optional second argument, so the caller doesn't need to worry about passing the empty string for the prefix. It then checks to see if the recursion bottomed out (empty?), returning the prefix in a vector (remember, this function always returns a collection).

Ignore flatten and distinct for the moment. If the input string isn't empty, use for to do a list comprehension across the characters of the input string. The results of each run of the body of the for loop is collected into a vector. It's important to note that I'm walking by index instead of by character. This is because I want to handle the case where the same character appears multiple times in the input, so I need to know exactly which character I'm on.

When recursing, I remove the current character from the input (using the .substring method) and append the character to the prefix (str). I can't use recur here, to avoid using stack, since the body of the for loop isn't actually a tail position.

Since permute always returns a vector, the for loop is now a vector of vecote. I'd prefer if the for loop could concatenate its results instead of collecting them, but that's not an option (my loop macro in the Common Lisp solution does do this). I use flatten to flatten the vector of vectors into a simple vector of strings.

If the same character appears twice or more, we'll see the same permutation again. I use distinct to remove any duplicates before returning the vector. This is a brute-force way to go about it and I bet there's a better way to avoid generating duplicates in the first place, but this wasn't obvious to me. That's why I made it a bonus when I wrote this challenge.

JavaScript

For JavaScript I recurse in a private function. This takes care of the optional argument but also has an addition advantage over the other two functions I wrote. It only removes duplicates once, at the top level function.

So recur is the same algorithm as Clojure, except ECMAScript 5 doesn't have nice list comprehensions, so I use an explicit for loop -- with explicit mutation, which is entirely absent from the Clojure version.

The bottom part creates an object called distinct and uses each of the permutations as properties on it. The value true is completely unimportant here and could be anything. This process collapses duplicates into a single instance -- in linear time, too -- because properties can only appear once. To pull out only the unique permutations I just grab all the properties of this object (Object.keys()).

0

u/[deleted] Jan 09 '13

[deleted] — view deleted comment

8

u/skeeto -9 8 Jan 10 '13 edited Jan 10 '13

In JavaScript, functions are first-class. This means functions can be passed around just like any other value, such as numbers and strings. In JavaScript it's also possible to create functions without a name, called anonymous functions. An expression that does this is sometimes called a lambda expression, named after Church's lambda calculus.

For example, this should be familiar to you. It creates a new variable, a binding, assigning the name x to the number 10 for some scope.

var x = 10;

Instead of a number, a function can be assigned to x.

var x = function() { return 5; }

Afterwards x can be treated just like a normally declared function. Here, x is called, evaluating its body and returning a value.

x();  // Calls `x`, evaluating to 5

This last assignment is nearly identical to the more familiar form. (I won't get into the two small differences here.)

function x() { return 5; }

The parameters of functions also create bindings in the same way, specifically for the body of the function (a scope). Here, the name x inside the function is bound to the value passed to the function, not the global variable x.

var x = 10; // Not directly accessible due to being masked!
function square(x) {
    return x * x;
}

square(4);  // Evaluates to 16

Applying the knowledge above, a function can be passed to another function, where it is bound to a name given by a parameter. That name can be treated just like a function.

function callWithTen(f) {
    return f(10);
}

callWithTen(function(x) { return 2 * x; });  // Evaluates to 20

Here, an anonymous function is passed to the function callWithTen, which applies the function to the value 10.

The forEach method on arrays accepts a function and applies that function to each element in the array (purely for side effects). Similarly, I could write my own each function, which takes an array and a function and applies it to each element of the array.

function each(array, f) {
    for (var i = 0; i < array.length; i++) {
        f(array[i]);
    }
}

In the same way I could have not used forEach and instead iterated over the array with a normal for loop. However, I prefer these higher-order constructs when available.

There's actually a whole lot more to first-class functions than this. In JavaScript, functions are full lexical closures, closing over the environment in which they were instantiated. I'm not taking advantage of this in my challenge solution. There's also a whole category of functions that accept functions as arguments and return other functions. These are called higher-order functions. Here's a parting example of a higher-order function that returns a closure,

/* A higher-order function. */
function complement(f) {
    return function(x) { return !f(x); };
}

[1, NaN, 3].filter(complement(isNaN)); // Evaluates to [1, 3]

For the long explanation: SICP

4

u/nint22 1 2 Jan 10 '13

+1 silver for an awesome solution approach, and +1 gold medal for being a great user, explaining your code! Thanks for helping out make our community great.

5

u/skeeto -9 8 Jan 10 '13

Don't I get another +1 gold since this was also my problem from r/dailyprogrammer_ideas? ;-)

7

u/nint22 1 2 Jan 10 '13

You think these virtual gold medals grow on trees?! (+1 gold added :P)

1

u/aredna 1 0 Jan 11 '13

You comment regarding no good way to remove an element from the middle reminded me that in SQL there is a STUFF function which replaces text at a specific position in the string. If you tell it to replace with an empty string it just removes that text instead. For example

select stuff('test',2,1,'')

will give you 'tst'.

It wouldn't surprise me to find this function in some real programming languages as well.