简体   繁体   中英

Repeating 2-D array?

So, here is the assignment we need to do.

https://docs.google.com/viewer?a=v&pid=sites&srcid=ZGVmYXVsdGRvbWFpbnx0c2NvbXB1dGVyc2NpZW5jZXxneDo1NWEyNjg0NGZhOGFhNDA5

I have done all of the methods except for the last one, method fullSymmetricPattern. I know I can use methods inside of other methods, especially for this last one, but I'm honestly unsure on where to start on this one. Can anyone give me any pointers on how to do it or where to start on this one? Thanks in advanced.

(c) Write the method fullSymmetricPattern. This method takes a two-dimensional array of String

as a parameter basePat that represents a pattern, and two int parameters, hReps and vReps. It returns

an array that has blocks repeated hReps times horizontally and vReps times vertically, where each

block is the two-way symmetrical pattern based on basePat.

public String[][] fullSymmetricPattern(String[][] basePat, int hReps, int vReps)

Method fullSymmetricPattern() is easiest implemented reusing the methods twoWaySymmetric() and copyOnce() (from (b) and (c) ).

  • Call twoWaySymmetric() to make a full pattern to be repeated
  • Create target matrix being hReps * vReps the size of the two-way-symmetric matrix
  • Using two nested loops, repeatedly call copyOnce() to copy two-way-symmetric matrix into target matrix, using appropriate offsets ( startRow and startCol ).

Followup to comment:

Can you confirm that my copyOnce method works before I move on? I think it's broken.

You deleted the code again, but it looked fairly ok, except:

  • Conditions for returning false were wrong.
  • Instead of looping until <= length - 1 , it's more common to simply write it as < length .
  • Since b[0].length will be used many times (for each iteration of inner times outer loop), it would be good to get it once, and by giving the variable a good name, it will also makes the code more readable.

Here is the updated version:

public static boolean copyOnce(String[][] a, String[][] b, int startRow, int startCol) {
    final int rowCount = b.length;
    final int colCount = b[0].length;
    if (startRow < 0 || startRow + rowCount > a.length)
        return false; // Invalid start row
    if (startCol < 0 || startCol + colCount > a[0].length)
        return false; // Invalid start column
    for (int row = 0; row < rowCount; row++)
        for (int col = 0; col < colCount; col++)
            a[startRow + row][startCol + col] = b[row][col];
    return true;
}

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