A program that handles one movie needs one Movie. A program that handles a library of them needs a
container — something that holds many records and lets you get at any one of them.
This lab builds the same small movie library three ways, in the order the language and the textbook
developed them, because each one fixes a problem with the last:
Then, because a container you cannot search is not much use, you write the two classic search algorithms and
apply them to both. The lab closes with a container of a different shape: a stack, which you build
yourself out of an array.
You will reuse the Movie class from Lab 5. If you no longer have it, here is the minimum this lab needs:
enum Genre { ACTION, COMEDY, DRAMA, ROMANCE, THRILLER };
class Movie
{
private:
string title;
Genre genre;
int duration; // in minutes
public:
Movie(); // default constructor
Movie(string t, Genre g, int d); // all three values
string getTitle() const;
Genre getGenre() const;
int getDuration() const;
};
together with the free function string genreName(Genre g); that you wrote in Lab 5.
Write movies-parallel.cpp. Store a library of five movies in three separate arrays — one for
titles, one for genres, one for durations — and print them all.
const int COUNT = 5;
string title[COUNT] = {"Back to the Future", "Black Panther", ... };
Genre genre[COUNT] = {COMEDY, ACTION, ... };
int duration[COUNT] = {116, 134, ... };
These are parallel arrays. Nothing in the language connects them. title[2], genre[2] and
duration[2] describe the same film only because you used 2 in all three, and if you ever sort one array
without sorting the others the library turns to nonsense with no error of any kind.
Then find and report the longest film. Note what that takes: you scan duration to find the subscript of
the largest value, and then use that subscript in title to say which film it was. The index is the
link — that is the whole technique.
$ ./movies-parallel
Back to the Future (COMEDY, 116 min)
Black Panther (ACTION, 134 min)
Casablanca (ROMANCE, 102 min)
Get Out (THRILLER, 104 min)
The Princess Bride (ROMANCE, 98 min)
Longest: Black Panther (134 min)
Write movies.cpp, which does exactly what Task A did, from a single array:
Movie library[COUNT] = {
Movie("Back to the Future", COMEDY, 116),
Movie("Black Panther", ACTION, 134),
...
};
An array of objects is declared and subscripted like any other array; the difference is that each
element is a Movie, so you reach its parts through its member functions:
library[i].getTitle()
Read that carefully — the subscript comes first, then the dot. library[i] selects one object, and
.getTitle() asks that object a question.
Each element is built by a constructor. With no initializer list, every element gets the default
constructor, which is why a class used in an array needs one. With the list above, each element gets the
three-argument constructor instead.
Add a free function void printMovie(const Movie &m); and use it in the loop. Pass by constant reference,
as in Lab 5: by reference so the whole object is not copied, const because printing changes nothing.
Then compare the two programs. Three arrays became one. Keeping the fields together is no longer your
responsibility, because they are no longer separate things. Write a sentence in a comment saying what
specifically can go wrong in movies-parallel.cpp that cannot go wrong here.
Finding a record means searching, and there are two algorithms worth knowing.
A linear search starts at element 0 and walks forward until it finds the value or runs out of array. It
works on any array, sorted or not. On average it examines half the elements, and all of them when the value
is absent.
A binary search needs a sorted array, and exploits that. It looks at the middle element: if that is
the value, it is done; if the middle is too small, the answer can only be in the upper half; if too large,
only in the lower half. Either way half the remaining array is eliminated by one comparison.
Both return the subscript where the value was found, or -1 to mean “not present”. That convention is
worth adopting permanently: -1 is never a valid subscript, so it cannot be mistaken for an answer.
In movies.cpp, add
int searchList(const Movie list[], int size, int value);
returning the index of the first film whose duration equals value, or -1. Call it twice from main —
once with a duration that exists, once with one that does not — and print the film when it is found.
Note the const on the array parameter, the habit from Lab 6: a search reads, so say so.
Write bsearch.cpp, operating on a sorted array of twenty durations:
int minutes[SIZE] = {81, 88, 90, 93, 95, 98, 99, 102, 104, 107,
110, 113, 116, 120, 124, 129, 134, 141, 150, 169};
Write both searches over this array, and have each one count the comparisons it makes:
int linearSearch(const int arr[], int size, int value, int &steps);
int binarySearch(const int arr[], int size, int value, int &steps);
steps is a reference parameter — Lab 3’s technique — because each function has to report two things and
return carries one.
The binary search keeps a first and a last subscript and narrows the gap between them. Work out on paper
what happens when first passes last, because that is how the loop ends when the value is absent.
Search for each of 81, 107, 169 and 100, and print a table of the step counts and the index found.
$ ./bsearch
value linear binary index
81 1 4 0
107 10 1 9
169 20 5 19
100 20 4 -1
Look at the first row before concluding that binary search is simply better. For 81 the linear search
wins, because 81 is element 0 and linear search starts there. Binary search starts in the middle, so the
value it finds fastest is the middle one. The advantage only appears as the array grows: on twenty elements
the worst case is 20 against 5, and on a million it is a million against twenty.
The search in Task C matched on a duration. In practice you search a record collection by the field that
identifies a record — its key field — and get back the whole record. Add to movies.cpp:
int searchByTitle(const Movie list[], int size, string key);
returning the index of the film with that title, or -1. Call it and print the film found.
The loop is identical to Task C’s. Only the field being compared changed, and that is the point of the
chapter: once you can search an array, you can search an array of anything, by any field it holds.
A stack is a container with a deliberately narrow interface: you may add to the top, and you may remove
from the top, and nothing else. Think of a stack of plates. The last item in is the first out, which is why
it is called LIFO — last in, first out.
That restriction is the feature. Undo histories, the back button, and the call stack that runs your
functions are all stacks, because “most recent first” is exactly what they need.
The implementation here is an array plus a single integer, top, holding the number of items currently
stored — which is also the subscript of the next free slot.
Split it across three files, as you did in Lab 5 — IntStack.h, IntStack.cpp, and a client
stacktest.cpp:
const int STACK_CAPACITY = 100;
class IntStack
{
private:
int stackArray[STACK_CAPACITY];
int top;
public:
IntStack(); // an empty stack: top is 0
bool push(int value); // false if the stack is full
bool pop(int &value); // false if the stack is empty
bool isEmpty() const;
bool isFull() const;
int size() const;
};
pop has to report two things — whether it worked, and the value — so the value comes back through a
reference parameter and the success through the return. That pattern is worth recognising; you have now met
it three times.
Your stacktest.cpp should push five values, print the height, pop everything and print the values as they
come out, then show that popping an empty stack and pushing onto a full one both return false rather than
corrupting anything.
$ ./stacktest
Pushing: 5 10 15 20 25
Height: 5
Popping: 25 20 15 10 5
Pop from an empty stack returns: false
Filling to capacity...
Height: 100
Push onto a full stack returns: false
The values come out backwards. That is not a bug — that is what a stack is.
A difference from the lecture. The textbook’s
IntStackallocates its array with a smart pointer and
reports full and empty conditions by throwing exceptions. We do neither here: the array is a fixed
member, and the two conditions come back asbool. Exceptions are not part of this course, and the array
version is what section 18.1 calls a static stack. The logic ofpush,popandtopis identical.
Write secret.cpp, which encodes and decodes messages by substituting one character for another —
f for c, t for a, x for t, so cat becomes ftx. Even the space is substituted, so the reader
cannot tell where the words end.
The substitutions live in a 95-element char array, one for each printable ASCII character from 32 (space)
through 126 (~). Read it from the supplied 10_code.dat in the constructor.
The two directions are not symmetric, and that is the interesting part.
Encoding needs no search. The original character’s ASCII code tells you the subscript directly:
newChar = codeChar[ascii - 32];
Decoding does. You have the substituted character and need the subscript it sits at, so you must look
through the array for it — a linear search, identical in shape to searchList from Task C, over a char
array instead of an array of objects. Its index plus 32 is the original character’s ASCII code.
Build a class CodeMaker with a private findIt helper and public encode and decode. Test it by
encoding a message and decoding the result — you should get back exactly what you typed.
$ ./secret
Enter the message to be encoded.
I can write a secret message.
Here is the encoded message.
;~i*N~Ek@Dt~*~!tiktD~Lt!!*$tx
Here is the decoded message.
I can write a secret message.
Watch the table size. The printable characters run from 32 to 126, which is 95 characters, not 94.
The listing in the textbook declares 94 and then reads 95 — the sort of off-by-one that hides until
somebody types a~.
Submit all six source files, plus the bonus if you did it:
movies-parallel.cpp movies.cpp bsearch.cpp
IntStack.h IntStack.cpp stacktest.cpp secret.cpp (bonus)
Do not submit compiled executables. Each file should start with a comment containing your name and a short
description, for example:
/*
Author: your name
Course: CSCI-135
Instructor: their name
Assignment: Lab 10
Here, briefly, at least in one or a few sentences
describe what this file contains.
*/