Array HACKS

This question involves reasoning about one-dimensional and two-dimensional arrays of integers. You will write three static methods, all of which are in a single enclosing class, named DiverseArray (not shown). The first method returns the sum of the values of a one-dimensional array; the second method returns an array that represents the sums of the rows of a two-dimensional array; and the third method analyzes row sums.

(A) Write a static method arraySum that calculates and returns the sum of the entries in a specified one-dimensional array. The following example shows an array arr1 and the value returned by a call to arraySum.

Complete method arraySum below.

/** Returns the sum of the entries in the one-dimensional array arr.**/ 
public static int arraySum(int[] arr) 
{
    int sum = 0; 
    for (int i = 0; i < arr.length; i++)
    {
        sum += arr[i]; 
    }
    return sum; 
}

Mistakes:

All these are possible mistakes that are almost garunteed to be made and appear on a mcq or frq and would be good to study. We suggest you create examples of these errors and mistakes (yourself or chatgpt or gemini) and solve them on your own. This is a good practice exercise and will help prepare you for the AP exam.

Traversing Arrays

1. Off by-One Errors:

Off by-one errors occur when a loop iterates too many or too few times, typically due to incorrect indexing or boundary conditions.

Example:

// Incorrect code
int[] numbers = {1, 2, 3, 4, 5};
int sum = 0;
for (int i = 0; i <= numbers.length; i++) {
    sum += numbers[i];
}
System.out.println("Sum: " + sum);

Solution:

// Corrected code
int[] numbers = {1, 2, 3, 4, 5};
int sum = 0;
for (int i = 0; i < numbers.length; i++) {
    sum += numbers[i];
}
System.out.println("Sum: " + sum);

2. Modifying Array Length:

Modifying the length of an array incorrectly can lead to unexpected behavior or errors, such as accessing out-of-bounds memory.

Example:

// Incorrect code
int[] numbers = {1, 2, 3, 4, 5};
numbers.length = 10; // Incorrect attempt to change array length

Solution: Arrays in Java are fixed in length once created. If you need to resize an array, you should create a new array and copy elements over.

3. Ignoring Returned Values:

Ignoring returned values can lead to loss of important data or failure to execute necessary operations.

Example:

// Incorrect code
String str = "Hello";
str.toUpperCase(); // Ignoring returned value
System.out.println(str); // Output: Hello (not converted to uppercase)

Solution:

// Corrected code
String str = "Hello";
str = str.toUpperCase(); // Assigning returned value to variable
System.out.println(str); // Output: HELLO

Practicing with these examples should help in understanding and avoiding these common mistakes in traversing arrays.

Using For-Each Loops:

1. Modifying Elements:

Modifying elements while iterating over them using a for-each loop can lead to unexpected behavior or errors because for-each loops are designed for read-only access.

Example:

// Incorrect code
int[] numbers = {1, 2, 3, 4, 5};
for (int num : numbers) {
    num *= 2; // Attempting to modify elements
}

Solution:

// Corrected code
int[] numbers = {1, 2, 3, 4, 5};
for (int i = 0; i < numbers.length; i++) {
    numbers[i] *= 2; // Modifying elements using index
}

2. Tracking Index:

For-each loops do not provide a built-in mechanism to track the index of the current element, which can be necessary in some situations.

Example:

// Incorrect code
String[] fruits = {"Apple", "Banana", "Orange"};
for (String fruit : fruits) {
    System.out.println("Fruit: " + fruit);
    // How to track the index here?
}

Solution: Use a traditional for loop if you need to track the index.

3. Removing Elements:

Removing elements from a collection while iterating over it using a for-each loop can lead to concurrent modification exceptions.

Example:

// Incorrect code
List<Integer> numbers = new ArrayList<>();
numbers.add(1);
numbers.add(2);
numbers.add(3);
for (int num : numbers) {
    numbers.remove(num); // Attempting to remove elements
}

Solution: Use an iterator and its remove method to safely remove elements while iterating.

4. Iterating Backwards or in Multiple Steps:

For-each loops iterate over elements sequentially and do not support iterating backwards or in multiple steps.

Example:

// Incorrect code
int[] numbers = {1, 2, 3, 4, 5};
for (int num : numbers) {
    System.out.println(num);
    // How to iterate backwards or in multiple steps here?
}

Solution: Use a traditional for loop with appropriate control structures for these cases.

5. Processing Two Arrays in Parallel:

For-each loops iterate over a single collection at a time and do not naturally support iterating over multiple arrays in parallel.

Example:

// Incorrect code
int[] arr1 = {1, 2, 3};
int[] arr2 = {4, 5, 6};
for (int num1 : arr1) {
    for (int num2 : arr2) {
        // Processing elements from both arrays
    }
}

Solution: Use a traditional for loop with a common index for processing elements from multiple arrays in parallel.

These examples should help clarify potential pitfalls when using for-each loops and how to avoid them.


2D Array HACKS

  • Write code to remove an element of an ArrayList moving from the first index to the last index, without skipping any like in the example.
  • Then use an insertion sort algorithm to sort the ArrayList you created.
import java.util.ArrayList;

public class Main {
    public static void main(String[] args) {
        // Create an ArrayList of Player objects
        ArrayList<Player> players = new ArrayList<>();
        players.add(new Player("Luna", 20));
        players.add(new Player("Rachita", 15));
        players.add(new Player("Tanisha", 25));

        // Remove an element moving from the first index to the last index
        for (int i = 0; i < players.size(); i++) {
            players.remove(0); // Remove the first element each time
            System.out.println("Removed: " + players);
        }

        // Perform insertion sort based on points a player has
        for (int i = 1; i < players.size(); i++) {
            Player key = players.get(i);
            int j = i - 1;
            while (j >= 0 && players.get(j).getPoints() > key.getPoints()) {
                players.set(j + 1, players.get(j));
                j = j - 1;
            }
            players.set(j + 1, key);
        }

        // Print the sorted ArrayList
        System.out.println("Sorted players based on points:");
        for (Player player : players) {
            System.out.println(player.getName() + ": " + player.getPoints() + " points");
        }
    }
}
class Player {
    private String name;
    private int points;

    public Player(String name, int points) {
        this.name = name;
        this.points = points;
    }

    public String getName() {
        return name;
    }

    public int getPoints() {
        return points;
    }
}
Main.main(null);
Removed: [REPL.$JShell$14$Player@56e54a91, REPL.$JShell$14$Player@5ee5ec77]
Removed: [REPL.$JShell$14$Player@5ee5ec77]
Sorted players based on points:
Tanisha: 25 points

2015 FRQ Q1

Finish FRQ from Friday, 2015 Q1

/** Returns the sum of the entries in the one-dimensional array arr.
 */ 
public static int arraySum(int[] arr) 
{
    int sum = 0; 
    for (int i = 0; i < arr.length; i++)
    {
        sum += arr[i]; 
    }
    return sum; 
}

/** Returns a one-dimensional array in which the entry at index k is the sum of * the entries of row k of the two-dimensional array arr2D. */ 
public static int[] rowSums(int[][] arr2D) { 
    int [] sums=new int[arr2D.length]; 
    int rowNum=0; 
    for(int[] row : arr2D) { 
        sums[rowNum]=arraySum(row); 
        rowNum++; 
    } return sums; 
}

/** Returns true if all rows in arr2D have different row sums; * false otherwise. */ 
public static boolean isDiverse(int[][] arr2D) { 
    int [] sums=rowSums(arr2D); 
    for (int i=0; i < sums.length; i++) { 
        for (int j=i+1; j < sums.length; j++) { 
            if (sums[i]==sums[j]){ return false; 
            } 
        } 
    } return true; 
}

Arraylist HACKS

The learning objective is that “Students will be able to represent collections of related object reference data using ArrayList objects.” What does this mean to you?

Quick lil popcorn hack Create 2 ArrayLists, 1 called studentName and 1 called studentAge

public class Student
{
    public static void main(String[] args)
    {
        ArrayList<String> studentName = new ArrayList<String>();
        ArrayList<Integer> studentAge = new ArrayList<Integer>();
    }
}

Answer the following questions:

  1. Look back at Size of the ArrayList. What does the code output and why? The code shows how many items are currently in the ArrayList. It does this by counting the elements stored in it.

  2. Look back at Adding items to an ArrayList. What does the code output and why? What type of function is void, and what will be the return value? The code displays the list after adding new items to it. The function used to add items is called void, meaning it doesn’t give back any specific value.

  3. Look back at Example 1. What two lines did we remove? Why? We removed two lines that were trying to add a number and a boolean to a list meant for strings. This keeps the list consistent with its intended type.

  4. If an ArrayList is being used as a parameter, what are the only two methods I can use from it? What would happen if I tried to use any other methods? You can only safely use the get and size methods with an ArrayList used as a parameter. If you try to use other methods, it might only affect a temporary copy of the list, not the original one passed into the method.

Using the Hack Helper, write code that will:

Add 2 items to the list. Remove an item from the list anywhere of the user’s choice. Replace am item anywhere in the list of the user’s choice. Get the first and last element of the list, no matter the length. Return the items added, removed, replaced, and the list’s size, in one string.

import java.util.ArrayList;

public class HackHelper {

    private String manipulateList(ArrayList<Integer> array) {
        array.add(1);
        array.add(2);
        Integer removedItem = array.remove(0);
        Integer replacedItem = array.set(0, 5);
        Integer firstElement = array.get(0);
        Integer lastElement = array.get(array.size() - 1);

        return "Added: 1, 2; Removed: " + removedItem + "; Replaced: " + replacedItem
               + " with 5; First element: " + firstElement + "; Last element: " + lastElement
               + "; List size: " + array.size();
    }

    public static void main(String[] args) {
        ArrayList<Integer> list = new ArrayList<>();
        list.add(10);
        
        HackHelper helper = new HackHelper();
        String result = helper.manipulateList(list);
        System.out.println(result);
    }
}

HackHelper.main(null);
Added: 1, 2; Removed: 10; Replaced: 1 with 5; First element: 5; Last element: 2; List size: 2

Answer the questions:

  1. Look back at the examples. What’s similar? What’s different? Both examples manipulate an ArrayList to perform various operations like adding, removing, replacing, and accessing elements. The main difference is how the elements are added: the first example initializes all values at once, while the second one initializes them one by one.

  2. Why do we use ArrayList? Why not just regular lists? We use ArrayList because it can hold objects, unlike regular arrays which have a fixed size in Java.

  3. Demonstrate at least two ArrayList methods that aren’t ArrayList<>.size() and ArrayList<>.get().

import java.util.ArrayList;

public class ArrayListExample {
    public static void main(String[] args) {
        ArrayList<Integer> numbers = new ArrayList<>();
        
        // Adding elements
        numbers.add(10);
        numbers.add(20);
        System.out.println("ArrayList after adding elements: " + numbers);
        
        // Removing element
        numbers.remove(0);
        System.out.println("ArrayList after removing element at index 0: " + numbers);
    }
}
ArrayListExample.main(null);
ArrayList after adding elements: [10, 20]
ArrayList after removing element at index 0: [20]
  1. Write the method findSum() using the Hack Helper and incorporating ArrayList
import java.util.ArrayList;

public class HackHelper {
    public int findSum(ArrayList<Integer> numbers) {
        int sum = 0;
        for (int num : numbers) {
            sum += num;
        }
        return sum;
    }

    public static void main(String[] args) {
        ArrayList<Integer> numbers = new ArrayList<>();
        numbers.add(10);
        numbers.add(20);
        numbers.add(30);

        HackHelper helper = new HackHelper();
        int sum = helper.findSum(numbers);
        System.out.println("Sum of elements in the ArrayList: " + sum);
    }
}
HackHelper.main(null);
Sum of elements in the ArrayList: 60