Конвертация ArrayList в двухмерный массив
Написал код по конвертации ArrayList в двухмерный массив,но тест проваливается. Прошу помочь найти ошибку.
public class ConvertList2Array {
public static int[][] toArray(List<Integer> list, int cells) {
int groups = (int) Math.ceil((double) list.size() / cells);
int[][] array = new int[groups][cells];
int row = 0, cell = 0, index = 0;
for (Integer num: list) {
while(cell < 3 && row < 3) {
array[row][cell] = num++;
cell++;
}
row++;
cell = 0;
}
return array;
}
public static void main(String[] args) {
List<Integer> list = List.of(1, 2, 3, 4, 5, 6, 7);
int[][] rsl = toArray(list, 3);
for (int[] row : rsl) {
for (int cell : row) {
System.out.print(cell + " ");
}
System.out.println();
}
}
}
public class ConvertList2ArrayTest {
@Test
public void when7ElementsThen9() {
ConvertList2Array list = new ConvertList2Array();
int[][] result = list.toArray(
Arrays.asList(1, 2, 3, 4, 5, 6, 7),
3
);
int[][] expect = {
{1, 2, 3},
{4, 5, 6},
{7, 0, 0}
};
assertThat(result, is(expect));
}
}
Ответы (1 шт):
Автор решения: Alexandr
→ Ссылка
Попробуйте так.
ConvertList2Array:
package com.somepackage;
import java.util.List;
public class ConvertList2Array {
public static int[][] toArray(List<Integer> list, int cells) {
int groups = (int) Math.ceil((double) list.size() / cells);
int[][] array = new int[groups][cells];
int i = 0;
int j = 0;
for (Integer n: list) {
array[i][j] = n;
if (++j >= cells) {
i++;
j = 0;
}
}
return array;
}
public static void main(String[] args) {
List<Integer> list = List.of(1, 2, 3, 4, 5, 6, 7);
int[][] rsl = toArray(list, 3);
for (int[] row : rsl) {
for (int cell : row) {
System.out.print(cell + " ");
}
System.out.println();
}
}
}
ConvertList2ArrayTest:
package com.somepackage;
import org.junit.jupiter.api.Test;
import java.util.Arrays;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class ConvertList2ArrayTest {
@Test
public void when7ElementsThen9() {
ConvertList2Array list = new ConvertList2Array();
int[][] result = list.toArray(
Arrays.asList(1, 2, 3, 4, 5, 6, 7),
3
);
int[][] expect = {
{1, 2, 3},
{4, 5, 6},
{7, 0, 0}
};
assertTrue(Arrays.deepEquals(result, expect));
}
}