תרגול 12: Iterator מחסנית תור 1. מחסנית (stack) מחסנית (stack) היא מבנה נתונים שמזכיר מחסנית של רובה : האיבר שנכנס ראשון למחסנית יוצא ממנה אחרון (LIFO.

Slides:



Advertisements
Similar presentations
תוכנה 1 סמסטר א ' תשע " ב תרגול מס ' 7 * מנשקים, דיאגרמות וביטים * לא בהכרח בסדר הזה.
Advertisements

Chapter 6 The Collections API. Simple Container/ Iterator Simple Container Shape [] v = new Shape[10]; Simple Iterator For( int i=0 ; i< v.length ; i++)
בתרגול הקודם הורשה: –ניתן להרחיב רק מחלקה אחת –כל מה שלא private – עובר בהורשה –המילה השמורה super –יצירת היררכיה –Object היא שורש ההיררכיה –דריסה אופרטור.
1 Formal Specifications for Complex Systems (236368) Tutorial #4 Refinement in Z: data refinement; operations refinement; their combinations.
Stacks, Queues, and Deques. 2 A stack is a last in, first out (LIFO) data structure Items are removed from a stack in the reverse order from the way they.
Elementary Data Structures CS 110: Data Structures and Algorithms First Semester,
Chapter 5 Queues Modified. Chapter Scope Queue processing Comparing queue implementations 5 - 2Java Software Structures, 4th Edition, Lewis/Chase.
1 תוכנה 1 תרגול 14 – סיכום. 2 קצת על מנשקים מנשק יכול להרחיב יותר ממנשק אחד שירותים במנשק הם תמיד מופשטים וציבוריים public interface MyInterface { public.
COMP 103 Linked Stack and Linked Queue.
טבלאות סמלים נכתב ע"י אלכס קוגן סמסטר חורף, תשס"ח.
תכנות מונחה עצמים Object Oriented Programming (OOP) אתגר מחזור ב'
מתמטיקה בדידה תרגול 3.
Stacks. What is a stack? Last-in first-out data structure (LIFO) New objects are placed on top Removal restricted to top object Examples?
חורף - תשס " ג DBMS, צורות נורמליות 1 צורה נורמלית שלישית - 3NF הגדרה : תהי R סכמה רלציונית ותהי F קבוצת תלויות פונקציונליות מעל R. R היא ב -3NF.
Unit 11 1 Unit 11: Data Structures H We explore some simple techniques for organizing and managing information H This unit focuses on: Abstract Data Types.
1 Formal Specifications for Complex Systems (236368) Tutorial #5 Refinement in Z: data refinement; operations refinement; their combinations.
1 CSCD 326 Data Structures I Stacks. 2 Data Type Stack Most basic property: last item in (most recently inserted) is first item out LIFO - last in first.
תכנות תרגול 6 שבוע : תרגיל שורש של מספר מחושב לפי הסדרה הבאה : root 0 = 1 root n = root n-1 + a / root n-1 2 כאשר האיבר ה n של הסדרה הוא קירוב.
1 Lecture 24 Abstract Data Types (ADT) –I Overview  What is an Abstract Data type?  What is Stack ADT?  Stack ADT Specifications  Array Implementation.
Stacks and Queues. Stack ADT סוג של מערך מוגבל מהר מאוד ולוקחים מעט זכרון שימוש ב LIFO – LIFO (Last In, First Out) lists. –אפשר להוסיף רק בסוף הרשימה.
עקרון ההכלה וההדחה.
מבוא למדעי המחשב תרגול 3 שעת קבלה : יום שני 11:00-12:00 דוא " ל :
תרגול 12: ומחסניתIteratorרשימה מקושרת, תור, 1. רשימה מקושרת (Linked List) רשימה מקושרת הינה קבוצה סדורה של אובייקטים, כאשר כל אובייקט ברשימה מכיל הצבעה.
1 Lecture 26 Abstract Data Types – IV Overview  The List ADT  Implementing Stacks as Linked List  Linked List Implementation of Queues .  Preview:
1 מבוא למדעי המחשב סיבוכיות. 2 סיבוכיות - מוטיבציה סידרת פיבונאצ'י: long fibonacci (int n) { if (n == 1 || n == 2) return 1; else return (fibonacci(n-1)
ומחסניתIteratorרשימה מקושרת, תור,
1 Stack Data : a collection of homogeneous elements arranged in a sequence. Only the first element may be accessed Main Operations: Push : insert an element.
Stacks, Queues, and Deques
CSE 143 Lecture 7 Stacks and Queues reading: "Appendix Q" (see course website) slides created by Marty Stepp and Hélène Martin
Ics202 Data Structures. U n i v e r s i t y o f H a i l 1. Stacks top push (8)push (2)
Jan 12, 2012 Introduction to Collections. 2 Collections A collection is a structured group of objects Java 1.2 introduced the Collections Framework Collections.
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’
LinkedList Many slides from Horstmann modified by Dr V.
CMSC 341 Linked Lists, Stacks and Queues. 8/3/2007 UMBC CMSC 341 LSQ 2 Implementing Your Own Linked List To create a doubly linked list as seen below.
1 Chapter 20 Lists, Stacks, Queues Lecture 7 Dr. Musab Zghoul برمجة هيكلية.
בתרגול הקודם כללי הרשאות (Visibility modifiers) בהורשה – Public – Protected – private חוקי גישה לשדות ושיטות בהורשה ב -Java מחלקות אבסטרקטיות –המילה השמורה.
1 מבוא למדעי המחשב הרצאה 21: Queue, Iterator & Iterable.
מחסנית ותור Stacks and Queues. מחסנית Stack מחסנית - Stack ADT סוג של מערך מוגבל מהיר מאוד ותופס מעט זיכרון שימוש ב LIFO – LIFO (Last In, First Out)
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.
1 המרכז להוראת המדעים © האוניברסיטה העברית בירושלים פולימורפיזם מתקדם ממשקים בג ' אווה 1.
CS 367 Introduction to Data Structures Lecture 5.
1 Stacks (Continued) and Queues Array Stack Implementation Linked Stack Implementation The java.util.Stack class Queue Abstract Data Type (ADT) Queue ADT.
מחסנית ותור Stacks and Queues. מחסנית Stack מחסנית - Stack ADT סוג של מערך מוגבל מהיר מאוד ותופס מעט זיכרון שימוש ב LIFO – LIFO (Last In, First Out)
1 נתבונן בפונקציה הבאה public static int min(int[] a,int n) { int min = a[0]; for (int i = 1; (i < n ) && (i < a.length) ; i++) if (min > a[i]) min = a[i];
Chapter 4 ADTs Stack and Queue. 4-2 Formal ADT Specifications The Java interface construct lets us collect together method interfaces into a syntactic.
M180: Data Structures & Algorithms in Java Stacks Arab Open University 1.
Iterators. Iterator  An iterator is any object that allows one to step through each element in a list (or, more generally, some collection).
Linked Data Structures
האוניברסיטה העברית בירושלים
Elementary Data Structures
QueueStack CS1020.
Formal Specifications for Complex Systems (236368) Tutorial #1
Stacks.
מחלקות classes.
מבוא למדעי המחשב סיבוכיות.
Static and enum קרן כליף.
Linked Lists, Stacks and Queues Textbook Sections
תכנות מכוון עצמים בשפת JAVA
ממשקים - interfaces איך לאפשר "הורשה מרובה".
Stacks and Queues.
הרצאה 21: Queue, Iterator & Iterable
בניית מחסנית סטטית Static Stack Implementation מורים מובילים תשע"ה
תכנות מכוון עצמים ושפת JAVA
מחסנית ותור Stacks and Queues.
פולימורפיזם מתקדם ממשקים בC# עריכה ועיצוב: קרן הרדי
More Data Structures (Part 1)
Lecture 16 Stacks and Queues CSE /26/2018.
Lecture 16 Stacks and Queues CSE /26/2018.
Stacks and Queues.
Presentation transcript:

תרגול 12: Iterator מחסנית תור 1

מחסנית (stack) מחסנית (stack) היא מבנה נתונים שמזכיר מחסנית של רובה : האיבר שנכנס ראשון למחסנית יוצא ממנה אחרון (LIFO - Last In First Out). ניתן לראות במחסנית קופסה סגורה בעלת פתח יחיד, שדרכו נעשות פעולות הדחיפה והשליפה. הטיפול דרך פתח יחיד יוצר מצב שבו איבר שנכנס אחרון יוצא ראשון - LIFO. מחסנית היא שימושית כאשר יש צורך לשמור נתונים בסדר מסוים ולשלוף אותם בסדר הפוך. 2

public interface Stack { /** * push - adds an element to the stack. o the elemented to be inserted to the stack. */ public void push (Object o); /** * pop - removes an element form the stack (LIFO order). the element from the top of the stack. */ public Object pop (); /** * isEmpty - checks if the stack is empty or not. true if there is no more elements in the stack. */ public boolean isEmpty(); } ממשק 3

מימוש מחסנית בעלת ע"י מערך import java.util.EmptyStackException; public class StackAsArray implements Stack { /* Defines the initial capacity of a stack */ private static final int INITIAL_CAPACITY = 5; /* Defines the capacity extension of a stack when it is full */ private static final int CAPACITY_EXTENSION = 5; protected Object[] elements; protected int size; /* Creates a new stack.*/ public StackAsArray() { elements = new Object[INITIAL_CAPACITY]; size = 0; } 4

מימוש מחסנית ע"י מערך public void push(Object o) { if (size >= elements.length) extend(); elements[size] = o; size = size + 1; } public Object pop() { if (size == 0) throw new EmptyStackException (); size = size - 1; return elements[size]; } public boolean isEmpty() { return size == 0; }

מימוש מחסנית ע"י מערך private void extend() { /* Create a new array with the new size */ Object[] tmpArray = new Object[elements.length + CAPACITY_EXTENSION]; /* Copy the old elements to the new array */ for ( int i = 0; i < elements.length; i=i+1) tmpArray[i] = elements[i]; /* Replace the elements array with the new one */ elements = tmpArray; }

Iterator 7

מידע ונתונים (data) הדרושים לתכנית מחשב נשמרים בתוך מבנה נתונים (data structure). על מבנה נתונים יש צורך לבצע מספר פעולות, כמו הכנסת נתונים והוצאת נתונים. אחת הדרכים להוציא נתונים היא לעבור על אוסף הנתונים פריט - מידע אחר פריט - מידע. האחריות על מבנה הנתונים היא של המתכנת שלו, ברצוננו להקל על המשתמש במבנה הנתונים ככל הניתן. 8

Iterator נרצה שתכונה זו תהיה משותפת למבני נתונים רבים, למשל לרשימה, שראינו זה עתה. לכן נגדיר ממשק, שאותו כל מבנה נתונים יממש. נרצה להגיד שמבנה נתונים הוא ניתן למעבר פריט - אחר - פריט, ובאנגלית : Iterable. ב -JAVA קיים הממשק : 9 public interface Iterable { /** * Returns an iterator over a set of elements. * an Iterator. */ Iterator iterator(); }

Iterator יהיה לנו אובייקט שיעזור בתהליך. אובייקט זה יעבור על אוסף הנתונים פריט אחר פריט, לפי סדר מסוים, ובאנגלית :Iterator. ב -JAVA מוגדר ממשק לעבודה עם אובייקט כזה : 10 public interface Iterator { boolean hasNext(); Object next(); void remove(); }

public interface Iterator { /** * Returns true if the iteration has more elements. true if the iterator has more elements. */ boolean hasNext(); /** * Returns the next element in the iteration. the next element in the iteration. NoSuchElementException iteration has no more elements. */ Object next(); /** * Removes from the underlying collection the last element returned by the * iterator (optional operation) UnsupportedOperationException if the "remove" * operation is not supported by this Iterator. * IllegalStateException if the "next" method has not * yet been called, or the "remove" method has already * been called after the last call to the "next" * method. */ void remove(); } 11

שימוש ב -Iterator בהמשך נראה כיצד להפוך את המחלקה StackAsArrayכך שתתמוך ב-Iterator, כרגע נניח שהמחלקה כבר תומכת בו, ועל סמך זאת נעשה שימוש ב-Iterator שמתקבל מהשיטה iterator(), שמובטחת לנו מכיוון ש- StackAsArray מממשת את Iterable. 12 public static void main(String[] args) { StackAsArray stack= new StackAsArray(); stack.push("Tasty"); stack.push(“Are"); stack.push("Shnitsels"); Iterator it = stack.iterator(); while (it.hasNext()) { Object currentData = it.next(); System.out.print(currentData); if (it.hasNext()) System.out.print(", "); } System.out.println(); }

מימוש ה -Iterator עבור StackAsArray public class StackAsArrayIterator implements Iterator { private int currentIndex; private Object[] Array; public ArrayIterator(int size, Object[] Array ) { currentIndex = size; this.Array = Array; } public boolean hasNext() { return (currentIndex != 0); } public Object next() { if (!hasNext()) { throw new NoSuchElementException(); } currentIndex = currentIndex -1; Object data = arry[currentIndex]; return data; } public void remove() { throw new UnsupportedOperationException(); } 13

עתה נראה כיצד נתמוך ב Iterator במחלקה LinkedList: 14 public interface Iterable { /** * Returns an iterator over a set of elements. * an Iterator. */ Iterator iterator(); } מימוש ה -Iterable במחלקה LinkedList

מימוש ה -Iterable במחלקה StackAsArray עכשיו כל מה שנותר לעשות הוא לממש את השיטה iterator() של הממשק Iterable ב StackAsArray : public class StackAsArray implements Iterable{ … protected Object[] elements; protected int size; /* Creates a new stack.*/ public StackAsArray() { elements = new Object[INITIAL_CAPACITY]; size = 0; } … public Iterator iterator(){ return new StackAsArrayIterator( elements,size ); }

הערות Iterator מניח שלא נעשה שינוי באוסף עליו הוא עובר במהלך המעבר. אם נעשה שינוי – האיטרטור איננו במצב חוקי ואין הבטחה לפעולה תקינה שלו. השיטה ()next מחוייבת לזרוק את החריגה NoSuchElementException במידה ואין יותר אלמנטים באוסף. ( אם לפני כל קריאה ל -next() נוודא ש hasNext() החזיר true אז לא נתקל בחריגה זו ). החריגה : UnsupportedOperationException נזרקת כאשר אנו מחוייבים להכריז שיטה מסויימת ( למשל כי היא חלק מממשק ) במחלקה שלנו, אך אנו לא תומכים בשיטה זו. לכן בגוף השיטה נזרוק את החריגה. 16

דוגמה נרצה לקלוט מהמשתמש מספר מחרוזות ורק כאשר הוא יסיים להקליד ( למשל ע " י זיהוי שורה ריקה ) נדפיס בחזרה את כל המחרוזות ההפך מסדר ההכנסה. 17

המשך import java.util.Scanner; … public static void main(String args[]) { Scanner sc = new Scanner(System.in); Queue s = new stackAsArray(); System.out.println("Insert few lines … "); while (sc.hasNextLine()) { String line = sc.nextLine(); s.push( line ); } System.out.println("Printing all the lines back! "); while (!s.isEmpty()) { System.out.println(s.pop()); } 18

השיטה copy מקבלת כארגומנט מחסנית s ומחזירה העתק של המחסנית s כאשר יש לשמור על סדר האיברים במחסנית המועתקת וב-s זהה. לא תמיד נצטרך לדעת כיצד מימשו את הממשק– העתק מחסנית public static Stack copy(Stack s) { } 19

השיטה copy מקבלת כארגומנט מחסנית s ומחזירה העתק של המחסנית s כאשר יש לשמור על סדר האיברים במחסנית המועתקת וב-s זהה. לא תמיד נצטרך לדעת כיצד מימשו את הממשק– העתק מחסנית public static Stack copy(Stack s) { Stack temp = new StackImpl(); Stack ans = new StackImpl(); while (!s.isEmpty()) { temp.push(s.pop()); } while (!temp.isEmpty()) { Object o = temp.pop(); ans.push(o); s.push(o); } return ans; } 20

תור - Queue תור (Queue) הוא מבנה נתונים המזכיר תור של בני אדם : האיבר שנכנס ראשון לתור - יוצא ממנו ראשון. ניתן לראות כקופסה סגורה בעלת 2 פתחים : פתח הכנסה ופתח יציאה. איבר שנכנס ראשון יוצא ראשון FIFO (FIFO - First In First Out). שימושים : ניהל תהליכים ע " י מערכת ההפעלה, ניהול תור בבית מרקחת,... 21

public interface Queue{ /** * isEmpty - checks if the queue is empty or not. true if the queue is empty */ public boolean isEmpty(); /** * dequeue - removes an object from the head of the queue. * (FIFO order) the next object in the queue. */ public Object dequeue(); /** * enqueue - inserts an object into the queue. o the object to be enqueued. */ public void enqueue(Object o); } 22

שיטה זו מקבלת תור כפרמטר והופכת את סדר האיברים בו. מוגדר לכם משתנה אחד מטיפוס.Object אין להגדיר משתנים נוספים בשיטה זו. דוגמה public static void reverse(Queue q) { Object o; } 23

שיטה זו מקבלת תור כפרמטר והופכת את סדר האיברים בו. מוגדר לכם משתנה אחד מטיפוס.Object אין להגדיר משתנים נוספים בשיטה זו. דוגמה public static void reverse(Queue q) { Object o; if(!q.isEmpty()){ o=q.deueue(); reverse(q); q.enqueue(o); } 24

תרגיל הוסיפו למחלקה StackAsArray המממשת את הממשק Iterable את השיטה filter לסינון איברים העונים על תנאי מתוך כלל איברי במחסנית. Stack filter(Filter f) התנאי ע " פ מסננים האיברים הוא Filter f. נגדיר ממשק Filter המכיל שיטה אחת והיא accept, המקבלת אובייקט ומחליטה האם הוא עובר את הסינון או לא. 25

public interface Filter { /** * accept – defines the filtration criterion. o the object to be examined. true if the object should not be * filtered out. */ public boolean accept(Object o); } אנו נממש Filter פשוט עבור המחלקה String, המשאיר רק את המחרוזות הלא ריקות: public class EmptyStringFilter implements Filter { public boolean accept(Object o) { boolean ans = false; if (o instanceof String) { String s = (String) o; ans = s.length() > 0; } return ans; } } 26

public stackAsArray filter(Filter filter) { stackAsArray filteredStack = new stackAsArray() ; Iterator it = this.iterator(); while (it.hasNext()) { Object data = it.next(); if(filter.accept(data)) { filteredStack.push(data) ; } return filteredStack; } כל שנותר הוא לממש את השיטת הסינון ב - StackAsArray : השיטה מקבלת כקלט מסנן, ומחזיר מחסנית חדשה שתכיל את כל אברי המחסנית הנוכחית שעברו את המסנן. 27