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.

Recommended Answers

All 3 Replies

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

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.

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.