Contents

Special two-dimensional array 1 (with.Java)

   Dec 2, 2023     2 min read

This is a recap of the “Special two-dimensional array 1” problem.

We’re going to learn about it by solving coding test problems, reflecting on the problems we’ve solved, and exploring other ways to solve them.

Let’s start with the problem

Problem

Write a solution function that, given an integer n as a parameter, returns a two-dimensional array arr of size n × n that looks like this

The value of arr[i][j] (0 ≤ i, j < n) is 1 if i = j and 0 otherwise.

Example input and output

nresult
3[[1, 0, 0], [0, 1, 0], [0, 0, 1]]
6[[1, 0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0], [0, 0, 0, 1, 0, 0], [0, 0, 0, 0, 1, 0], [0, 0, 0, 0, 0, 1]]
1[[1]]

My solution to the ### problem

class Solution {
    public int[][] solution(int n) {
        int[][] answer = new int[n][n];
        for(int i = 0; i < n; i++){
            for(int j = 0; j < n; j++){
                if(i == j){
                    answer[i][j] = 1;
                }else {
                    answer[i][j] = 0;
                }
            }
        }
    } return answer;
}

Solution

int[][] answer = new int[n][n];: create a two-dimensional array answer of size n x n.

for(int i = 0; i < n; i++) : Iterate through the rows of the array, with the value of i representing the current row.

for(int j = 0; j < n; j++) : Iterates through the columns of the array, with the value of j representing the current column.

if(i == j) : if the current row and column have the same index (main diagonal element):

Store 1 in the array element at that position.

else : Otherwise (non-major diagonal element):

Store a 0 in the array element at that position.

return answer;: Returns a two-dimensional array answer initialized with the unit matrix.