Y
Y
Yuri Averyanov2018-11-11 22:06:38
Java
Yuri Averyanov, 2018-11-11 22:06:38

Under what condition should the array end?

I am writing a method that should evenly split the sheet into the number of rows of a two-dimensional array. What condition should be for break; what would the array display all the values?

public class  ConvertList2Array {
    public int[][] toArray(List<Integer> list, int rows) {
        int cells = list.size() / rows == 0 ? list.size() / rows : (list.size() / rows) + 1;
        int[][] array = new int[rows][cells];
        int row = 0;
        int colum = 0;
        for (int i : list) {
            array[row][colum++] = i;
            if (i == rows) {
                colum = 0;
                row++;
            } else if (??) {
                break;
            }
        }
        return array;
    }
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
Egor, 2018-11-14
@RATlius

You have 2 errors in the code:
1 - The number of cells is not checked correctly. You need it like this:
2 - You don't need the "else if{}" block at all

PS Simplified implementation of your method:
public class  ConvertList2Array {
    public int[][] toArray(List<Integer> list, int rows) {
        int cells = list.size() % rows == 0 ? list.size() / rows : (list.size() / rows) + 1;
        int[][] array = new int[rows][cells];
        int index = 0;
        for (int c=0; c<cells; c++) //проход по столбцу
            for (int r=0; r<rows; r++) //проход по строкам
                array[r][c] = index++
                if (index == list.size()) break; //проверка на выход за предел list
        return array;
    }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question