1 CSC 222: Computer Programming II Spring 2004 HW1 review arrays vs. vectors class design object-oriented design data objects + functionality example:

Slides:



Advertisements
Similar presentations
CS Data Structures I Chapter 6 Stacks I 2 Topics ADT Stack Stack Operations Using ADT Stack Line editor Bracket checking Special-Palindromes Implementation.
Advertisements

Chapter 7 Constructors and Other Tools. Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 7-2 Learning Objectives Constructors Definitions.
StructuresStructures Systems Programming. Systems Programming: Structures 2 Systems Programming: 2 StructuresStructures Structures Structures Typedef.
Victory in the Card Game ‘War’ and Initial Hand Strength
StructuresStructures Systems Programming. StructuresStructures Structures Structures Typedef Typedef Declarations Declarations Using Structures with Functions.
Chapter 4 Linked Lists. © 2005 Pearson Addison-Wesley. All rights reserved4-2 Preliminaries Options for implementing an ADT List –Array has a fixed size.
CSC211 Data Structures Lecture 9 Linked Lists Instructor: Prof. Xiaoyan Li Department of Computer Science Mount Holyoke College.
Alan YorinksLecture 7 1 • Tonight we will look at:: • List ADT • Unsorted List • Sequential Search • Selection Sort • Sorted List • Binary Search.
1 CSC 221: Introduction to Programming Fall 2011 List comprehensions & objects building strings & lists comprehensions conditional comprehensions example:
1 Linked Lists III Template Chapter 3. 2 Objectives You will be able to: Write a generic list class as a C++ template. Use the template in a test program.
The Stack Data Structure. Classic structure What is a Stack? An abstract data type in which accesses are made at only one end Last In First Out (LIFO)
CSE Lecture 12 – Linked Lists …
1 / / / /. 2 (Object) (Object) –, 10 (Class) (Class) –, –, – (Variables) [ Data member Field Attribute](, ) – (Function) [ Member function Method Operation.
Chapter 10 C Structures, Unions, Bit Manipulations and Enumerations Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc.
C9, a case study: Solitaire
Programming in C Chapter 10 Structures and Unions
Java Coding 8 David Davenport Computer Eng. Dept., Bilkent University Ankara - Turkey. Object-Oriented Design Example - The.
CS 206 Introduction to Computer Science II 09 / 05 / 2008 Instructor: Michael Eckmann.
© Glenn Rowe AC Lab 2 A simple card game (twenty- one)
1 CSC 221: Computer Programming I Fall 2006 interacting objects modular design: dot races constants, static fields cascading if-else, logical operators.
C++ Templates. What is a template? Templates are type-generic versions of functions and/or classes Template functions and template classes can be used.
Win32 Programming Lesson 4: Classes and Structures.
Lecture 5 Sept 15 Goals: stacks Implementation of stack applications Postfix expression evaluation Convert infix to postfix.
Design Example. Requirements Make a program that simulates the game of blackjack For now, we ignore money/betting…. just simulate game play But… this.
Lecture 7 Sept 16 Goals: stacks Implementation of stack applications Postfix expression evaluation Convert infix to postfix.
Lecture 6 Feb 12 Goals: stacks Implementation of stack applications Postfix expression evaluation Convert infix to postfix.
Arrays Hanly - Chapter 7 Friedman-Koffman - Chapter 9.
Java Coding 8 David Davenport Computer Eng. Dept., Bilkent University Ankara - Turkey. Object-Oriented Design Examples.
Chapter 5 Black Jack. Copyright © 2005 Pearson Addison-Wesley. All rights reserved. 5-2 Chapter Objectives Provide a case study example from problem statement.
AP Computer Science.  Not necessary but good programming practice in Java  When you override a super class method notation.
Lecture 5 of Computer Science II Arrays Instructor: Mr.Ahmed Al Astal.
o Simulate a deck of playing cards o Shuffle the deck o Deal (5) cards into the hand o Turn over the first card o The user must guess whether the next.
o Simulate a deck of playing cards o Shuffle the deck o Deal 5 cards into the hand o Turn over the first card o The user must guess whether the next card.
CS161 Topic #14 1 Today in CS161 Lecture #14 Practicing! Writing Programs to Practice Write a program that counts the number of vowels in a sentence, ended.
Neal Stublen Key Concepts  Classes  Objects  Inheritance  Polymorphism  Encapsulation.
1 CSC 533: Organization of Programming Languages Spring 2008 Object-oriented programming in C++  C++ design goals  C++ reliability features by-reference,
1 CSC 222: Computer Programming II Spring 2004 Searching and efficiency  sequential search  big-Oh, rate-of-growth  binary search Class design  templated.
1 CSC 222: Computer Programming II Spring 2005 Stacks and recursion  stack ADT  push, pop, peek, empty, size  ArrayList-based implementation, java.util.Stack.
CS161 Topic #15 1 Today in CS161 Lecture #15 Practicing! Writing Programs to Practice Write a game program (1 player) of Mad Math Reuse the functions to.
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 7 Single-Dimensional.
1 CSC 222: Computer Programming II Spring 2004 Pointers and linked lists  human chain analogy  linked lists: adding/deleting/traversing nodes  Node.
French Territory of St. Pierre CSE 114 – Computer Science I Arrays.
1 Linked Stack Chapter 4. 2 Linked Stack We can implement a stack as a linked list. Same operations. No fixed maximum size. Stack can grow indefinitely.
Implementation of the Hangman Game in C++
1 CSC 221: Computer Programming I Spring 2008 Lists, data storage & access  ArrayList class  methods: add, get, size, remove, contains, set, indexOf,
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
Comp 245 Data Structures (A)bstract (D)ata (T)ypes ADT.
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved Stacks.
1 Linked-list, stack and queue. 2 Outline Abstract Data Type (ADT)‏ Linked list Stack Queue.
Chapter 5 Array-Based Structures © 2006 Pearson Education Inc., Upper Saddle River, NJ. All rights reserved.
Data Structures & Algorithms
1 CSC 221: Computer Programming I Fall 2006 Lists, data storage & access  ArrayList class  methods: add, get, size, remove, contains, set, indexOf, toString.
Advanced Higher Computing Science Stacks Queues and linked lists.
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 6 Arrays.
Copyright © 2000, Department of Systems and Computer Engineering, Carleton University 1 Introduction An array is a collection of identical boxes.
1 CSC 222: Computer Programming II Spring 2004  classes and objects  abstract data types, classes and objects  using existing classes, #include, member.
More About Data Types & Functions. General Program Structure #include statements for I/O, etc. #include's for class headers – function prototype statements.
Chapter 5 Array-Based Structures © 2006 Pearson Education Inc., Upper Saddle River, NJ. All rights reserved.
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 15. Dictionaries (1): A Key Table Class.
1 CSC 222: Computer Programming II Spring 2004 Stacks and recursion  stack ADT  push, pop, top, empty, size  vector-based implementation, library 
Array-Based Implementations Chapter 3 Data Structures and Problem Solving with C++: Walls and Mirrors, Carrano and Henry, © 2013.
CS 116 Object Oriented Programming II Lecture 4 Acknowledgement: Contains materials provided by George Koutsogiannakis and Matt Bauer.
Chapter 2 Creating a C++ Program. Elements of a C++ Program Four basic ways of structuring a program Four basic ways of structuring a program 1.Sequencing.
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X 1 Chapter 7 Pointers and C-Strings.
Chapter 4 Repetition Statements Program Development and Design Using C++, Third Edition.
Click to edit Master text styles Stacks Data Structure.
Section 5.5 Application: The Card Game of War. 5.5 Application: The Card Game of War A deck of cards is shuffled and dealt to two players The players.
REPETITION CONTROL STRUCTURE
Chapter 16-2 Linked Structures
Stacks Data Structures and Problem Solving with C++: Walls and Mirrors, Carrano and Henry, © 2013.
Presentation transcript:

1 CSC 222: Computer Programming II Spring 2004 HW1 review arrays vs. vectors class design object-oriented design data objects + functionality example: card game, interacting classes

2 First, consider HW1 when solving a problem, first focus on the data involved & key tasks data involved: constant to represent MAX_WORD_LENGTH array of MAX_WORD_LENGTH+1 counters, one for each word length counter to keep track of number of words key tasks: create and initialize counters read words from file, determine lengths, increment counters open file, strip punctuation display statistics to represent data: select a built-in data structure (or design your own class) to perform key tasks: define functions (or member functions of your class) see

3 HW1 using vectors since the array size is known at compile time and doesn't change array and vector are pretty much equivalent however, using a vector can generalize so that max word length is variable prompt the user for the maximum word length create a vector that size+1 when displaying the counts, use size() to determine how many see

4 Class design object-oriented design is focused on data determine the objects involved in solving a problem if a predefined type exists (e.g., string), use it if not, define a new class to capture the data & its behavior ideally, the main program is simple, application-specific general functionality is built into the member functions of the objects involved suppose we were to write a program for playing a card game, e.g. War data objects? behavior?

5 Cards will need to be able to represent a card data fields: suit and rank functionality: construct a card with a given suit and rank get the suit get the rank get the rank value const string SUITS = "SHDC"; const string RANKS = " TJQKA"; class Card { public: Card(char r = '?', char s = '?'); char GetSuit() const; char GetRank() const; int GetValue() const; private: char rank; char suit; }; rank = 'A' suit = 'H' member functions structure of a Card object

6 Card class implementation Card::Card(char r, char s) // Constructor: initializes card to rank and suit { rank = r; suit = s; } char Card::GetRank() const // Returns: rank of card (e.g., '2', 'T', 'K') { return rank; } char Card::GetSuit() const // Returns: suit of card (e.g., 'S', 'H', 'D', 'C') { return suit; } int Card::GetValue() const // Returns: number value of card rank (2 - 14), // -1 if not a valid card character { for (int i = 0; i < RANKS.length(); i++) { if (rank == RANKS.at(i)) { return i+2; } return -1; } constructor initializes the rank and suit data fields GetRank and GetSuit simply access the private data fields GetValue determines the card's value by finding its index in an ordered string 2-9 : number value T : 10 J : 11 Q : 12 K : 13 A : 14

7 DeckOfCards also, need to represent a deck (ordered collection) of cards data fields: collection of cards functionality: create a deck in sorted order shuffle the deck draw a card from the top determine when the deck is empty note: a DeckOfCards contains a vector of Cards which contain chars class DeckOfCards { public: DeckOfCards(); void Shuffle(); Card DrawFromTop(); bool IsEmpty() const; private: vector cards; }; cards = member functions structure of a DeckOfCards object 'A' 'J' '4' … 'S' 'H' 'D' …

8 DeckOfCards implementation DeckOfCards::DeckOfCards() // Constructor: cards initialized in non-random order { for (int suitNum = 0; suitNum < SUITS.length(); suitNum++) { for (int rankNum = 0; rankNum < RANKS.length(); rankNum++) { Card card(RANKS.at(rankNum), SUITS.at(suitNum)); cards.push_back(card); } void DeckOfCards::Shuffle() // Results: deck of cards in random order { Die shuffleDie(cards.size()); for (int i = 0; i < cards.size(); i++) { int randPos = shuffleDie.Roll()-1; Card temp = cards[i]; cards[i] = cards[randPos]; cards[randPos] = temp; } Card DeckOfCards::DrawFromTop() // Assumes: deck has at least one card // Returns: card at top of deck and removes it { Card top = cards.back(); cards.pop_back(); return top; } bool DeckOfCards::IsEmpty() const // Returns: true if no cards in deck, false otherwise { return (cards.size() == 0); } constructor creates the 52 cards in order and adds to vector Shuffle repeatedly picks random indices, swaps cards DrawFromTop returns card from top (back) of deck & removes it IsEmpty determines if no cards remain

9 Implementing the main program consider a simplification of War: nobody wins a tie, equal cards are thrown away only one pass through deck, player with most head-to-head wins is overall winner pseudocode: create deck of cards for each player shuffle each deck initialize score for each player while (cards remain) { draw top cards for each player & display if not same rank, determine winner & add to score } display final score

10 war.cpp #include #include "Cards.h" using namespace std; int main() { DeckOfCards deck1, deck2; deck1.Shuffle(); deck2.Shuffle(); int player1 = 0, player2 = 0; while (!deck1.IsEmpty()) { Card card1 = deck1.DrawFromTop(); Card card2 = deck2.DrawFromTop(); cout << card1.GetRank() << card1.GetSuit() << " vs. " << card2.GetRank() << card2.GetSuit(); if (card1.GetValue() > card2.GetValue()) { cout << ": Player 1 wins" << endl; player1++; } else if (card2.GetValue() > card1.GetValue()) { cout << ": Player 2 wins" << endl; player2++; } else { cout << ": Nobody wins" << endl; } cout << endl <<"Player 1: " << player1 << " Player2: " << player2 << endl; return 0; } constructor creates the 52 cards in order and adds to vector Shuffle repeatedly picks random indices, swaps cards DrawFromTop returns card from top (back) of deck & removes it IsEmpty determines if no cards remain

11 Another example: word frequencies consider a variation of the word lengths program (HW1) want to analyze a work of literature by counting words e.g., does Twain use the same common words over and over? data objects? key tasks? read words from file, add to list (???) open file, strip punctuation, case-insenstive display statistics list of words (+ ???) number of unique words total number of words

12 WordList class define a class to store and access a list of words underlying data structures??? class WordList { public: WordList(); void Add(string word); bool IsStored(string word) const; int GetFrequency(string word) const; int GetUnique() const; int GetTotal() const; void DisplayAll() const; private: ??? }; int main() { ifstream myin; OpenFile(myin); WordList filewords; string word; while (myin >> word) { word = LowerCase(Strip(word)); filewords.Add(word); } filewords.DisplayAll(); return 0; } can consider the overall design of the solution, based on these operations

13 Underlying data structures? choice of data structures will not affect functionality, but may affect efficiency example: could store the words in a vector, with duplicates makes it easy to read and store initialize a vector of strings, read each word & push_back can use LOTS of storage, since each duplicate word is stored makes displaying word frequencies VERY MESSY & INEFFICIENT for each word in the vector, must traverse the entire vector & count occurrences if N words, then N passes of N comparisons N 2 comparisons better approach, store unique words and their frequencies more work to add a word (must check if already stored, increment frequency) only needs space proportional to the number of unique words displaying words & frequencies is simple & efficient (1 pass through vector)

14 Parallel vectors simple approach, use two vectors to store the words & frequencies words stores unique words, frequencies stores their frequencies parallel, since frequencies[i] stores the frequency of words[i] "the""thousand" "injuries"... words frequencies when a word is added, first go through words to see if already stored if so, go to the corresponding count and increment if not, push the word onto the words vector and push a corresponding 1 class WordList { public: WordList(); void Add(string word); bool IsStored(string word) const; int GetFrequency(string word) const; int GetUnique() const; int GetTotal() const; void DisplayAll() const; private: vector words; vector frequencies; int totalWordCount; };

15 WordList implementation note: Add, IsStored, and GetFrequency all traverse & search words serious duplication of code instead, have a private help function for searching, have other functions call it …/~davereed/csc222/Code/WordList.h../~davereed/csc222/Code/WordList.cpp../~davereed/csc222/Code/wordfreq.cpp will look at a better(?) alternative later class WordList { public: WordList(); void Add(string word); bool IsStored(string word) const; int GetFrequency(string word) const; int GetUnique() const; int GetTotal() const; void DisplayAll() const; private: vector words; vector frequencies; int totalWordCount; int Locate(string word) const; };