Hi Guys,

I need some help with a permutation problem. Say I have a string, 6 characters long - "123456" - how can I generate a list of all permutations of that string, limited to 4 characters long? So basically, each permutation generated can only be 4 characters long. As an example, my output should look something like:

1234
1235
1236
1243
...
6234
6235
6243
6245

There are plenty of code examples on the web that show you how to generate permutations of a string, but I haven't been able to find any limit the permutation length.

Can someone here show me how to do it? Or does anyone know where I could find a solution to this on the web? This isn't part of a homework assignment, or anything like that, but rather, I'm developing a game in Java, and this specific problem is to do with the computers AI in solving its part of the board.

Thanks in advance for any help you can provide,
Demi

Hello again,

So basically, I wrote my own code to do what I wanted. It is by no means pretty, but it was actually a lot easier than I had first thought. A lot of the code samples online used recursion, and I guess it confused me quite a bit. I suppose I could transform what I have into a recursive method, but what I have at the minute is fine.

For anyone who is interested, the code I have is as follows:

import java.util.*;

public class Permute{

	int [] numbers = new int[]{1,2,3,4,5,6};
	
	int pos1;
	int pos2;
	int pos3;
	int pos4;

	TreeSet<String> set = new TreeSet<String>();

	
	public static void main(String [] args)
	{
		Permute perm = new Permute();
		perm.generatePermutations();
	}

	public void generatePermutations()
	{
		for(int a = 0; a < numbers.length; a++)
		{
			pos1 = numbers[a];
			
			for(int b = 0; b < numbers.length; b++)
			{
				if(pos1 != numbers[b])
				{
					pos2 = numbers[b];

					for(int c = 0; c < numbers.length; c++)
					{
						if(pos2 != numbers[c] && pos1 != numbers[c])
						{
							pos3 = numbers[c];

							for(int d = 0; d < numbers.length; d++)
							{
								if(pos3 != numbers[d] && pos2 != numbers[d] && pos1 != numbers[d])
								{
									pos4 = numbers[d];
									
									set.add("" + pos1  + "" + pos2 + "" + pos3 + "" + pos4);

								}
							}
						}
					}
				}
			}
		}

		Iterator it = set.iterator();

		while(it.hasNext())
		{
			System.out.println(it.next());
		}

		System.out.println("Total number of permutations: " + set.size());
	}
}

Thanks,
Demi

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.