[英]Copy 2D array and increase size to fill new values
如果我的問題措辭不好,我想首先道歉。 我參加了tmmrw考試,教授給了最終考試樣本供我們練習。 不幸的是,他沒有在論壇上提供解決方案,因此,我嘗試在該論壇上提供解決方案。 我似乎被這個問題困擾。 我必須編寫一個方法,該方法接受以整數值填充的NxM數組作為參數。 該方法將返回一個(N + 1)x(M + 1)數組,其中包含前N行和M列中原始數組的內容,以及每行/列中大於或等於零的項數在該行/列的末尾,將值-1放在右下角。 例如。
1 -2 0 returns 1 -2 0 2
3 -4 -5 3 -4 -5 1
2 0 1 -1
我似乎能夠復制該數組,但是我對如何在新數組的外部輸入值感到困惑。 這是我到目前為止所擁有的。
public static void main(String[] args) {
int[][] arr = { { 1, -2, 0 }, { 3, -4, -5 } };
int[][] newMatrix = processing2D(arr);
printArray(newMatrix);
}
//Method where I am having problems
public static int[][] processing2D(int[][] arr) {
int[][] matrix = new int[arr.length][arr[0].length];
for (int row = 0; row < matrix.length; row++) {
for (int col = 0; col < matrix[0].length; col++) {
// once I reach the last pos I enter the count
// of numbers greater than or equal to zero in that row/col
matrix[row][col] = arr[row][col];
}
}
// assign the corner -1 here
return matrix;
}
public static void printArray(int[][] list) {
for (int row = 0; row < list.length; row++) {
for (int col = 0; col <= list.length; col++) {
System.out.print(list[row][col] + " ");
}
System.out.println();
}
}
首先,您正在錯誤地初始化新數組
int[][] matrix = new int[arr.length+1][arr[0].length+1];
您不希望它的長度與您希望的長度+1相同。 另外,在您的for循環中,您想要的是arr而不是矩陣的長度,因為這就是您要提取的內容。 將值放入新的N + 1xM + 1數組中時,如果該行和列中對應的最后一個元素的值> = 0,則將其遞增1。
for (int row = 0; row < arr.length; row++) {
for (int col = 0; col < arr[0].length; col++) {
// once I reach the last pos I enter the count
// of numbers greater than or equal to zero in that row/col
if(arr[row][col]>=0){
matrix[row][matrix[row].length-1] = matrix[row][matrix[row].length-1] + 1;
matrix[matrix.length-1][col]= matrix[matrix.length-1][col] + 1;
}
matrix[row][col] = arr[row][col];
}
將所有值放回到新的N + 1xM + 1數組中之后,現在應該將這些值放入n個大小和m個大小的數組中,並將它們放入N + 1xM + 1數組中的相應插槽中。 之后,只需手動將-1放到右下角。
matrix[matrix.length-1][matrix[0].length-1]=-1;
在您的process2D方法中,首先創建一個具有正確大小的數組,該數組比原始數組多1行,多1列:
int[][] matrix = new int[arr.length+1][arr[0].length+1];
然后,要像以前一樣填充矩陣數組,但是需要注意不要引用超出范圍的arr數組的索引。 因為您的矩陣索引大於arr。 如果要填充新索引,則可以使用隨機數。
if(row < arr.length && col < arr[0].length)
{
matrix[row][col] = arr[row][col];
}
else
{
matrix[row][col] = new Random().nextInt(10);
}
所以這是完整的方法process2D:
public static int[][] processing2D(int[][] arr) {
int[][] matrix = new int[arr.length+1][arr[0].length+1];
for (int row = 0; row < matrix.length; row++) {
for (int col = 0; col < matrix[0].length; col++) {
// once I reach the last pos I enter the count
// of numbers greater than or equal to zero in that row/col
if(row < arr.length && col < arr[0].length)
{
matrix[row][col] = arr[row][col];
}
else
{
matrix[row][col] = new Random().nextInt(10);
}
}
}
// assign the corner -1 here
return matrix;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.