mdinfotech.net  



blank

  1. Lesson: Computer Science, Degrees, and Careers Slides
  2. Assignment: The last slide has an exercise to complete with a partner. Be prepared to present to the class.
Create an account on AP Classroom and join my 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:
  1. Primitive Data Types, Variables, Arithmetic Operators, Casting (covered in Grade 11 Unit 1)
  2. Methods (cs 11), Instantiation of Objects (cs 12), String and Math classes (cs 11), Wrapper Classes (new sort of)
  3. Boolean Expressions, if statement, .equals vs == (cs 11)
  4. Iteration (cs 11)
  5. Writing Classes (cs 12) and Methods (cs 11)
  6. Arrays, Enhanced for loop (cs 11 and cs 12)
  7. ArrayLists (partially covered in cs 12, lots new)
  8. 2D Arrays (cs 11/12)
  9. Inheritance and Polymorphism (mostly new)
  10. Recursion (new)
How will we be using AP Classroom?
  • Use videos for review if needed
  • Class quizzes
  • Two Unit Exams
  • AP Practice Exam
  • Progress Checks (for exam prep)
ALL OF IT. It's all on the AP Exam.

AP Topics covered in CS 11/12 from Barrons AP CS A Premium 2022-23 :
  1. Chapter 2 final variables, operators, conditionals, loops
  2. Chapter 3: Objects, classes, access modifiers, static, methods, constructors, method overloading, this, references vs primitive data types, null, method parameters
  3. Chapter 4: Inheritance
Also, don't forget:
  1. Coding Conventions Original Java Code Conventions, Google's Java Code Conventions
  2. File I/O: Not on the exam, but needed for this course: one way to read and write to files using Java: File Input/Output Code.
An important part of commenting methods is using preconditions and postconditions. We can leave notes at the top of our methods about assumptions that we make. The precondition statement indicates what must be true before a method is called. The postcondition statement indicates what will be true when a method finishes its work. They go in the comments of a method.
// 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.
Ms. Wear's Notes on the subject

Know Barron's AP Text Chapter 5:
  1. inheriting from the Object class (p 171)
  2. Strings.
  3. String API.
  4. Math API.
  5. Random Numbers (review from CS 11)
  6. Integer and Double classes p 179
  7. (p 180) Auto-boxing and -unboxing.


Do Barron's APCS text MC Q's starting on page 185

Activities
  1. Textbook Chapter 5 - read and do questions at end of chapter
  2. Unit 2 of AP Classroom - complete progress check(s)
  1. Create a 10x10 integer array, initialized to all 0's
  2. Write a new class calledPoint with two instance variables (int x and int y) and get and set methods for each. Do not use the built in Java Point class.
  3. 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
  4. 0,0 is the top left.
  5. 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
  6. set the starting Point x,y to one in the array.
  7. 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
  8. if the array element of the new position contains 0, replace it with a 1, otherwise multiply its current value by 2
  9. if the new position is out of bounds, print a message "Out of Bounds" and end the program.
  10. If the end of file is reached, add up all the elements of the two dimensional array and output that number to the console.
  11. 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.

A. The Experiment
  1. 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);
    
  2. Now run it. What is the output? Discuss why this is happening.
  3. Change the variable types to short and run the loop 20 times.
  4. Change it to an int and run the loop 40 times.
  5. Change it to a long and run the loop 80 times.
  6. On the Google Classroom Assignment, answer:
    1. Explain what is happening.
    2. When does overflow occur for each data type?
    3. What patterns do you notice in how the sum changes?
    4. What happens when p becomes zero?
B. The Fix
  1. Modify the code to detect overflow before it happens. Print an error message and break out of the loop before it happens.
  2. On the Google Classroom Assignment, explain how your check works.
C. Real World Problems
  1. Many video games and financial applications need to prevent integer overflow (e.g., keeping track of high scores, bank balances).
  2. 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.
  3. Now rewrite the same program using BigInteger.
  4. On your sheet of paper, answer these questions:
    1. What are the advantages of using BigInteger?
    2. Why isn’t BigInteger used for all integer operations in Java?
    3. How does this apply to cryptography or large financial calculations?
D. Final Reflection
  1. On the Google Classroom Assignment, answer these questions:
    1. What is integer overflow?
    2. How does Java handle it?
    3. How can programmers prevent it?
  2. Submit your assignment on Google Classroom, one per pair.
Ms. Wear's Slides

Review

  1. Boolean Operators
  2. Operator Precedence Table

New Material:

  1. 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)) {} 
  2. Boolean Expressions and Demorgan’s Law and Short Circuiting

Exercises:

  1. Boolean Expressions Worksheet
  2. Boolean Expressions MC Questions
Lesson: Ms. Wear's AP Slides and Review: Ms. Wear's CS 12 Slides
  1. Classes and Objects
  2. Encapsulation: the packing of data and functions into a single component
  3. specifiers: public, private and static
  4. methods: defining, parameters, constructors, accessor and mutators
  5. scope
  6. this
  7. static vs instance variables
  8. static vs instance methods
  9. References, aliases, null
  10. passing objects as parameters
  11. what is OOP, the 4 pillars of OOP
  12. basics of writing a class: constructors, get/set methods
  13. this
  14. toString
Activities
  1. Barron's AP Text Chapter 3 Chapter 3 - read and do questions at end of chapter
  2. Unit 5 of AP Classroom - complete progress check(s)
Remind Ms. Wear to do this.
Ms. Wear's Slides

Found in: Barron's AP Text Chapter 4.
In class discussion on:

  1. 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.
  2. Superclass and Subclass
  3. class hierarchy: parent class, child class
  4. is-a relationship
  5. method overriding - read about @override: Predefined Annotation Types.
  6. protected keyword
  7. extends keyword
  8. super keyword
  9. declaring subclass objects
  10. 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
    					   
Need a refresher? Watch this video on inheritance.
Activities
  1. Textbook Chapter 3 - read and do questions at end of chapter
  2. Unit 9 on AP Classroom
  1. Download this starter code for the account class: download here
  2. Add a transfer method Account 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. Return true if the funds are successfully transferred, otherwise return false.
       //---------------------------------------------------------------------------------------
       //  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) {
          
       }               
                   
  3. 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) {
         
       }           
                   
  4. Create a subclass called ChequingAccount that has methods writeCheque(double amt) that withdraws amt, and depositCheque(double amt) that deposits amt.
  5. For evaluation, you will be given a Banking class which contains a driver to test your Account class. See example below:
Sample Test Case:
      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
      
  1. Spires of Vulcan Challenge
  2. My notes - you won't have access to this.
  3. Shown in Class: When to choose recursion over iteration.
  4. For AP, know recursive algorithms for Factorial, Fibonacci, and isPrime
Resources
  1. Watch What is Recursion?
  2. Java Recursion
  3. Fibonacci Problem
  4. Recursive Algorithms
  5. Difference Between Recursion and Iteration.
AP Textbook: Chapter 8 Recursion
Do all the questions at the end of the recursion chapter in the textbook.
In this Lab, you are responsible for learning and understanding iterative and recursive algorithms for the following:
  • 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) {
     ...
  } 

}

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 (Arrays only, no Arraylists), 8. 30 Multiple Choice Questions
AP Exam Allowance Per MC Q: 2.25 minutes
30x2.25 = 67.5 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 8 - 2 Questions, Unit 9 - 3 Questions, Unit 10 - 3 questions (does not cover searches/sorts).

Use the following resources to complete this activity:
  1. Big O Notation Video
  2. O(log n) explained
  3. O(n log n) explained
  4. Comparison Chart of Different Orders
  5. 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:

  1. searching in ordered and unordered lists
  2. Sequential/Linear O(n) vs Binary O(log n) searches
  3. Sorting - O(n2)
    • insertion sort
    • selection sort
    • quicksort (recursive)
    O(n log n)
    • mergesort (recursive)
Resources
  1. Sorting Algorithms Compared
  2. HTML5 Canvas Demo: Sorting Algorithms
  3. Binary Search: Demo, Code
  4. 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

  1. demonstrate that algorithm,
  2. show and explain the code
  3. Discuss the Big O efficiency
  4. Discuss pros and cons of the algorithm (see textbook)
  5. does the initial ordering of the data affects performance?(see textbook)
  6. Is there a difference in run time between worst and average cases? (see textbook)

AP Textbook: Chapter 9 Sorting and Searching

Write a class that contains methods implementing the
  • iterative Linear Search
  • iterative Binary Search
  • iterative Insertion Sort,
  • iterative Selection Sort,
  • recursive Merge Sort.
  • recursive Quick Sort.
Steps to complete:
  1. 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.
  2. Calculate the time each sort algorithm takes to sort each array. Be sure to re-randomize the arrays before doing a new sort.
  3. 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.
  4. 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.
  5. Print the times for smaller n in ms and for larger n in s, for ease of comparison.
  6. Run each test 1000 times and calculate the average the sort/search time for each data size.
  7. 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

Do all the questions at the end of the searches/sorts chapter 9 in the textbook.
Practice makes perfect! Expect a few quizzes using old exam FRQs with peer evaluations.
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:

  1. What two months have the highest average daily rainfall? (Ex. January and July)
  2. What 4 week numbers have the highest average rainfall? (Ex 1, 3, 5 and 51)
  3. 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

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
  • A description of how you cleaned the data, and include any code you used to clean the data
  • Ptolemy package is used to produce the plots

Assessment (/25)

  • Code: working formatted code that cleans data and produces plots (/10)
  • Tables: Accurate, clearly labelled, easy to read (/5)
  • Plots: Clear, correctly labelled, highlights shown (/5)
  • Ptolemy Used: to generate all plots (/5)
Using the rain fall data for the last 30(ish) years, analyze the frequency of the first digit of each total. You will be randomly assigned a data set to use: 1) one of daily totals, 2) 48 hours totals, 3) weekly totals, or 4) monthly totals. (NOT AVERAGES) Plot the frequencies of each digit on a plot where the x axis is the digits 1 on the left increasing to 9 on the right and the y axis is the number of occurrences. We will be using these plots for a class comparison of results.
Class Diagrams
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
Remind Ms. Wear to put this in class quiz online.

You will be writing a program in Eclipse to solve this problem. Closed everything except you may use the Java API.

Ms. Wear's Notes on Polymorphism

Barron's AP Text Chapter 4
  1. Declaring Subclass objects references and class hierarchies (p. 145)
  2. Polymorphism - tutorial: applies only to overridden methods in subclasses (p 135)
  3. static (early) binding and dynamic (late) binding - explained(p 147)
  4. downcasting (p 150)
Activities
  1. Textbook Chapter 4 - read and do questions at end of chapter
  2. Unit 9 of AP Classroom - complete progress check(s)
Remind Ms. Wear to put this exercise online.

Closed EVERYTHING. You may have the problem open in a browser, a sheet of paper, and a text editor that is not Eclipse.

Lesson:
  1. An ArrayList is an implementation of the List interface. A List is a Collection. To learn more about Collections, look at Collections Tutorial.
  2. Ms. Wear's ArrayList Slides (Reminder to Ms. Wear: Power Point Presentation is saved on Documents/APCS)
  3. ArrayList Efficiency: Notes from Ms. Wear.
More Resources:
  1. Review what you need to know about ArrayLists for the AP Exam: AP ArrayList Skills List.
  2. Arraylists: API, Tutorial
  3. Watch what you need of these AP Online Lessons:
Practice
  1. Textbook Chapter 7 - read and do questions at end of chapter
  2. Unit 7 of AP Classroom - complete progress check(s)

Barron's 2022-23 Textbook Chapter 6

Program Design and Analysis Slides

Activities
  1. Barron's AP Text Chapter 6 - read and do questions at end of chapter

Practice Problems:

Covers everything, will be held on AP Classroom.
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):

  1. 2 kg package of chicken for $15
  2. 1 kg bag of flour for $2.50
  3. 0.25 kg can of beans fror $2.40
  4. 0.5 kg box of cereal for $1.20
  5. 0.3 kg box of cookies for $3.99
  6. 1 kg bottle of soda for $0.99
  7. 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:
  1. Print iterative solution, commented so it is easy to read. (/5)
  2. Print iterative output (/5 if correct)
  3. Print recursive solution, commented so it is easy to read.(/5)
  4. Print recursive output (/5 if correct)
  5. Print GroceryItem.java (/2)
  6. Staple and hand in to my wire inbasket

Watch Graph Theory: A CS Perspective

You will complete the following project with a partner:

RFS Project Description

Use this Sample Program which uses this map to test your code.

How to Hand in:

Hand in entire Eclispe Folder to Wear_IT

Assessment (/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