0

Мне нужно подсчитать длину строк и колонок в двухмерном массиве. Как это сделать со строками я знаю, но как это сделать с колонками в этом массиве:

int maxColumns = 8;
Integer[][] j = {
        {2, 4, 8, 5, 1, 3, 7, 2},
        {6, 7, 4, 8, 2},
        {2, 3, 5, 9, 7, 1}};

for (int row = 0; row < j.length; row++) {
    for (int col = 0; col < j[row].length; col++) {
        System.out.print(j[row][col] + "  ");
    }
    System.out.println();
}

System.out.println();
System.out.println("------------");
System.out.println();

for (int row = 0; row < j.length; row++) {
    System.out.println("row " + row + " has " + j[row].length + " elements");
}
System.out.println();

for (int col = 0; col < maxColumns; col++) {
    // код я не знаю
}

Результат должен быть такой:

3, 3, 3, 3, 3, 2, 1, 1
0

1 ответ 1

0

Ну самое простое, что пришло в голову:

for (int col = 0; col < maxColumns; col++) {
    int count = 0;
    for(int row = 0; row < j.length; ++row)
        if(j[row].length >= col + 1)
            ++count;
    System.out.print(count + " ");
}

Идея в том, что для рассматриваемого столбца мы считаем кол-во строк у которых длина >= номеру столбца.

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.