Class Examples (Simple, Airplane, Queue, Pile) Copy vs. Clone.

Slides:



Advertisements
Similar presentations
Traversing a Binary Tree Binary Search Tree Insertion Deleting from a Binary Search Tree.
Advertisements

Linked List: Traversal Insertion Deletion. Linked List Traversal LB.
Stacks, Queues, and Linked Lists
DATA STRUCTURES USING C++ Chapter 5
Linked List 1. Introduction to Linked List 2. Node Class 3. Linked List 4. The Bag Class with Linked List.
Stack & Queues COP 3502.
Ceng-112 Data Structures I Chapter 5 Queues.
Data Structures Lecture 13: QUEUES Azhar Maqsood NUST Institute of Information Technology (NIIT)
ADT Queue 1. What is a Queue? 2. STL Queue 3. Array Implementation of Queue 4. Linked List Implementation of Queue 5. Priority Queue.
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.”
Queue Overview Queue ADT Basic operations of queue
1 CSC 211 Data Structures Lecture 22 Dr. Iftikhar Azim Niaz 1.
Linked Lists Compiled by Dr. Mohammad Alhawarat CHAPTER 04.
Linked List Improvements & Memory. BigO's What is BigO for our basic linked list operations? InsertStart Insert at middle InsertEnd Retrieve First Value.
Stacks, Queues & Deques CSC212.
Queues CS-240 & CS-341 Dick Steflik. Queues First In, First Out operation - FIFO As items are added they are chronologically ordered, items are removed.
Queues CS-240 & CS-341 Dick Steflik. Queues First In, First Out operation - FIFO As items are added they are chronologically ordered, items are removed.
Searching via Traversals Searching a Binary Search Tree (BST) Binary Search on a Sorted Array Data Structure Conversion and Helper Modules.
Buzzback Inheritance Class Hierarchies Deferred Classes.
Generic Classes Use Cases Inheritance. Generic Classes.
Data Structures - Queues
Objectives of these slides:
Lists ADT (brief intro):  Abstract Data Type  A DESCRIPTION of a data type  The data type can be anything: lists, sets, trees, stacks, etc.  What.
Announcements NP-Complete Problems Decidable vs. Undecidable Problems Review.
Searching Given a collection and an element (key) to find… Output –Print a message (“Found”, “Not Found) –Return a value (position of key ) Don’t modify.
1 Chapter 7 Stacks and Queues. 2 Stack ADT Recall that ADT is abstract data type, a set of data and a set of operations that act upon the data. In a stack,
Data Structures (part 2). Stacks An Everyday Example Your boss keeps bringing you important items to deal with and keeps saying: “Put that last ‘rush’
Announcements Review problems Review Outline. Online Survey
Introduction to Classes and Objects Initializing Objects Making Use of Classes in Algorithms Class Examples.
1 Linked-list, stack and queue. 2 Outline Abstract Data Type (ADT)‏ Linked list Stack Queue.
Data Structures Stacks and Queues Phil Tayco Slide version 1.0 Feb. 16, 2015.
Review Records Dynamic Memory and Pointers Introduction to Linked Lists.
Introduction to Classes and Objects. Real Life When a design engineer needs an electrical motor he doesn’t need to worry about –How a foundry will cast.
Computer Science Department Data Structures and Algorithms Queues Lecture 5.
Review Problems. What is the Big O? i
Graphs Arrays Iteration Combining Data Structures.
Stacks Queues Introduction to Trees. Stacks An Everyday Example Your boss keeps bringing you important items to deal with and keeps saying: “Put that.
Chapter 17: Linked Lists. Objectives In this chapter, you will: – Learn about linked lists – Learn the basic properties of linked lists – Explore insertion.
Lecture 21 Data Structures, Algorithms and Complexity Stacks and Queues GRIFFITH COLLEGE DUBLIN.
Review Linked List Insertion Description Deletion Description Basic Node Implementation Conclusion 1.
 2015, Marcus Biel, Linked List Data Structure Marcus Biel, Software Craftsman
Arrays, Link Lists, and Recursion Chapter 3. Sorting Arrays: Insertion Sort Insertion Sort: Insertion sort is an elementary sorting algorithm that sorts.
Chapter 3 Lists, Stacks, Queues. Abstract Data Types A set of items – Just items, not data types, nothing related to programming code A set of operations.
Chapter 16: Linked Lists.
Review Array Array Elements Accessing array elements
Queues Chapter 4.
Stacks and Queues Chapter 4.
CC 215 Data Structures Queue ADT
CSCI-255 LinkedList.
CS 1114: Implementing Search
Lecture 14 Traversals of Linked Lists Preorder BST Traversal Postorder BST Traversal Miscellaneous BST Traversals Depth First vs Breadth First Array Traversals.
Queue data structure.
Stacks and Queues.
Queues Queues Queues.
Stack and Queue APURBO DATTA.
Queues Chapter 4.
Simple Dynamic Data (Linked Lists)
Prof. Neary Adapted from slides by Dr. Katherine Gibson
Queues.
Popping Items Off a Stack Lesson xx
Initializing Objects.
Queues: Implemented using Arrays
ADT list.
Stacks: Implemented using Linked Lists
Sorted Linked List A linked list is a data structure that consists of a sequence of data records such that in each record there is a field that contains.
Queues CSC212.
Mutators for compound data Stack Queue
Circular Queues: Implemented using Arrays
Queues: Implemented using Linked Lists
CSCS-200 Data Structure and Algorithms
Presentation transcript:

Class Examples (Simple, Airplane, Queue, Pile) Copy vs. Clone

Class Examples Simple, Airplane, Queue, Pile

World’s Simplest Class! class Simple public Procedure setValue(dataIn isoftype in Number) // Precon: Initialization // Purpose: Sets value to dataIn // Postcon: Value is changed Function getValue returnsa Num() // Precon: Initialization // Purpose: Returns value to user // Postcon: No changes to object Procedure Initialize() // Precon: Object exists // Purpose: Initialization // Postcon: Value is defined to be zero LB

(continued) protected value isoftype Num Procedure setValue(dataIn isoftype in Number) value <- dataIn endprocedure // setValue Function getValue returnsa Num() getValue returns value endfunction // getValue Procedure Initialize() value <- 0 endprocedure // Initialize endclass // Simple LB

Once Written, It’s Easy! Once we’ve written the class… We test it and validate that it works We can then make use of it in any algorithm Notice in the following algorithm examples how little work is done –All manipulation is hidden from the algorithm –All the “details” are abstracted into the object

Airplane Example An Airplane knows how to: Take off Land Fly to a destination (and serve a snack) Change its altitude It also has the following attributes Current altitude Whether it’s flying or not

Airplane Symbolic Diagram Airplane Initialize TakeOff ChangeAltitude InTheAir Altitude IsFlying ServeSnack Land Fly

class Airplane public procedure TakeOff // comments here procedure Land // comments here procedure ChangeAltitude (NewHeight iot in Num) // comments here function IsFying returnsa boolean // comments here procedure Initialize // comments here procedure Fly (destination iot in String) // comments here protected // create the persistent data InTheAir isoftype Boolean Altitude isoftype Num

// still in the protected section procedure Initialize InTheAir <- FALSE Altitude <- 0 endprocedure // Initialize procedure TakeOff if InTheAir then print("I'm in the air!") else InTheAir <- TRUE ChangeAltitude(3000) endif endprocedure // TakeOff

// still in the protected section procedure ChangeAltitude (NewHeight iot in Num) Altitude <- NewHeight endprocedure // ChangeAltitude procedure Fly (destination iot in String) print(“I’m flying to”, destination) ServeSnack endprocedure // Fly procedure ServeSnack // comments here MAKE PASSENGERS HAPPY endprocedure // ServeSnack

// still in the protected section function IsFlying returnsa boolean IsFlying returns InTheAir endfunction // IsFlying procedure Land if InTheAir then InTheAir <- FALSE ChangeAltitude(0) else print("I'm not in the air!") endif endprocedure // Land endclass // Airplane

Using the Airplane Class algorithm Airport uses Airplane Cessna1090 isoftype Airplane Cessna1090.Initialize Cessna1090.Takeoff Cessna1090.ChangeAltitude(30000) Cessna1090.Fly(“Baltimore”) Cessna1090.Land endalgorithm

The Queue A collection with restricted set of operations to change its state: only modified by adding to one end and deleting from the other. Enqueue Dequeue

NumberQueue Symbolic Diagram NumberQueue Initialize Enqueue Dequeue head tail IsEmpty … IsFull

class NumberQueue public procedure Enqueue(value iot in Num) // contract information here procedure Dequeue(value iot out Num) // contract - queue not empty procedure Initialize // contract information here function IsEmpty returnsa Boolean // contract information here function IsFull returnsa Boolean // contract information here protected List_type definesa record data isoftype Num next isoftype Ptr toa List_type endrecord // create the persistent data head, tail isoftype Ptr toa List_type

// still in the protected section procedure Enqueue(value iot in Num) temp isoftype Ptr toa List_type temp <- new(List_type) temp^.data <- value temp^.next <- NIL if(IsEmpty) then head <- temp else tail^.next <- temp endif tail <- temp endprocedure // Enqueue

// still in the protected section procedure Dequeue (value iot out Num) if(IsEmpty) then // violates contract! Error! else value <- head^.data head <- head^.next if(IsEmpty) then tail <- NIL endif endprocedure // Dequeue

// still in the protected section function IsEmpty returnsa Boolean IsEmpty returns (head = NIL) endfunction // IsEmpty function IsFull returnsa Boolean IsFull returns FALSE // dynamic endfunction // IsFull procedure Initialize // initialize the persistent data head <- NIL tail <- NIL endprocedure // Initialize endclass // NumberQueue

algorithm Store uses NumberQueue temp isoftype num checkout isoftype NumberQueue checkout.Initialize... loop some people enter and leave store randomly exitif ((no people in store) AND (closing_time)) if (someone walks up for service) then checkout.Enqueue(person’s number) endif if (NOT checkout.IsEmpty) then checkout.Dequeue(temp) print(“Now servicing person”, temp) endif endloop endalgorithm // Store

Example: Simulating the Lotto We want to define a class that will allow us to simulate the lottery. We want to place elements into random locations in the collection. When we get an item from the collection, we want a random element.

A “Pile” Class A data structure in which –Items are inserted somewhere randomly in the middle of the structure –Items are removed from a random location in the structure

Pile Symbolic Diagram NumPile Initialize StickOn DigOut Head num_of_things IsEmpty Random …

class NumPile public procedure StickOn (the_thing iot in Num) //purpose: put an item on the pile. //pre: none //post: the pile has the item added to it procedure DigOut (the_thing iot out Num) //purpose: get an item off of the pile. //pre: the pile is not empty. // post: the pile has a random element // removed. function IsEmpty returnsa boolean // comments here - contract procedure Initialize // comments here - contract

protected PileNode definesa Record thing isoftype Num next isoftype ptr to PileNode endrecord // PileNode head isoftype ptr toa PileNode num_of_things isoftype Num procedure Initialize num_of_things <- 0 head <- NIL endprocedure // Initialize function IsEmpty returnsa boolean IsEmpty returns (head = NIL) endfunction // IsEmpty

// still in the protected section function Random returnsa Num // returns a random number <= // num_of_things endfunction // Random procedure StickOn (thing isoftype in Num) place_to_insert isoftype Num place_to_insert <- Random new_node isoftype ptr toa PileNode new_node <- new(PileNode) // loop through pile until place-to- // insert is reached, then insert node num_of_things <- num_of_things + 1 endprocedure // StickOn

// still in the protected section procedure DigOut (thing isoftype out Num) thing_to_snag isoftype Num place_to_get isoftype Num place_to_get <- Random // code for looping through pile to // find right thing-to-snag, then // remove it num_of_things <- num_of_things - 1 thing <- thing_to_snag endprocedure // Dig-Out endclass // NumPile

Using the Pile Class algorithm Lotto uses NumPile lotto_pile isoftype NumPile lotto_pile.Initialize ticket isoftype Num loop exitif (All Entries Purchased) Get_Entry(ticket) // get input from user lotto_pile.StickOn(ticket) endloop // Now, find one winner lotto_pile.DigOut(ticket) print ("The winning number is", ticket) endalgorithm // Lotto

Summary Writing classes involves considerable work in –Design, Implementation, & Testing But once done, algorithms may make use of the classes –Instantiating objects and manipulating them –Hiding the details and implementation –Much of the work is done inside the object

Questions?

Copy vs. Clone

The Scenario Imagine we have an object of type Queue We’d like to duplicate the contents of the object The assignment operator ( <- ) duplicates variables How do we duplicate objects?

Representing Objects Objects may have static and dynamic components. q_headq_tail 1113 \\ 9 MyNumQueue

Shallow vs. Deep Duplication Copy performs a shallow duplication – duplicating only the static data. Cloning performs a deep duplication – duplicating the static and dynamic data (i.e. following pointers into the heap and duplicating the heap data)

Create Two Objects MyNumQueue isoftype Queue(Num) YourNumQueue isoftype Queue(Num) // do some work to fill in MyNumQueue q_headq_tail MyNumQueue q_headq_tail \\ YourNumQueue \\ 1113 \\ 9

Copying an Object YourNumQueue <- copy(MyNumQueue) q_headq_tail MyNumQueue q_headq_tail YourNumQueue 1113 \\ 9

Risk of Copying an Object YourNumQueue.Enqueue(42) q_headq_tail \\ MyNumQueue q_headq_tail YourNumQueue

Risk of Copying an Object MyNumQueue.Enqueue(31) q_headq_tail \\ MyNumQueue q_headq_tail YourNumQueue 42 \\

Create Two Objects MyNumQueue isoftype Queue(Num) YourNumQueue isoftype Queue(Num) // do some work to fill in MyNumQueue q_headq_tail MyNumQueue q_headq_tail \\ YourNumQueue \\ 1113 \\ 9

Cloning an Object YourNumQueue <- clone(MyNumQueue) - or – YourNumQueue <- MyNumQueue q_headq_tail 1113 \\ 9 MyNumQueue q_headq_tail YourNumQueue 1113 \\ 9

Summary Duplication of objects: –Shallow: only duplicate static memory –Deep: duplicate static and dynamic memory Copy is shallow duplication Clone is deep duplication Assignment operation on objects is clone

Questions