Download
cs1020 n.
Skip this Video
Loading SlideShow in 5 Seconds..
CS1020 PowerPoint Presentation

CS1020

221 Vues Download Presentation
Télécharger la présentation

CS1020

- - - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - - -
Presentation Transcript

  1. CS1020 Week 7: 6th March 2014

  2. Contents • Part 1: Discussion on Sit-in Lab #2 • Part 2: Discussion on Linked List practice exercises (#25 – 27) • Part 3: Discussion on Take-home Lab #3 Week 7

  3. Part 1 Discussion on Sit-in Lab #2 Week 7

  4. Set A: Automatic Storage Facility Set A: Automatic Storage Facility • Simulate an automatic storage facility • Consists of N sections • Each section is a shelf containing M columns, with different sections having columns of different sizes • Items to be stored have 2 attributes: id and size. • Two operations • Store • Retrieve Week 7

  5. Requirements Set A: Automatic Storage Facility • Usage of Scanner class • Usage of ArrayList class • Ability to design classes to solve the problem • Ability to come up with simple algorithm quickly to perform store and retrieve Week 7

  6. Designing the classes (1/3) Set A: Automatic Storage Facility • 3 things in the problem • Automated storage facility • Section • Item • Need 3 classes! Automated Storage facility The has-a relationship between the 3 items Section Item Week 7

  7. Designing the classes (2/3) Set A: Automatic Storage Facility • Item class • Encapsulates id and size info relating to an item and methods to access them • Section class • Encapsulates number of columns in each section, size of each column and items stored in section • Encapsulates method to store a given item in the section and also to retrieve a given item and other methods • Automated storage facility class • Encapsulates the different sections in the facility • Encapsulates method to store and retrieve item among the different sections Week 7

  8. Item class Set A: Automatic Storage Facility Item • id: int • size: int + Item(id: int, size:int) + getId(): int + getSize():int + equals(obj: Object): boolean {redefines} Override equals()method to easily compare if two items are the same. Useful when retrieving item. Week 7

  9. Section class Set A: Automatic Storage Facility Class variable and methods since number of columns is same for all sections Section • nCol: int • colSize: int • shelf: ArrayList of Item + Section(colSize: int) + setNCol(): void • +getNCol(): int + getColSize(): int + storeItem(anItem: Item):boolean +retrieveItem(anItem: Item): boolean + toString(): String {redefine} Methods to store and retrieve items in a section, return true is successfully stored or retrieved, false otherwise Override toString()method to print out a section Week 7

  10. Automated storage facility class Set A: Automatic Storage Facility Constructor which reads in input and initialize all required sections and items AutomatedStorage • sectionList: ArrayList of Section Methods to store and retrieve items in the facility, nothing returned since no output required until end of simulation + AutomatedStorage(sc: Scanner) + storeOperation(anItem: Item): void +retrieveOperation(anItem: Item): void • + simulate(): void + toString(): String Method to read in input and simulate operation of the facility Overload toString method to print out the automated storage facility Week 7

  11. Designing the classes (3/3) Set A: Automatic Storage Facility • The classes can be designed differently but must show • Loose coupling between classes - should not be much interdependencies between classes • Information hiding – expose only what is needed, especially underlying data structures used should not be exposed • Abstraction – methods designed should reflect what is to be done and not how to do it (which should be hidden in the method/class) Week 7

  12. Simulating Facility Set A: Automatic Storage Facility • Read in each input operation and determine whether it is store or retrieve • If store operation, use algorithm for storing item • If retrieve operation, use algorithm for retrieving item • Keep reading input and performing operations until there is no more input • hasNext() method of scanner returns false Week 7

  13. Algorithm for storing Item (1/2) Set A: Automatic Storage Facility • Store item in section with smallest column size that still has available space for the item • storeOperation(anItem:Item) of AutomatedStorage • Sections are already given in the input from smallest column to largest column, which should also be how sections are stored in sectionList • Loop through sectionList (from index 0 to last index) and try storing item into each section • Call storeItem()method for each section • Break out of loop when storeItem()returns true Week 7

  14. Algorithm for storing Item (2/2) Set A: Automatic Storage Facility • storeItem(anItem:Item) of Section • Check if size of shelf < nCol, if yes, insert item in index 0 of shelf using add method and return true • shelf.add(0,anItem) read up add method of ArrayList • Otherwise return false (since shelf is full) Week 7

  15. Algorithm for retrieving Item (1/4) Set A: Automatic Storage Facility • Find item if it exists and remove it from its section, shifting items so that there are no gaps • retrieveOperation(anItem:Item) of AutomatedStorage • Loop through sectionList and try retrieving item from each section • Call retrieveItem()method for each section • Break out of loop when retrieveItem()returns true Week 7

  16. Algorithm for retrieving Item (2/4) Set A: Automatic Storage Facility • retrieveItem(anItem:Item) of Section • Use indexOf() method in ArrayList to test if the item exists in shelf • shelf.indexOf(anItem)  read up indexOf method • If indexOf() return value >= 0, value is the index of the item in shelf. Use remove method in ArrayList to remove the item and return true • shelf.remove(value)  read up remove method • Otherwise return false Week 7

  17. Algorithm for retrieving Item (3/4) Set A: Automatic Storage Facility • Note that indexOf() method in ArrayList uses the equals method to compare if given item and item in the ArrayList is equal • This is why we override equal method in Item class public boolean equals(Object obj) { if (objinstanceof Item) { Item item = (Item) obj; return this.id == item.id; } else return false; } Week 7

  18. Algorithm for retrieving Item (4/4) Set A: Automatic Storage Facility • If do not use indexOf() method • Loop through shelf and compare id of each item in shelf with id of given item Check out the code on CS1020 “Sit-in Labs” web page: http://www.comp.nus.edu.sg/~cs1020/3_ca/sitinlabs.html Week 7

  19. Set B: Card Game Set B: Card Game • Simulate a number card game • Consists of N players • Each player holds 5 cards from left to right • Game runs for M rounds, where each round is played from player 1 to player N. • A card is chosen from each player at the end and the winner if there is any is determined • Player can take two possible actions • Remove a card • Exchange cards Week 7

  20. Requirements Set B: Card Game • Usage of Scanner class • Usage of ArrayList class • Ability to design classes to solve the problem • Ability to come up with simple algorithm quickly to perform remove card and exchange cards Week 7

  21. Designing the classes (1/3) Set B: Card Game • 3 things in the problem • Number Card Game itself • Player • Cards • Cards is only an integer  don’t need a class to represent them • Player has a hand of 5 cards and cards can be removed and/or added to his hand • Use a class to represent the player hand • Number Card Game should be a class containing the implementation of the game mechanics Week 7

  22. Designing the classes (2/3) Set B: Card Game • PlayerHand class • Encapsulates the hand of cards a player has • Encapsulates the methods to access player hand as well as remove and add cards to his hand. • NumberCardGame class • Encapsulates the different player hands for a game • Encapsulates the method to simulate playing of the game in rounds and execution of action taken by players in each round, and also choose winner at the end Week 7

  23. PlayerHand class Set B: Card Game Get the card at a particular position PlayerHand • cardList: ArrayList of Integer Add a card to back (rightmost position) + PlayerHand() • + getNumCard(): int + getCard(pos:int): int + addCard(card:int): void + removeCard(): int +toString(): String {redefines} Remove a card from front (leftmost position) Override this method to print out the cards in player hand from left to right Week 7

  24. Number Card Game class Set B: Card Game Constant since each player only has up to 5 cards NumberCardGame Other required variables • playerList: ArrayList of PlayerHand • numRonds: int • NUM_CARD_PLAYER: int • . . . Constructor which reads in input and initialize player hands + NumberCardGame(sc: Scanner) + exchangeCard(player:int, k: int): void +removeCard(player: int): void • + simulate(): void + toString(): String Methods to implement remove a card and exchange cards actions Method to read in input and simulate M rounds of playing Overload toString method to print out the player hands at the end as well as winner if any Week 7

  25. Designing the classes (3/3) Set B: Card Game • The classes can be designed differently but must show • Loose coupling between classes - should not be much interdependencies between classes • Information hiding – expose only what is needed, especially underlying data structures used should not be exposed • Abstraction – methods designed should reflect what is to be done and not how to do it (which should be hidden in the method/class) Week 7

  26. Simulating Game Set B: Card Game • Read in input to initialize player hand and number of rounds • For each round, read in player action for the round from player 1 to player N • If remove a card action, use algorithm for removing a card • If exchange cards action, use algorithm for exchanging cards • At the end pick card for each player as indicated in input and determine winner if any Week 7

  27. Algorithm for removing a card (1/2) Set B: Card Game • Remove a card from opponent player clockwise to current player if that opponent player has more than 1 card • removeCard(player: int) of NumberCardGame • player is index of current player who takes the remove card action • To find index of opponent player from which to remove card oppPlayer= (player+1) % playerList.size(); Modulo arithmetic Week 7

  28. Algorithm for removing a card (2/2) Set B: Card Game • Call removeCard() of PlayerHand if opponent player has > 1 card • removeCard() removes leftmost card from cardList • cardList.remove(0)  read up remove() method of ArrayList if (playerList.get(oppPlayer).getNumCard() > 1) playerList.get(oppPlayer).removeCard(); Week 7

  29. Algorithm for exchanging cards (1/2) Set B: Card Game • Exchange k cards between current player and first player clockwise to current player who has >= k cards • exchangeCard(player: int, k: int) of NumberCardGame • Go in clockwise manner from current player (player) to find opponent player who fits criteria intoppPlayer= (player+1)%playerList.size(); while (oppPlayer!= player) { if (playerList.get(oppPlayer).getNumCard() < k) oppPlayer= (oppPlayer+1)%playerList.size(); else break; } Week 7

  30. Algorithm for exchanging cards (2/2) Set B: Card Game • If opponent player found (oppPlayer!= player) • Loop k times and each time • Take card from front (leftmost) of cardList of player put it to back (rightmost) of cardList of oppPlayer • Take card from front (leftmost) of cardList of oppPlayerput it to back (rightmost) of cardListof player Try write this code yourself using removeCard and addCard methods in Playerhand How should addCard be written? (read add method of ArrayList) Week 7

  31. Algorithm for determining winner Set B: Card Game • Loop through playerList and compare card picked for current player with best card picked so far • If current player has better card, best card set to current player’s card What happens if there are more than 2 best cards? Check out the code on CS1020 “Sit-in Labs” web page: http://www.comp.nus.edu.sg/~cs1020/3_ca/sitinlabs.html Week 7

  32. Part 2 Practice Exercises #25 – 27 Week 7

  33. Ex #25: List Reversal (1/4) • No nodes are removed; no new nodes are added • Contents of nodes are not changed • Only the next pointer of each node is changed head here here were Sue were Sue Mike and Mike and After reversal: head Week 7

  34. Ex #25: List Reversal (2/4) • Key ideas: • Keep a curr pointer, initialised to head, and make it point from one node to the next in a loop. • Keep a prevpointer, pointing to the node that precedes curr ListNode <E> curr = head, prev = null; while (curr != null) { // update something prev = curr; curr = curr.getNext(); } Week 7

  35. Ex #25: List Reversal (3/4) • At each iteration, the sub-list before the node pointed to by curr would have been reversed prev curr were Sue WRONG!!! and . . . . . . ListNode<E> curr = head, prev = null; while (curr != null) { curr.setNext(prev); prev = curr; curr = curr.getNext(); } Already reversed How about next iteration? How to make curr point to the node with “were”? Week 7

  36. Ex #25: List Reversal (4/4) • Need another pointer nxt, to make it point to the next node of curr prev curr nxt were Sue and . . . . . . ListNode<E> curr = head, prev = null, nxt; while (curr != null) { nxt = curr.getNext(); curr.setNext(prev); prev = curr; curr = nxt; } Already reversed Done! After the loop, update head. Week 7

  37. Ex #26: Self-Adjusting List (1/2) • Remove searched node from list • Insert searched node in front of list head here here were Sue were Sue Mike and Mike and After searching for “Sue”: head Week 7

  38. Ex #26: Self-Adjusting List (2/2) • Use curr and prev pointers as in Exercise #25 in a loop while searching for a string (eg: “Sue”) • When found, curr points to the node with “Sue” here were Sue prev curr head Mike and while (curr != null) { if (node contains required string) { prev.setNext(curr.getNext()); curr.setNext(head); head = curr; break; } prev = curr; curr = curr.getNext(); } Week 7

  39. Ex #27: Sorted Linked List (1/3) • Use a loop to search for the right place to insert the new node • Like exercise #26, use curr and prevpointers • When the right place is found, the new node is inserted between the nodes pointed to by prev and curr my my Kye car Kye car go . . . . . . After inserting node with “go”: . . . . . . Week 7

  40. Ex #27: Sorted Linked List (2/3) newNode prev curr . . . . . . go my Kye car public void addOrdered(E item) { ListNode<E> newNode = new ListNode<E> (item, null); ... // check for boundary case (see next slide) ListNode<E> curr = head.getNext(), prev = head; while ((curr!= null) && (compare item with curr.getElement())) { prev = curr; curr = curr.getNext(); } // insert between prev and curr newNode.setNext(curr); prev.setNext(newNode); } numNodes++; } Week 7

  41. Ex #27: Sorted Linked List (3/3) • Make sure you cater to the boundary case of inserting the new node in front of the list • Need to update the head pointer then Week 7

  42. Part 3 Discussion on Take-Home Lab #3 Week 7

  43. Parking Manager (1/5) • Objective: Using LinkedList class • A linked list of nodes containing: • Starting lot number, start • Size (number of lots), size • Node will be shown with start and size as follows, eg: start=12 and size=8 12 8 • Somewhat similar to exercise #27 as list is ordered by increasing value of start • 2 operations • ADD start size: Add this group of lots to the list • REMOVE start size: Remove this group of lots from the list • Splitting or merging nodes wherever necessary Week 7

  44. Parking Manager (2/5) • We will focus only on valid ADD requests • Original list: . . . . . . . . . . . . • Case 1: Add a new node • ADD 32 3 . . . . . . 90 10 10 90 32 10 90 3 5 5 3 8 3 3 • Case 2: Update a node • ADD 15 3 Week 7

  45. Parking Manager (3/5) • We will focus only on valid ADD requests • Original list: . . . . . . . . . . . . . . . . . . • Case 3: Update a node • ADD 87 3 10 87 10 90 10 3 5 6 83 5 • Case 4: Merge nodes • ADD 15 75 Week 7

  46. Parking Manager (4/5) • We will focus only on valid REMOVE requests • Original list: . . . . . . . . . . . . . . . . . . . . . . . . • Case 1: Split node into 2 • REMOVE 50 10 • Case 2: Update a node (only size) • REMOVE 95 15 60 50 10 10 25 10 40 100 85 85 • Case 3: Update a node (both start and size) • REMOVE 10 15 Week 7

  47. Parking Manager (5/5) • Make sure you check for all possible cases of valid requests • Make sure you check for invalid request Week 7

  48. END OF FILE