Developer's Playground: Developing Algorithms Using ArrayLists - AP CSA Study Guide
Welcome!
Hey code wizards! Ready to make your mark in the mystical land of algorithms, where the ArrayList
is your magic wand? 🪄 Get comfy as we unravel the secrets of developing algorithms with ArrayLists. It’s going to be a wild ride with plenty of loops, conditions, and maybe even some code dragons to slay. Let’s dive in!
Standard Algorithms: Your Coding Arsenal
Doubling Array Values: Because Why Not?
Imagine if every cupcake you had suddenly doubled—life would be twice as sweet, right? 🍰 Similarly, here’s how you can double the elements in an ArrayList:
public static void doubleArray(ArrayList<Integer> array) {
for (int i = 0; i < array.size(); i++) {
array.set(i, array.get(i) * 2); // doubles each element
}
}
Every element in the array gets a makeover, becoming twice as fabulous as before!
Modifying Instance Variables: The Student Edition 🎓
Here’s an example where we set every student's name to a default value. Imagine it's like a teacher calling everyone "Student" because they forgot their names!
public class Student {
private String name;
public void setName(String name) {
this.name = name;
}
}
public static void resetNames(ArrayList<Student> students, String defaultName) {
for (Student student : students) {
student.setName(defaultName);
}
}
Here, every student in the ArrayList now has the same default name.
Finding Extremes: Minimum and Maximum
Want to find the top score or the lowest grade? You're in luck. 🌟
Maximum Finder: The Treasure Hunt
Finding the maximum value in an ArrayList is like finding the tallest basketball player in a lineup.
public static int maximum(ArrayList<Integer> array) {
int maxValue = array.get(0);
for (int number : array) {
if (number > maxValue) {
maxValue = number;
}
}
return maxValue;
}
You start with the first value and move through each, always keeping track of the tallest player (or max value).
Minimum Finder: The Deep Dive
Finding the minimum value is like searching for the shortest actor in Hollywood.
public static int minimum(ArrayList<Integer> array) {
int minValue = array.get(0);
for (int number : array) {
if (number < minValue) {
minValue = number;
}
}
return minValue;
}
Start with the first value and keep updating if you find a shorter (or smaller) value.
The Sum of All Parts: Adding It Up
If you have an ArrayList of ice cream scoops, and you want to know how many scoops in total you’ve eaten:
public static int sum(ArrayList<Integer> array) {
int total = 0;
for (int number : array) {
total += number;
}
return total;
}
The Mean Machine: Calculating Averages
Finding the average score on a math test:
public static double mean(ArrayList<Integer> array) {
int sum = sum(array);
return (double) sum / array.size();
}
Remember to cast to double to avoid integer division. Math can be tricky like that! 🤓
The Mode Chameleon: Most Frequent Element
Finding the mode is like finding the most popular kid in school:
public static int mode(ArrayList<Integer> array) {
int mostCommon = 0;
int mostCommonFrequency = 0;
for (int i = 0; i < array.size(); i++) {
int currentFrequency = 0;
for (int j = 0; j < array.size(); j++) {
if (array.get(i).equals(array.get(j))) {
currentFrequency++;
}
}
if (currentFrequency > mostCommonFrequency) {
mostCommon = array.get(i);
mostCommonFrequency = currentFrequency;
}
}
return mostCommon;
}
This algorithm checks how often each element shows up and keeps track of the most frequent one.
Advanced Techniques:
Checking for Even Numbers
This method checks if all your guests at the party brought gifts divisible by 2:
public static boolean isEven(ArrayList<Integer> array) {
for (int number : array) {
if (number % 2 != 0) {
return false;
}
}
return true;
}
Consecutive Sequences: The Code Marathon
Need all sequences of length n? Here’s how to run through them:
public static void printAllConsecutiveSequences(ArrayList<Integer> array, int length) {
for (int i = 0; i <= array.size() - length; i++) {
for (int j = 0; j < length; j++) {
System.out.print(array.get(i + j) + " ");
}
System.out.println();
}
}
Print out all sublists of a particular length. Handy for generating playlists or checking for trends!
Checking for Duplicates: The Twin Detective
Let’s see if you’ve got any duplicate entries in your ArrayList:
public static boolean hasDuplicates(ArrayList<Integer> array) {
for (int i = 0; i < array.size() - 1; i++) {
for (int j = i + 1; j < array.size(); j++) {
if (array.get(i).equals(array.get(j))) {
return true;
}
}
}
return false;
}
Counting Specific Elements: Evens and Odds
How many even balloons in the party? Let’s count:
public static int countEvens(ArrayList<Integer> array) {
int count = 0;
for (int number : array) {
if (number % 2 == 0) {
count++;
}
}
return count;
}
Shift Left: All Aboard the Left Train
Shifting elements left is like moving cars in a train:
public static ArrayList<Integer> shiftLeft(ArrayList<Integer> array) {
int firstItem = array.get(0);
for (int i = 0; i < array.size() - 1; i++) {
array.set(i, array.get(i + 1));
}
array.set(array.size() - 1, firstItem);
return array;
}
Shift Right: Jump on the Right Bus!
Shifting elements to the right:
public static ArrayList<Integer> shiftRight(ArrayList<Integer> array) {
int lastItem = array.get(array.size() - 1);
for (int i = array.size() - 1; i > 0; i--) {
array.set(i, array.get(i - 1));
}
array.set(0, lastItem);
return array;
}
Reverse, Reverse!
Because sometimes you need to see things backward:
public static ArrayList<Integer> reverse(ArrayList<Integer> array) {
ArrayList<Integer> reversedArray = new ArrayList<>();
for (int i = array.size() - 1; i >= 0; i--) {
reversedArray.add(array.get(i));
}
return reversedArray;
}
ArrayList to Array and Vice Versa
Transmute your collections between ArrayLists and arrays:
public static int[] arrayListToArray(ArrayList<Integer> arrayList) {
int[] array = new int[arrayList.size()];
for (int i = 0; i < arrayList.size(); i++) {
array[i] = arrayList.get(i);
}
return array;
}
public static ArrayList<Integer> arrayToArrayList(int[] array) {
ArrayList<Integer> arrayList = new ArrayList<>();
for (int i : array) {
arrayList.add(i);
}
return arrayList;
}
Key Terms to Review:
- % Operator (Modulus): This operator gives you the remainder of a division operation. Perfect for checking if a number is divisible by another.
- += Operator: This sneaky operator adds and assigns in one swift move.
- ArrayList: A dynamic, resizeable array of objects that’s cooler than your average array.
- Boolean: A data type that only has two values: true or false, like a light switch.
- Get Method: Grabs the value of an object’s property.
- If Statement: executes a block of code only if a condition is true.
- Private: A visibility modifier that keeps variables or methods hidden from other classes, like a secret passage.
- Return: sends back a value from a method to where it was called.
Conclusion
Congratulations! You've mastered the essential algorithms using ArrayLists, from doubling values to sniffing out duplicates. 🤖 Keep practicing and testing your code, and soon you’ll be a wizard capable of transforming data structures with ease. Happy coding, and may the source be with you!