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);
}
}
}
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.