ArrayTester is #4 from the from the 2018 AP Computer Science A Free Response problems.

https://secure-media.collegeboard.org/ap/pdf/ap18-frq-computer-science-a.pdf

Part (a) getColumn method

public static int[] getColumn(int[][] arr2D, int c)
{
    int[] column = new int[arr2D.length];

    for(int i = 0; i < column.length; i++)
        column[i] = arr2D[i][c];

    return column;
}

Part (b) isLatin method

public static boolean isLatin(int[][] square)
{
    if(containsDuplicates(square[0]))
        return false;

    for(int r = 1; r < square.length; r++)
        if( ! hasAllValues(square[0], square[r]) )
            return false;

    for(int c = 0; c < square[0].length; c++)
        if( ! hasAllValues(square[0], getColumn(square, c)))
            return false;

    return true;
}

A 2D array in Java is an array of 1D arrays. square[0] stores a reference to the 1D array representing the first row of square. square[r] stores a reference to the 1D array representing row r. See Treating a 2D array as an array of 1D arrays for additional details.

hasAllValues method

This method was NOT required to be implemented on the Exam. It is provided in case anyone would like to test their code with it.

Note: The inner loop could be made more efficient by stopping at the first occurrence. I was targeting ease of implementation.

public static boolean hasAllValues(int[] arr1, int[] arr2)
{
    for(int arr1Index = 0; arr1Index < arr1.length; arr1Index++)
    {
        boolean contains = false;
        for(int arr2Index = 0; arr2Index < arr2.length; arr2Index++)
        {
            if(arr1[arr1Index] == arr2[arr2Index])
                contains = true;
        }

        if( ! contains )
            return false;
    }

    return true;
}

containsDuplicates method

This method was NOT required to be implemented on the Exam. It is provided in case anyone would like to test their code with it.

public static boolean containsDuplicates(int[] arr)
{
    for(int i = 0; i < arr.length; i++)
        for(int j = i + 1; j < arr.length; j++)
            if(arr[i] == arr[j])
                return true;

    return false;
}

2018 AP CS Exam Free Response Solutions

Additional 2D array resources

Help & comments

Get help from AP CS Tutor Brandon Horn

Comment on ArrayTester