[英]Dividing a 1D array into a 2D array
所以我有作業要求我:
編寫一個帶有兩個參數的方法:一個整數數組和一個代表多個元素的 integer。 它應該返回一個二維數組,該數組是將傳遞的一維數組分成包含所需元素數量的行。 請注意,如果數組的長度不能被所需的元素數量整除,則最后一行的元素數量可能會更少。 例如,如果將數組
{1,2,3,4,5,6,7,8,9}
和數字4
傳遞給此方法,它應該返回二維數組{{1,2,3,4},{5,6,7,8},{9}}
。
我嘗試使用以下代碼解決它:
public static int[][] convert1DTo2D(int[] a, int n) {
int columns = n;
int rows = a.length / columns;
double s = (double) a.length / (double) columns;
if (s % 2 != 0) {
rows += 1;
}
int[][] b = new int[rows][columns];
int count = 0;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
if (count == a.length) break;
b[i][j] = a[count];
count++;
}
}
return b;
}
但是我遇到了一個問題,當我嘗試打印新數組時,這是 output:
[[1, 2, 3, 4], [5, 6, 7, 8], [9, 0, 0, 0]]
那么我怎樣才能刪除最后的 3 個零呢? 請注意,我不能使用java.util.*
中的任何方法或任何內置方法來執行此操作。
將二維數組的初始化更改為不包含第二維: new int[rows][]
。 您的陣列現在內部有 null arrays。 您必須在循環中初始化它們: b[i]=new int[Math.min(columns,remainingCount)];
其中剩余計數是二維數組之外的數字數量。
如果最終數組的大小不合適,則將此 if 條件添加到您的代碼中將縮短它:
...
final int[][] b = new int[rows][columns];
if ((a.length % columns) != 0) {
b[rows - 1] = new int[a.length % columns];
}
int count = 0;
...
%
是模運算符,它為您提供第一個和第二個數字除法的余數。
9 % 4
將返回 1,即我們最終數組所需的確切大小。
然后,我們只需要用該大小的新數組替換最終數組。
在方法中切換arguments可能會更好:
int[][] convert1DTo2D(int cols, int... arr)
允許使用可變參數。
此外,可以迭代輸入數組(單循環)而不是嵌套循環。
示例實現:
public static int[][] convert1DTo2D(int cols, int... a) {
int lastRowCols = a.length % cols;
int rows = a.length / cols;
if (lastRowCols == 0) {
lastRowCols = cols;
} else {
rows++;
}
int[][] b = new int[rows][];
for (int i = 0; i < a.length; i++) {
int r = i / cols;
int c = i % cols;
if (c == 0) { // start of the row
b[r] = new int[r == rows - 1 ? lastRowCols : cols];
}
b[r][c] = a[i];
}
return b;
}
用一維數組中的值填充二維數組,只要它們存在:
public static int[][] convert1DTo2D(int[] arr, int n) {
// row count
int m = arr.length / n + (arr.length % n == 0 ? 0 : 1);
// last row length
int lastRow = arr.length % n == 0 ? n : arr.length % n;
return IntStream.range(0, m)
.mapToObj(i -> IntStream.range(0, i < m - 1 ? n : lastRow)
.map(j -> arr[j + i * n])
.toArray())
.toArray(int[][]::new);
}
public static void main(String[] args) {
int[] arr1 = {1, 2, 3, 4, 5, 6, 7, 8, 9};
int[][] arr2 = convert1DTo2D(arr1, 4);
System.out.println(Arrays.deepToString(arr2));
// [[1, 2, 3, 4], [5, 6, 7, 8], [9]]
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.