简体   繁体   中英

2d array constructor that take array less equals or more than 3x3

Got a project from my degree that I'm stuck on one of the constructors.

  • The constructor name needs to look like this Square3x3(int[][] array) .
  • It has to construct a 2d array of the size 3x3, whose value are taken from the given array.
  • If the given array's size is bigger than 3x3, only the first 3x3 cells are taken.
  • If the given array is smaller, the rest of the cells are initialized to -1.

Note that the given array may be non-symmetrical, or may even have rows of different length.

Make sure to initialize cells to -1 if and only if the corresponding cell in the given array does not exist.

You may assume the array is not null.

The following code works for me when the given array is bigger than 3x3, but I cannot make it work when it's less than 3x3.

Note that all of this needs to be in a different class than main .

Thank you for the help.

I got the following code:

public class Square3x3 {
        
    private int[][] Square3x3;
    
    public Square3x3(int[][]array) {
        Square3x3 = new int[3][3];
        int count =0;
        for (int i = 0; i < 3 && i < array.length; i++) {
            for (int j = 0; j < 3 && j < array[count].length; j++) {
                Square3x3[i][j] = array[i][j];
            }
            count++;
        }
    }
}

You have to look in more detail at the logic for initializing the array. It's -1 if the index doesn't exist; otherwise it will be the value at the ij index. So you have to see if the array has at least the i-th row. If it doesn't, you know right away that for a given (i,j) you've got -1. If it does have at least the i-th row, does it have the j-th element? If no, -1 again. Otherwise it's the ij-th element of the array.

private int[][] square3x3;

public Square3x3(int[][] array) {
    final int dim = 3;
    final int defVal = -1;
    square3x3 = new int[dim][dim];
    for (int i = 0; i < dim; i++) {
        for (int j = 0; j < dim; j++) {
            final int val;
            if (array.length < (i + 1)) {
                val = defVal;
            } else {
                if (array[i].length < (j + 1)) {
                    val = defVal;
                } else {
                    val = array[i][j];
                }
            }
            square3x3[i][j] = val;
        }
    }
}
  1. Construct a result array of 3x3 size and fill it with -1.
  2. Copy the values from the input array as necessary, selecting a minimal value of 3 and rows/columns of the input array.
private int[][] square3x3 = {
    {-1, -1, -1},
    {-1, -1, -1},
    {-1, -1, -1}
};

public Square3x3(int[][] array) {
    for (int i = 0, n = Math.min(3, array == null ? -1 : array.length); i < n; i++) {
        for(int j = 0, m = Math.min(3, array[i] == null ? -1 : array[i].length); j < m; j++) {
            square3x3[i][j] = array[i][j];
        }
    }
}

So, if the dimensions of the input array are less than 3x3, the prepopulated values of -1 will be used when copying the values.

Tests:

Square3x3 sq = new Square3x3(new int[3][2]); // input 2D arr initialized with 0
        
System.out.println(Arrays.deepToString(sq.square3x3));

// jagged input
sq = new Square3x3(new int[][]{{1, 2}, {3}, {4, 5, 6}});
System.out.println(Arrays.deepToString(sq.square3x3));
// input with nulls
mc = new MyClass(new int[][]{{1, 2}, null, {3}});
System.out.println(Arrays.deepToString(mc.square3x3));

Output:

[[0, 0, -1], [0, 0, -1], [0, 0, -1]]
[[1, 2, -1], [3, -1, -1], [4, 5, 6]]
[[1, 2, -1], [-1, -1, -1], [3, -1, -1]]

To address a bit whimsical requirement about setting cells to -1 if and only if the corresponding cell in the given array does not exist the following implementation may be offered:

private int[][] square3x3;
public Square3x3(int[][] array) {
    square3x3 = new int[3][3]; // anyway an array filled with 0 is created
        
    for (int i = 0; i < 3; i++) {
        for(int j = 0; j < 3; j++) {
            square3x3[i][j] = null != array    && i < array.length 
                           && null != array[i] && j < array[i].length
                            ? array[i][j] : -1;
        }
    }
}

The requirement tries to provide specific implementation in a convoluted/sophisticated way which is nevertheless irrelevant for the expected output and actually necessitates running through all 3x3 cells in the loops while exactly the same can be achieved with proper initialization and irrelevant rows/cols may be skipped.

public void whosThereRow (int row, boolean [] values)

How the method works:

The method receives a row number (from the values 2,1,0) and a Boolean array Size 10.

For each number between 9-1 that appears in the corresponding row in the two-dimensional array of the method class will place a true value in the corresponding cell in the values array.

The rest of the cells in the array will be left without change.

I was handling this way less prettier and less logically.

What I did is to handle each edge case seperatley...

 public Square3x3(int[][] array)
{
    int val;
    int vala;

    _square3x3 = new int[ROWS][COLS];
    if(_square3x3.length <= array.length ) // checking if given array length is bigger or equal
    {
        {
            for(int i = 0; i < ROWS; i++) // iterating over the first row
            {
                for(int j = 0; j < COLS; j++ ) // iterating over row indexes
                {
                    if(_square3x3[j].length > array[j].length) //if 3 is bigger the array row length
                    {
                        val = array[j].length; // saving the row length
                        vala = i; //saving row index
                        for(int k = val; k < COLS; k++ ) //loop between the array row length till k is 3
                            _square3x3[vala][k] = -1; // completing missing row cells with -1

                    }
                    else if(_square3x3[j].length <= array[j].length) //if given array row lenght is equal or bigger
                    {
                        for(int a = 0; a < ROWS; a++)
                        {
                            for(int b = 0; b < COLS; b++ )
                            {
                                _square3x3[a][b] = array[a][b]; //taking only first 3x3 cells
                            }
                        }
                    }

                }
            }
        }
    }
    else  // applied this condition only if array.length is smallar then square3x3.length
    {
        int rowNdxCounter = 0;

        for (int i = 0; i < array.length; i++)
        {
            for (int j =0; j < COLS; j++) //looping over all cells
            {
                rowNdxCounter++; // for each cell value is increasing by one
            }
            if (rowNdxCounter != 3) //if counter not equals to three then i need to fill in the row with value of -1
            {
                for (int c=rowNdxCounter; c < COLS; c++)
                    _square3x3[i][c] = -1;
            } 
            rowNdxCounter = 0;
        }
        for (int k = array.length; k < ROWS; k++) //looping over the missing row
            for(int j = 0; j < COLS; j++) //looping over cells in the missing rows
                _square3x3[k][j] = -1; // filling them with -1

    }

Of course with all the brackets it does look long and very raw. But in first section of the method, I was dealing the case when given array is larger or equals and seperated it for two cases:

First case: If row length is bigger than given array's row lenght, and one of the the given array row lenght is smaller

  1. keeping the row cell index and keeping the current row index.
  2. Then running on the traget row and fill in the missing cells with -1 If one of the given array's row length is bigger or equals
  3. Running on target row and and make sure to take the first 3 cells

Second Case

If given array lengh is smaller. Only then it gets to second case scenario.

  1. setting a counter for later use.
  2. First making sure that each rows has three cells in it. For that im looping all over the row to get how many cells i have in the row and using the counter.

If row doesnt has three cells, (this is why using the counter),then filling in the missing cells with -1

  1. After making sure that the rows are filled, then im looping over the remaining rows and fill them with -1.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM