Is there any algorithm to achieve this combination of output? Input :
arr1 = {x, y, z}
arr2 = {a, b}
Output :
xa, ya, za
xa, ya, zb
xa, yb, za
xa, yb, zb
xb, ya, za
xb, ya, zb
xb, yb, za
xb, yb, zb
Is there any algorithm to achieve this combination of output? Input :
arr1 = {x, y, z}
arr2 = {a, b}
Output :
xa, ya, za
xa, ya, zb
xa, yb, za
xa, yb, zb
xb, ya, za
xb, ya, zb
xb, yb, za
xb, yb, zb
static char[] arr1 = {'x', 'y', 'z'};
static char[] arr2 = {'a', 'b'};
public static void main(String[] args) {
print(new char[arr1.length - 1], 0);
}
static void print(char[] store, int depth) {
for(char c : arr2) {
if(depth < store.length) {
store[depth] = c;
print(store, depth + 1);
} else {
for(int i = 0; i < store.length; i++) {
System.out.print(arr1[i] + "" + store[i] + ", ");
}
System.out.println(arr1[depth] + "" + c);
}
}
}
EDIT: Couldn't resist trying out @DenisKulagin's method, so here goes:
public static void main(String[] args) {
char[] arr1 = {'x', 'y', 'z'};
char[] arr2 = {'a', 'b'};
for(int i = 0; i < 1 << arr1.length; i++) {
for(int j = 0; j < arr1.length; j++) {
int inverted = arr1.length - 1 - j;
int index = (i & (1 << inverted)) >>> inverted;
System.out.print(arr1[j] + "" + arr2[index] + " ");
}
System.out.println();
}
}
Not quite as flexible as my version, since arr2
can only contain 2 elements, but definitely a clever approach.
It maybe a 2 power 3 (arr2.length power arr1.length). This should give the num of rows.
So you need an Algorithm that calculates every single row. The shorter one gives the num and the longer one the exponent.