多维数组 – 输入数组的维度

huangapple go评论76阅读模式
英文:

Multidimensional array - dimmension of input array

问题

我正在Hyperskill平台上学习Java入门课程。我遇到了一个编译错误,但没有在任何地方找到描述(第6个错误测试未通过。答案错误)。

你能否查看我的代码并帮助我?

请查看任务描述。

你需要实现printCorners方法。它应该按照以下顺序打印twoDimArray的所有角元素:从左到右,从上到下。

这些元素必须用空格分隔,并按以下示例打印。

输入数组:

1 0 2
0 0 0
3 0 4

打印的角元素:

1 2
3 4

请注意,你必须始终打印4个角元素,例如:

输入数组:

1
2
3

打印的角元素:

1 1
3 3

代码:

public class ArrayOperations {
    public static void printCorners(int[][] twoDimArray) {
        int n = 2;
        int[][] myTable = new int[n][n];
        int cols = twoDimArray[0].length;
        if (cols == 1) {
            for (int i = 0; i < twoDimArray.length; i++) {
                if (i == 0) {
                    myTable[0][0] = twoDimArray[i][0];
                    myTable[0][1] = twoDimArray[i][0];
                    myTable[1][0] = twoDimArray[i][0];
                    myTable[1][1] = twoDimArray[i][0];
                }
                else if (i < twoDimArray.length - 1) {
                    myTable[1][0] = twoDimArray[i][0];
                    myTable[1][1] = twoDimArray[i][0];
                }
            }
            System.out.println(myTable[0][0] + " " + myTable[0][0]);
            System.out.println(myTable[1][0] + " " + myTable[1][1]);
        }
        else if (cols > 1) {
            for (int i = 0; i < twoDimArray.length; i++) {
                for (int j = 0; j < twoDimArray[i].length; j++) {
                    if (i == 0 && j == 0) {
                        myTable[0][0] = twoDimArray[i][j];
                    }
                    else if (i == 0 && j == twoDimArray[i].length - 1) {
                        myTable[0][1] = twoDimArray[i][j];
                    }
                    else if (i == twoDimArray.length - 1 && j == 0) {
                        myTable[1][0] = twoDimArray[i][j];
                    }
                    else if (i == twoDimArray.length - 1 && j == twoDimArray[i].length - 1) {
                        myTable[1][1] = twoDimArray[i][j];
                    }
                }
            }
            for (int i = 0; i < myTable.length; i++) {
                for (int j = 0; j < myTable[i].length; j++) {
                    System.out.print(myTable[i][j] + " ");
                }
                System.out.println();
            }
        }
    }
}
英文:

I am doing course in Hyperskill platform - Introduction to Java. I am facing with an error of compilation which is not described anywhere (Failed test #6 of 8. Wrong answer)

Would you be able to look into my code and help me?

Please see the task description.

You need to implement printCorners method. It should print all corner elements of the twoDimArray in the following order: left to right and top to bottom.

The elements must be separated by space and printed as an example below.

Input array:

1 0 2
0 0 0
3 0 4

Printed corners:

1 2
3 4

Notice, that you must always print 4 corners, for example:

Input array:

1
2
3

Printed corners:

1 1
3 3

code:

public class ArrayOperations {
    public static void printCorners(int[][] twoDimArray) {
        int n = 2;
        int[][] myTable = new int[n][n];
        int cols = twoDimArray[0].length;
        if (cols == 1) {
            for (int i = 0; i &lt; twoDimArray.length; i++) {
                if (i == 0) {
                    myTable[0][0] = twoDimArray[i][0];
                    myTable[0][1] = twoDimArray[i][0];
                    myTable[1][0] = twoDimArray[i][0];
                    myTable[1][1] = twoDimArray[i][0];
                }
                else if (i &lt; twoDimArray.length - 1) {
                    myTable[1][0] = twoDimArray[i][0];
                    myTable[1][1] = twoDimArray[i][0];
                }
            }
            System.out.println(myTable[0][0] + &quot; &quot; + myTable[0][0]);
            System.out.println(myTable[1][0] + &quot; &quot; + myTable[1][1]);
        }
        else if (cols &gt; 1) {
            for (int i = 0; i &lt; twoDimArray.length; i++) {
                for (int j = 0; j &lt; twoDimArray[i].length; j++) {
                    if (i == 0 &amp;&amp; j == 0) {
                        myTable[0][0] = twoDimArray[i][j];
                    }
                    else if (i == 0 &amp;&amp; j == twoDimArray[i].length - 1) {
                        myTable[0][1] = twoDimArray[i][j];
                    }
                    else if (i == twoDimArray.length - 1 &amp;&amp; j == 0) {
                        myTable[1][0] = twoDimArray[i][j];
                    }
                    else if (i == twoDimArray.length - 1 &amp;&amp; j == twoDimArray[i].length - 1) {
                        myTable[1][1] = twoDimArray[i][j];
                    }
                }
            }
            for (int i = 0; i &lt; myTable.length; i++) {
                for (int j = 0; j &lt; myTable[i].length; j++) {
                    System.out.print(myTable[i][j] + &quot; &quot;);
                }
                System.out.println();
            }
        }
    }
}

答案1

得分: 0

这是基于 Java 的完整解决方案

import java.util.ArrayList;
import java.util.List;

class ArrayOperations {

    public static void main(String[] args) {
        int[][] multiDimensionalArray1 = {
            {1, 2, 3},
            {4, 5, 6},
            {7, 8, 9}
        };

        int[][] multiDimensionalArray2 = {
            {1, 2},
            {4, 5}
        };

        int[][] multiDimensionalArray3 = {
            {1}
        };

        int[][] transformedArray1 = transformToMultiDimensionalArray(multiDimensionalArray1, 2);
        int[][] transformedArray2 = transformToMultiDimensionalArray(multiDimensionalArray2, 2);
        int[][] transformedArray3 = transformToMultiDimensionalArray(multiDimensionalArray3, 2);

        for (int[] subarray : transformedArray1) {
            for (int element : subarray) {
                System.out.print(element + " ");
            }
            System.out.println();
        }

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

        for (int[] subarray : transformedArray2) {
            for (int element : subarray) {
                System.out.print(element + " ");
            }
            System.out.println();
        }

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

        for (int[] subarray : transformedArray3) {
            for (int element : subarray) {
                System.out.print(element + " ");
            }
            System.out.println();
        }
    }

    public static int[][] transformToMultiDimensionalArray(int[][] matrix, int elementsPerSubarray) {
        int rows = matrix.length;
        int cols = matrix[0].length;

        if (rows == 1 && cols == 1) {
            return new int[][]{{matrix[0][0]}};
        }

        List<Integer> corners = new ArrayList<>();

        for (int row = 0; row < rows; row++) {
            for (int col = 0; col < cols; col++) {
                if (row == 0 && col == 0) {
                    corners.add(matrix[row][col]); // 第一个元素,第一行
                } else if (row == 0 && col == cols - 1) {
                    corners.add(matrix[row][col]); // 最后一个元素,第一行
                } else if (row == rows - 1 && col == 0) {
                    corners.add(matrix[row][col]); // 第一个元素,最后一行
                } else if (row == rows - 1 && col == cols - 1) {
                    corners.add(matrix[row][col]); // 最后一个元素,最后一行
                }
            }
        }

        int[][] multiDimensionalArray = new int[corners.size() / elementsPerSubarray][elementsPerSubarray];
        for (int i = 0; i < corners.size(); i++) {
            int row = i / elementsPerSubarray;
            int col = i % elementsPerSubarray;
            multiDimensionalArray[row][col] = corners.get(i);
        }

        return multiDimensionalArray;
    }
}
这不是来自 Java 的代码我使用了 JavaScript出于呈现目的我采用了基于 JavaScript 的答案但是逻辑与上述 Java 解决方案相同

请参考下面的代码

function printCornerElements(matrix, elementsPerSubarray) {
  let rows = matrix.length;
  let cols = matrix[0].length;

  if (rows === 1 && cols === 1) { 
    return [matrix[0][0]];
  }

  let corners = [];

  for (let row = 0; row < rows; row++) {
    for (let col = 0; col < cols; col++) {
      if (row === 0 && col === 0) {
        corners.push(matrix[row][col]); // 第一个元素,第一行
      } else if (row === 0 && col === cols - 1) {
        corners.push(matrix[row][col]); // 最后一个元素,第一行
      } else if (row === rows - 1 && col === 0) {
        corners.push(matrix[row][col]); // 第一个元素,最后一行
      } else if (row === rows - 1 && col === cols - 1) {
        corners.push(matrix[row][col]); // 最后一个元素,最后一行
      }
    }
  }
  
  let multiDimensionalArray = [];
  for (let i = 0; i < corners.length; i += elementsPerSubarray) {
    let subarray = corners.slice(i, i + elementsPerSubarray);
    multiDimensionalArray.push(subarray);
  }

  return multiDimensionalArray;
}

const multiDimensionalArray1 = [
  [1, 2,3],
  [4, 5,6],
  [7, 8,9],

];

const multiDimensionalArray2 = [
  [1, 2],
  [4, 5],

];

const multiDimensionalArray3 = [
  [1]
];

console.log(JSON.stringify(printCornerElements(multiDimensionalArray1,2)));
console.log(JSON.stringify(printCornerElements(multiDimensionalArray2,2)));
console.log(JSON.stringify(printCornerElements(multiDimensionalArray3,2)));
英文:

Here is full java based solution:

import java.util.ArrayList;
import java.util.List;
class ArrayOperations {
public static void main(String[] args) {
int[][] multiDimensionalArray1 = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
int[][] multiDimensionalArray2 = {
{1, 2},
{4, 5}
};
int[][] multiDimensionalArray3 = {
{1}
};
int[][] transformedArray1 = transformToMultiDimensionalArray(multiDimensionalArray1, 2);
int[][] transformedArray2 = transformToMultiDimensionalArray(multiDimensionalArray2, 2);
int[][] transformedArray3 = transformToMultiDimensionalArray(multiDimensionalArray3, 2);
for (int[] subarray : transformedArray1) {
for (int element : subarray) {
System.out.print(element + &quot; &quot;);
}
System.out.println();
}
System.out.println(&quot;------------------------------------&quot;);
for (int[] subarray : transformedArray2) {
for (int element : subarray) {
System.out.print(element + &quot; &quot;);
}
System.out.println();
}
System.out.println(&quot;------------------------------------&quot;);
for (int[] subarray : transformedArray3) {
for (int element : subarray) {
System.out.print(element + &quot; &quot;);
}
System.out.println();
}
}
public static int[][] transformToMultiDimensionalArray(int[][] matrix, int elementsPerSubarray) {
int rows = matrix.length;
int cols = matrix[0].length;
if (rows == 1 &amp;&amp; cols == 1) {
return new int[][]{{matrix[0][0]}};
}
List&lt;Integer&gt; corners = new ArrayList&lt;&gt;();
for (int row = 0; row &lt; rows; row++) {
for (int col = 0; col &lt; cols; col++) {
if (row == 0 &amp;&amp; col == 0) {
corners.add(matrix[row][col]); // first element first row
} else if (row == 0 &amp;&amp; col == cols - 1) {
corners.add(matrix[row][col]); // last element first row
} else if (row == rows - 1 &amp;&amp; col == 0) {
corners.add(matrix[row][col]); // first element last row
} else if (row == rows - 1 &amp;&amp; col == cols - 1) {
corners.add(matrix[row][col]); // last element last row
}
}
}
int[][] multiDimensionalArray = new int[corners.size() / elementsPerSubarray][elementsPerSubarray];
for (int i = 0; i &lt; corners.size(); i++) {
int row = i / elementsPerSubarray;
int col = i % elementsPerSubarray;
multiDimensionalArray[row][col] = corners.get(i);
}
return multiDimensionalArray;
}
}

This is not from Java. I've used javascript. For presentational purposes, I've adopted javascript based answer for this. But logic remains the same as above java solution.

Refer the code below:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

function printCornerElements(matrix, elementsPerSubarray) {
let rows = matrix.length;
let cols = matrix[0].length;
if (rows === 1 &amp;&amp; cols === 1) { 
return [matrix[0][0]];
}
let corners = [];
for (let row = 0; row &lt; rows; row++) {
for (let col = 0; col &lt; cols; col++) {
if (row === 0 &amp;&amp; col === 0) {
corners.push(matrix[row][col]); // first element first row
} else if (row === 0 &amp;&amp; col === cols - 1) {
corners.push(matrix[row][col]); // last element first row
} else if (row === rows - 1 &amp;&amp; col === 0) {
corners.push(matrix[row][col]); // first element last row
} else if (row === rows - 1 &amp;&amp; col === cols - 1) {
corners.push(matrix[row][col]); // last element last row
}
}
}
let multiDimensionalArray = [];
for (let i = 0; i &lt; corners.length; i += elementsPerSubarray) {
let subarray = corners.slice(i, i + elementsPerSubarray);
multiDimensionalArray.push(subarray);
}
return multiDimensionalArray;
}
const multiDimensionalArray1 = [
[1, 2,3],
[4, 5,6],
[7, 8,9],
];
const multiDimensionalArray2 = [
[1, 2],
[4, 5],
];
const multiDimensionalArray3 = [
[1]
];
console.log(JSON.stringify(printCornerElements(multiDimensionalArray1,2)));
console.log(JSON.stringify(printCornerElements(multiDimensionalArray2,2)));
console.log(JSON.stringify(printCornerElements(multiDimensionalArray3,2)));

<!-- end snippet -->

答案2

得分: 0

你似乎把这个问题复杂化了。角元素的索引可以很容易确定如下:

  • 左上角 = 0, 0
  • 右上角 = 0, 行长度减一
  • 左下角 = 行数减一, 0
  • 右下角 = 行数减一, 行长度减一

运行上述代码会产生以下输出:

1 1 
3 3 
====================================================================
1 2 
3 4
英文:

You seem to be making this more complicated than it needs to be. The indexes of the corner elements can easily be determined as follows:

  • top left = 0, 0
  • top right = 0, length of row minus one
  • bottom left = number of rows minus one, 0
  • bottom right = number of rows minus one, length of row minus one
public class ArrayOperations {
    public static void printCorners(int[][] twoDimArray) {
        int n = 2;
        int[][] myTable = new int[n][n];
        myTable[0][0] = twoDimArray[0][0];
        myTable[0][1] = twoDimArray[0][twoDimArray[0].length - 1];
        myTable[1][0] = twoDimArray[twoDimArray.length - 1][0];
        myTable[1][1] = twoDimArray[twoDimArray.length - 1][twoDimArray[0].length - 1];
        for (int row = 0; row &lt; 2; row++) {
            for (int col = 0; col &lt; 2; col++) {
                System.out.print(myTable[row][col] + &quot; &quot;);
            }
            System.out.println();
        }
    }

    public static void main(String[] args) {
        printCorners(new int[][]{{1}, {2}, {3}});
        System.out.println(&quot;====================================================================&quot;);
        printCorners(new int[][]{{1, 0, 2},
                                 {0, 0, 0},
                                 {3, 0, 4}});
    }
}

Running above code produces following output:

1 1 
3 3 
====================================================================
1 2 
3 4

答案3

得分: 0

>你需要实现`printCorners`方法它应该按照从左到右从上到下的顺序打印出`twoDimArray`的所有角落元素

由于你只被要求打印数组所以不需要构建一个新的数组这也可以从方法声明为`void`且不允许返回创建的数组来证明

**一些测试数据**
```java
int[][] a1 = {{1},{2},{3}};
int[][] a2 = {{1,2,3,4},{2,3,4,5},{4,5,6,7}};
int[][] jagged = {{1},{2,3},{3,4},{5,6,7,7}};

该方法

为了简单起见,定义一些位置:

  • lri - 最后一行索引
  • lifr - 第一行的最后一个索引
  • lilr - 最后一行的最后一个索引
public static void printCorners(int[][] arr) {
    int lri = arr.length-1;
    int lifr = arr[0].length-1;
    int lilr = arr[lri].length-1;
    System.out.printf(" %d %d%n", arr[0][0],arr[0][lifr]);
    System.out.printf(" %d %d%n", arr[lri][0],arr[lri][lilr]);
}
printCorners(a1);  System.out.println();
printCorners(a2);  System.out.println();
printCorners(jagged);  System.out.println();

输出

1 1
3 3

1 4
4 7

1 1
5 7
英文:

>You need to implement printCorners method. It should print all corner elements of the twoDimArray in the following order: left to right and top to bottom.

Since all you are asked to do is print the arrays, there is no need to build a new array. Also evidenced by the method being declared void and does not permit the return of the created array.

Some test Data

int[][] a1 = {{1},{2},{3}};
int[][] a2 = {{1,2,3,4},{2,3,4,5},{4,5,6,7}};
int[][] jagged = {{1},{2,3},{3,4},{5,6,7,7}};

The Method

To make it easy, define some positions

  • lri - last row index
  • lifr - last index of first row
  • lilr - last index of last row
public static void printCorners(int[][] arr) {
int lri = arr.length-1;
int lifr = arr[0].length-1;
int lilr = arr[lri].length-1;
System.out.printf(&quot;%d %d%n&quot;, arr[0][0],arr[0][lifr]);
System.out.printf(&quot;%d %d%n&quot;, arr[lri][0],arr[lri][lilr]);
}
printCorners(a1);  System.out.println();
printCorners(a2);  System.out.println();
printCorners(jagged);  System.out.println();

prints

1 1
3 3
1 4
4 7
1 1
5 7
</details>

huangapple
  • 本文由 发表于 2023年7月23日 17:41:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/76747554.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定