473,386 Members | 1,779 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes and contribute your articles to a community of 473,386 developers and data experts.

Permutations A

11,448 Expert 8TB
Greetings,

last week I stated that a lot of topics in a lot of forums mention all sorts
of sorting problems. Last week's tip gave an answer to quite a bit of those
sorting problems. Another "favourite" (mind the quotes) topic is about
permutations and combinations. This week's tip shows how permutations can be
generated in an efficient way. A next tip talks about how combinations can
be generated efficiently.

First here's an extremely sloppy definition:
Expand|Select|Wrap|Line Numbers
  1. if a word S < T lexicographically then word S can be found before word T can
  2. be found in a dictionary.
Here are all the words containing the three distinct characters A, B and C
in lexicographic order: ABC, ACB, BAC, BCA, CAB and CBA. Note that this is
the order in which they can be found in a dictionary (if the editors of that
dictionary considers them legitimate dictionary words at all.

The core of our algorithm attempts to find a next permutation given a current
permutation. The notion 'next' is defined as lexicographically next.

As an example consider the word ACEDB; what would the next permutation of this
word be? After a bit of fiddling you can figure out the next one: ADBCE

Here's how it's formally (pseudo code) done:

1) for a permutation p_0 p_1 ... p_n find the rightmost index value i such
that p_i < p_(i+1). If no such i can be found the current permutation is the
last permutation of them all; if so, stop.

For our example p_i would be the letter C because it's the rightmost letter
that happens to be less than the one to the right of it: C < E

2) find a rightmost index j such that p_j > p_i. Note that such a j can
always be found if step 1) succeeds.

For our example p_j would the letter D because it's the rightmost letter
that happens to be greater than p_i (D > C)

We count starting from zero (0) so i == 1 and j == 3.

3) Swap the elements p_i and p_j

For our example we swap the letters D and C and obtain: ADECB

4) reverse the postfix p_(i+1) ... p_n

For our example we reverse ECB and obtain ADBCE which happens to be the next
permutation of the current permutation ACEDB.

Note that we didn't need any recursion; just a bit of looping over indexes and
a bit of testing. Remember our Sortable interface from the previous Tip Of
The Week? Here it is again:

Expand|Select|Wrap|Line Numbers
  1. public interface Sortable {
  2.     int length();
  3.     int compare(int i, int j);
  4.     void swap(int i, int j);
  5. }
  6.  
It looks like we can use that interface again, i.e. we need to compare
different things, we need to know the length of the permutation and we need
to be able to swap things. Note that we keep the notion of those 'things'
as vague as possible again.

Let's use this interface for our permutation algorithm. The four steps
of our pseudo code algorithm (see above) can easily be implemented as follows:

Expand|Select|Wrap|Line Numbers
  1.     public static Sortable permute(Sortable s) {
  2.  
  3.         int i, j;
  4.  
  5.         // step 1        
  6.         for (i= s.length()-1; --i >= 0;)
  7.              if (s.compare(i, i+1) < 0)
  8.                  break;
  9.  
  10.         if (i < 0) return null;
  11.  
  12.         // step 2        
  13.         for (j= s.length(); --j > i;)
  14.             if (s.compare(i, j) < 0)
  15.                 break;
  16.  
  17.         // step 3
  18.         s.swap(i, j);
  19.  
  20.         // step 4
  21.         for (j= s.length(); ++i < --j;)
  22.             s.swap(i, j);
  23.  
  24.         return s;
  25.     }
  26.  
The comments just refer to the steps of the pseudo code algorithm. The method
above uses a Sortable for the generation of the next permutation (if any) and
doesn't really know *what* it is actually manipulating. The same advantages
as shown in the previous TOTW show up again: the algorithm couldn't care less
about what it's actually manipulating to construct a next permutation.

If no next permutation is present this method returns null, otherwise the
next permutation in the Sortable object is returned.

For your convenience, so you can copy and paste it directly to your private
bag of tricks again, here's the entire class definition. Note that the class
is just a utility class, i.e. it's not necessary to have a 'Permuter' object
around; the class doesn't have any state by itself and only has functionality.
Here's the complete class:

Expand|Select|Wrap|Line Numbers
  1.  
  2. public final class Permute {
  3.  
  4.     private Permute() { }
  5.  
  6.     public static Sortable permute(Sortable s) {
  7.         // code as above
  8.     }
  9. }
  10.  

Note that this algorithm also works fine when a permutation contains duplicate
elements; e.g. for a first permutation AAB, the next permutations are produced:
ABA and BAA.

Here's a little class that exercises the above utility class:

Expand|Select|Wrap|Line Numbers
  1. public class MySortable implements Sortable {
  2.  
  3.     private String[] array;
  4.  
  5.     private MySortable(String array) { this.array= array; }
  6.  
  7.     public int length() {  // interface implementation
  8.  
  9.         return array.length;  
  10.     }
  11.  
  12.     public int compare(int i, int j)  { // interface implementation
  13.  
  14.         return array[i].compareTo(array[j]); 
  15.     }
  16.  
  17.     public void swap(int i, int j) { // interface implementation
  18.  
  19.         String t= array[i]; array[i= array[j]; array[j]= t;
  20.     }
  21.  
  22.     public void print() {
  23.  
  24.         for (int i= 0; i < array.length; i++)
  25.             System.out.print(array[i]+" ");
  26.         System.out.println();
  27.     }
  28.  
  29.     public static void main(String[] args) {
  30.  
  31.         MySortable s= new MySortable(new String[] {
  32.                         "Fred",
  33.                         "Pebbles",
  34.                         "Wilma" });
  35.         do {
  36.             s.print(s);
  37.         } 
  38.         while (s.permute() != null);
  39.     }
  40. }
  41.  
In the next part of this Tip Of The Week we'll talk a bit about combinations.

kind regards,

Jos
Apr 9 '07 #1
0 12571

Sign in to post your reply or Sign up for a free account.

Similar topics

10
by: Steve Goldman | last post by:
Hi, I am trying to come up with a way to develop all n-length permutations of a given list of values. The short function below seems to work, but I can't help thinking there's a better way. ...
20
by: John Trunek | last post by:
I have a set of X items, but want permutations of length Y (X > Y). I am aware of the permutation functions in <algorithm>, but I don't believe this will do what I want. Is there a way, either...
2
by: Alex Vinokur | last post by:
Does STL contain algorithms which generate (enable to generate) exponents, permutations, arrangements, and combinations for any numbers and words? -- Alex Vinokur mailto:alexvn@connect.to...
11
by: Girish Sahani | last post by:
Hi guys, I want to generate all permutations of a string. I've managed to generate all cyclic permutations. Please help :) def permute(string): l= l.append(string) string1 = '' for i in...
20
by: anurag | last post by:
hey can anyone help me in writing a code in c (function) that prints all permutations of a string.please help
7
by: Christian Meesters | last post by:
Hi, I'd like to hack a function which returns all possible permutations as lists (or tuples) of two from a given list. So far, I came up with this solution, but it turned out to be too slow for...
1
by: JosAH | last post by:
Greetings, last week we talked a bit about generating permutations and I told you that this week will be about combinations. Not true; there's a bit more to tell about permutations and that's...
5
by: Shraddha | last post by:
Suppose we are having 3 variables...a,b,c And we want to print the permutations of these variables...Such as...abc,acb,bca...all 6 of them... But we are not supposed to do it mannually... I...
2
by: Assimalyst | last post by:
Hi I have a Dictionary<string, List<string>>, which i have successfully filled. My problem is I need to create a filter expression using all possible permutations of its contents. i.e. the...
82
by: Bill Cunningham | last post by:
I don't know if I'll need pointers for this or not. I wants numbers 10^16. Like a credit card 16 digits of possible 10 numbers, so I guess that would be 10^16. So I have int num ; These are of...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.