Estoy tratando de poner en práctica un método que utiliza múltiples [] matrices de cadenas para imprimir una lista de palabras que contiene todas las combinaciones posibles de las cadenas en las matrices, en orden y utilizando máx. 1 Cadena de cada matriz.
ejemplo: {"this" | "that"} {"is" | "was"} {"cool" | "lame"}
String[] array1 = {"this", "that"};
String[] array2 = {"is", "was"};
String[] array3 = {"cool", "lame"};
debe ser utilizado para el siguiente resultado:
thisiscool
thatiscool
thiswascool
thatwascool
thiswaslame
thatwaslame
thisislame
thatislame
He estado experimentando con anidados para bucles:
String out1 = "";
for(int a = 0; a < array1.length; a++) {
out1 = array1[a];
System.out.println(out1);
for(int b = 0; b < array2.length; b++) {
out1 += array2[b];
System.out.println(out1);
for(int c = 0; c < array3.length; c++) {
out1 += array3[c];
System.out.println(out1);
Esto no funcionó bien sin embargo. Tal vez hay una mejor aproximación a este?
@Super guay. ya ha dejado una respuesta perfecta.
Pero como su opinión, que he estado tratando de averiguar si hay una mejor manera de visualizar que anida para-bucles , y yo he llegado con una forma de " llamada recursiva "
Mediante el uso de un ' double array
' y ' recursive
',
aunque se agrega una nueva matriz, que no tienen que escribir un adicional de bucle .
Me gusta esto
public class StackOver
{
static String[][] array = {{"this","that"},
{"is","was"},
{"cool","lame"},};
public static void recString(String[][] a, int index, String output) {
//make break-point
if(index == a.length) { //if 'index' reached to the end of array 'a'?
System.out.println(output); //print out string 'output' that collected so far
//output should be = (a[0][?] + a[1][?] +...+ a[length-1][?])
return; //And end the method.
}
// if 'index' didn't reach to the end of array ::
//If there's an array that hasn't been explored yet,
for(int i = 0; i < a[index].length; i++) {
recString(a, index+1, output + a[index][i]);
//Add 1 to 'index' and add String out put that added '[index][i]'
//as parameters and call this method again.
//This form is called recursive call!
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
String t = "";
recString(array,0,t);
}
}
Incluso si los cambios de la matriz, con llamadas recursivas, se puede examinar cada matriz sin cambiar el código y extraer posibles combinaciones.
Ex).
static String[][] array = {{"I","You","They"},
{"love","hate"},
{"me","you"},
{"too","either"},};
Bueno, la gramática es un poco incómodo, pero es un ejemplo de la disposición que se extiende un poco más largo.