Question

Permutations for test data

Asked by: Programmer_to_be

Hi experts.

I need to generate some test data for an experiment im doing. The following explanation of what im trying to do is very abstract, I just need to get a simple algorithm working in java that does this, then I can change it accordingly (i.e. the strings/characters for the permutations will actually be some data coming out of a database).

Imagine I have a list of strings or characters {x, y, z}

I need to generate all permutations of the list, each permutations length is dependent on a parameter which I will be providing as input to the algorithm.

i.e. if I invoke the algorithm with the input 2, I get the permutations:
X, X
X, Y
X, Z
Y, Y
Y, X
Y, Z
Z, Z
Z, X
Z, Y

so the input number is the 'length' of each permutation

Can someone help me to create an algorithm for this, if its in pseudo code thats fine, as I can translate it into Java myself

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2009-09-28 at 04:07:53ID24766420
Tags

java

,

algorithm

,

permutations

Topics

Java Programming Language

,

Algorithms

Participating Experts
4
Points
200
Comments
10

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. Permutation Algorithm
    Given a string "ABC" (a sequence of three items, all different from one another, initially sorted low-to-high) the following list includes all possible permutations of that string: ABC ACB BAC BCA CAB CBA What I need is an *algorithm* that will generate each and e...
  2. Random Permutation
    Hi. Any efficient way to generate a random permutation? Or java do provide such method? Random Permutation: (6) {5,2,4,6,1,3} thanks. chunmeng
  3. permutations
    I need to write the code that has for input two integers m,n with m>=n and output to print all the permutations 1,2,...,m by n. Please help!
  4. PHP Permutation
    This code is extremely slow, is there a way to make it faster? When trying to permutate 20 numbers, it takes quite a long time. I'd also like to select a certain number out of 20 For example, I may want only 7 out of 20 and find all possible permutation with the length o...

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: Programmer_to_bePosted on 2009-09-28 at 04:54:31ID: 25438442

Hi ab, thank you for the link.

I had a look at some existing algorithms online, but im not too clear on whether they take my requirement of an input number that restricts the lengths of the permutations, into consideration?

 

by: brunoguimaraesPosted on 2009-09-28 at 06:27:23ID: 25439107

I adapted the algorithm in http://www.merriampark.com/perm.htm to reach your solution. It's probably not the most efficiente way, but it works. It does not print the permutations in a sorted way, though.

//--------------------------------------
// Systematically generate permutations. 
//-------------------------------------- 
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List; 
public class PermutationGenerator { 
	private int[] a;
	private BigInteger numLeft;
	private BigInteger total; 
	// -----------------------------------------------------------
	// Constructor. WARNING: Don't make n too large.
	// Recall that the number of permutations is n!
	// which can be very large, even when n is as small as 20 --
	// 20! = 2,432,902,008,176,640,000 and
	// 21! is too big to fit into a Java long, which is
	// why we use BigInteger instead.
	// ---------------------------------------------------------- 
	public PermutationGenerator(int n) {
		if (n < 1) {
			throw new IllegalArgumentException("Min 1");
		}
		a = new int[n];
		total = getFactorial(n);
		reset();
	} 
	// ------
	// Reset
	// ------ 
	public void reset() {
		for (int i = 0; i < a.length; i++) {
			a[i] = i;
		}
		numLeft = new BigInteger(total.toString());
	} 
	// ------------------------------------------------
	// Return number of permutations not yet generated
	// ------------------------------------------------ 
	public BigInteger getNumLeft() {
		return numLeft;
	} 
	// ------------------------------------
	// Return total number of permutations
	// ------------------------------------ 
	public BigInteger getTotal() {
		return total;
	} 
	// -----------------------------
	// Are there more permutations?
	// ----------------------------- 
	public boolean hasMore() {
		return numLeft.compareTo(BigInteger.ZERO) == 1;
	} 
	// ------------------
	// Compute factorial
	// ------------------ 
	private static BigInteger getFactorial(int n) {
		BigInteger fact = BigInteger.ONE;
		for (int i = n; i > 1; i--) {
			fact = fact.multiply(new BigInteger(Integer.toString(i)));
		}
		return fact;
	} 
	// --------------------------------------------------------
	// Generate next permutation (algorithm from Rosen p. 284)
	// -------------------------------------------------------- 
	public int[] getNext() { 
		if (numLeft.equals(total)) {
			numLeft = numLeft.subtract(BigInteger.ONE);
			return a;
		} 
		int temp; 
		// Find largest index j with a[j] < a[j+1] 
		int j = a.length - 2;
		while (a[j] > a[j + 1]) {
			j--;
		} 
		// Find index k such that a[k] is smallest integer
		// greater than a[j] to the right of a[j] 
		int k = a.length - 1;
		while (a[j] > a[k]) {
			k--;
		} 
		// Interchange a[j] and a[k] 
		temp = a[k];
		a[k] = a[j];
		a[j] = temp; 
		// Put tail end of permutation after jth position in increasing order 
		int r = a.length - 1;
		int s = j + 1; 
		while (r > s) {
			temp = a[s];
			a[s] = a[r];
			a[r] = temp;
			r--;
			s++;
		} 
		numLeft = numLeft.subtract(BigInteger.ONE);
		return a; 
	} 
	private static <T extends Comparable<? super T>> List<List<T>> powerSet(List<T> A, int length) {
		List<List<T>> ans = new ArrayList<List<T>>();
		int ansSize = (int) Math.pow(2, A.size());
		for (Integer i = 0; i < ansSize; ++i) {
			String bin = Integer.toString(i, 2);
			while (bin.length() < A.size())
				bin = "0" + bin;
			if (bin.replaceAll("[^1]", "").length() == length) {
				List<T> thisComb = new ArrayList<T>();
				for (int j = 0; j < A.size(); ++j) {
					if (bin.charAt(j) == '1')
						thisComb.add(A.get(j));
				}
				Collections.sort(thisComb);
				ans.add(thisComb);
			}
		}
		return ans;
	} 
	public static void main(String[] args) {
		int[] indices;
		int numberOfElements = Integer.valueOf(args[0]);
		List<String> elements = Arrays.asList(new String[] { "a", "b", "c", "d" });
		PermutationGenerator x = new PermutationGenerator(numberOfElements); // number of elements in permutation
		StringBuffer permutation;
		List<List<String>> subsets = powerSet(elements, numberOfElements); 
		for (List<String> aux : subsets) {
			x.reset();
			while (x.hasMore()) {
				permutation = new StringBuffer();
				indices = x.getNext();
				for (int i = 0; i < indices.length; i++) {
					permutation.append(aux.get(indices[i]));
				}
				System.out.println(permutation.toString());
			}
		}
	}
}

                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:
54:
55:
56:
57:
58:
59:
60:
61:
62:
63:
64:
65:
66:
67:
68:
69:
70:
71:
72:
73:
74:
75:
76:
77:
78:
79:
80:
81:
82:
83:
84:
85:
86:
87:
88:
89:
90:
91:
92:
93:
94:
95:
96:
97:
98:
99:
100:
101:
102:
103:
104:
105:
106:
107:
108:
109:
110:
111:
112:
113:
114:
115:
116:
117:
118:
119:
120:
121:
122:
123:
124:
125:
126:
127:
128:
129:
130:
131:
132:
133:
134:
135:
136:
137:
138:
139:
140:
141:
142:
143:
144:
145:
146:
147:
148:
149:
150:
151:
152:
153:
154:
155:
156:
157:
158:
159:
160:
161:
162:
163:
164:
165:
166:
167:
168:
169:
170:
171:
172:
173:
174:

Select allOpen in new window

 

by: Programmer_to_bePosted on 2009-09-28 at 06:54:21ID: 25439329

hi bruno, thanks. Its very close to how I need it, except just a minor problem.

If the list is {"x", "y"}

and i invoke the algorithm with the number 2, I get the permutations:

xy
yx

But i also require

xx
yy

in the results, is this easily achievable?

 

by: brunoguimaraesPosted on 2009-09-28 at 09:13:23ID: 25440575

Technically this is not a permutation. Here's another not so pretty solution.

First argument is a string containing all the elements, for example XYZ.
Second argument is the groupe size.

So if you call the program with arguments XYZ 2, you would get as output:

XX
XY
XZ
YX
YY
YZ
ZX
ZY
ZZ

	public static void main(String[] args) {
 
		String elements = args[0];
		int r = Integer.valueOf(args[1]);
		int n = elements.length();
		
		Collection<String> result = new ArrayList<String>((int) Math.pow(n, r));
		String[] v = new String[n];
 
		for (int k = 0; k < n; k++) {
			v[k] = String.valueOf(elements.charAt(k));
		}
		for (int m1 = 0; m1 < n; m1++) {
			for (int m2 = 0; m2 < n; m2++) {
				if (r == 2) {
					result.add(v[m1] + v[m2]);
				} // end if r==2
				for (int m3 = 0; m3 < n; m3++) {
					if (r == 3) {
						result.add(v[m1] + v[m2] + v[m3]);
					} // end if r==3
					for (int m4 = 0; m4 < n; m4++) {
						if (r == 4) {
							result.add(v[m1] + v[m2] + v[m3] + v[m4]);
						} // end if r==4
						for (int m5 = 0; m5 < n; m5++) {
							if (r == 5) {
								result.add(v[m1] + v[m2] + v[m3] + v[m4] + v[m5]);
							} // end if r==5
							for (int m6 = 0; m6 < n; m6++) {
								if (r == 6) {
									result.add(v[m1] + v[m2] + v[m3] + v[m4] + v[m5] + v[m6]);
								} // end if r==6
							} // end for m6
						} // end for m5
					} // end for m4
				} // end for m3
			} // end for m2
		} // end for m1
 
		for (String s : result) {
			System.out.println(s);
		}
	}

                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:

Select allOpen in new window

 

by: brunoguimaraesPosted on 2009-09-28 at 09:14:48ID: 25440593

Oh, and the group size should be 6 at maximum.

 

by: thehagmanPosted on 2009-09-28 at 09:25:00ID: 25440682

Something like below should work (give or take a syntactic bug)

Collection<String> AllCombis(String elements, int count) {
   Collection <String> result;
   if (count > 0) {
      Collection <String> subresult = AllCombis(elements, count-1);
      for (int i=0; i<elements.length; ++i) {
         for (int j=0; j<subresult.length; ++j) {
            result.add( subresult[j] + elements[i] );
         }
      }
   }
   return result;
}

                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:

Select allOpen in new window

 

by: epasquierPosted on 2009-09-28 at 10:53:44ID: 25441498

thehagman is absolutly right, the only solution to this kind of problems is RECURSIVITY (a function that calls itself)

Problem with recursivity is always the lower level which is always different, it is the only missing part in his solution. Too bad because it will propagate in all the call stack and produce no result at all (subresult.length is always 0)

I'm no Java programmer but I'll try to correct his code. I'll also change "elements" type to a collection of strings and not a string (collection of char) as I believe is what you want.

I don't know also if Collection<Collection<String>> is valid in Java, but that certainly is what you need in essence (a List of List of Strings)

Collection<Collection<String>> AllCombis(Collection<String> elements, int count) 
{
   Collection <Collection <String>> result;
   if (count == 1) 
   {
      for (int i=0; i<elements.count; i++)
      {
          Collection <String> SubList;
          SubList.Add(elements[i]);
          result.Add(SubList);
      }
   }
   else
   {
      Collection <Collection <String>> subresult = AllCombis(elements, count-1);
 
      for (int i=0; i<subresult.length; ++i) 
      {
         for (int j=0; j<elements.length; ++j) 
         {
// Copy one of the last result 
// and add each of the elements to create N new results per last result
// So your number of results for level L is N^L (exception with L=0, 
// you have either 0 result (your collection is empty) or if you want
// mathematical exactness you have one result, being a list of 
// one empty string list. I have implemented the later as for level 0
// the result is created but returned empty
            Collection <String> SubList=subresult[i];
            SubList.Add(elements[j]);
            result.Add(SubList);
         }
      }
   }
   return result;
}

                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:

Select allOpen in new window

 

by: Programmer_to_bePosted on 2009-09-28 at 15:09:39ID: 31634317

Thanks to everyone for their help

 

by: thehagmanPosted on 2009-09-30 at 02:04:44ID: 25456687

(Actualy, the "correct" way to correct my code would have been to add a single empty string to the result in case count==0)

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...