- course introduction on mdinfotech
- expectations
- the backup talk
- logging in
- H drive vs C drive vs Student_Collab Drive (SAVE EVERY PROGRAM YOU WRITE ON THE H (Host) DRIVE.)
- saving and renaming files, creating folders
- Printing
- evaluation
- 100/80/60 Quizzes: short programming problems given at the beginning of class. They are used to assess if your programming skills are where they should be.
- 60% - indicates your programming skills are not where they should be and will require a meeting with the teacher to discuss what you can do differently to succeed
- 80% indicates your programming skills are close to what they should be you may need to adjust the way you approach your learning in this class
- 100% indicates you have the correct solution and that your programming skills are where they should be.
- There are a number of small programming exercises to be handed in and a few larger ones.
- There are two Java Exams worth a total of 30% your final mark.
- Term Project: a large scale problem that will take about 3 weeks to solve, in a group. Problem complexity will try to be matched with programmer skill.
Do Programmers Actually Need Touch Typing?
Important Dates
- Canadian Computing Contest - Wed Feb 21 12-3
- Spring Break - March 15 to April 2
- APCS Exam - Wednesday May 8
Resources
- AP Classroom
- AP Computer Science A Home Page
- AP Textbook: Barron's AP Computer Science A
- Java API
- Java Quick Reference (2019)
- Java For Beginners Video Tutorials
- Review for AP Comp Sci Exam
- What is Java?
- How to program Hello World
- Ms. Wear's Slides for this Lesson
- Read Hello World for an explanation of HelloWorld.java.
- Java API
- Learn to Program in Java Video Tutorial
- w3 Schools Java Tutorials
- Download Eclipse Installer, and follow the directions on the download page. You want to install the version "Eclipse for Java Developers".
- Watch this video to run Hello World on your new Eclipse Installation: How To: Create a Simple Java Program Using Eclipse
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
- Homework: Review all of CS 11 and CS 12 Java Units
- Quiz
We will spend the first week or two prepping for the CCC. This will get your programming skills up to speed for AP.
To write the Canadian Computing Contest on Wednesday Feb 21 12 - 3:- Read What's on the CCC?
- Join my CCC Google Classroom.
- Register (http://cemc.uwaterloo.ca/contests/computing/computing-grader.html). You will need the school number :
091301202
- Get me to approve your registration.
- Do practice questions. (http://cemc.uwaterloo.ca/contests/computing/computing-grader.html)
- Ensure you can submit solutions that are accepted by the online grader BEFORE the day of the test. A number of students submitted correct solutions last year but got marked with a zero because they did not follow the instructions.
- Read the CCC Rules.
- all your classes must be called
Main
to be marked by the online grader. - You should know how to use
BufferedReader
for console input: Console input in Java, instead of Scanner. It is faster and some harder problems will require speedy code for large test cases in order to meet the time requirements. Here is sample code of mine: Ms. Wear's Buffered Reader - If you are writing the Junior contest it is useful to know the following:
- Do more practice J3/J4 in class, than J1/J2
- Review String manipulation (usually J3).
- Review 2D Arrays (J5)
- Previous students have suggested it is useful to know the Breadth First search (for J5's)
- If you are writing the Senior contest, it is useful to know the following:
- Know Comparable. Ms. Wear's Comparable. Here is my solution to CCC 2020 S1 Surmising a Sprinter's Speed. Use it as an example of how to solve one of these problems with an object oriented that implements comparable and uses console input.
- You should know how to use String Tokenizer instead of String.split(), because it is faster and some harder problems will require speedy code for large test cases in order to meet the time requirements. Here is sample code of mine: Ms. Wear's StringTokenizer
- Searches/Sorts (S1)
- It has been suggested by previous students that it is also useful to know:
- If you are not in AP CS but want to write, complete this google form in addition to everything else.
Review the following topics:
Console Input and Output- Review how to get user input from the command line: run this program using Eclispe: ConsoleInput.java and refer to the Scanner Class API.
- Review dialog boxes: run this program using Eclispe: Greeting.java
- See Greeting.java for an example of exception handling.
- Read about it here: Try Statements and Exception Handling
- If you missed the in class lesson, watch this Input and Scanner Class Tutorial
- Types of input dialog boxes: JOptionPane API, (JOptionPane Tutorial).
// 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)
Integer
andDouble classes
p 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
- Unit 2 of AP Classroom - complete progress check(s)
- Create a 10x10 integer array, initialized to all 0's
- Write a new class called
Point
with two instance variables (int x
andint 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,0
is 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,y
to 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 data
and end the program.
The class will be split into groups to come up with sample test cases each. This lab will be peer evaluated.
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)) {}
- Read Barrons Text page 71 top
- Read Short-Circuit Boolean Expressions
- Complete this Boolean Expressions exercise. Note: the online marker does not work, compare your solutions with each other.
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? Why?
Try changing it to a short and running the loop 20 times.
Now change it to an int and run the loop 40 times.
What is happening?
- 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
- Unit 5 of AP Classroom - complete progress check(s)
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
transfer
methodAccount
class 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. Returntrue
if 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
ChequingAccount
that has methodswriteCheque(double amt)
that withdrawsamt
, anddepositCheque(double amt)
that deposits amt. - For evaluation, you will be given a
Banking
class which contains a driver to test yourAccount
class. 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 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.14000000000001 Gomez balance after deposit: $320.0 Gomez balance after withdrawal: $218.0 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
- Stuff
- Watch What is Recursion?
- Make notes: What is Recursion, What are the two minimum criteria required to end recursion?
- Write the SayHi() recursive method from the video.
- In class activity: write recursive solutions for Factorial, Fibonacci, and isPrime
Recursion vs Iteration
There are times where using recursion is better than using a loop, and times where using a loop is better than using recursion. Choosing the "right" one can save resources and/or result in fewer lines of code. Are there any cases where a task can only be done using recursion, rather than a loop?
Yes and no. Ultimately, there's nothing recursion can compute that looping can't, but looping takes a lot more plumbing. Therefore, the one thing recursion can do that loops can't is make some tasks super easy. Take walking a tree. Walking a tree with recursion is stupid-easy. It's the most natural thing in the world. Walking a tree with loops is a lot less straightforward. You have to maintain a stack or some other data structure to keep track of what you've done. Often, the recursive solution to a problem is prettier. That's a technical term, and it matters.
- Fibonacci Sequence
- Factorial
- IsPrime
Examine this code for Fibonacci. Now write similar programs that compare the runtime and number of method calls for factorial and isPrime (both recursive and iterative solutions). Research the algorithms for each if you need to.
Now devise a way to determine for each algorithm the number of method calls it takes. Print it out formatted in a way that clearly compares the number of method calls and time is takes for recursion vs iteration for each of the 3 algorithms.
What to hand in:A hard copy of your program's output with the data and results clearly explained.
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 sentence)
Example: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) { ... } }
- 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
- Sequential/Linear O(n) vs Binary O(log n) searches
- Sorting - O(n2)
- insertion sort
- selection sort
- quicksort (recursive)
- 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, Quicksort 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.
- recursive Quick 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
The following links describe what parts of Java you need to know for the AP Exam:
AP Exam Allowance Per MC Q: 2.25 minutes
34x2.25 = 77 minute time limit.
Topic Distribution: Unit 1 and 2 - 5 questions, Unit 3 - 4 questions, Unit 4 - 4 questions, Unit 5 - 5.5 questions, Unit 6 - 4 questions, Unit 7.5/7.6 - 3 questions, Unit 8 - 2 Questions, Unit 9 - 3 Questions, Unit 10 - 5 questions.
Go Home Property Insurance has noticed a number of recent invalid insurance claims related to natural causes from clients in Victoria. They are wondering if this has been going on historically our region. They want an independent third party to analyze local rainfall data and to identify
- historically, what two months have the highest average daily rainfall? (Ex. January and February)
- historically, what 4 week numbers have the highest average rainfall? (Ex 1, 3, 5 and 51)
- what are the 10 highest dates of rainfall over a 48 hour period? (Ex. Jan 8, 2020, Nov 13, 2019 etc)
You have been hired to answer these questions.
- This is an exercise in gathering, cleaning, and analyzing data, and also in using a third party plotting package.
- Download this zip file: PTPlot Package. This is a package from the Ptolemy Homepage that allows easy 2D plotting of data. 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.
- Copy the program from below. It is from listing A.1 in this document: PT Plot PDF. Run this program as your PTPlot Hello World. It should 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 } }
- Now you are ready for some weather data! Download and extract this zip file: weather.zip. This is rainfall data in CSV files for two stations in Victoria for the past until 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.
- Download similar data for 2021, 20222, 2023, and the portion of 2024 that has passed. Add it to the data from the zip file.
- The code below reads in all the lines of a file and saves it into an array of strings. For more info, see Streams to Arrays.
BufferedReader in = new BufferedReader(new FileReader("src/weather/" + year + ".txt")); String lines = in.lines().toArray(String::new);
- Clean and analyze the data to answer the following questions which are to be presented in a report on Google Classroom:
- What two months have the highest average rainfall per day? List the two months, each with average rainfall per day AND produce a plot to visualize your evidence.
- What four week numbers have the highest average rainfall? List the for week numbers, each with average rainfall per week AND produce a plot to visualize your evidence.
- What are the 10 highest dates of rainfall over a 48 hour period? List the 10 dates, each with rainfall over 48 hours AND produce a plot to visualize your evidence.
- All plots must have the x axis labelled appropriately (month numbers, week numbers, or days from the start) and the y axis labelled in millimetres of rainfall (mm). Each plot must have a relevant heading and highlight the maximum values of interest. (Note this can be done with additional software, or by hand on the hard copy. Ptolemy does not do this very easily)
- All tables must have titles, and labelled columns and be placed in close proximity to the plots in which they reference.
- To hand in: Print your plots and corresponding tables together for easy reference. Print all your code.
Evaluation (/20)
Code submitted /10
Tables: correct data and easy to read format /5
Plots: correct, with years labelled, important points highlighted /5
UML Basics
Know these symbols
Association - uses
Inheritance - is-a
Implementation - interfaces
Dependancy - we are not going to use this
Aggregation - has-a
Composition - also has-a, but we are not going to use this
You will be writing a program in Eclipse to solve this problem. Closed everything except you may use the Java API.
Barron's AP Text Chapter 4
- Declaring Subclass objects references and class hierarchies (p. 145)
- Polymorphism - tutorial: applies only to overridden methods in subclasses (p 135)
- static (early) binding and dynamic (late) binding - explained(p 147)
- downcasting (p 150)
- Textbook Chapter 4 - read and do questions at end of chapter
- Unit 9 of AP Classroom - complete progress check(s)
Closed EVERYTHING. You may have the problem open in a browser, a sheet of paper, and a text editor that is not Eclipse.
- 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
- Generics, 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
- Unit 7 of AP Classroom - complete progress check(s)
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
35 Multiple Choice Questions
AP Exam Allowance Per MC Q: 2.25 minutes
35 x 2.25 = 78 minute 45 second time limit.
Topic Distributio (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 - 1 Questions, Unit 9 - 8 Questions, Unit 10 - 1 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. You may choose what type of algorithm (brute force, greedy, or recursive) to write for the first solution. Use it to determine the optimal answer to the problem. 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 + " ms"); 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"); ArrayListtemp = new ArrayList(); startTime = System.nanoTime(); perfectBag = bestBagRecursive(temp); endTime = System.nanoTime(); duration = (endTime - startTime); System.out.println("Time: " + duration/1000 + " ms"); 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: tba
Please take the time to complete the following course evaluation. It will be used for future course offerings.
Course Evaluation