Iterators CS101 2012.1. Chakrabarti What is an iterator?  Thus far, the only data structure over which we have iterated was the array for (int ix = 0;

Slides:



Advertisements
Similar presentations
Arrays.
Advertisements

Introduction to arrays
Chapter 6 Lists and Dictionaries CSC1310 Fall 2009.
Quick Sort, Shell Sort, Counting Sort, Radix Sort AND Bucket Sort
Computer Science 1620 Loops.
Computer Science 1620 Multi-Dimensional Arrays. we used arrays to store a set of data of the same type e.g. store the assignment grades for a particular.
©2004 Brooks/Cole Chapter 8 Arrays. Figures ©2004 Brooks/Cole CS 119: Intro to JavaFall 2005 Sometimes we have lists of data values that all need to be.
Loops – While, Do, For Repetition Statements Introduction to Arrays
 2003 Prentice Hall, Inc. All rights reserved. 1 Arrays –Structures of related data items –Static entity (same size throughout program) A few types –Pointer-based.
1 CS150 Introduction to Computer Science 1 Relational Operators and the If Statement 9/22/08.
Chapter 8 Arrays and Strings
1 Lab Session-III CSIT-120 Spring 2001 Revising Previous session Data input and output While loop Exercise Limits and Bounds GOTO SLIDE 13 Lab session.
Basic Elements of C++ Chapter 2.
CS0007: Introduction to Computer Programming Introduction to Arrays.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 5: Control Structures II (Repetition)
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 10. Pointers & Dynamic Data Structures.
1 Lab Session-III CSIT-120 Fall 2000 Revising Previous session Data input and output While loop Exercise Limits and Bounds Session III-B (starts on slide.
Memory Management CS Chakrabarti Variable storage thus far  Never used global variables  All variables allocated inside functions, passed.
Chapter 5: Control Structures II (Repetition)
CHAPTER 5: CONTROL STRUCTURES II INSTRUCTOR: MOHAMMAD MOJADDAM.
EGR 2261 Unit 5 Control Structures II: Repetition  Read Malik, Chapter 5.  Homework #5 and Lab #5 due next week.  Quiz next week.
Handling Lists F. Duveau 16/12/11 Chapter 9.2. Objectives of the session: Tools: Everything will be done with the Python interpreter in the Terminal Learning.
Project 1 Due Date: September 25 th Quiz 4 is due September 28 th Quiz 5 is due October2th 1.
Decision II. CSCE 1062 Outline  Boolean expressions  switch statement (section 4.8)
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
Contents of Chapter 7 Chapter 7 Backtracking 7.1 The General method
Targil 6 Notes This week: –Linear time Sort – continue: Radix Sort Some Cormen Questions –Sparse Matrix representation & usage. Bucket sort Counting sort.
C++ Programming: From Problem Analysis to Program Design, Fifth Edition Arrays.
Sudoku Jordi Cortadella Department of Computer Science.
Vectors and Grids Eric Roberts CS 106B April 8, 2009.
Built-in Data Structures in Python An Introduction.
Chapter 5 Control Structure (Repetition). Objectives In this chapter, you will: Learn about repetition (looping) control structures Explore how to construct.
Chapter 5: Control Structures II (Repetition). Objectives In this chapter, you will: – Learn about repetition (looping) control structures – Learn how.
Lecture 4 Looping. Building on the foundation Now that we know a little about  cout  cin  math operators  boolean operators  making decisions using.
CS Midterm Study Guide Fall General topics Definitions and rules Technical names of things Syntax of C++ constructs Meaning of C++ constructs.
Data TypestMyn1 Data Types The type of a variable is not set by the programmer; rather, it is decided at runtime by PHP depending on the context in which.
Chapter 7 Selection Dept of Computer Engineering Khon Kaen University.
+ Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy Walters, and Godfrey Muganda Chapter 5: Looping.
Data Structures & Algorithms
CSE 232: C++ memory management Overview of Arrays Arrays are the simplest kind of data structure –One item right after another in memory (“contiguous range”
POINTERS.
Algorithms Java Methods A & AB Object-Oriented Programming and Data Structures Maria Litvin ● Gary Litvin Copyright © 2006 by Maria Litvin, Gary Litvin,
Chapter 8: Arrays Copyright © 2008 W. W. Norton & Company. All rights reserved. 1 Chapter 8 Arrays.
1 One Dimensional Arrays Chapter 11 2 "All students to receive arrays!" reports Dr. Austin. Declaring arrays scores :
Arrays Dr. Jose Annunziato. Arrays Up to this point we have been working with individual primitive data types Arrays allow working with multiple instances.
Pointers It provides a way of accessing a variable without referring to its name. The mechanism used for this is the address of the variable.
EGR 115 Introduction to Computing for Engineers MATLAB Basics 1: Variables & Arrays Wednesday 03 Sept 2014 EGR 115 Introduction to Computing for Engineers.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 5: Control Structures II (Repetition)
CS 31 Discussion, Week 5 Faisal Alquaddoomi, Office Hours: BH 2432, MW 4:30-6:30pm, F 12:00-1:00pm (today)
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 5: Control Structures II (Repetition)
Arrays Chapter 12. Overview Arrays and their properties Creating arrays Accessing array elements Modifying array elements Loops and arrays.
CSE 332: C++ STL iterators What is an Iterator? An iterator must be able to do 2 main things –Point to the start of a range of elements (in a container)
Visual C# 2005 Using Arrays. Visual C# Objectives Declare an array and assign values to array elements Initialize an array Use subscripts to access.
Arrays Declaring arrays Passing arrays to functions Searching arrays with linear search Sorting arrays with insertion sort Multidimensional arrays Programming.
CS162 - Topic #12 Lecture: –Arrays with Structured Elements defining and using arrays of arrays remember pointer arithmetic Programming Project –Any questions?
CS Class 04 Topics  Selection statement – IF  Expressions  More practice writing simple C++ programs Announcements  Read pages for next.
Arrays. C++ Style Data Structures: Arrays(1) An ordered set (sequence) with a fixed number of elements, all of the same type, where the basic operation.
C++ Programming: From Problem Analysis to Program Design, Fifth Edition Chapter 5: Control Structures II (Repetition)
Topic 4: Looping Statements
REPETITION CONTROL STRUCTURE
Chapter 5: Control Structures II (Repetition)
LOOPS.
Prof. Michael Neary Lecture 7: The STL Prof. Michael Neary
Arrays, For loop While loop Do while loop
Jordi Cortadella Department of Computer Science
Chapter 5: Control Structures II (Repetition)
Objectives You should be able to describe: The while Statement
Arrays Arrays A few types Structures of related data items
Presentation transcript:

Iterators CS

Chakrabarti What is an iterator?  Thus far, the only data structure over which we have iterated was the array for (int ix = 0; ix < arr.size(); ++ix) { … arr[ix] … // access as lhs or rhs }  In general there may not be such a simple notion of a single index; e.g., iterate over:  All dim  val map entries in sparse array  All permutations of n items  All non-attacking n-queen positions on an n by n chessboard

Chakrabarti Iterator as an abstraction  We initialize an iterator  Given any state of the iterator, we can ask if there is a next state or we have run out  If there is a next state, we can move the iterator from the current to the next state  We can fetch or modify data associated with the current state of the iterator

Chakrabarti Iterator on vector  Print all elements of a vector, using iterator vector vec; // suitably filled for (vector ::iterator vx = vec.begin(); vx != vec.end(); ++vx) { cout << (*vx) << endl; } Iterator type “++” overloaded to mean “advance the iterator” Access the current contents of the iterator

Chakrabarti Iterator lineage categorycharacteristicvalid expressions all categories Can be copied and copy-constructedX b(a); b = a; Can be incremented++a, a++, *a++ Random Access Bidirectional Forward Input Accepts equality/inequality comparisonsa == b, a != b Can be dereferenced as an rvalue*a, a->m Output Can be dereferenced to be the left side of an assignment operation *a = t, *a++ = t Can be default-constructedX a;, X() Can be decremented--a, a-- *a-- Supports arithmetic operators + and - a + n, n + a, a – n, a – b Supports inequality comparisons (, =) between iterators a b a = b Supports compound assignment operations += and -=a += n, a -= n Supports offset dereference operator ([])a[n] We will see other kinds of iterators after we study C++ collection types beyond vector

Chakrabarti Counting in any radix  Print all numbers in a given radix up to a given number of “digits”  E.g. nDigits = 2, radix = 3 gives 00, 01, 02, 10,11, 12, 20, 21, 22  (Note radix could be arbitrarily large) for dig n-1 = 0 to radix-1 for dig n-2 = 0 to radix-1 … for dig 0 = 0 to radix-1 print dig n-1, dig n-2, …, dig 1, dig 0 Don’t know how to do this for input variable nDigits

Chakrabarti Counting  Instead of writing nested loops…  Stick the loop indices into vector dig  Given any state of dig, to get the next state:  Locate least significant digit that can be incremented (i.e., is less than radix  1)  Increment this digit  Reset to zero all less significant digits

Chakrabarti Printing permutations without recursion  Given input n, print all n! permutations of n items (say characters a, b, …)  0 th item placed in 1 way, “way #0”  1 th item placed in 2 ways, “ways #0, #1” Left of first item or right of first item  Three gaps now, 2 th item in ways 0, 1, 2  … and so on to the (n-1) th item  Suppose we had integer variables way 0, way 1, …, way n-1

Chakrabarti Permutation example way 0 way 1 way 2 cba bcabaccabacbabc abba a

Chakrabarti Nested for loops for way 0 = 0 (up to 0) { for way 1 = 0 to 1 { for way 2 = 0 to 2 { … for way n-1 = 0 to n-1 { convert way 0, …, way n-1 into permutation } … } Unfortunately, we cannot read n as an input parameter and implement a variable number of nested for loops

Chakrabarti Variable number of nested loops?  Vector of wayi variables has n! possible tuple values  Is in 1-1 correspondence with the permutations of n items  Design two functions …  Given vector way that satisfies above properties, arrange way.size() items according to that correspondence  From one way find the next way (the iteration)

Chakrabarti bool nextPerm(vector & way) bool didChange = false; for (int ch=0; ch < way.size(); ++ch) { if (way[ch] < ch) { ++way[ch]; didChange = true; for (int zx = 0; zx < ch; ++zx) { way[zx] = 0; } break; } return didChange; nextPerm is an iterator --- it modifies way to the next permutation if any, returning true if it succeeded

Chakrabarti printPerm(vector way) vector arrange(way.size(), 0);//empty for (int px=way.size()-1; px >= 0; --px) { // skip way[px] empty slots in arrange int wx = 0; for (int sx = way[px]; ; --sx) { while (arrange[wx] != 0) { ++wx; } if (sx == 0) { break; } ++wx; } arrange[wx] = 'a' + px; } print(arrange);

Chakrabarti Semi-magic square  A semi-magic square contains non-negative integers  Each row and column adds up to the same positive integer c  A permutation matrix is a semi-magic square having c=1  Can always subtract a permutation matrix from a semi-magic square (but not greedily)  In time proportional to the number of nonzero elements in the square  Here we look at a brute force solution using iterators

Chakrabarti Iterator state  For each row, keep a (sparse) vector containing column indices with nonzero elements  vector  > nzCols;  For row rx, there are nzCols[rx].size() possible column options  Declare vector colsTaken, where colsTaken[rx] can range between 0 and nzCols[rx].size()-1

Chakrabarti Nested loop way of thinking for colsTaken[0] = 0 … nzCols[0].size()-1 { for colsTaken[1] = 0 … nzCols[1].size()-1 { … … … for colsTaken[n-1] = 0 … nzCols[n-1].size()-1 { check if colsTaken[0…n-1] define a permutation matrix if so { subtract from magic; update nzCols; return } } // end of colsTaken[n-1] loop … … … } // end of colsTaken[1] loop } // end of colsTaken[0] loop Can easily turn into iterator style

Chakrabarti Other applications Maze with walls  Starting point and destination  For every decision point, declare a “loop variable”, keep in vector  Earliest decision = lowest index of loop variable Game trees  Different possible moves = branch out  Represent with “loop variable”