Unit 8 - 2D Arrays
Unit 8.1
Popcorn Hack 1
int[][] exampleArray = {
{"Hello", "World"},
{"Java", "Array"}
};
It needs to be String[][]
and not int[][]
because the elements in the array are string (they are surrounded by quotes).
Popcorn Hack 2
int[][] matrix = new int[2][3]; // has 2 * 3 elements = 6 elements
Popcorn Hack 3
D: You can dynamically calculate the lengths or manually select it. Also, indexing is at 0 so you need to keep that in mind.
Popcorn Hack 4
public class ArrayPractice {
public static void main(String[] args) {
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]]
Popcorn Hack 5
String[][] hack = {
{"Hello", "World"},
{"Java", "Array"}
};
//Insert code below:
hack[1][0] = "Programming";
Programming
Popcorn Hack 6
B is correct: You need to access the 1st row (indexing is at 0) and the 0th column. This will change the Australia to Athens properly.
Unit 8.2
Popcorn Hack 1
public class Main {
public static void main(String[] args) {
int find[][] = {
{10, 20, 30},
{40, 55, 60},
{70, 80, 90},
};
for (int i = 0; i < find.length; i++) {
for (int j = 0; j < find[i].length; j++) {
if (find[i][j] == 55) {
System.out.println("Number " + find[i][j] + " has positon of: " + i + ", " + j);
}
}
}
}
}
Main.main(null);
Number 55 has positon of: 1, 1
Popcorn Hack 2
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
int[][] array = {
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 22},
{13, 14, 15, 16}
};
linearSearch(array, 22);
binarySearch(array, 10);
linearSearch(array, 222);
binarySearch(array, 101);
}
public static void linearSearch(int[][] array, int target) {
// loop through rows and columns
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[i].length; j++) {
// do we have a match? if so, print that we did
if (array[i][j] == target) {
System.out.println("Element found at index: [" + i + ", " + j + "]");
return;
}
}
}
// we found nothing
System.out.println("Element not found.");
}
public static void binarySearch(int[][] array, int target) {
// rows, columns, pre checking
int rows = array.length;
int cols = array[0].length;
if (rows == 0) {
System.out.println("Element not found.");
}
int left = 0;
int right = rows * cols - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
int midValue = array[mid / cols][mid % cols];
if (midValue == target) {
// match was found
System.out.println("Element found at: Row " + mid / cols + ", Column " + mid % cols);
return;
}
if (midValue < target) {
left = mid + 1; // move to right half
}
else {
right = mid - 1; // move to left half
}
}
// match not found
System.out.println("Element not found.");
}
}
Main.main(null);
Element found at index: [2, 3]
Element found at: Row 2, Column 1
Element not found.
Element not found.
Popcorn Hack 3
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
// create an array
int[][] array = {
{4, 1, 9},
{7, 5, 2},
{8, 3, 6}
};
// show original array
System.out.println("Original 2D Array:");
print2DArray(array);
// flatten array
int[] flattenedArray = flatten2DArray(array);
// sort the 1d array
Arrays.sort(flattenedArray);
// unflatten
int[][] sortedArray = reshape1DTo2D(flattenedArray, array.length, array[0].length);
// show
System.out.println("\nSorted 2D Array:");
print2DArray(sortedArray);
}
// flatten a 2D array into a 1D array
public static int[] flatten2DArray(int[][] array) {
int rows = array.length;
int cols = array[0].length;
int[] result = new int[rows * cols];
int index = 0;
// traverse 2D array and store elements in the 1D array
for (int[] row : array) {
for (int element : row) {
result[index++] = element;
}
}
return result;
}
// reshape a 1D array back into a 2D array
public static int[][] reshape1DTo2D(int[] array, int rows, int cols) {
int[][] result = new int[rows][cols];
int index = 0;
// traverse 1D array and assign values to the 2D array
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
result[i][j] = array[index++];
}
}
return result;
}
// function to print a 2D array
public static void print2DArray(int[][] array) {
for (int[] row : array) {
for (int element : row) {
System.out.print(element + " ");
}
System.out.println();
}
}
}
Main.main(null);
Original 2D Array:
4 1 9
7 5 2
8 3 6
Sorted 2D Array:
1 2 3
4 5 6
7 8 9
HW
8.1
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?
The correct table would be B. In B, there is the sequence “My” + “AP” + “CS” in that order. The sequence “A” + “Class” + “Rocks!” is there too. These sequences have to be there to match the sentence which was printed.
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:
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”.
public class GradeSearch {
public static String searchGrade(String[][] grades, String name) {
/*
* TODO: Implement the logic to find the grade of the student with the given name
* Loop through each row in the grades array
* Check if the first element (name) matches the search name
* If the name matches, return the second element (grade)
* If the student is not found, return "Student not found"
*/
int a = 0; // keep track of the column
// enhanced loop
for (String[] i : grades) {
a++;
for (String j : i) {
if (j == name) {
// match was found
// return the grade (we kept track of the column so this is easy)
return grades[a - 1][1];
}
}
}
// no match 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 = "Alice";
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);
Alice's grade: 85
Charlie's grade: Student not found