вывести список объединенных строк - PullRequest
1 голос
/ 22 марта 2020

Я пытаюсь реализовать метод, который использует несколько массивов String [] для печати списка слов, который содержит все возможные комбинации строк в массивах, по порядку и с использованием max. 1 строка каждого массива.

пример: {"this" | "that"} {"is" | "was"} {"cool" | "lame"}

String[] array1 = {"this", "that"};
String[] array2 = {"is", "was"};
String[] array3 = {"cool", "lame"};

должен использоваться для следующего вывода:

thisiscool
thatiscool
thiswascool
thatwascool
thiswaslame
thatwaslame
thisislame
thatislame

Я экспериментировал с вложенным for-loop:

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

Хотя это не сработало. Может быть, есть лучший подход к этому?

Ответы [ 2 ]

2 голосов
/ 22 марта 2020
   String[] array1 = {"this", "that"};
   String[] array2 = {"is", "was"};
   String[] array3 = {"cool", "lame"};
   String text="";
   for(int a = 0; a < array1.length; a++) {
        text=array1[a];
        for(int b = 0; b < array2.length; b++) {
            text+=array2[b];
            for(int c = 0; c < array3.length; c++){
                System.out.println(text+array3[c]);
            }
            text=array1[a];
        }
   }

Демонстрация тех же логи c в JS

Запустите следующий фрагмент

let array1 = ["this", "that"];
let array2 = ["is", "was"];
let array3 = ["cool", "lame"];
let text="";
for(let a = 0; a < array1.length; a++) {
    text=array1[a];
    for(let b = 0; b < array2.length; b++) {
        text+=array2[b];
         for(let c = 0; c < array3.length; c++){
              console.log(text+array3[c]);
         }
         text=array1[a]
    }
}
.as-console-wrapper { max-height: 100% !important; top: 0; }
1 голос
/ 23 марта 2020

@Supercool. уже оставил идеальный ответ.
Но, по вашему мнению, я пытался выяснить , есть ли лучший способ визуализации, чем вложенные циклы for , и я нашел способ " рекурсивного вызова "

Используя 'double array' и 'recursive',
, хотя вы добавьте новый массив, вам не нужно писать дополнительный для -l oop.

Как это

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

enter image description here

Даже при изменении массива с помощью рекурсивных вызовов вы можете исследовать каждый массив без изменения кода и рисовать возможные комбинации.

Ex).

static String[][] array = {{"I","You","They"},
                               {"love","hate"},
                               {"me","you"},
                               {"too","either"},};

Ну, грамматика немного неловкая, но это пример растягивания аранжировки немного дольше.

enter image description here

...