Question 8 (Mati and Edwin) - Loop Practice

mainscore

College Board Explanation:

Incorrect. This would be the result if the array results were assigned the products in the opposite order that they are calculated. In other words, for each value of j, the calculated product was assigned to result[result.length – 1 - j]. Correct. In the first iteration of the for loop, j is 0. The value of result[0] is assigned the product of row 1, column 0, which is 1 and row 0, column 2, which is 1. Therefore, result[0] is assigned the value 1. The second iteration of the for loop, when j is 1, result[1] is assigned the product of row 1, column 1, which is 2, and row 1, column 2, which is 3. Therefore, result[1] is assigned the value 6. The third iteration of the for loop, when j is 2, result[2] is assigned the product of row 1, column 2, which is 3, and row 2, column 2, which is 1. Therefore, result[2] is assigned the value 3. The final iteration of the for loop, when j is 3, result[3] is assigned the product of row 1, column 3, which is 4, and row 3, column 2, which is 1. Therefore, result[3] is assigned the value 4.

Popcorn Hack

To make sure you understand the concept, please complete this question, even though it is the same code, the values of the rows and columns are different to show you understand the concept

Consider the Following Method:

public static int[] operation(int[][] matrix, int r, int c)
{
    int[] result = new int[matrix.length];
    for (int j = 0; j < matrix.length; j++)
    {
        result[j] = matrix[r][j] * matrix[j][c];
    }
    return result;
}

The following code segment appears in another method in the same class:

int[][] mat = {(2, 3, 4, 1),
    (4, 3, 2, 1),
    (1, 4, 3, 2),
    (2, 2, 2, 2)};

Question 18 - Math with Java

mainscore

I was surprised I got this question wrong, but again it was because I was rushing. The first operation that is executed is 404/10. This returns 40 NOT 40.4 since they are both integers going through integer division. Then the value of 40 will be multiplied by 10, resulting in 400. 400 + 1 = 401 which is printed as the final answer.

There were just a lot of things at play that were tricky about this especially that the 404/10 != 40.4. Multiplication and division have the same priority so the order of operations was not much of a struggle for me.

Numerical Data Types: In Java, numerical data types represent numbers. The two main categories are integers and floating-point numbers.

Integers: Whole numbers without decimal points. Examples include int and long.

Floating-point: Numbers with decimal points. Examples include float and double.

Mathematical Operations: Java supports a variety of mathematical operations that you can perform on numerical data types.

Addition (+): Combines two numbers.

int result = 5 + 3; // Result will be 8

Subtraction (-): Finds the difference between two numbers.

int result = 7 - 4; // Result will be 3

Multiplication ():* Multiplies two numbers.

int result = 6 * 2; // Result will be 12

Division (/): Divides one number by another.

double result = 10.0 / 3.0; // Result will be 3.3333...

Modulus (%): Returns the remainder after division.

int result = 15 % 4; // Result will be 3

Summary:

Integers (int):

Experience truncation during division (decimal part discarded). May result in rounding down or loss of precision. Final result is exact within the range of integers.

Doubles (double):

Preserve decimal precision during division. More accurate results in floating-point operations. Final result may have a decimal part, providing a more precise answer.

Key Takeaway:

Integer Operations:

Rounding or truncation occurs during division. Exact within the range of integers but may lead to loss of precision.

Floating-Point Operations:

Maintain decimal precision during operations. Provide more accurate results but might introduce rounding errors.

Understanding how each type of number behaves during operations is important. Integers may be exact within their range but could lose precision, while doubles preserve decimal precision, offering more accurate results despite the potential for rounding errors. Choosing the appropriate type depends on the nature of the calculations and the desired level of precision.

Question 20 - Binary Search

mainscore

Let’s Review Some Concepts! What is a binary search?

A search algorithm that works by continuously cutting the array in half until the desired value is found Simple binary search example

public class BinarySearch {

    public static int binarySearch(int[] arr, int target) {
        int left = 0;
        int right = arr.length - 1;

        while (left <= right) {
            int mid = left + (right - left) / 2;

            if (arr[mid] == target) {
                return mid;
            }

            if (arr[mid] < target) {
                left = mid + 1;
            }

            else {
                right = mid - 1;
            }
        }

        return -1;
    }

    public static void main(String[] args) {
        int[] arr = {4, 8, 10, 11, 15, 32, 38, 42, 56, 100};
        int target = 15;

        int result = binarySearch(arr, target);

        if (result == -1) {
            System.out.println("Element not present in the array");
        } else {
            System.out.println("Element found at index " + result);
        }
    }
}

BinarySearch.main(null)

Popcorn hack! Add comments to the algorithm above explaining the process

Answering the Question As we know binary seach reduces the search space by half each time it’s ran. Since there are 2,000 elements in the array, that means we can figure out the answer to this question by figuring out how many times the algorithm runs in order to isolate the selected value. We can use the expression 2^x to find the value that is the closest to 2000 without going under.

A. 2^2000 = basically infinity B. 2^1000 = 1.071509e+301 C. 2^20 = 1048576 D. 2^11 = 2048 E. 2^1 = 2

Since 2048 is the closest number to 2000, that means the D, or 11 is our answer.

Hacks Problem Statement: You are given a sorted array of integers. Write a Java program to implement a binary search algorithm to find the index of a given element in the array. If the element is present, return its index; otherwise, return -1.

Use this code:

public class BinarySearchPractice {
    public static int binarySearch(int[] array, int target) {
        // Your implementation here
    }

    public static void main(String[] args) {
        int[] sortedArray = {1, 3, 5, 7, 9, 11, 13, 15, 17, 19};
        int targetElement = 11;

        int result = binarySearch(sortedArray, targetElement);

        if (result != -1) {
            System.out.println("Element " + targetElement + " found at index " + result);
        } else {
            System.out.println("Element " + targetElement + " not found in the array");
        }
    }
}

Question 24 (Shaurya) - Method Signature

mainscore

Example:

public class EmployeeDatabase {

    // Method signature: addEmployee(String, double)
    public void addEmployee(String name, double salary) {
        // Implementation to add an employee with name and salary
        System.out.println("Added employee: " + name + " with salary: $" + salary);
    }

    // Method signature: addEmployee(String, int)
    public void addEmployee(String name, int employeeId) {
        // Implementation to add an employee with name and employee ID
        System.out.println("Added employee: " + name + " with ID: " + employeeId);
    }

    // Method signature: addEmployee(String, double, String)
    public void addEmployee(String name, double salary, String department) {
        // Implementation to add an employee with name, salary, and department
        System.out.println("Added employee: " + name + " with salary: $" + salary + " in " + department + " department");
    }

    public static void main(String[] args) {
        EmployeeDatabase database = new EmployeeDatabase();

        // Adding employees using different method signatures
        database.addEmployee("Alice", 60000);  // Uses addEmployee(String, int)
        database.addEmployee("Bob", 75000.50); // Uses addEmployee(String, double)
        database.addEmployee("Charlie", 90000, "Engineering"); // Uses addEmployee(String, double, String)
    }
}
EmployeeDatabase.main(null)

In this example:

We have a class EmployeeDatabase with three addEmployee methods, each having a different method signature.

The first method takes a String name and a double salary.

The second method takes a String name and an int employeeId.

The third method takes a String name, a double salary, and a String department.

By having different method signatures, we can effectively overload the addEmployee method, allowing it to handle various scenarios with different parameter types and orders. The main method demonstrates how we can use each version of the addEmployee method based on the specific information available when adding employees to the database.

Question 26 - String Method

mainscore

What is it requiring?

Pretty straight forward, asking what will print out as a result of calling the method start(). However, why is this question easy to mess up?

Most common mistake: You MUST be careful when see which string is brought in.

public class CBq26 {
    public static void changeIt(int[] arr, int val, String word) {
        arr = new int[5];
        val = 0;
        word = word.substring(0, 5);

        for (int k = 0; k < arr.length; k++) {
            arr[k] = 0;
        }
    }

    public static void start() {
        int[] nums = {1, 2, 3, 4, 5};
        int value = 6;
        String name = "blackboard";

        changeIt(nums, value, name); 

        for (int k = 0; k < nums.length; k++) {
            System.out.print(nums[k] + " ");
        }
        
        System.out.print(value + " ");
        System.out.print(name);
    }

    public static void main(String[] args) {
        start();
    }
}

CBq26.main(null);

Popcorn Hack:

public class CBq26 {
    public static void changeIt(int[] arr, int val, String word) {
        arr = new int[5];
        val = 0;
        word = word.substring(0, 5);
        System.out.println("Word changed locally: " + word);

        for (int k = 0; k < arr.length; k++) {
            arr[k] = 0;
        }
    }

    public static void start() {
        int[] nums = {1, 2, 3, 4, 5};
        int value = 6;
        String name = "blackboard";
        String word = "blackboard"; 

        changeIt(nums, value, name);

        for (int k = 0; k < nums.length; k++) {
            System.out.print(nums[k] + " ");
        }
        
        System.out.print(value + " ");
        System.out.print(name);
    }

    public static void main(String[] args) {
        start();
    }
}

CBq26.main(null);

Question 31 (Orlando) - Traversing 2D Arrays

mainscore

Topic:

This question is a test of your knowledge of traversing 2D arrays.

Traversing a 2D array involves visiting each element of the array in a systematic way, usually using nested loops to iterate over both rows and columns. The process ensures that you access and perform operations on every element within the 2D array.

In this example, The first set of nested for loops sets each element in board to “O”. The next for loop starts val at 0 and increments by 1 until val is 4, when val is 5 the loop terminates. When val is even, board is not updated, so nothing happens when val is 0.

When val is 1, row is assigned 1 and col is assigned 0. The boolean condition in the while loop is true, so board[1][0] is assigned “X”. Then col is incremented to 1 and row is decremented to 0 and board[0][1] is assigned “X”. Then col is incremented to 2 and row is decremented to -1 and the while loop terminates. When val is 2, nothing changes about board. When val is 3, row is assigned 3 and col is assigned 0.

The boolean condition in the while loop is true, so board[3][0] is assigned “X”. Then col is incremented to 1 and row is decremented to 2 and board[2][1] is assigned “X”. Then col is incremented to 2 and row is decremented to 1 and board[1][2] is assigned “X”. Then col is incremented to 3 and row is decremented to 0 and board[0][3] is assigned “X”. Finally, col is incremented to 4 and row is decremented to -1 and the while loop terminates. When val is 4, nothing changes about board.

Answer

Option E is correct because it accurately reflects the end product of the board after the code is executed. The code fills the board with “O” initially, and then for each value of val from 0 to 4, it sets diagonal elements starting from the top right corner to “X” for even values of val. When val is odd, no changes are made to the board since the while loop condition fails immediately due to the decrement of col and row before the loop

Popcorn Hack

Here is a similar example to the code with an intentional mistake for you to solve String[][] board = new String[5][5]; for (int row = 0; row < 5; row++) { for (int col = 0; col < 5; col++) { board[row][col] = “O”; } } for (int val = 0; val < 5; val++) { int row = val; int col = 4; while (col >= 0 && row >= 0) { if (val % 2 == 0) { board[row][col] = “X”; } else { // Intentional mistake: This should be ‘board[row][col] = “O”;’ // Students need to identify and fix this line. board[row][col] = “X”; // Incorrect assignment } col–; row–; } } The mistake is in the else block where it incorrectly assigns “X” instead of “O”. Students should correct this to: board[row][col]=”0”; in order to fix the code. The corrected code will alternate between “X” and “O” on the diagonals for each value of val

Question 33 - Max Value

mainscore
mainscore

Popcorn Hacks

Look at each of the 3 methods below. Which ones will successfully calculate the max value? Why do the other methods not work?

public class Q33Hacks {
    public int methodI(int[] arr) {
        int max = Integer.MAX_VALUE;
        for (int value:arr) {
            if (max<value) {
                max = value;
            }
        }
        return max;
    }

    public int methodII(int[] arr) {
        int max = 0;
        for (int value: arr) {
            if (max < value) {
                max = value;
            }
        }
        return max;
    }

    public int methodIII(int[] arr) {
        int max = arr[0];
        for (int k = 1; k>arr.length; k++) {
            if (max<arr[k]) {
                max = arr[k];
            }
        }
        return max;
    }
}


Question 35 - Binary Search Pt. 2

mainscore

Here’s a breakdown of the process:

Initially, the search range is set with start = 0 and end = 7 (length of the array - 1).

In the first iteration, the midpoint mid is calculated as (0 + 7) / 2 = 3. Since the target (8) is greater than data[3] (4), the search continues in the right half of the array, and start is updated to 4.

In the second iteration, the midpoint is calculated as (4 + 7) / 2 = 5. Here, the target (8) is equal to data[5], so the method returns 5 as the index where the target is found.

As a result, the value returned by the call binarySearch(values, target) is 5. This indicates that the target value 8 is found at index 5 in the given array values.

Here’s an example to try:

Fill in the blanks in the following Java code to declare an array of characters and choose a target character for a binary search. Once the blanks are filled, run the code to perform the binary search and determine whether the target character is present in the array. If found, print the index; otherwise, print a message indicating that the target character was not found.

public class CharBinarySearchExample {

    public static int charBinarySearch(char[] data, char target) {
        int start = 0;
        int end = data.length - 1;

        while (start <= end) {
            int mid = (start + end) / 2;

            if (target < data[mid]) {
                end = mid - 1;
            } else if (target > data[mid]) {
                start = mid + 1;
            } else {
                return mid;
            }
        }

        return -1;
    }

    public static void main(String[] args) {
        // Fill in the blank: Declare an array of characters (similar to the previous example)
        char[] characters = ____;

        // Fill in the blank: Choose a target character to search for in the array
        char targetChar = ____;

        int result = charBinarySearch(characters, targetChar);

        if (result != -1) {
            System.out.println("Target character '" + targetChar + "' found at index " + result);
        } else {
            System.out.println("Target character '" + targetChar + "' not found in the array.");
        }
    }
}

Your task is to fill in the blanks with appropriate values for the array of characters (characters) and the target character (targetChar). After filling in the blanks, you can run the code to see the results of the binary search.

Question 39 - Array Lists

mainscore

Question 39 (5-Minute Lesson): Problem:

Consider the following code segment:

List<String> students = new ArrayList<String>();

students.add("Alex");
students.add("Bob");
students.add("Carl");

for (int k = 0; k < students.size(); k++) {
    System.out.println(students.set(k, "Alex") + " ");
}

System.out.println();

for (String str : students) {
    System.out.print(str + " ");
}

I got this one correct. It is a matter of ArrayLists, understanding their methods, and visualizing how loops work. At this point in the test, I was able to do so pretty well. Let’s now go over each of the wrong choices and explain why they were wrong:

A: This would be the case if the set method returned the value that was stored in the element after it was assigned “Alex” instead of returning the value being replaced “Alex”.

B: In this case the lines of output are reversed.

D: This would the result if the first for loop used the get method instead of the set method.

E: The set method can be used in the System.out.print() method, because it returns the value that was at this index before it was updated to “Alex”.

Finally, choice C was correct. This is because the first for loop uses the set method to change the value of each element in students to “Alex”. When the set method is called, it returns the value that was originally at this index. So, the first loop will print Alex Bob Carl. At this point all elements have been set to “Alex”. The second for loop uses an enhanced for loop to access every element and will print Alex Alex Alex.

If you got this wrong, I would suggest going back to ArrayList methods and how to traverse an ArrayList through different methods and algorithms. Since this was the student lesson I taught, I didn’t struggle with these questions, and I also know how to help those who might be struggling.

Popcorn Hack:

Master ArrayList manipulation and loop comprehension by dissecting the code snippet, understanding the nuances of the set method, and creating a similar exercise that involves updating ArrayList elements for a comprehensive grasp of core concepts.