blank
- Lesson: Computer Science, Degrees, and Careers Slides
- Assignment: The last slide has an exercise to complete with a partner. Be prepared to present to the class.
Go over its features and how to use it. It has great review materials and test prep materials.
How the curriculum is organized on AP Classroom:- Primitive Data Types, Variables, Arithmetic Operators, Casting (covered in Grade 11 Unit 1)
- Methods (cs 11), Instantiation of Objects (cs 12), String and Math classes (cs 11), Wrapper Classes (new sort of)
- Boolean Expressions, if statement, .equals vs == (cs 11)
- Iteration (cs 11)
- Writing Classes (cs 12) and Methods (cs 11)
- Arrays, Enhanced for loop (cs 11 and cs 12)
- ArrayLists (partially covered in cs 12, lots new)
- 2D Arrays (cs 11/12)
- Inheritance and Polymorphism (mostly new)
- Recursion (new)
- Use videos for review if needed
- Class quizzes
- Two Unit Exams
- AP Practice Exam
- Progress Checks (for exam prep)
AP Topics covered in CS 11/12 from Barrons AP CS A Premium 2022-23 :
- Chapter 2 final variables, operators, conditionals, loops
- Chapter 3: Objects, classes, access modifiers, static, methods, constructors, method overloading, this, references vs primitive data types, null, method parameters
- Chapter 4: Inheritance
- New in 2026: File I/O using Scanner and File
- Coding Conventions Original Java Code Conventions, Google's Java Code Conventions
// Preconditions: x >= 0
// Postconditions: returns the value of the square root of x
public static double squareRoot(double x) {
return Math.sqrt(x);
}
The method calls squareroot(10) and squareroot(5) meet the precondition, but the method call squareroot(-1) does not.
// Precondition: letter is an uppercase or // lowercase letter (in the range 'A'...'Z' or 'a'...'z'). // Postcondition: returns true if letter is a vowel; // otherwise the value returns false public static boolean isVowel(char letter)Code according to the specifications and preconditions and postconditions. Don’t code anything outside of the specifications! You don’t want to include any “bells and whistles,” since you are likely to lose points if you do. It’s important to note that you should never add System.out.print unless you are asked to. Additionally, don’t include any unnecessary checks to your code.
Know Barron's AP Text Chapter 5:
- inheriting from the Object class (p 171)
- Strings.
- String API.
- Math API.
- Random Numbers (review from CS 11)
IntegerandDouble classesp 179- (p 180) Auto-boxing and -unboxing.
Do Barron's APCS text MC Q's starting on page 185
Activities- Textbook Chapter 5 - read and do questions at end of chapter
For the first time in 2026, the AP Exam will have File Input/Output on it. It does not use the code I showed you in CS 11/12. It only uses the classes Scanner, File, and PrintWriter.
- Create a 10x10 integer array, initialized to all 0's
- Write a new class called
Pointwith two instance variables (int xandint y) and get and set methods for each. Do not use the built in Java Point class. - Write a test driver with a minimum of the six methods listed below:
void init(int


board, Point p) - initializes board to 0, and sets start position to 1
int sum (int 

board) - returns sum of the board
// the following methods return true if the move is successful,
// or false if an ArrayIndexOutOfBounds Exception is thrown
boolean north (int 

board, Point p) - moves position north
boolean south (int 

board, Point p) - moves position south
boolean east (int 

board, Point p) - moves position east
boolean west (int 

board, Point p) - moves position west 0,0is the top left.- read in a file where:
- first line is the x position to start at
- second line is the y position to start at
- the remaining lines of the file each contain N, E, S, W for North, East, South or West
- set the starting Point
x,yto one in the array. - for each line read, move current position by one space in that direction. North is up, East is right, South is down, West is left
- if the array element of the new position contains 0, replace it with a 1, otherwise multiply its current value by 2
- if the new position is out of bounds, print a message "Out of Bounds" and end the program.
- If the end of file is reached, add up all the elements of the two dimensional array and output that number to the console.
- If any invalid data is read from the file, or the format of the file is invalid, print
invalid dataand end the program.
The class will be split into groups to come up with sample test cases each. This lab will be peer evaluated.
Complete the steps below with the corresponding Google Classroom assignment. While you will work on the program together, each person is expected to answer the questions on Google Classroom and submit the answers individually.
A. The Experiment- Sit with a partner. Predict the output of this code:
byte sum = 0; byte p = 1; for (int count = 1; count <= 10; count++) { sum += p; p *= 2; } System.out.println(sum); - Now run it. What is the output? Discuss why this is happening.
- Change the variable types to
shortand run the loop 20 times. - Change it to an
intand run the loop 40 times. - Change it to a
longand run the loop 80 times. - On the Google Classroom Assignment, answer:
- Explain what is happening.
- When does overflow occur for each data type?
- What patterns do you notice in how the sum changes?
- What happens when p becomes zero?
- Modify the code to detect overflow before it happens. Print an error message and break out of the loop before it happens.
- On the Google Classroom Assignment, explain how your overflow check works.
- Many video games and financial applications need to prevent integer overflow (e.g., keeping track of high scores, bank balances).
- Write a program that uses the above algorithm to sum the powers of 2 for n up to 100. Use
longbut print a warning message when it exceeds its limit. - Now rewrite the same program using BigInteger.
- On your sheet of paper, answer these questions:
- What are the advantages of using BigInteger?
- Why isn’t BigInteger used for all integer operations in Java?
- How does this apply to cybersecurity or large financial calculations? Help: Integer Overflow.
- On the Google Classroom Assignment, answer these questions:
- What is integer overflow?
- How does Java handle it?
- How can programmers prevent it?
- Each of you submit your assignment on Google Classroom
Review
New Material:
- Short-Circuit Boolean Expressions: In some languages, the following code may throw an exception and in some languages it WILL NOT throw an exception.
Why? Which is true for Java?if (x != 0 && (y/x > 1)) {} - Boolean Expressions and Demorgan’s Law and Short Circuiting
Exercises:
- Classes and Objects
- Encapsulation: the packing of data and functions into a single component
- specifiers: public, private and static
- methods: defining, parameters, constructors, accessor and mutators
- scope
- this
- static vs instance variables
- static vs instance methods
- References, aliases, null
- passing objects as parameters
- what is OOP, the 4 pillars of OOP
- basics of writing a class: constructors, get/set methods
- this
- toString
- Barron's AP Text Chapter 3 Chapter 3 - read and do questions at end of chapter
Complete this exercise in the time provided.
Found in: Barron's AP Text Chapter 4.
In class discussion on:
- Class relationships
- associations - a use relationship, when two classes are aware of each other through such as one class method accepting a parameter from another class type.
- aggregation - a has-a relationship. An aggregate object is any object that has other objects as instance data.
- Superclass and Subclass
- class hierarchy: parent class, child class
- is-a relationship
- method overriding - read about
@override: Predefined Annotation Types. - protected keyword
- extends keyword
- super keyword
- declaring subclass objects
- know the modifiers
| Class | Package | Subclass | World ————————————+———————+—————————+——————————+——————— public | y | y | y | y ————————————+———————+—————————+——————————+——————— protected | y | y | y | n ————————————+———————+—————————+——————————+——————— no modifier | y | y | n | n ————————————+———————+—————————+——————————+——————— private | y | n | n | n y: accessible n: not accessible
Activities
- Textbook Chapter 3 - read and do questions at end of chapter
- Unit 9 on AP Classroom
- Download this starter code for the account class: download here
- Add a
transfermethodAccountclass so that funds can be moved from one account to another. Think of this as withdrawing money from one account and depositing it into another. Returntrueif the funds are successfully transferred, otherwise returnfalse.//--------------------------------------------------------------------------------------- // Validates the transaction. If sufficent funds exist, withdraws the specified amount // from this account and deposits it to the "to" account returning true, // else does nothing and returns false. //----------------------------------------------------------------------------------------- public boolean transfer (double amount, Account to) { } - Add an additional constructor so that a user can open an account with just a name and an account number, and a starting balance of 0.
//----------------------------------------------------------------- // Sets up the account by defining its owner and account number. // Initial balance is set to zero //----------------------------------------------------------------- public Account (String owner, long account) { } - Create a subclass called
ChequingAccountthat has methodswriteCheque(double amt)that withdrawsamt, anddepositCheque(double amt)that deposits amt. - For evaluation, you will be given a
Bankingclass which contains a driver to test yourAccountclass. See example below:
Account acct1 = new Account ("Ted Murphy", 12345, 214.56);
Account acct2 = new Account ("Anita Gomez", 54321, 20.00);
ChequingAccount cacct = new ChequingAccount("Sara Foobar", 33432, 2000.0);
System.out.println ("Murphy balance after deposit: $" + acct1.deposit (14.58));
System.out.println ("Gomez balance after deposit: $" + acct2.deposit (300.00));
System.out.println ("Gomez balance after withdrawal: $" + acct2.withdraw (100.00, 2.00));
System.out.print("\nWithdraw $800 from Gomez account: ");
acct2.withdraw (800.00, 0.0); // exceeds balance
acct1.addInterest();
acct2.addInterest();
System.out.println ("\nAccount Balances:");
System.out.println (acct1);
System.out.println (acct2);
// transfer $50 from account 1 to account 2
System.out.println ("\nTransfer $50 from Murphy to Gomez:");
acct1.transfer(50, acct2);
System.out.println (acct1);
System.out.println (acct2);
// chequing account test driver
System.out.println("\nFoobar account balance: " + cacct);
cacct.writeCheque(100.0);
System.out.println("Foobar account balance: " + cacct);
cacct.depositCheque(1000.0);
System.out.println("Foobar account balance: " + cacct);
Sample Output
Murphy balance after deposit: $229.14
Gomez balance after deposit: $320.00
Gomez balance after withdrawal: $218.00
Withdraw $800 from Gomez account:
Error: Insufficient funds.
Account: 54321
Requested: $800.00
Available: $218.00
Account Balances:
12345 Ted Murphy $237.16
54321 Anita Gomez $225.63
Transfer $50 from Murphy to Gomez:
12345 Ted Murphy $187.16
54321 Anita Gomez $275.63
Foobar account balance: 33432 Sara Foobar $2,000.00
Foobar account balance: 33432 Sara Foobar $1,900.00
Foobar account balance: 33432 Sara Foobar $2,900.00
- Spires of Vulcan Challenge
- My notes - you won't have access to this.
- Shown in Class: When to choose recursion over iteration.
- For AP, know recursive algorithms for Factorial, Fibonacci, and isPrime
In this lab, you will explore and compare iterative and recursive algorithms for the following problems:
- Fibonacci Sequence
- Factorial
- isPrime
You are provided with an example for Fibonacci. Using this as a model, write similar programs for Factorial and isPrime, implementing both recursive and iterative solutions for each.
Your Tasks
Implement the Algorithms
Write both recursive and iterative versions for:
- Factorial
- isPrime
- (Fibonacci is already provided as your reference.)
Track Method Calls
- Devise a way to count how many method calls each algorithm makes.
- Ensure your program outputs this value clearly.
Measure Runtime
- Measure how long each algorithm takes to run.
- Convert and display the runtime in human-readable units (e.g., milliseconds instead of nanoseconds).
Display Results Clearly
Format your output so that it is easy to compare:
- Recursive vs Iterative
- Runtime
- Number of method calls
- A table-style format is recommended.
Conclusion (Required)
Write a short paragraph (3–5 sentences) explaining:
- Which approach (recursive or iterative) was faster for each algorithm
- How the number of method calls differed
- Any patterns or trends you noticed
What to Hand In
- A printed copy of your program output
- Your clearly formatted results
- Your written conclusion
Note: Use a long, not an int. for Fibonacci, try n = 25. For smaller n, the inaccuracy of nanosecond measurements leads to unrealistic results. For larger n (like n = 50) the recursion takes too long. Ignore the timing calculations of the first loop, the timing is extra long due to the JVM warm-up process which includes one-time overheads such as class loading, bytecode verification, and Just-in-time (JIT) compilation. subsepquest calls are faster because the code is already loaded, potentially optimized into native machine code, and cached.
import java.io.*;
public class Main {
// Counts the number of calls to a given method
private static long methodCalls;
/**
* Method to calculate the nth Fibonacci number recursively.
*
* @param n an integer >=1
* @return nth Fibonacci number precondition: n >= 1
*/
public static long rfib(long n) {
methodCalls++;
if ((n == 1) || (n == 2)) {
return 1;
} else {
return rfib(n - 1) + rfib(n - 2);
}
}
/**
* Method to calculate the nth Fibonacci number iteratively.
*
* @param n
* @return nth Fibonacci number precondition: n >= 1
*/
public static long ifib(long n) {
methodCalls++;
if ((n == 1) || (n == 2)) {
return 1;
} else {
long prev = 1; // previous number
long current = 1; // current number
long next = 0; // next number
for (long i = 3; i <= n; i++) {
next = prev + current;
prev = current;
current = next;
}
return next;
}
}
/**
* Main method to call the recursive and iterative Fibonacci methods.
*/
public static void main(String args<>) throws Exception {
long n; // The Fibonacci number to compute
long startTime = 0;
long endTime = 0;
long timeElapsed = 0;
BufferedReader keyboard = new BufferedReader(new InputStreamReader(System.in), 1);
// run a long algorithm to ignore loading time of JVM
startTime = System.nanoTime();
rfib(45);
endTime = System.nanoTime();
n = 45; // number to test
// Call the iterative Fibonacci method and measure the elapsed time and
// the number of method calls
methodCalls = 0;
startTime = System.nanoTime();
System.out.println("\nIterative Fibonacci: the " + n + "-th Fibonacci number is " + ifib(n));
endTime = System.nanoTime();
timeElapsed = endTime - startTime;
System.out.println("Elapsed time: " + timeElapsed/1000000 + "ms or " + timeElapsed
+ "ns; number of calls to the algorithm: " + methodCalls);
System.out.println("\nStarting recursive Fibonacci ...");
// Call the recursive Fibonacci method and measure the elapsed time and
// the number of method calls
methodCalls = 0;
startTime = System.nanoTime();
System.out.println("Recursive Fibonacci: the " + n + "-th Fibonacci number is " + rfib(n));
endTime = System.nanoTime();
timeElapsed = endTime - startTime;
System.out.println("Elapsed time: " + timeElapsed/1000000 + "ms or " + timeElapsed
+ "ns; number of calls to the algorithm: " + methodCalls);
System.out.println("End of program");
}
}
A word is considered emulike if it contains the letters: e, m, u in it, if any order. For example, the following words are emulike: "mustache", "umbrella", "temperature", and "guatemala".
Write a program WordLike.java to support the following features.
- Write this method, any solution that works is acceptable:
/* Precondition: word is a single word * Postcondition: returns true if word is emulike, otherwise false */ public static boolean emulike(String word)
- Write this recursive method. You may use String.contains and String.substring.
/* Precondition: foo and bar are single words * Postcondition: returns true if all the letters of foo are contained in bar */ public static boolean foobarlike(String foo, String bar)
Examples:foobarlike("left", "felt") returns true. foobarlike("ado", "dormant") returns true. foobarlike("fold", "skyfall") returns false. - Write this recursive method. You may use String.contains and Arrays.copyOfRange.
/* Precondition: sentence is a sentence in the form of a string array * Postcondition: returns a string of the leftlike words in the sentence */ public static String keepLeftlike(String
Example:
sentence)
String
a = {"this", "stressful", "time", "on", "the", "twelfth", "felt", "extremely", "uneventful"};
keepLeftlike(a) returns "stressful twelfth felt uneventful"
Use the skeleton code below:
public class Wordlike {
public static void main(String
args) {
System.out.println("Testing emulike: ");
System.out.println("emulike(\"mustache\") is " + emulike("mustache"));
System.out.println("emulike(\"horses\") is " + emulike("horses"));
System.out.println("Testing foobarlike:");
System.out.println("foobarlike(\"ado\", \"dormant\") is " + foobarlike("ado", "dormant"));
System.out.println("foobarlike(\"fold\", \"skyfall\") is " + foobarlike("fold", "skyfall"));
String
a = {"this", "stressful", "time", "on", "the", "twelfth", "felt", "extremely", "uneventful"};
System.out.println("Testing keepLeftlike:");
System.out.println("keepLeftlike(a) is " + keepLeftlike(a));
}
/* Precondition: word is a single word
* Postcondition: returns true if word is emulike, otherwise false
*/
public static boolean emulike(String word) {
...
}
/* a recursive method
* Precondition: foo and bar are single words
* Postcondition: returns true if all the letters of foo are contained in bar
*/
public static boolean foobarlike(String foo, String bar) {
...
}
/* a recursive method
* Precondition: sentence is a sentence in the form of a string array
* Postcondition: returns a string of the leftlike words in the sentence
*/
public static String keepLeftlike(String
sentence) {
...
}
}
The following links describe what parts of Java you need to know for the AP Exam:
Covers all of Barron's APCS Text Chapters 1, 2, 3, 4 (Inheritance only, no polymorphism)5, 7 , 8 (only 1 recursion question)
30 Multiple Choice QuestionsAP Exam Allowance Per MC Q: 128 seconds
30 x 128 s = 64 minute time limit.
- Big O Notation Video
- O(log n) explained
- O(n log n) explained
- Comparison Chart of Different Orders
- Wikipedia
In your notes, for each of the orders of Big O in this list:
O(n2), O(n log n), O(1), O(log n), O(n)
List them in order from slowest to fastest and write a sample algorithm with that run time.
Note: For the AP Exam, you are required to know the "analysis of programs or algorithms in order to understand their time and space requirements when applied to different data sets." and "the relative running time of " search and sort algorithms. APCS Course Description.
Required for AP:
- searching in ordered and unordered lists
- Compare Search Algorithms:
- Sequential/Linear O(n) - iterative
- Binary O(log n) Search - recursive (Ms. Wear wants you to also know iterative)
- Sorting - O(n2)
- insertion sort (iterative)
- selection sort (iterative)
- mergesort (recursive)
- Sorting Algorithms Compared
- HTML5 Canvas Demo: Sorting Algorithms
- Binary Search: Demo, Code
- Wikipedia:
In class activity:
Each student will be assigned the Linear Search, Binary Search, or Insertion, Selection, or Mergesort. Learn it.
Your group will
- demonstrate that algorithm,
- show and explain the code
- Discuss the Big O efficiency
- Discuss pros and cons of the algorithm (see textbook)
- does the initial ordering of the data affects performance?(see textbook)
- Is there a difference in run time between worst and average cases? (see textbook)
AP Textbook: Chapter 9 Sorting and Searching
- iterative Linear Search
- iterative Binary Search
- iterative Insertion Sort,
- iterative Selection Sort,
- recursive Merge Sort.
- Create 4 arrays of sizes size 100 (disregard), size 10,000, size 100,000, and another of size 1,000,000, initialized with random numbers between 0 and 5000.
- Calculate the time each sort algorithm takes to sort each array. Be sure to re-randomize the arrays before doing a new sort.
- Calculate the time each search alogorithm takes for a "worst case scenario" search, that is, the elements being searched for is not in the array.
- You will need to use
System.nanotime()WITHIN the iterative methods. Otherwise you will be timing method calls as well. To time the recursive algorithms, start timing before the method call and finish timing after the method call. - Print the times for smaller n in ms and for larger n in s, for ease of comparison.
- Run each test 1000 times and calculate the average the sort/search time for each data size.
- Display the output to the console in a table like the one shown below:
Average search times:
| 100 (disregard)| 10,000 | 100,000 | etc..
----------------------------------------------------------
Linear Src | ms | ms |
----------------------------------------------------------
Binary Src | ms | ms |
Average sort times:
| 100 (disregard)| 10,000 | 100,000 | etc..
-------------------------------------------------------
Insertion It | ms | ms |
-------------------------------------------------------
Selection It | ms | ms |
-------------------------------------------------------
Merge Rc | ms | ms | |
To hand in: print the output of your program, write your names on it, and hand in to my wire in-basket
Past Exam Questions
Background
Go Home Property Insurance suspects a rise in suspicious natural disaster claims in Victoria. They've asked you, an independent analyst, to investigate historical rainfall data and answer the following questions:
Your Task
Using the provided ranifall data:
- What two months have the highest average daily rainfall? (Ex. January and July)
- What 4 week numbers have the highest average rainfall? (Ex 1, 3, 5 and 51)
- What are the top 10 48-hour periods with the highest total rainfall? (Ex. Jan 8-9, 2020, Nov 13-14, 2019 etc)
You will analyze, clean, and visualize the data to answer these questions in a report.
Steps to Complete the Assignment
Prepare Your Tools
- Learn about data cleaning: Data Cleaning with Google Sheets
- Download and extract:
- PTPlot Package: A simple Java plotting tool from the Ptolemy Homepage
Extract the zip file into your Eclipse Project folder, and add the package to an Eclipse project. This tutorial may help you: How to Add Existing Files to Eclipse Projects.
- weather.zip: Contains CSV files from two Victoria weather stations up to 2020.
The CSV files from Environment Canada are daily rainfall amounts in millimetres from two weather stations in Victoria. There are data gaps sometimes in one or both files. Data missing in the record is blank and has an M in the next column.
- PTPlot Package: A simple Java plotting tool from the Ptolemy Homepage
Test the Plotting Library
Run this sample program to test PTPlot in Eclipse (source):
// Show a plot of the cosine function.
import ptolemy.plot.*;
public class EasyPtPlot {
public static final double Xmin = -5.0;
public static final double Xmax = 5.0; // Graph domain
public static final int Npoint = 500;
public static void main ( String
args ) {
Plot plotObj = new Plot () ; // Create Plot object
plotObj.setTitle("f(x) vs x") ;
plotObj.setXLabel("x") ;
plotObj.setYLabel ("f(x)");
// plotObj.setSize (400 , 300) ;
// plotObj.setXRange ( Xmin , Xmax ) ;
// plotObj.addPoint ( int Set , double x , double y , boolean connect );
double xStep = (Xmax - Xmin ) / Npoint;
// Plotting loop
for (double x = Xmin; x <= Xmax; x += xStep) {
double y = Math.sin( x ) * Math.sin ( x ) ;
plotObj.addPoint (0 , x , y , true ) ;
}
PlotApplication app = new PlotApplication ( plotObj ) ; // Display
}
}
Get the Full Rainfall Dataset
- Add rainfall data for 2021, 2022, 2023, and part of 2024 to the dataset. Get it from Environment Canada.
- Use this Java snippet to read file data into an array:
BufferedReader in = new BufferedReader(new FileReader("src/weather/" + year + ".txt")); String
lines = in.lines().toArray(String
::new);
Clean and Analyze the Data
- Average rainfall from two stations when both are available.
- If data is missing from one station, use the other.
- If both are missing, skip that day.
- Organize your results in tables and plots.
Report Your Results
Prepare a printed report that includes:
- Tables
- 2 months with highest average daily rainfall
- 4 weeks with highest average weekly rainfall
- 10 highest 48-hour rainfall periods
- Plots
- One plot for each analysis (month, week, 48-hour period)
- Label x-axis (month, week, or day)
- Label y-axis (rainfall in mm)
- Include titles and highlight max values (manually, if needed)
Plots and tables should be placed close together for easy comparison.
What to Hand In
- Printed plots with matching tables (Ptolemy package is used to produce the plots)
- A description of how you cleaned the data, and include any code you used to clean the data
- All your code, commented and formatted
Assessment (/25)
- Code and Description: working formatted code that cleans data and produces plots, and a paragraph description of how the data was cleaned (/10)
- Tables: Accurate, clearly labelled, easy to read (/5)
- Plots: Clear, correctly labelled, highlights shown (/5)
- Ptolemy Used: to generate all plots (/5)
- An ArrayList is an implementation of the List interface. A List is a Collection. To learn more about Collections, look at Collections Tutorial.
- Ms. Wear's ArrayList Slides (Reminder to Ms. Wear: Power Point Presentation is saved on Documents/APCS)
- ArrayList Efficiency: Notes from Ms. Wear.
- Review what you need to know about ArrayLists for the AP Exam: AP ArrayList Skills List.
- Arraylists: API, Tutorial
- Watch what you need of these AP Online Lessons:
- Mostly review: Intro to and Traversing ArrayLists.
- Mostly new: ArrayList Methods.
- Textbook Chapter 7 - read and do questions at end of chapter
You will be writing a program in Eclipse to solve this problem. Closed everything except you may use the Java API.
Barron's 2022-23 Textbook Chapter 6
Program Design and Analysis Slides
- Barron's AP Text Chapter 6 - read and do questions at end of chapter
Practice Problems:
- Exam Details
- AP Classroom - obviously (ask me to unlock all Progress Checks if I haven't already)
- Do all the multiple choice questions in the textbook
- Do all the practice tests in the textbook
- Java Subset
- AP Java Quick Reference
- Old AP exam questions and solutions.
- Course Content
- Brandon Horn's Page
- Mini Multiple Choice Practice Tests
- FRQ Marking Criteria: Marking criteria
37 Multiple Choice Questions
Topic Distribution (as organized on AP Classroom): Unit 1 - 4 questions, Unit 2 - 2 questions, Unit 3 - 4 questions, Unit 4 - 2 questions, Unit 5 - 4 questions, Unit 6 - 2 questions, Unit 7 - 7 questions, Unit 8 - 2 Questions, Unit 9 - 8 Questions, Unit 10 - 2 questions.
You have a stretchable cloth grocery bag that can hold up to 8.5 kg (this value can change) of groceries. You have won a contest where you get two minutes to fill your grocery bag with any items from the MINI-MARKET grocery store. These are the items available to you (this list can change):
- 2 kg package of chicken for $15
- 1 kg bag of flour for $2.50
- 0.25 kg can of beans fror $2.40
- 0.5 kg box of cereal for $1.20
- 0.3 kg box of cookies for $3.99
- 1 kg bottle of soda for $0.99
- 0.3 kg can of Spam for $4.99
Create a GroceryItem class as shown below:
public class GroceryItem {
double weight = 0;
double cost = 0;
String item = "";
// write required methods
}
You are only allowed at most 2 of each item. Your goal is to fill the grocery bag so that the combined weight of all the items is <= 8.5 kg while maximizing the total value of the items.
You will write two solutions to this problem. Your first solution is either greedy or brute force. Use it to determine the optimal answer to the problem. Your second solution is the one you haven't written yet (greedy or brute force). The second solution must be recursive IF your first solution was iterative. The second solution must be iterative IF your first solution was recursive.
What are the time and space requirements of each algorithm?Use the skeleton code below:
import java.util.ArrayList;
public class Groceries {
private static int counter = 0;
// returns an array of Grocery items, the angle brackets should be square.
private static GroceryItem 
groceryItems = {
new GroceryItem(1, 2.5, "flour") ,
new GroceryItem(0.25,2.4,"beans"),
new GroceryItem(0.5,1.20, "cereal"),
new GroceryItem(0.3, 3.99,"cookies"),
new GroceryItem(0.3,4.99, "Spam"),
new GroceryItem(2, 15, "chicken"),
new GroceryItem(1, 0.99, "soda")
};
/* Recursive solution that counts method calls
* Precondition: b is an arraylist of groceries already in the bag
* Postcondition: returns the optimized bag
*/
private static ArrayList bestBagRecursive(ArrayList < GroceryItem > b) {
// counts recursive calls
counter++;
if(counter % 10000000 == 0)
System.out.println("# method calls : " + counter);
} // bestBagRecursive
/* Iterative solution
* Postcondition: returns an optimized bag
*/
private static ArrayList bestBagIterative() {
} // bestBagIterative
// returns the weight of bag b
public static double bagWeight(ArrayList < GroceryItem > b) {
}
// returns the value of bag b
public static double bagCost(ArrayList < GroceryItem > b) {
}
// returns number of items of i in bag b
public static int bagCount(ArrayList < GroceryItem > b, String i) {
}
// prints contents of bag b
public static void printBag(ArrayList < GroceryItem > b) {
}
public static void main (String 
args) {
System.out.println("************Iterative Solution******\n");
long startTime = System.nanoTime();
ArrayList < GroceryItem > perfectBag = bestBagIterative();
long endTime = System.nanoTime();
long duration = (endTime - startTime);
System.out.println("Time: " + duration/1000 + " µs");
System.out.println("# items = " + perfectBag.size());
System.out.println("weight items = " + bagWeight(perfectBag) + " kg.");
System.out.println("cost items = $" + bagCost(perfectBag));
printBag(perfectBag);
System.out.println("************Recursive Solution******\n");
ArrayList temp = new ArrayList();
startTime = System.nanoTime();
perfectBag = bestBagRecursive(temp);
endTime = System.nanoTime();
duration = (endTime - startTime);
System.out.println("Time: " + duration/1000 + " µs");
System.out.println("# method calls = " + counter);
System.out.println("# items = " + perfectBag.size());
System.out.println("weight items = " + bagWeight(perfectBag) + " kg.");
System.out.println("cost items = $" + bagCost(perfectBag));
printBag(perfectBag);
}
} // Groceries
Evaluation Criteria (/22)
How to hand in:
- Print iterative solution, commented so it is easy to read. (/5)
- Print iterative output (/5 if correct)
- Print recursive solution, commented so it is easy to read.(/5)
- Print recursive output (/5 if correct)
- Print GroceryItem.java (/2)
- Staple and hand in to my wire inbasket
Watch Graph Theory: A CS Perspective
You will complete the following project with a partner:Use this Sample Program which uses this map to test your code.
How to Hand in:
Hand in entire Eclispe Folder to Wear_ITAssessment (/85)
- Semi-working, or working solution submitted (/10)
- Specific Test Cases (/75)
Please take the time to complete the following course evaluation. It will be used for future course offerings.
Course Evaluation