Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "Take-Home Lab #02 CS1020 – DATA STRUCTURES AND ALGORITHMS 1 AY2015-16 SEMESTER 2 1."— Presentation transcript:

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

2 Problem 1 Tournament 2

3  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

4  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

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

6  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

7  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

8 Problem 2 File 8

9  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

10 FolderFile File Manager File 10

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

12 File Manager FolderFile 12

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

14 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

15 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

16 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

17  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

18 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 https://docs.oracle.com/javase/8/docs/api/java/util/HashMap.html 18

19 Problem 3 Restaurant 19

20  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

21 Restaurant Group Table Group Problem Illustration 21

22 Restaurant GroupTable Contains Has Uses Relationship Between Entities 22

23 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

24  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

25 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

26 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

27  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

28 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

29 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

30 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

31 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

32  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

33  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

34 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

35 /* * 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

36  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

37  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

38  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

39 End Of File Any Questions? 39


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

Similar presentations


Ads by Google