0% found this document useful (0 votes)
97 views4 pages

Guidelines: Std::clock Ctime Clock F

This document provides instructions for Lab 4 on data structures and algorithms. Students will work with dynamic arrays and vectors in C++, generalizing arrays to different data types using templates. Tasks include implementing dynamic arrays, measuring runtime of element insertion, and modeling store/customer concepts in C++ using classes and data structures like vectors and inheritance. Guidelines are provided on submission, attendance, and using std::clock to time code execution.

Uploaded by

Karima Baba
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
97 views4 pages

Guidelines: Std::clock Ctime Clock F

This document provides instructions for Lab 4 on data structures and algorithms. Students will work with dynamic arrays and vectors in C++, generalizing arrays to different data types using templates. Tasks include implementing dynamic arrays, measuring runtime of element insertion, and modeling store/customer concepts in C++ using classes and data structures like vectors and inheritance. Guidelines are provided on submission, attendance, and using std::clock to time code execution.

Uploaded by

Karima Baba
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 4

Data Structures and Analysis of Algorithms

EECE 330
Lab 4 – Fall 2020

In this lab assignment we will continue our C++ familiarity exercises. We will start with using
dynamic memory allocation to improve our use of arrays. We will build dynamic arrays and support
their functionality to add elements and provide a linear amortized behavior. We will then use the
STL vector class and compare it against our own arrays.
We will then generalize the arrays of integers to work for other types using C++ templates.
We will then use the dynamic vector concept to solve an interesting problem.

Guidelines
ˆ This programming assignment consists of 4 problems.

ˆ It is due on Wednesday, October 14, 2020 11:55 pm.

ˆ Topics: Arrays, classes, inheritance, dynamic memory allocation, templates

ˆ Readings: Stroustrup book chapters 9 and 14.3

? You are supposed to submit your own work. We have a zero tolerance policy for cheating.
Penalties may include one or more of the following: zero grades on programming assignments,
failing the course, disciplinary committee, Dean’s warning, and suspension .

? Lab attendance is mandatory. Violating this rule can lead to a failing grade.

Measuring time
The std::clock() method returns the CPU time your process used since it started. To use it, you
need to include the ctime header file as in the example below. The returned value does not make
sense on its own. The difference between two values returned by clock denotes the time passed
between the two function calls. Consequently, the following code measures how long function f()
takes to execute.
#include < iostream > // used for cout and endl i n t main () {
#include < iomanip > // used for set precision // clock_t type abstracts time
#include < ctime > // used for clock std :: clock_t c_start = std :: clock () ;
f () ;
// function does some time - consuming work std :: clock_t c_end = std :: clock () ;
void f () { // CLOCKS _PER_SEC constant is system dependent
double d = 0; // denotes number of clocks per second
double elapsed = 1000.0*( c_end - c_start ) /
f o r ( i n t n =0; n <10000; ++ n ) { CLOC KS_PER_S EC ;
f o r ( i n t m =0; m <10000; ++ m ) { std :: cout << std :: fixed << std :: setprecision (2)
d += d * n * m ; << " CPU time used : " << elapsed << " ms "
} << std :: endl ;
} return 0;
} }

1
Problem 1: Dynamic array expansion
A dynamic array (DA) starts with zero elements: a fixed capacity and zero size. When inserting
an element in a DA either

ˆ The resulting size of the DA is within its capacity, so the code places the element and
increments size; or

ˆ The resulting size is greater than the capacity, so the code expands the DA by allocating twice
the memory, copies the existing data into the newly allocated memory, discards the old data,
places the element, increments size, and sets capacity.

The code below is a simple implementation of a dynamic array of integers.

const i n t O R I G I N A L _ C A P A C I T Y = 16; void insert ( i n t t ) {


const i n t GROW_FACTOR = 2; i f ( size >= capacity ) { // grow the array
unsigned i n t newcapacity = capacity * GROW_FACTOR ;
struct DynArr { i n t * newdata = new i n t [ newcapacity ];
i n t * data ; f o r ( i n t i =0; i < size ; i ++) {
unsigned i n t size , capacity ; newdata [ i ] = data [ i ]; // copy old data
}
// constructor delete [] data ; // discard old memory
DynArr () : // initialize data = newdata ; // point to the new data
size (0) , capacity ( O R I G I N A L _ C A P A C I T Y ) capacity = newcapacity ; // set capacity
{ // preallocate memory }
data = new i n t [ capacity ]; data [ size ] = t ; // place new element
} size = size + 1; // increment size
}
};

ˆ Variables ORIGINAL CAPACITY and GROW FACTOR defined this way (outside main and outside any
function or class) are called global variables. They are accessible anywhere in the code.

ˆ Write code that uses DynArr to allocate and insert a large number of elements into a DynArr
object.

ˆ Use std::clock to measure the time needed to insert 1000, 2000, 3000, 4000, 5000, ..., 200000
elements into the DynArr object.

ˆ Change the way the array is expanded and instead of doubling the capacity, only increase the
capacity by 10. Repeat measuring the time for 1000, 2000, ... 200000 insertions.

ˆ What difference do you notice? Try to explain. Hint: try to chart the two sequences.

ˆ Repeat the same exercise but now use the STL vector<int> class instead of DynArr. Use the
push back method to insert the elements.

ˆ Compare the behavior of the vector<int> insertions with the DynArr (with double growth)
insertions. Try to explain the difference in runtime behavior if any.

2
Problem 2: Generalize dynamic arrays to more types
The dynamic array from Problem 1 works for integer objects. We will use templates to generalize
it to objects of other types. Inspect the code for DynArr from Problem 1 and decide how to change
it to make it work with the following.

c l a s s Course { public : DynArr <double > da ;


string name ; i n t n = rand () % 1024;
string description ; f o r ( i n t i =0; i < n ; i ++) {
string instructor ; double val = rand () /(1+ rand () ) ;
da . insert ( val ) ;
Course ( const string & n , }
const string & d ,
const string & i ) : DynArr < Course > dc ;
name ( n ) , description ( d ) , Course c1 ( " Python " ," Scripting / prototyping " ," Louay "
instructor ( i ) );
{} Course c2 ( " C ++ " ," System level / control " ," Fadi " ) ;
/* Course c3 ( " Java " ," Memory safe / cross platform " ,"
* You may need more Wassim " ) ;
* constructors here dc . insert ( c1 ) ;
*/ dc . insert ( c2 ) ;
}; dc . insert ( c3 ) ;

Problem 3: Purchasing from a store


Consider the following paragraph in English and then consider the following code that expresses
the same concepts in C++.

An item has a name, a price, and an expiry date. A store item is an item that has the
number of available items in the store. A monetary bill has a value and a unit; e.g.
1,000 L.L. For simplicity we consider coins to be bills as well. A basket has a sequence
of items. A customer has a basket and only one bill of cash to pay for the basket. A cash
register has monetary bills each associated with a number of bills. Each cash register
has also a set of customers waiting to be served. A store has a set of store items and a
set of cash registers.

// a date tuple has a day , month and year values .


struct dateT {unsigned i n t day , month , year ;};
// an item has a name , a price , an expiry date , and a number of items available
struct itemT { string name ; double price ; dateT expiry ;};
// a store item is an item , it has the number of available items
struct storeItemT : public itemT {
unsigned i n t available ;};
// a bill has a value and a unit
struct billT {unsigned i n t value ; string unit ;};
// a basket has items
struct basketT { vector < itemT > items ; };
// a customer has a basket and one bill of cash
struct customerT { basketT b ; billT cash ;};
// a register has drawers for bills and a count for each bill
struct registerT { vector < billT > bills ; vector <unsigned int > count ;
vector < customerT > customers ;};
// a store has a sett of items and a set of registers
struct storeT { vector < storeItemT > items ; vector < registerT > registers ;};

Notice the basic structure of the English sentences and how all “noun” concepts were translated
into structures, objects, sets of objects, and relations between objects. The “has” verb occurrences
translate into data members denoting an “ownership” relation between the two objects. The “is”

3
verb occurrences translates to an inheritance relation indicating an identity or a subset relation.
You will exercise the same translation in the next problem.
Add methods (functions) to the classes to perform the following actions (verbs).

ˆ The basket is smart. It computes the total price of its items. So develop a method double
getTotal() const in class basketT that computes and returns the total price of all its items.

ˆ The register handles one customer at a time using method (handleCustomer(custometT &
cu)). It takes as input a customer from the set of customers, checks the total for the basket
of the customer, checks whether the bill with the customer is enough to pay for the basket. If
all checks pass, then the method adds the bill from the customer to the register and returns
to the customer the minimum number of bills. advice: you can split this into more than one
function. hint: you might want to sort some of the vectors you have for an efficient solution.

ˆ OPTIONAL: The store runs its business as follows. It iterates over all its registers, and
once a register handles a customer successfully, it updates the store items by removing the
corresponding basket items. think of a fast search to match the items of the basket with the
items of the store. In case the count of a store item drops below 5, the program outputs a list
of requests to refill the inventory.

Write a main function to test your program one method at a time. You may want to use rand
to reduce the time you need for data entry.

Problem 4 (Optional): English to C++: Soccer game


In this exercise you will translate English design to C++ yourself using the “is”, “is type of” and
“has” relations. In case some English sentences were too complicated to translate, refine them as
much as possible by rewriting them into “is” (to be) and “has” (to have) sentences. The verbs in
the remaining sentences that you could not refine might be your methods.

A soccer game runs with one ball, two adversary teams, one field referee, and two side
referees. A soccer game has a result which is the number of goals scored by each team.
Each team has 11 field players, 10 bench players, a strategy, a main coach and a coach
assistant. A player has a name, a number, a position, and a state. The position of
the player could be goalie, defender (left, right, center), midfielder (left, right, center),
or attacker (left, right center). The state of the player could be active, active with a
yellow card, or benched. If benched, the player could also be red carded, or wounded.
A strategy tuple has three numbers dictating how the players are split on the field. A
h3, 5, 2i strategy denotes three defenders, five midfielders, and two attackers. The main
coach can call for up to three substitutions where a non wounded and non-red carded
bench player substitutes for an active player during a soccer game. The main coach can
also change the strategy. The referee can issue a yellow card or a red card to a specific
player. Two yellow cards are equivalent to one red card. Once a red card is issued the
player should be benched with no substitution.

Develop C++ structures that simulate “soccer game” as described above. Your classes and
structures should use the concepts we covered so far in the labs. Test your classes by simulating
the coach issuing cards, the teams scoring, and the coaches substituting and changing strategies.

You might also like