Take-Home Lab #02 CS1020 – DATA STRUCTURES AND ALGORITHMS 1 AY2015-16 SEMESTER 2 1.

Slides:



Advertisements
Similar presentations
Java Review Interface, Casting, Generics, Iterator.
Advertisements

Lab 10: Bank Account II Transaction List, error checking & aggregation.
Collections & Loops Chapter 5 Copyright © 2012 Pearson Education, Inc.
Loops Notes adapted from Dr. Flores. It repeats a set of statements while a condition is true. while (condition) { execute these statements; } “while”
Arrays, Loops weeks 4-6 (change from syllabus for week 6) Chapter 4.
© The McGraw-Hill Companies, 2006 Chapter 7 Implementing classes.
Writing algorithms using the while-statement. Previously discussed Syntax of while-statement:
ADSA: Maps/ Advanced Data Structures and Algorithms Objectives – –examples of maps, and introduce map collection views Semester 2,
Week 4-5 Java Programming. Loops What is a loop? Loop is code that repeats itself a certain number of times There are two types of loops: For loop Used.
Random, Collections & Loops Chapter 5 Copyright © 2012 Pearson Education, Inc.
Writing Methods Using if, loops, and variables to implement algorithms Copyright © 2012 Pearson Education, Inc.
Grouping objects Collections and iterators. Main concepts to be covered Collections Loops Iterators.
A Computer Science Tapestry 1 Recursion (Tapestry 10.1, 10.3) l Recursion is an indispensable technique in a programming language ä Allows many complex.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 22 Java Collections.
CIS 068 Welcome to CIS 068 ! Stacks and Recursion.
Java Quiz Bowl A fun review of the Java you should know from CMPT 201 If you don’t know the answers - this week is for you to study up!
The while Loop Syntax while (condition) { statements } As long condition is true, the statements in the while loop execute.
CSE 143 Lecture 11 Maps Grammars slides created by Alyssa Harding
Objects First With Java A Practical Introduction Using BlueJ Grouping objects Collections and iterators 2.0.
Arrays and ArrayLists in Java L. Kedigh. Array Characteristics List of values. A list of values where every member is of the same type. Each member in.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
Arrays BCIS 3680 Enterprise Programming. Overview 2  Array terminology  Creating arrays  Declaring and instantiating an array  Assigning value to.
Arrays An array is a data structure that consists of an ordered collection of similar items (where “similar items” means items of the same type.) An array.
The while Loop Syntax while (condition) { statements } As long condition is true, the statements in the while loop execute.
Data structures Abstract data types Java classes for Data structures and ADTs.
Collection 105 Yola. To store data in RAM Variables (name all the types with their length) Arrays (one, two or more) Collections and Maps.
Lab 7 Queue ADT. OVERVIEW The queue is one example of a constrained linear data structure. The elements in a queue are ordered from least recently added.
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
CSC1401 Classes - 2. Learning Goals Computing concepts Adding a method To show the pictures in the slide show Creating accessors and modifiers That protect.
(c) University of Washington15-1 CSC 143 Java List Implementation via Arrays Reading: 13.
More Methods and Arrays Material from Chapters 5 to 7 that we didn’t cover in 1226.
Unit Testing CSIS 3701: Advanced Object Oriented Programming.
Lab 1 Logbook ADT. OVERVIEW A monthly logbook consists of a set of entries, one for each day of the month.
CreatingClasses-SlideShow-part31 Creating Classes part 3 Barb Ericson Georgia Institute of Technology Dec 2009.
Objects First With Java A Practical Introduction Using BlueJ Grouping objects Collections and iterators 1.0.
CSE 110 Review Session Hans Hovanitz, Kate Kincade, and Ian Nall.
Problem 1 Bank.  Manage customers’ bank account using the following operations: Create a new account given a customer’s name and initial account. Deposit.
Chemistry CS1020.  Given a set of mappings and chemical formula: Calculate the molecule mass of the formula Problem Description C12 H1 N14 O16 (NH 4.
Cinema SIT-IN LAB 2 (JAVA). Problem 1.Chairs in the cinema are arranged in rows 2.Each row has a name, and a capacity 3.Allocate groups of people to the.
GROUPING OBJECTS CITS1001. Lecture outline The ArrayList collection Process all items: the for-each loop 2.
Sit-In Lab 2 - OOP Restaurant.  Manage a restaurant and perform these types of queries: Assign a favorite table to a specific group Assign the lexicographically-smallest.
Jeopardy Print Me Which loop? Call Me Name Me My Mistake Q $100 Q $200 Q $300 Q $400 Q $500 Q $100 Q $200 Q $300 Q $400 Q $500 Final Jeopardy.
Class Everything in Java is in a class. The class has a constructor that creates the object. If you do not supply a constructor Java will create a default.
Collections Dwight Deugo Nesa Matic
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Decisions and Iterations.
CS 115 OBJECT ORIENTED PROGRAMMING I LECTURE 11 GEORGE KOUTSOGIANNAKIS 1 Copyright: 2015 Illinois Institute of Technology_ George Koutsogiannakis.
Arrays Chap. 9 Storing Collections of Values 1. Introductory Example Problem: Teachers need to be able to compute a variety of grading statistics for.
Coming up Implementation vs. Interface The Truth about variables Comparing strings HashMaps.
Problem of the Day  Why are manhole covers round?
Programming in Java Transitioning from Alice. Becomes not myFirstMethod but …. public static void main (String[] arg) { // code for testing classes goes.
Building Java Programs Chapter 12: Recursive public/private pairs Chapter 13: Searching reading: 13.3.
Sit-in Lab 4 Orders Topic: Stack and Queue. Overview Simulate an order management system that:  Can take multiple orders and processing them according.
CS1020 – Data Structures And Algorithms 1 AY Semester 2
The need for Programming Languages
Lecture 7 D&D Chapter 7 & 8 Composite Classes and enums Date.
CS1020 – Data Structures And Algorithms 1 AY Semester 2
Testing and Debugging.
ENEE150 Discussion 13 Section 0101 Adam Wang.
User input We’ve seen how to use the standard output buffer
Prof. Neary Adapted from slides by Dr. Katherine Gibson
Week 6 Discussion Word Cloud.
COMPUTER 2430 Object Oriented Programming and Data Structures I
Array Lists CSE 1310 – Introduction to Computers and Programming
Collections and iterators
OBJECT ORIENTED PROGRAMMING I LECTURE 11 GEORGE KOUTSOGIANNAKIS
Web Design & Development Lecture 6
slides created by Ethan Apter and Marty Stepp
Objects with ArrayLists as Attributes
Collections and iterators
ITE “A” GROUP 2 ENCAPSULATION.
Presentation transcript:

Take-Home Lab #02 CS1020 – DATA STRUCTURES AND ALGORITHMS 1 AY SEMESTER 2 1

Problem 1 Tournament 2

 Simulate a tournament: Two important numbers: M (the number of participants) and N (the number of rounds). Assign initial seat numbers and scores for each participant. Just simulate the tournament as given in the problem description. 3

 For each Participant, we need to implement: Setter method for seat number Setter method for multiplier Getter methods Method for calculating new seat number Method for adding points Tournament 4

 Appropriate attributes:  name: String  cardNumber: int  score: int  seatNumber: int Class: Participant Tournament 5

 What you will need in order to ease the process: Array of Participants Use the participant’s seat number as the index. You can easily retrieve Participants by having the seat number and easily modify the seat number of a participant Tournament 6

 Just simulate the process of the tournament and you should be fine.  Use the remainder/modulo operator (%) in Java to get the new seat number of a Participant to avoid “overflow”  After that, just iterate through all participants to find out who has the maximum score. Tournament 7

Problem 2 File 8

 Simulate a file manager system: Create files and folders Delete a file from a folder Move a file to another folder Calculate the size of a folder Find the folder with the largest size File 9

FolderFile File Manager File 10

File Manager Tutorials Take-Home Labs Sit-In Labs filenameOne tournament file restaurant File 11

File Manager FolderFile 12

File FileManager: public class FileManager() File: class File(String name, int fileSize, String folderName) Folder: class Folder(String name) 13

FileManager Keeps a list of all folders currently in the system Reads and executes the queries Folder Some tips: Have a method to get the size of the folder. Instead of having a setter to set the list of files, create an “addFile” method that acts as a “setter” of a file being added to the folder. Whenever you add a file to a folder, change the folderName attribute of that file File Contains information about: The file name The file size The folder in which the file is in File 14

public void addFile(File newFile) { this.listOfFiles.add(newFile); newFile.setFolderName(this.getName()); } Folder public int getSize() { int size = 0; for (File f : listOfFiles) { //read as: for every File f in listOfFiles size += f.getSize(); } return size; } File 15

FileManager ?  How do I get the Folder (or File) object, given its name? ArrayList HashMap VS Need to iterate through the list. Elaborated further in the Restaurant problem discussion Fast and Easy File 16

 How do I use HashMap? HashMap HashMap hashMapName = new HashMap (); public class FileManager { private HashMap fileMapping; private HashMap folderMapping; private ArrayList listOfFolders; public FileManager() { this.fileMapping = new HashMap (); this.folderMapping = new HashMap (); this.listOfFolders = new ArrayList (); } … //etc. } FileManager File 17

Adding a Key-Value Mapping folderMapping.put(folderName, newFolder); Value Retrieval using a Key Folder retrievedFolder = folderMapping.get(folderName); folderName is a String while newFolder is a Folder folderName is a string containing the name of the folder retrievedFolder 18

Problem 3 Restaurant 19

 Manage a restaurant and perform these types of queries: Assign a specific table to a specific group Assign the lexicographically-smallest available table to a specific group A specific group leaves the restaurant Prints the name of the table that a specific group is currently in Prints the name of the group of a specific table Problem Description 20

Restaurant Group Table Group Problem Illustration 21

Restaurant GroupTable Contains Has Uses Relationship Between Entities 22

Class Overview Restaurant Keeps a list of all tables and groups currently in the restaurant Reads and executes the queries Table Contains information about: Capacity of the table The group that is assigned to it The status of the table Its name Group Contains information about: The number of people The assigned table The group’s name 23

 Class Restaurant Class Overview Restaurant -tables : ArrayList -groups : ArrayList +//methods  Class Table Table -name : String -capacity : int -isOccupied : Boolean -currentGroup : Group +getName() : String +reset() : void -toggle() : void …  Class Group Group -name : String -capacity : int -currentTable : Table +getName() : String +getCapacity() : int +getTable() : Table … No need getter-setter for Restaurant; Restaurant acts as a “Controller” 24

public void setGroup(Group g) { this.currentGroup = g; this.toggle(); } public void reset() { this.currentGroup = null; this.toggle(); } private void toggle() { this.isOccupied = !this.isOccupied; } Private Helper in Table 25

Constructors Restaurant: public class Restaurant() Group: class Group(String name, int numOfPeople, Table assignedTable) Table: class Table(String name, int capacity) Some questions to ponder: When do we create a new group?  When we can assign it a table. A group cannot “queue”, i.e. if it could not be assigned a table, it leaves the restaurant. When do we add tables (or groups) to the list in Restaurant?  After the creation of each object. When do we remove tables (or groups) from the list in Restaurant?  You remove a group from the list when it leaves the restaurant. You do not remove tables from the list. 26

 Some tips for processing the queries:  Perform all logical operations in the Restaurant class  Avoid the use of static variables and methods  The methods in the table and group class are only for operations that modifies or returns their own attributes. These operations are called by the Restaurant class. E.g:  getName(): returns the name of the table (or group)  reset(): resets a table back to vacant (and toggle the status of the table)  We define helper methods in Restaurant as we go along, e.g:  getTableBasedOnName(String tableName): returns the Table with the name tableName, returns null if not found  getValidLexiSmallestTable(int numOfPeople): returns the lexicographically smallest Table that fits the group with numOfPeople. Useful Tips 27

How to avoid static In the Restaurant Class  What most of you did (in your take-home lab submissions): public static void main(String[] args) { //your code } public static Table getTableBasedOnName(String name) { //implementation }  How to avoid static: public static void main(String[] args) { Restaurant myRestaurant = new Restaurant(); myRestaurant.run(); } public void run() { //your code (treat this as “main”) } public Table getTableBasedOnName(String name) { //implementation } 28

The Run Method (in Restaurant) public void run() { Scanner sc = new Scanner(System.in); int N = sc.nextInt(); sc.nextLine(); readAndStoreTables(sc, N); int Q = sc.nextInt(); sc.nextLine(); executeQueries(sc, Q); } 29

Read and Store Tables private void readAndStoreTables(Scanner sc, int N) { for (int i = 0; i < N; i++) { //reads the input and split it if //a blank space (" ") is found String[] split = sc.nextLine().split(" "); //store table information into local variables String tableName = split[0]; int capacity = Integer.parseInt(split[1]); //create new table object and store it into //the list of tables Table newTable = new Table(tableName, capacity); tables.add(newTable); } 30

Execute Queries private void executeQueries(Scanner sc, int Q) { for (int i = 0; i < Q; i++) { String[] splittedInput = sc.nextLine().split(" "); int input = Integer.parseInt(splittedInput[0]); //execute queries based on type //you can also use switch-case if (input == 1) { assignFavoriteTable(splittedInput); } else if (input == 2) { assignLexiSmallestTable(splittedInput); } else if (input == 3) { leaveRestaurant(splittedInput); } else if (input == 4) { printOccupiedTable(splittedInput); } else { printCurrentGroupName(splittedInput); } 31

 Query 1 Query 1: Assign group to specific table private void assignFavoriteTable(String[] splittedInput) { String groupName = splittedInput[1]; int numOfPeople = Integer.parseInt(splittedInput[2]); String tableName = splittedInput[3]; Table favTable = getTableBasedOnName(tableName); } If table is not null and can assign*  create group and assign table If not  print “not possible” * Can assign if: 1. The capacity of favTable is at least numOfPeople 2. favTable is currently vacant 32

 Helper Method (Reusable for queries 1 and 5) /* for sit-in labs, this is a good example of pre- and post- condition * pre-condition: The arraylist of tables has been initialized and tables * have been stored properly * * post-condition: Returns the table with name tableName and null if there * is no such table * * description: iterates through the list of tables and return the most * appropriate table based on tableName. Returns null if no such table is * found */ private Table getTableBasedOnName(String tableName) { } Helper Method: getTableBasedOnName -Loop through the list of tables -If the current table’s name matches tableName, return that Table and stop the loop. Why can we stop? -After finish iterating and no table is found: return null 33

private void assignLexiSmallestTable(String[] splittedInput) { String groupName = splittedInput[1]; int numOfPeople = Integer.parseInt(splittedInput[2]); Table assigned = getValidTable(numOfPeople); }  Query 2 Query 2: Assign group to a table If table is not null*  create group and assign table If null (we don’t find a table that fits)  print “not possible” * We don’t need to check if it is assignable as in query 1 since we do the checking inside getValidTable(). Why?  we will iterate through all tables and find the lexicographically smallest valid table. Hence, as we iterate, we also check its validity.  Why do we need to iterate through all tables? Think! 34

/* * pre-condition: ??? * post-condition: ??? * description: ??? */ private Table getValidTable(int numOfPeople) { }  Helper Method Helper Method: getValidTable -Loop through the list of tables while keeping the current lexi- smallest and valid table in a local variable -For each table: check its validity. If it’s invalid, skip. If it’s valid, compare with the current lexi-smallest table. If this new table is lexicographically smaller, update the local variable that keeps the table. -Return the lexi-smallest available table (if it exists) or null otherwise 35

 Query 3 Query 3: A group leaves the restaurant private void leaveRestaurant(String[] splittedInput) { String groupName = splittedInput[1]; Group currentGroup = getGroupBasedOnName(groupName); } If currentGroup is not null  reset its table and assign null as currentGroup ’s table and remove currentGroup from the list of groups inside the restaurant If null (there is no such group)  do nothing The implementation of getGroupBasedOnName is similar to getTableBasedOnName. This helper is useful for Queries 3 and 4. 36

 Query 4 Query 4 : Print the current group’s table Why?  we only add groups to the list when we assign it a table  when a group leaves, we remove it from the list of groups private void printOccupiedTable(String[] splittedInput) { String groupName = splittedInput[1]; Group currentGroup = getGroupBasedOnName(groupName); } If currentGroup is not null  print its table name. We do not need to check if it has a table or not. Why*? If null  print “invalid” 37

 Query 5 private void printCurrentGroupName(String[] splittedInput) { String tableName = splittedInput[1]; Table curTable = getTableBasedOnName(tableName); } Query 5 : Print the current group of the table If curTable is not null and it is occupied  print the occupying group’s name. Else  print “invalid” 38

End Of File Any Questions? 39