tags:

views:

589

answers:

12

input: array of unique integers, sorted

output: all permutations. edit: output order is not important, as long as it's correct :-)

example:

[2, 6, 9]

output:

[ [2, 6, 9], [2, 9, 6], [6, 2, 9], [6, 9, 2], [9, 2, 6], [9, 6, 2] ]
A: 

Using Permutations in .NET for Improved Systems Security

Chris Ballance
Are you sure you've read the question?
Kinopiko
this is code golf, not "when should I use premutations?" :D
CrazyJugglerDrummer
+6  A: 

A few easy ones, in alphabetical order...

Haskell

import Data.List
permutations

J

(A.~[:i.*/@:>:@i.@#)

Python

from itertools import permutations
ephemient
can you please provide a full code for the Haskell example?
Mark G
Oh, cheating. Importing a permutations library isn't nearly the same as writing one.
McPherrinM
+2  A: 

C++

#include <algorithm>
std::next_permutation
Shay Erlichmen
+6  A: 

Haskell without libraries (63 chars):

p(l)=case(l)of{_:_:_->l>>=(\i->map(i:)(p$filter(i/=)l));_->[l]}
Dario
+4  A: 

Python without using libraries:

f=lambda a:a and[[e]+x for i,e in enumerate(a)for x in f(a[:i]+a[i+1:])]or[a]

Usage:

print f([2,6,9])

Mark Byers
+4  A: 

Haskell without libraries (42 chars)

p []=[[]]
p l=[a:b|a<-l,b<-p$filter(/=a)l]
Matajon
This will only work if `(Eq a) => [a]` *and* all elements in the list are unique.
Stephan202
(Which the input is, in this case, so it's ok :)
Stephan202
Then again, so is Dario's answer.
codebliss
@codebliss: correct.
Stephan202
+4  A: 

Prolog

perm(List,[H|Perm]):-delete(H,List,Rest),perm(Rest,Perm).
perm([],[]).

delete(X,[X|T],T).
delete(X,[H|T],[H|NT]):-delete(X,T,NT).
Mark Harrison
+1  A: 
#include <string>
#include <vector>
#include <iostream>
using namespace std;
void Permute(string permutation,string dict){
    if(dict.length()==0)
     cout<<permutation;
    for(int i=0;i<dict.size();i++){
     Permute(permutation+dict[i],
      dict.substr(0,i)+dict.substr(i+1));
    }
}
Dasuraga
+1  A: 

Perl

Maybe not the most efficient nor shortest-code version, but I thought I'd give it a try for practice. Of course $ignore may be substituted by $i for shorter code.

p([2,6,9], []);

sub p {
  my ($a, $ignore) = @_;
  for(my $n = 0; $n <= $#$a; ++$n){
    if(!{map {$_ => 1} @$ignore}->{$n}){
      if($#$a == $#$ignore + 1){
        print join(",", map {$a->[$_]} (@$ignore, $n)), "\n";
      }
      else {
        p($a, [@$ignore, $n]);
      }
    }
  }
}
Frank
+2  A: 

Implement permutations in Haskell (76 75 characters)

i e[]=[[e]]
i e(a:b)=(e:a:b):[a:s|s<-i e b]
f=foldr(\e->concatMap(i e))[[]]

Unlike some other Haskell answers, this one doesn't evaluate the elements of its input list.

I've been looking around for some prelude function that makes defining i (for "insert") more concise than the above, but so far I haven't found anything...

comingstorm
+1  A: 

F#

I am using this as a way to learn F# so I would greatly appreciate anyone's suggestions on improving the code here, especially on the factorial calculation. Also, I try to avoid recursive functions whenever possible unless they can be made tail recursive, just as a personal challenge.

#light
let permutations lst =
    let result = ref [lst]
    for i = 1 to (List.fold (fun number product -> number * product) 1 [List.length(lst) .. -1 .. 1]) / (lst.Length - 1) do
        for start = 0 to (List.length(lst) - 2) do
            result := [List.permute (fun n -> match n with |_ when n=start->(start+1) |_ when n-1=start->start |_->n) (result.Value.Item(result.Value.Length-1))]
                      |> List.append result.Value
            ()
    Seq.take (result.Value.Length-1) result.Value // Have to get rid of the last one which is a duplicate of the given list.

permutations [2;6;9] |> Seq.iter (fun l -> printfn "%A" l)
System.Console.ReadKey(true) |> ignore
David
A few tips:1. Replace 'Seq.iter (fun l -> printfn "%A" l)' by 'Seq.iter (printfn "%A") ...2. !result is the same as result.Value ...3. here's a shorter factorial: 'let fac n = Seq.reduce (*) [1..n]' ...4. 'fun n -> match n with |_ when n=start<etc...>' can be replaced by 'function |n when n=start<etc...>' ...5. You can omit the () in your for loop, since updating the result already is a unit action.
cfern
Excellent! Thank you cfern.
David
+1  A: 

C# (not using recursion)

Not the shortest, but here's an implemenetation of Edsger Dijkstra's algorithm from the classic text A Discipline of Programming (Prentice-Hall). (I mostly just wanted to see if it could be done without recursion and have a play with generics).

static List<T> GetNext<T>(List<T> input) where T : IComparable<T>, IEquatable<T>    
{
    int N = input.Count;  
    int i, j; 
    for (i = N - 2; i > -1; i--)
        if (input[i].CompareTo(input[i+1]) < 0)                         
            break;          

    if (i < 0)
        return null;  

    j = N - 1;
    while (input[j].CompareTo(input[i]) <= 0)
        j = j - 1;     
    swap(input, i, j);   

    i+=2; j = N; 
    while (i < j)
    {
        swap(input, i - 1, j - 1);  
        i++;
        j--;
    }    
    return input;
}
Matt Warren
What is 'swap'?
Maxim Zaslavsky
Just a simple function that I wrote, all it does it swap around the items in the list specified by the 2nd and 2rd arguments.So if the list is {1. 2. 4, 6, 2, 3}, after calling swap(list, 2, 4) it will be {1. 2. 2, 6, 4, 3}. The items are zero based!
Matt Warren