1 / 54

CS1020

CS1020. Week 8: 13 th March 2014. Contents. Part 1 : : Discussion on Stacks/Queues practice exercises (#28 – 32) Part 2: Discussion on Take-home Lab #4. Part 1. Practice Exercises #28 – 32. Ex #28: Simple Exercise on Stack (1/6). Add 10 5. Top. 5. 10. Add 7 2 12. Top. 12. 2.

monet
Download Presentation

CS1020

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. CS1020 Week 8: 13thMarch 2014

  2. Contents • Part 1: : Discussion on Stacks/Queues practice exercises (#28 – 32) • Part 2: Discussion on Take-home Lab #4 Week 8

  3. Part 1 Practice Exercises #28 – 32 Week 8

  4. Ex #28: Simple Exercise on Stack (1/6) Add 10 5 Top 5 10 Add 7 2 12 Top 12 2 7 5 10 Query 2 5 Top 10 Add 11 20 18 4 7 Top 7 4 18 20 11 10 Query 4 18 Top 20 11 10 Add 3 8 9 Top 9 8 3 20 11 10 Query 20 3 Query (3) not met Top Add 17 6 15 Top 15 6 17 Query 15 Top 6 17 Week 8

  5. Ex #28: Simple Exercise on Stack (2/6) • StackLL class (given) uses BasicLinkedList (also given) as its internal data structure, providing all stack operations such as isEmpty(), peek(), pop() and push(). • To complete client program StackExercise.java Week 8

  6. Ex #28: Simple Exercise on Stack (3/6) public class StackExercise { public static void main(String [] args) throws NoSuchElementException { StackLL <Integer> stack = new StackLL <Integer> (); Scanner sc = new Scanner(System.in); String op; while (sc.hasNext()) { op = sc.next(); if (op.equals("Add")) { // Fill in the code } else if (op.equals("Query")) { // Fill in the code } } } // You may write additional method(s) to make your program more modular } Week 8

  7. Ex #28: Simple Exercise on Stack (4/6) if (op.equals("Add")) { // Fill in the code } while(sc.hasNextInt()) { stack.push(sc.nextInt()); } System.out.println("Items added: " + stack); Week 8

  8. Ex #28: Simple Exercise on Stack (5/6) else if(op.equals("Query")) { // Fill in the code } booleansuccess = true; while(sc.hasNextInt()) { if(!found(stack, sc.nextInt())) { success = false; break; } } if(success) System.out.print("Query met: "); else System.out.print("Query not met: "); System.out.println(stack); Week 8

  9. Ex #28: Simple Exercise on Stack (6/6) // To find an item in the stack by repeatedly // popping item to see if it is the item required public static boolean found(StackLL <Integer> stack, inti) { while (!stack.isEmpty()) { if (stack.pop() == i) returntrue; } returnfalse; } Week 8

  10. Ex #29: Simple Exercise on Queue (1/6) Add 10 5 Front 10 5 Add 7 2 12 Front 10 5 7 2 12 Query 5 2 Front 12 Add 11 20 18 4 7 Front 12 11 20 18 4 7 Query 12 20 Front 18 4 7 Add 3 8 9 Front 18 4 7 3 8 9 Query 3 4 Query (4) not met Front Add 17 6 15 Front 17 6 15 Query 17 Front 6 15 Week 8

  11. Ex #29: Simple Exercise on Queue (2/6) • QueueLLclass (given) uses TailedLinkedList(also given) as its internal data structure, providing all queue operations such as isEmpty(), peek(), poll() and offer(). • Note that poll() is often called dequeue(), and offer() is often called enqueue() in the literature. • To complete client program QueueExercise.java Week 8

  12. Ex #29: Simple Exercise on Queue(3/6) public class QueueExercise { public static void main(String [] args) throws NoSuchElementException { QueueLL <Integer> queue= newQueueLL <Integer> (); Scanner sc = new Scanner(System.in); String op; while (sc.hasNext()) { op = sc.next(); if (op.equals("Add")) { // Fill in the code } else if (op.equals("Query")) { // Fill in the code } } } // You may write additional method(s) to make your program more modular } Week 8

  13. Ex #29: Simple Exercise on Queue (4/6) if (op.equals("Add")) { // Fill in the code } while(sc.hasNextInt()) { queue.offer(sc.nextInt()); } System.out.println("Items added: " + queue); Week 8

  14. Ex #29: Simple Exercise on Queue(5/6) else if(op.equals("Query")) { // Fill in the code } booleansuccess = true; while(sc.hasNextInt()) { if(!found(queue, sc.nextInt())) { success = false; break; } } if(success) System.out.print("Query met: "); else System.out.print("Query not met: "); System.out.println(queue); Week 8

  15. Ex #29: Simple Exercise on Queue(6/6) // To find an item in the queue by repeatedly // dequeueingitem in front to see if it is the //item required public static boolean found(QueueLL <Integer> queue, inti) { while(!queue.isEmpty()) { if (queue.poll() == i) returntrue; } returnfalse; } Week 8

  16. Ex #30: QuickEat (1/9) • Problem • Customers order food and are served on a first-come-first-serve basis. • When the dish is ready • Case1: It is given to the first customer in the queue who ordered it. • Case2: It is thrown away if no one ordered it. Week 8

  17. Ex #30: QuickEat (2/9) • Input • Number of food items N > 0 3 Fish n Chips Chicken Chop Grilled salmon • Number of instructions K > 0 4 Order 1 2 1 3 Order 2 1 3 Ready 3 Ready 2 Week 8

  18. Ex #30: QuickEat (3/9) • Input • ‘Order’ instruction: Order + tag number + K ordered dishes + K selected items Examples: Order 1 2 1 3 Order 2 1 3 • ‘Ready’ instruction: Ready + ready dish Examples: Ready 3 Ready 2 Week 8

  19. Ex #30: QuickEat (4/9) • Output: • If the dish is ready, print out: • Case 1: [Dish name] ready to be served to Tag [Tag number]. • Case 2: Throw away [Dish name]. Examples: Grilled salmon ready to be served to Tag 1 Throw away Chicken Chop. Week 8

  20. Ex #30: QuickEat (5/9) • Hint: • Class ListOrder to store all orders of customers. class ListOrder { intnumDishes; // each dish has a queue of customers who // ordered this dish private ArrayList<Queue<Integer>> dishQueues; … } Week 8

  21. Ex #30: QuickEat (6/9) • Hint: • ArrayList of all dishes, each list is a queue: Order 1 2 1 3  Customer 1 ordered 2 dishes: dish 1 and dish 3 Order 2 1 3  Customer 2 ordered 1 dish: dish 3 • Dish 1Dish 2Dish 3 Customer 1  front of queueCustomer 1 Customer 2 Week 8

  22. Ex #30: QuickEat (7/9) • Hint • In Java API, Queue is an interface and thus cannot be instantiated, i.e. Queue<Integer> queue = new Queue<Integer> produces compile-error. • You may implement your own Queue class class Queue<E> { … } • Or … Week 8

  23. Ex #30: QuickEat (8/9) • Hint: • Use LinkedList API which implements Queue Queue<Integer> queue= new LinkedList<Integer> • After that, we can use these methods from the API: queue.offer() queue.peek() queue.poll() Week 8

  24. Ex #30: QuickEat (9/9) • Hint: • Be careful of reading input 4 Order 1 2 1 3 … intnumOfInstructions = sc.nextInt(); sc.nextLine(); // to capture the '\n' character String instruction = sc.next(); Week 8

  25. Ex #31: Web Browser History Ex #31: Web Browser History • This is one of last year’s sit-in lab exercises • Objective • Simulate navigating the web using browsing history • Browsing history stores the list of web pages the user has navigated to in the past • Navigation rules • User can go backwards and forwards along the browsing history to revisit past pages • Once user navigates to a new URL, all pages in front of the new page are cleared from the browsing history so that the new page becomes the current last page. • Print out the browsing history at the end and also the current page the user is on. Week 8

  26. Solution – Linked List Ex #31: Web Browser History • Use a Linked List to store the pages browsed. • Represent the webpages as a String • ListNode<E>  ListNode<String> • Variable to track starting node, head ,already given • Need a variable curpageto track node representing the current page user is at. • Initialize – curpage = head = null Week 8

  27. Navigating to a new page (1/3) Ex #31: Web Browser History • Insert a new node (newnode) containing the new page into the Linked List. • LinkedList class given does not have a method to insert a node, so create one • public ListNode<E> addAfter(ListNode <E> current, E item) • Insert new page item after current page currentand return the new node inserted. Week 8

  28. Navigating to a new page (2/3) Ex #31: Web Browser History • Insert new node after curpageand delete all pages/nodes after new node newnode newnode.setNext(null) head null … … curpage curpage.setNext(newnode) Deleted Week 8

  29. Navigating to a new page (3/3) Ex #31: Web Browser History • Point curpage to newnode. • If head == null, head = curpage/* head is never changed after adding the 1st page .. Why?*/ newnode head null … curpage curpage.setNext(newnode) Week 8

  30. Moving Forwards Ex #31: Web Browser History • If curpage.getNext() is not null, point curpageto curpage.getNext() • Otherwise don’t do anything since curpage is at the latest page Week 8

  31. Moving Backwards Ex #31: Web Browser History • If curpage == head, that is curpage is earliest page in the browsing history, don’t do anything • Otherwise use a temporary reference ListNode<String> temp to find the new current page curpage head temp null … Week 8

  32. Moving Backwards Ex #31: Web Browser History • Move temp forwards – temp = temp.getNext() curpage head temp null … Week 8

  33. Moving Backwards Ex #31: Web Browser History • Until temp.getNext() == curpage curpage head temp null … Week 8

  34. Moving Backwards Ex #31: Web Browser History • curpage = temp • /* Can this be made easier using a variant of the linked list? */ curpage head temp null … Week 8

  35. Printing Browsing History Ex #31: Web Browser History • Point temporary variable to head and move forward while printing out the String in node pointed to. Stop when hit null. • Print out String in node that curpage is pointing to. Week 8

  36. Stack implementation - Overview Ex #31: Web Browser History • Use 2 stacks, Backward stack and Forward stack, and a reference curpage to current page being browsed • Algorithm • If browse backward, and Backward stack not empty • Push curpage onto Forward stack • Pop top of Backward stack and point curpage to it. • If browse forward, and Forward stack not empty • Push curpage onto Backward stack • Pop top of Forward stack and point curpage to it. • Navigate to a new page • Push curpage onto Backward stack if curpage is not null • Point curpage to new page • Clear Forward stack Week 8

  37. Stack implementation - Overview Ex #31: Web Browser History • At the end, how do you print out the browsing history from earliest page to latest page? Week 8

  38. Ex #32: Simple Parser Ex #32: Simple Parser • This is one of last year’s sit-in lab exercises • Objective • Implement a simple parser for a markup language • Markup language rules • An empty source file is syntactically correct. • An opening tag must be closed. • There should not be any invalid tags in the source file. • If an opening tag is embedded in the environment of another opening tag, the inner opening tag must be closed before closing the outer opening tag. • Print out whether the given source file is syntactically correct or not. Week 8

  39. How to check given input is correct – Linked List solution Ex #32: Simple Parser • Notice that only need to check 2 things • Input tags are all valid • All open tags are closed properly (encounter their corresponding close tags before the close tags of outer open tags) Week 8

  40. Checking that input tag is valid (1/3) Ex #32: Simple Parser • Need to create a Tag class to represent tags • Member variables • private String tag– stores string representation of tag • private int id– stores id of tag (open and close tag of paired tags have the same id) • private int type– stores type of tag (open,close,other -> use 3 distinct values to distinguish, eg0,1,2) • Constructor • public Tag (String itag, intidentity, intitype) { tag = itag; id = identity; type = itype; } • Other corresponding methods to access and set member variables Week 8

  41. Checking that input tag is valid (2/3) Ex #32: Simple Parser • Create a Tagarray in Parserclass to contain information on all valid tags. private static final Token[] ValidTags= { new Tag("<S>",0,0),new Tag("<P>",1,0), new Tag("<B>",2,0),new Tag("<I>",3,0), new Tag("</S>",0,1),new Tag("</P>",1,1), new Tag("</B>",2,1),new Tag("</I>",3,1) new Tag("<LB>",4,2),new Tag("<PB>",5,2), new Tag("<TEXT>",6,2)}; Note that open and close tags of paired tags have the same id, and all paired tags and non-paired tags have distinct ids. Week 8

  42. Checking that input tag is valid (3/3) Ex #32: Simple Parser • When reading in a tag, check if it is a valid tag by comparing with string representation of each tag in ValidTags. • If it cannot be found in ValidTags, then tag is invalid, and input is not syntactically correct. Week 8

  43. Checking that all open tags are closed properly (Linked List solution) (1/2) Ex #32: Simple Parser • If tag is valid, and it is an open tag (check its type), create a new node and add to front of Linked List. • In the skeleton program, adding to front of Linked List is not given. Need to implement this • public void addFront(E item) Week 8

  44. Adding to front of Linked List Ex #32: Simple Parser Current tag read <S> head null … public void addFront(item E) { head = new ListNode <E> (item, head); num_nodes++; /* increment number of nodes */ } Week 8

  45. Checking that all open tags are closed properly (Linked List solution) (2/2) Ex #32: Simple Parser • If tag is valid, and it is a close tag (check its type), check if node that head is pointing to is corresponding open tag (check that id is the same) • Is not corresponding open tag, then input is not syntactically correct–incorrectly placed close tag. • Is corresponding open tag; remove node that head is pointing to. • Implement remove front node function • public void removeFront() Week 8

  46. Remove front node of Linked List Ex #32: Simple Parser null head null … public void removeFront() { ListNode<E> temp; temp = head; head = head.getNext(); temp.setNext(null); num_nodes--; /* decrement number of nodes */ } Week 8

  47. After reading all input tags Ex #32: Simple Parser • If Linked List still has some nodes (num_nodes > 0), then input is not syntactically correct – some open tags are not closed. Week 8

  48. Stack implementation - Overview Ex #32: Simple Parser • Check if all input tags are valid – as described previously • Put valid open tags into stack • If encounter valid close tag check if top of stack is corresponding open tag. • Pop it off the stack if it is • Input is syntactically incorrect if it is not. • If stack is not empty after reading in all input tags, then input is syntactically incorrect, otherwise it is correct. Week 8

  49. Part 2 Discussion on Take-Home Lab #4 Week 8

  50. Cargo Optimization (1/4) • Problem: • Containers arrives at the terminal in a random order, addressed to different destination ships (A-Z) • They need to be stacked at the terminal • The destination ships arrives at the terminal in a fixed sequence (A-Z) Week 8

More Related