Queues21 Queues II: Applications. queues22 Palindrome recognition Palindrome: collection of characters that reads the same backwards and forwards Examples:

Slides:



Advertisements
Similar presentations
Chapter 7 User-Defined Methods. Chapter Objectives  Understand how methods are used in Java programming  Learn about standard (predefined) methods and.
Advertisements

Queues CS 308 – Data Structures. What is a queue? It is an ordered group of homogeneous items of elements. Queues have two ends: –Elements are added at.
Topic 9 The Queue ADT.
Queues CS 3358 – Data Structures. What is a queue? It is an ordered group of homogeneous items of elements. Queues have two ends: – Elements are added.
Chapter 14 Queues. Chapter Scope Queue processing Using queues to solve problems Various queue implementations Comparing queue implementations Java Foundations,
Copyright 2008 by Pearson Education Building Java Programs Chapter 7 Lecture 7-1: Arrays reading: 7.1 self-checks: #1-9 videos: Ch. 7 #4.
Loop variations do-while and for loops. Do-while loops Slight variation of while loops Instead of testing condition, then performing loop body, the loop.
Loops Repeat after me …. Loops A loop is a control structure in which a statement or set of statements execute repeatedly How many times the statements.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 7 User-Defined Methods.
Chapter 7: User-Defined Methods
Building Java Programs
ADT Stacks and Queues. Stack: Logical Level “An ordered group of homogeneous items or elements in which items are added and removed from only one end.”
Control Structures II. Why is Repetition Needed? There are many situations in which the same statements need to be executed several times. Example: Formulas.
Chapter 4: Control Structures II
MSc IT Programming Methodology (2). MODULE TEAM Dr Aaron Kans Dr Sin Wee Lee.
CSE 373 Data Structures and Algorithms Lecture 2: Queues.
CSE 143 Lecture 7 Stacks and Queues reading: "Appendix Q" (see course website) slides created by Marty Stepp and Hélène Martin
Chapter 6 Iteration.  Executes a block of code repeatedly  A condition controls how often the loop is executed while (condition) statement  Most commonly,
Chapter 6: Iteration Part 2. Create triangle pattern [] [][] [][][] [][][][] Loop through rows for (int i = 1; i
Java Programming: From the Ground Up
 The pool rack example could be implemented using a for loop.  It is also possible to write recursive methods that accomplish things that you might.
CS1101: Programming Methodology Recitation 3 – Control Structures.
ITI Introduction to Computing II Lab-8 Dewan Tanvir Ahmed University of Ottawa.
The while Loop Syntax while (condition) { statements } As long condition is true, the statements in the while loop execute.
Week 2 - Wednesday.  What did we talk about last time?  Data representation  Binary numbers  Types  int  boolean  double  char  String.
The while Loop Syntax while (condition) { statements } As long condition is true, the statements in the while loop execute.
 Executes a block of code repeatedly  A condition controls how often the loop is executed  Most commonly, the statement is a block statement (set of.
CSC 205 Programming II Lecture 22 Carwash Simulation.
Lecture 3 Decisions (Conditionals). One of the essential features of computer programs is their ability to make decisions. Like a train that changes tracks.
Collection 105 Yola. To store data in RAM Variables (name all the types with their length) Arrays (one, two or more) Collections and Maps.
Chapter 4: Control Structures II
Stacks and Queues. 2 3 Runtime Efficiency efficiency: measure of computing resources used by code. can be relative to speed (time), memory (space), etc.
© 2010 Pearson Addison-Wesley. All rights reserved. Addison Wesley is an imprint of CHAPTER 5: Queues Java Software Structures: Designing and Using Data.
Iteration Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.
1 CMPSCI 187 Computer Science 187 Introduction to Introduction to Programming with Data Structures Lecture 13: Queues Announcements.
AITI Lecture 18 Introduction to Data Structure, Stack, and Queue Adapted from MIT Course 1.00 Spring 2003 Lecture 23 and Tutorial Note 8 (Teachers: Please.
Stacks Ellen Walker CPSC 201 Data Structures Hiram College.
Java Variables, Types, and Math Getting Started Complete and Turn in Address/Poem.
CONTROL STATEMENTS LOOPS. WHY IS REPETITION NEEDED?  There are many situations in which the same statements need to be executed several times.  Example:
Chapter 8 Queues. © 2004 Pearson Addison-Wesley. All rights reserved 8-2 The Abstract Data Type Queue A queue –New items enter at the back, or rear, of.
CSE 373: Data Structures and Algorithms Lecture 2: Queues.
Chapter 7 Queues Introduction Queue applications Implementations.
Copyright © Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Java From Control Structures through Data Structures by Tony.
College Board Topics – A.P. Computer Science A Program Design - Read and understand a problem's description, purpose, and goals; Apply data abstraction.
CSCI S-1 Section 8. Coming Soon Problem Set Four (72 + 5/15 points) – Tuesday, July 21, 17:00 EST.
Exam 2 EXAM 2 Thursday!!! 25% of Final Grade Know: loops, switch/case Files Input failure (e.g. scan.hasNextInt())
Click to edit Master text styles Stacks Data Structure.
Stacks and Queues. 2 Abstract Data Types (ADTs) abstract data type (ADT): A specification of a collection of data and the operations that can be performed.
CSC111 Quick Revision.
CSCE 210 Data Structures and Algorithms
Chapter 7 User-Defined Methods.
Java Programming: From Problem Analysis to Program Design, 3e Chapter 7 User-Defined Methods.
Chapter 5: Control Structures II
Computer Programming Methodology Input and While Loop
Repetition-Sentinel,Flag Loop/Do_While
Chapter 5: Control Structures II
The switch Statement The switch statement provides another way to decide which statement to execute next The switch statement evaluates an expression,
Java Methods Stacks and Queues A & AB Object-Oriented Programming
Iteration.
Introduction to Java Programming
Building Java Programs
slides created by Alyssa Harding
slides created by Marty Stepp
Queues.
Generics, Stack, Queue Based on slides by Alyssa Harding
Random Numbers while loop
More on iterations using
Computer Science Club 1st November 2019.
Presentation transcript:

queues21 Queues II: Applications

queues22 Palindrome recognition Palindrome: collection of characters that reads the same backwards and forwards Examples: –“otto” is a palindrome –“34543” is a palindrome –“snub no man; nice cinnamon buns!” is a palindrome, if you ignore spaces and punctuation

queues23 Palindrome recognition program Read string, storing each character in both a stack and a queue Once string is read, pop stack and dequeue queue, comparing characters if all characters have matched when both structures are empty, you’ve got a palindrome

queues24 Palindrome recognition program import java.util.LinkedList; // implements Queue interface import java.util.Queue; import java.util.Stack; import java.util.Scanner; public class Palindrome {

queues25 Palindrome recognition program public static void main(String[ ] args) { Scanner stdin = new Scanner(System.in); String line; do { System.out.print("Your expression (or return to end): "); line = stdin.nextLine( ); if (is_palindrome(line)) System.out.println("That is a palindrome."); else System.out.println("That is not a palindrome."); } while (line.length( ) != 0); }

queues26 Palindrome recognition program public static boolean is_palindrome(String input) { Queue q = new LinkedList ( ); Stack s = new Stack ( ); Character letter; int mismatches = 0; int i; for (i = 0; i < input.length( ); i++) { letter = input.charAt(i); if (Character.isLetter(letter)) { q.add(letter); s.push(letter); } }

queues27 Palindrome recognition program while (!q.isEmpty( )) { if (q.remove( ) != s.pop( )) return false; } return true; } // end of method } // end of class

Simulations – a brief intro The code on the next couple of slides gives a very simple example of a class that simulates a real-world situation In this case, the situation is simple one: simulate the action of a traffic light It would be a lot more interesting if it was graphical, but then you would stay awake, and who needs that? queues28

TrafficLight simulator Inputs: –amount of time light should be green or red –total time to simulate Outputs: current state of light queues29

TrafficLight simulator queues210 public class TrafficLight { private int redSpan; // Seconds that the light stays red private int greenSpan; // Seconds that the light stays green private boolean nowRed;// True if the light is now red private int secondsUntilChange; // Seconds until the next color change // member variables represent amount of time light stays green or // red, current color of light, and time left in current color // constructor sets values for red & green time, starts red light timer

TrafficLight simulator - constructor queues211 public TrafficLight(int r, int g) { if (r <= 0) throw new IllegalArgumentException("r <= 0: " + r); if (g <= 0) throw new IllegalArgumentException("g <= 0: " + g); redSpan = r; greenSpan = g; nowRed = true; secondsUntilChange = r; }

TrafficLight simulator – accessor methods queues212 public boolean isRed( ) { return nowRed; } public boolean isGreen( ) { return !nowRed; }

TrafficLight simulator – simulation method queues213 public void simulateTime(int t) { while (t >= secondsUntilChange) { t -= secondsUntilChange; nowRed = !nowRed; secondsUntilChange = nowRed ? redSpan : greenSpan; } secondsUntilChange -= t; }

TrafficLight simulator – test driver queues214 public static void main (String [] args) { Scanner kb = new Scanner(System.in); int simTime, r, g; System.out.print("Enter length of simulation (in seconds): "); simTime = kb.nextInt(); System.out.print("Enter number of seconds light stays red: "); r = kb.nextInt(); System.out.print("Enter number of seconds light stays green: "); g = kb.nextInt();

TrafficLight simulator – test driver continued queues215 TrafficLight tl = new TrafficLight(r,g); for (int x = 0; x < simTime; x++) { tl.simulateTime(x); if (tl.isGreen()) System.out.println("Green"); else System.out.println("Red"); } }

queues216 Using queues for simulation Many real-world situations can be simulated by employing a queue or queues to represent clients waiting for service “Clients” might be cars at a traffic light, customers at a grocery store, jobs awaiting CPU time in a computer, etc. Clients are represented by number indicating time of entry into the queue

queues217 Queue simulation program Inputs: –amount of time needed to serve one client –probability of customer arriving at any given time –length of simulation Outputs: –number of clients served during simulation –average time spent waiting in line

queues218 Queue simulation program: required data structures Queue of clients -- represented by time stamp (second when user entered queue) Server -- an object that simulates the service to be performed -- includes: –start( ) method –reduceRemainingTime( ) method –isBusy( ) method –variables secondsForService, timeLeft –constructor that establishes variable values

queues219 Queue simulation program: required data structures ClientGenerator: reports whether or not a client has arrived in a given second, using probability input to determine odds of arrival Averager: tracks total number of customers served and average time spent waiting in queue

queues220 Simulation: main method import java.util.*; public class CarWash { public static void main(String[ ] args) { final int WASHTIME = 240; final double ARRIVALPROB = ; final int TOTALTIME = 6000; carWashSimulate(WASHTIME, ARRIVALPROB, TOTALTIME); }

queues221 Simulation: carWashSimulate() public static void carWashSimulate (int washTime, double arrivalProb, int totalTime) { Queue arrivalTimes = new LinkedList ( ); int next; ClientGenerator arrival = new ClientGenerator(arrivalProb); Server machine = new Server(washTime); Averager waitTimes = new Averager( ); int currentSecond; System.out.println("Seconds to wash one car: " + washTime); System.out.print("Probability of customer arrival during a second: "); System.out.println(arrivalProb); System.out.println("Total simulation seconds: " + totalTime);

queues222 carWashSimulate continued if (washTime 1 || totalTime < 0) throw new IllegalArgumentException("Values out of range"); for (currentSecond = 0; currentSecond < totalTime; currentSecond++) { if (arrival.query( )) arrivalTimes.add(currentSecond); if ((!machine.isBusy( )) && (!arrivalTimes.isEmpty( ))) { next = arrivalTimes.remove( ); waitTimes.addNumber(currentSecond - next); machine.start( ); } // end if

queues223 carWashSimulate continued // Subtract one second from the time in the current wash cycle. machine.reduceRemainingTime( ); } // end of for loop // Write the summary information about the simulation. System.out.println("Customers served: " + waitTimes.howManyNumbers( )); if (waitTimes.howManyNumbers( ) > 0) System.out.println("Average wait: " + waitTimes.average( ) + " sec"); } // end method } // end class

queues224 Server class public class Server { private int secondsForService; private int timeLeft; public Server(int s) { secondsForService = s; timeLeft =0; }

queues225 Server class public boolean isBusy( ) { return (timeLeft > 0); } public void reduceRemainingTime( ) { if (timeLeft > 0) timeLeft--; }

queues226 Server Class public void start( ) { if (timeLeft > 0) throw new IllegalStateException ("Server is already busy."); timeLeft = secondsForService; } } // end class

queues227 ClientGenerator class public class ClientGenerator { private double probability; public ClientGenerator(double p) { if ((p < 0) || (1 < p)) throw new IllegalArgumentException ("Illegal p: " + p); probability = p; }

queues228 ClientGenerator class public boolean query( ) { return (Math.random( ) < probability); } } // end class

queues229 Averager class public class Averager { private int count; private double sum; public Averager( ) { count =0; sum = 0; }

queues230 Averager class public void addNumber(double value) { if (count == Integer.MAX_VALUE) throw new IllegalStateException ("Too many numbers"); count++; sum += value; }

queues231 Averager class public double average( ) { if (count == 0) return Double.NaN; else return sum/count; } public int howManyNumbers( ) { return count; } } // end class