junpos
BAN USERHey, guys. I tried to take care of repeated numbers too hence I used HashSet().
Please leave comment if there is a better way or improvement.
Thank you
public static void main(String args[]) {
int[] pw = {1,2,1,3,1};
Arrays.sort(pw);
combo(pw);
}
static void combo(int[] pw){
combo(pw, 0, pw.length, new HashSet());
}
static void combo(int[] pw, int num, int count, HashSet set) {
if (count == 0) {
if(set.add(num)){
System.out.println(num);
}
return;
}
int[] temp;
for (int i = 0; i < pw.length; i++) {
temp = delete(pw, i);
combo(temp, num * 10 + pw[i],count-1,set);
}
}
static int[] delete(int[] pw, int skip) {
int[] updated = new int[pw.length - 1];
for (int i = 0, j = 0; i < pw.length; i++) {
if (i == skip) {
continue;
}
updated[j++] = pw[i];
}
return updated;
}
It's for Java
static void spiral(char[][] mat) {
int length = mat.length;
int i=0, j;
int count = 0;
while(i < mat.length/2+1){
i=count;
j=count;
while(j<length){
System.out.print(mat[i][j++]);
}
j--;
while(i<length-1){
System.out.print(mat[++i][j]);
}
while(j>count){
System.out.print(mat[i][--j]);
}
while(i>count+1){
System.out.print(mat[--i][j]);
}
count++;
length--;
}
}
My understanding is to simply print all the number from 0 to the maximum value that is calculated from the digit.
static void allCombo(int digit){
int maxVal = (int)Math.pow(10, digit);
int num_of_zero;
StringBuffer sb = new StringBuffer();
for(int i=0;i<maxVal;i++){
if(i==0){
for(int k=0;k<digit;k++){
sb.append('0');
}
System.out.println(sb);
sb.delete(0, sb.length()+1);
continue;
}
num_of_zero = digit - ((int)Math.log10(i)+1); //the number of 0 that hold the digit
for(int j=0;j<num_of_zero;j++){
sb.append('0');
}
sb.append(i);
System.out.println(sb);
sb.delete(0,sb.length()+1);
}
}
In this type of question(ex. permutation/combination), I prefer using string to hold and pass intermediate data through recursive function.
- junpos June 04, 2013