954,174 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

permutation

Hi, i was writing a program to make permutations of strings, but I ran into a snag and can't figure out what's wrong. It prints out the permutated strings, but some of them are duplicates.
I attached the source
Thanks for the help.

Attachments StringPermDriver.java (0.28KB) ArrayUtils.java (0.33KB) StringPerm.java (1.81KB)
Dark_Omen
Posting Pro
573 posts since Apr 2004
Reputation Points: 23
Solved Threads: 6
 

This might not be of help if this is homework.

http://www.google.co.uk/search?hl=en&q=string+permutations+java&meta=

Why bother reinventing the wheel?

iamthwee
Posting Expert
5,950 posts since Aug 2005
Reputation Points: 1,543
Solved Threads: 439
 

Since you are using arraylist, use the contains() method to check if the entry already exists. If it doesn't, then add it.

server_crash
Postaholic
2,111 posts since Jun 2004
Reputation Points: 113
Solved Threads: 20
 

I actually found a better way to do this problem, less chaotic as the way I was doing it.
Here is the source for it:

public class StringPerm {
 private int count = -1;
 private int numOfPerms;
 private String word;
 private int stringLength;
 private int[] permNums;
 private String[] permWords;
 private int permWordsCt = 0;
 
 
 public StringPerm(String word) {
  this.word = word;
  stringLength = word.length();
  numOfPerms = numberOfPermutations(stringLength);
  permNums = new int[stringLength];
  permWords = new String[numOfPerms];
 }
 
 public void makePermutations(int characterPos) {
  count++;
  permNums[characterPos] = count;
  
  if (count == stringLength) {
   append();
  }
  else {
   for (int i=0; i<stringLength; i++) {
	if (permNums[i] == 0) {
	 makePermutations(i);
	}
   }
  }
  count--;
  permNums[characterPos] = 0;
  }
 
 public void append(){
  String tmpWord = "";
  for (int i = 0; i < stringLength; i++) {
   tmpWord = tmpWord + word.charAt(permNums[i] - 1);
  }
  if(permWordsCt < numOfPerms){
   permWords[permWordsCt] = tmpWord;
   permWordsCt++;
  }
 }
 
 public void printPermutations(){
   for(int i = 0; i < numOfPerms; i++){
	System.out.println(permWords[i]);
   }
  }
 
 public int numberOfPermutations(int length){
   int total = length;
   for (int i = length - 1; i > 0; i--){
	total *= i;
   }
   return total;
  }
}



Thanks for the ideas though.

Dark_Omen
Posting Pro
573 posts since Apr 2004
Reputation Points: 23
Solved Threads: 6
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You