Skip to the content.

Unit 8 Hacks

Popcorn Hack 1

What’s wrong with this code:

int[][] exampleArray = {
    {"Hello", "World"},
    {"Java", "Array"}
};

Fixed version:

String[][] exampleArray = {
    {"Hello", "World"},
    {"Java", "Array"}
};

Popcorn Hack 2

How many total elements can this 2D array hold, and how would you calculate it?

int[][] matrix = new int[2][3];

Answer: 6. The total number of elements in a 2D array is the product of the number of rows and the number of columns.

example1

How would you write the code to access the last score? MC

A. grades[6][3] B. grades[7][4] C. grades[grades.length - 1] [grades[0].length - 1] D. A and C

Answer: D. A and C

Try on your own!

Write a code to declare and initialize a 2D array that stores the following matrix: 1 2 3 4 5 6 7 8 9

public class ArrayPractice {
    public static void main(String[] args) {
        // Declare and initialize the 2D array
        int[][] array = {
            {1, 2, 3},
            {4, 5, 6},
            {7, 8, 9}
        };

        // Print the array
        System.out.println(java.util.Arrays.deepToString(array));
    }
}

ArrayPractice.main(null);
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]

Try on your own!

Write the code to change the element “Java” to “Programming”

public class ArrayPractice {
    public static void main(String[] args) {
        String[][] hack = {
            {"Hello", "World"},
            {"Java", "Array"}
        };

        // Change "Java" to "Programming"
        hack[1][0] = "Programming";

        // Print the updated array
        System.out.println(java.util.Arrays.deepToString(hack));
    }
}

ArrayPractice.main(null);
[[Hello, World], [Programming, Array]]

Popcorn Hack!

mc1

Answer: B II only

Popcorn Hack

An array called find is shown below. In this popcorn hack, I want you to loop through the numbers until you get to the number that doesn’t belong (55). Then print that number along with which row and column it is located in.

public class Main {
    public static void main(String[] args) {
        int find[][] = {
            {10, 20, 30},
            {40, 55, 60},
            {70, 80, 90},
        };

        for (int row = 0; row < find.length; row++) {
            for (int col = 0; col < find[row].length; col++) {
                if (find[row][col] == 55) {
                    System.out.println("Number: " + find[row][col] + 
                                       ", Row: " + (row+1) + 
                                       ", Column: " + (col+1));
                    return;
                }
            }
        }
    }
}

Main.main(null);
Number: 55, Row: 2, Column: 2

Popcorn Hack:

Create your own 2D array and use either binary search or linear search. (maybe both 😏 )

public class Main {
    public static void main(String[] args) {
        int[][] array = {
            {1, 2, 3},
            {4, 5, 6},
            {7, 8, 9},
            {10, 11, 12}
        };

        int target = 5;

        // Perform linear search
        System.out.println("Linear Search:");
        int[] linearResult = linearSearch(array, target);
        if (linearResult != null) {
            System.out.println("Found " + target + " at Row: " + linearResult[0] + ", Column: " + linearResult[1]);
        } else {
            System.out.println(target + " not found.");
        }

        // Perform binary search
        System.out.println("\nBinary Search:");
        int binaryResult = binarySearch(array, target);
        if (binaryResult != -1) {
            System.out.println("Found " + target + " at index: " + binaryResult);
        } else {
            System.out.println(target + " not found.");
        }
    }

    public static int[] linearSearch(int[][] array, int target) {
        for (int row = 0; row < array.length; row++) {
            for (int col = 0; col < array[row].length; col++) {
                if (array[row][col] == target) {
                    return new int[]{row, col}; 
                }
            }
        }
        return null;
    }

    public static int binarySearch(int[][] array, int target) {
        for (int row = 0; row < array.length; row++) {
            int left = 0;
            int right = array[row].length - 1;

            while (left <= right) {
                int mid = left + (right - left) / 2;
                if (array[row][mid] == target) {
                    return row * array[row].length + mid;
                } else if (array[row][mid] < target) {
                    left = mid + 1;
                } else {
                    right = mid - 1;
                }
            }
        }
        return -1;
    }
}

Main.main(null);
Linear Search:
Found 5 at Row: 1, Column: 1

Binary Search:
Found 5 at index: 4

Popcorn Hack:

Write a code that performs global sorting on your own 2D array.

import java.util.Arrays;

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

        int[] sortedArray = sort2DArray(array);
        System.out.println("Sorted Array: " + Arrays.toString(sortedArray));

        int target = 5;

        int[] linearResult = linearSearch(array, target);
        if (linearResult[0] != -1) {
            System.out.println("Linear Search: Element found at: Row " + linearResult[0] + ", Column " + linearResult[1]);
        } else {
            System.out.println("Linear Search: Element not found.");
        }

        int[] binaryResult = binarySearch(array, target);
        if (binaryResult[0] != -1) {
            System.out.println("Binary Search: Element found at: Row " + binaryResult[0] + ", Column " + binaryResult[1]);
        } else {
            System.out.println("Binary Search: Element not found.");
        }
    }

    public static int[] sort2DArray(int[][] array) {
        int totalElements = 0;
        for (int[] row : array) {
            totalElements += row.length;
        }

        int[] flatArray = new int[totalElements];
        int index = 0;
        for (int[] row : array) {
            for (int num : row) {
                flatArray[index++] = num;
            }
        }

        Arrays.sort(flatArray);
        return flatArray;
    }

    public static int[] linearSearch(int[][] array, int target) {
        for (int row = 0; row < array.length; row++) {
            for (int col = 0; col < array[row].length; col++) {
                if (array[row][col] == target) {
                    return new int[]{row, col};
                }
            }
        }
        return new int[]{-1, -1};
    }

    public static int[] binarySearch(int[][] array, int target) {
        for (int row = 0; row < array.length; row++) {
            Arrays.sort(array[row]);
            int left = 0;
            int right = array[row].length - 1;

            while (left <= right) {
                int mid = left + (right - left) / 2;
                if (array[row][mid] == target) {
                    return new int[]{row, mid};
                } else if (array[row][mid] < target) {
                    left = mid + 1;
                } else {
                    right = mid - 1;
                }
            }
        }
        return new int[]{-1, -1};
    }
}

PopcornHack.main(null);
Sorted Array: [1, 3, 4, 5, 6, 7, 8, 9, 12]
Linear Search: Element found at: Row 0, Column 2
Binary Search: Element found at: Row 0, Column 1

HW Hack for 8.1:

You are given a function below, and your goal is to match the table to match the 2d array provided in the function.

public class Main {
    public static void main(String[] args) {
        String[][] array = {
            {"My", "A"}, 
            {"AP", "Class"}, 
            {"CS", "Rocks!"}
        };
        
        for (int col = 0; col < array[0].length; col++) {
            for (int row = 0; row < array.length; row++) {
                System.out.print(array[row][col] + " ");
            }
        }
    }
}

Main.main(null);
My AP CS A Class Rocks! 

Of the following, which is the correct table for the 2d array provided in the function?

A)

  1 2 3
1 My CS Class
2 AP A Rocks!

B)

  1 2 3
1 My AP CS
2 A Class Rocks!

C)

  1 2 3
1 My AP Class
2 Rocks! CS A

Answer: B

HW Hack for 8.2:

Write a program to search through a 2d array to find the grade for John. You will be given a list of students and their grades and you must find the grade of John. If a student is not in the list, then return “Student not found”.

Use this program as a template:

public class GradeSearch {
    public static String searchGrade(String[][] grades, String name) {
        // Loop through each row in the 2D array
        for (String[] student : grades) {
            // Check if the first element (student's name) matches the search name
            if (student[0].equals(name)) {
                // Return the second element (student's grade) if the name matches
                return student[1];
            }
        }
        // If the student is not found, return "Student not found"
        return "Student not found";
    }

    public static void main(String[] args) {
        // Sample 2D array with names and grades
        String[][] grades = {
            {"John", "93"},
            {"Alice", "85"},
            {"Bob", "78"},
            {"Eve", "92"}
        };

        // Test the search function
        String nameToSearch = "John";
        String grade = searchGrade(grades, nameToSearch);
        System.out.println(nameToSearch + "'s grade: " + grade);

        nameToSearch = "Charlie";
        grade = searchGrade(grades, nameToSearch);
        System.out.println(nameToSearch + "'s grade: " + grade);
    }
}

// Execute the main method to see the output
GradeSearch.main(null);
John's grade: 93
Charlie's grade: Student not found

Heres a hint, try to use enhanced for loops to check each row for the name John. If you find John, then return the grade. If you don’t find John, then return “Student not found”.