Reputation: 103
I wrote this code to find all possible permutations of some numbers. But i dosen't want to use one digit twice:
123,132,213 are OK, but it produces numbers like 122, 121 etc.
What am i doing wrong?
import java.util.HashSet;
public class main {
public static void main(String[] args) {
HashSet<Integer> l = new HashSet<Integer>();
for(int i=0;i<=3;i++){
l.add(i);
}
perm(l,3,new StringBuffer());
}
static void perm(HashSet<Integer> in, int depth,StringBuffer out){
if(depth==0){
System.out.println(out);
return;
}
int len = in.size();
HashSet<Integer> tmp = in;
for(int i=0;i<len;i++){
out.append(in.toArray()[i]);
tmp.remove(i);
perm(tmp,depth-1,out);
out.deleteCharAt(out.length()-1);
tmp.add(i);
}
}
}
Upvotes: 0
Views: 1364
Reputation: 83
Here's a much simpler implementation using a HashSet. I'm using strings but the concept remains the same.
public void printPermutations(String str){
HashSet<String> hs = new HashSet<>();
printPermutations("", str, hs);
}
public void printPermutations(String prefix, String end, HashSet<String> hs){
if(end.equals(""))
System.out.println(prefix);
for(int i = 0; i < end.length(); ++i)
if(hs.add(prefix + end.charAt(i))){
printPermutations(prefix + end.charAt(i),
end.substring(0,i) + end.substring(i + 1, end.length()), hs);
}
}
Upvotes: 0
Reputation: 86
It looks like Autoboxing is getting you. When you call the remove with 'i', My guess is that 'i' has been boxed to a different object and is thus not found in your HashSet.
Upvotes: 1
Reputation: 28292
tmp.remove(i)
is wrong. You need to remove the ith element from tmp... you are removing the element "i". So, do tmp.remove(in.toArray()[i])
. I think that will fix this up. For instance, if the zeroth element is 17, doing tmp.remove(i)
will remove all zeroes from the HashSet, not "17".
Upvotes: 2