16
16
16
For
example, tot
and otto are rather short palindromes. Write a program that lets a user enter a
string
and that passes to a bool function a reference to the string. The function should
return
true if the string is a palindrome and false otherwise. At this point, dont worry
about
complications such as capitalization, spaces, and punctuation. That is, this
simple version
should reject Otto and Madam, Im Adam. Feel free to scan the list of string
methods in Appendix F for methods to simplify the task.
cp16ex1.cpp
1 #include <iostream>
2 #include <string>
3
4 using namespace std;
5
6 bool ispalindrome(const string &); // function takes a string ref and returns true
if string is palindrome
7
8
9
1
0
1
1
1
2
1
3
int main()
{
string my;
cout << "Enter words (case and punctuation sensitive), q to quit: ";
while (cin >> my && my != "q") // enter words until q is entered
{
if (ispalindrome(my)) // check if entered word is palindrome
1
4
1
5
1
6
1
7
1
8
1
9
2
0}
cin.get();
cin.get();
return 0;
2
1
bool ispalindrome(const string & st) // const & reference, we need original
2 string to compare with reversed version
2
{
2
string temp = st; // save original string to a temporary string
3
2
4
2
5
2
6
2
7
2
}
8
2
9
3
0
3
1
3
2
3
3
3
4
3
5
3
6
3
7
3
8
7
8
bool ispalindrome(const string &); // function takes a string ref and returns true
if string is palindrome
9
1
int main()
0
{
1
1
string my;
1
2
1
3
1
4
cout << "Enter words (capitalization and punctuation ignored), q to quit: ";
while (getline(cin,my) && my != "q") // enter words until q is entered
{
if (ispalindrome(my)) // check if entered word is palindrome
1
5
1
6
1
7
1
8
1
9
2
0
cin.get();
cin.get();
return 0;
2}
1
2
2 bool ispalindrome(const string & st) // const & reference, we need original
string to compare with reversed version
2
3{
string temp_orig = st; // save string value to temporary variable, thus
2
preserving
original passed string untouched
4
2
5
string temp_rev;
2
6
int j = 0;
2
7
continue;
else
{
3
7
3
8
3
9
4
0
4
1
4
2
4
3
4
4
4
5
4
6
else
4
7}
4
8
4
9
5
0
5
1
5
2
5
3
5
4
3. Redo Listing 16.3 so that it gets it words from a file. One approach is to use a
vector object instead of an array of string. Then you can use push_back() to
copy how ever many words are in your data file into the vector object and use
the size() member to determine the length of the word list. Because the program
should read one word at a time from the file, you should use the >> operator
rather than
getline(). The file itself should contain words separated by spaces, tabs, or new
lines.
cp16ex3.cpp
1 #include <iostream>
2 #include <fstream> // include fstream to read files
3 #include <string>
4 #include <cstdlib>
5 #include <ctime>
6 #include <cctype>
7 #include <vector> // include vector to contain array of words read from file
8
9 using namespace std;
10
11 int main()
12 {
13
std::srand(std::time(0));
14
15
16
string str_finput; // string buffer to read one word at a time from file
17
18
19
20
cout << "Enter filename with words to guess: "; // get the filename
21
22
23
fin.open(filename); // open it
24
if (fin.fail())
25
26
cout << "Error opening file: " << filename << " not found!\n"; // if
invalid file name or not found - display the error
else
27
28
29
30
31
32
33
34
35
36
37
if (words.size() > 0 && words.size() < 2 && words[0].length() < 2) // if file
was opened but did not contain any words (less than 2 chars in length, it is
39 error!
38
cout << "No words to guess or file is empty!\n"; // display error msg
40
41
42
43
44
45
46
47
48
49
50
cout << "Total words loaded: " << words.size() << endl; // display total
# of words loaded to vector array
char play;
cout << "Will you play a word game? <y/n> ";
cin >> play;
play = tolower(play);
while (play == 'y')
{
55
string badchars;
56
int guesses = 6;
57
58
59
60
61
62
63
64
char letter;
65
66
67
68
69
70
continue;
71
72
73
74
75
}
int loc = target.find(letter);
if (loc == string::npos)
{
cout << "Oh, bad guess!\n";
76
--guesses;
77
78
79
80
81
82
83
84
85
86
87
}
else
{
cout << "Good guess!\n";
attempt[loc]=letter;
// check if letter appears again
loc = target.find(letter, loc + 1);
while (loc != string::npos)
{
attempt[loc]=letter;
88
89
90
91
92
93
if (attempt != target)
94
95
if (badchars.length() > 0)
96
97
98
99
10
0
if (guesses > 0)
cout << "That's right!\n";
10
1
else
cout << "Sorry, the word is " << target << ".\n";
10
2
10
3
10
4
10
5
10
6
10
7
cin.get();
10
8
cin.get();
return 0;
}
10
9 list.txt
1
2
3
4
5
6
7
8
9
10
apiary
beetle
cereal
danger
ensign
florid
garage
health
insult
jackal
keeper
loaner
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
manage
nonce
onset
plaid
quilt
remote
stolid
train
useful
valid
whence
xenon
yearn
zippy
1 48};
2
1
3
int i = 0;
1
4
1
5
2
0
int newNUM = reduce(arr, NUM); // reduce array and store the number of
1 new sequence elements into variable
6
cout << "\nNumber of elements in arr[] after reduce: " << newNUM <<
1 endl; // disp the info
7
cout << "Array after sort & duplicates removal: "; // display sorted & unique
1 original array
8
for (i = 0; i < newNUM; i++) // dupe values are still in array after newNUM
1 but not displayed, STL functions such as erase can be used with list or vector
9 list if needed
2
1
cin.get();
cin.get();
2
2
return 0;
2}
3
2
4 int reduce(long ar[], int n)
2{
5
2
6
2
}
7
2
8
2
9
3
0
3
1
3
2
3
3
int main()
{
long arr[NUM] = {1, 1, 2, 3, 45, 5, 4, 11, 45, 70, 9, 47, 48, 47, 73, 90, 11,
48}; // array of long(S)
string city[NUM2] = {"new york", "washington", "philadelphia",
cin.get();
cin.get();
return 0;
}
{
for (int i = 0; i < n; i++) // go through every element of array
cout << ar[i] << " "; // and display its contents
cout << endl;
}
6.
Redo the example shown in Listing 12.15, using the STL queue template class instead of
the Queue class described in Chapter 12.
customer.h
1 #ifndef CUSTOMER_H_ // queue class is reduced to customer class only, since for this
2 #define CUSTOMER_H_ // programming exercise we'll use STL queue class instead of
our own Queue class from Chapter 12
3
// This queue will contain Customer items
4
class Customer
5
{
6
private:
7
long arrive; // arrival time for customer
8
int processtime; // processing time for customer
9
public:
1
0
Customer() { arrive = processtime = 0; }
11
1
2
1
3 };
1
4
1
5
1
6
inline void Customer::set(long when)
1
7 {
processtime = std::rand() % 3 + 1;
1
8
arrive = when;
1
9 }
2
0
#endif
2
1
2
2
cp16ex6.cpp
1 #include <iostream>
2 #include <cstdlib> // for rand() and srand()
3 #include <ctime> // for time()
4 #include "customer.h" // include our Customer class without any former Queue class
elements from Chapter 12
5
#include <queue> // include queue<typename T> class from STL library for this exercise
6
7
typedef Customer Item; // customer Item class instance is declared here instead of former
8 Queue.h
// because we'll use STL queue class instead of our own Queue class from
9
Chapter 12
1
0
using std::cout;
using std::endl;
using std::ios_base;
1
7
1
8
1
9
2
0
2
1
2
2
2
3
2
4
2
5
2
6
2
// setting things up
std::srand(std::time(0)); // random initializing of rand()
cout << "Case Study: Bank of Heather Automatic Teller\n";
cout << "Enter maximum size of queue: ";
int qs;
cin >> qs; // line queue holds up to qs people
std::queue<Item> line; // declare the queue STL class variable - line, formerly Queue
line(qs);
cout << "Enter the number of simulation hours: ";
int hours; // hours of simulation
cin >> hours;
// simulation will run 1 cycle per minute
long cyclelimit = MIN_PER_HR * hours; // # of cycles
cout << "Enter the average number of customers per hour: ";
double perhour; // average # of arrival per hour
cin >> perhour;
2
8
2
9
3
0
3
1
3
2
3
3
3
4
3
5
3
6
{
customers++;
4
0
4
1
4
2
4
if (wait_time <= 0 && !line.empty()) // change from !line.isempty() to !line.empty() to
3 reflect new queue STL class
4
4
{
line.pop(); // attend next customer, formerly line.dequeue (temp);
4
5
4
6
4
7
4
8
}
if (wait_time > 0)
wait_time--;
4
9
5
0
5
1
5
2
sum_line += line.size();
}
// reporting results
if (customers > 0)
{
cout << "customers accepted: " << customers << endl;
5
3
cout << " customers served: " << served << endl;
5
4
5
5
cout.precision(2);
5
6
cout.setf(ios_base::fixed, ios_base::floatfield);
cout.setf(ios_base::showpoint);
5
7
5
8
5
9
6
else
6
1
6
2
6
3
cin.get();
cin.get();
6
4
return 0;
6 }
5
6
6 // x = average time, in minutes, between customers
6 // return value is true if customer shows up this minute
7
bool newcustomer(double x)
6
8 {
6
9
7
0
7
1
7
2
7
3
7
4
7
5
7
6
7
7
7
8
7
9
8
0
8
1
8
2
8
3
8
4
8
5
8
6
8
7
8
8
8
9
9
0
9
1
9
2
9
3
9
4
9
5
9
6
7. A common game is the lottery card. The card has numbered spots of which a certain
number are selected at random. Write a Lotto() function that takes two arguments. The
first should be the number of spots on a lottery card, and the second should be the
number of spots selected at random. The function should return a vector object
that contains, in sorted order, the numbers selected at random. For example, you could
use the function as follows:
vector winners;
winners = Lotto(51,6);
This would assign to winners a vector that contains six numbers selected randomly from
the range 1 through 51. Note that simply using rand() doesnt quite do the job because
it may produce duplicate values. Suggestion: Have the function create a vector that contains
all the possible values, use random_shuffle(), and then use the beginning of the
shuffled vector to obtain the values. Also write a short program that lets you test the
function.
cp16ex7.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>
#include <vector>
// include vector for vector template
#include <algorithm>
// include algorithm header to use with sort,
random_shuffle, and find STL functions
using namespace std;
typedef vector<int> Ticket;
// Ticket is now vector<int> for ease
of use, holds lottery numbers (array)
Ticket Lotto(int, int);
// function returns vector<int> (or Ticket),
first int argument is a max range (from 1 to max range) to draw Lottery
numbers, and second int argument is how many spots or numbers to guess
to win the lotto
void DisplayTicket(const Ticket &); // display ticket or vector<int>
array
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
int main()
{
int lotMaxR, winN, matchingN = 0; // lotMaxR = max range number for
lottery numbers to be drawn, from 1 to lotMaxR
do
{
cout << "Enter lottery range, from 1 to (5 or greater): "; //
ask to input maximum range of possible lottery draw number
} while(cin >> lotMaxR && lotMaxR < 5); // get proper number from
user until 5 or more is entered
do
{
cout << "Enter how many numbers to draw (2 or greater): "; //
ask for how many spots on the lotto card or winning numbers to draw in
lottery play
} while(cin >> winN && winN < 2); // ask for input until 2 or
number is entered
Ticket winners = Lotto(lotMaxR,winN); // generate random numbers
for winning numbers
Ticket myticket = Lotto(lotMaxR,winN); // generate random numbers
for user's playing ticket, something like QuickPick
cout << "Winning numbers: ";
DisplayTicket(winners); // display winning numbers
cout << "Your ticket numbers: ";
DisplayTicket(myticket); // display playing user's numbers
cout << "Number(s) matched on your ticket: "; // display matching
numbers from both arrays (lottery drawn numbers and user's quick pick)
for (int i = 0; i < winN; i++)
if (find(winners.begin(), winners.end(), myticket[i]) !=
winners.end()) // compare each winning number to user's picked numbers
{
cout << myticket[i] << " "; // if matched, display the
number
matchingN++; // and increase the number of matched numbers
}
if (matchingN == 0) // if no numbers were matched display the
message
cout << "None" << endl;
else
cout << endl;
if (matchingN == winN && matchingN > 5) // if all winning numbers
guessed correctly and the total number of them is 6 or more - almost
impossible win, display epic congratulations message!
cout << "Oh my Flying Spaghetti Monster, you've guessed all
numbers!!! BEER IS ON ME!";
else if (matchingN == winN && matchingN == 2 ) // special occasion:
if out of 2 winning numbers 2 guessed correctly, display FREE ticket
prize msg
cout << "Congratulations, you've won min 2x2 game! Prize: 10
FREE tickets!" << endl;
else if (matchingN > 5) // display messages for each number of
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
10
0
10
1
10
2
10
3
10
4
10
5
10
6
10
7
correctly guessed numbers, the greater the number the more fun and
expensive prize....or maybe not :)
cout << "Congratulations, You've guessed " << matchingN << "
winning numbers!!! PRIZE: Skyscraper in New York City!" << endl;
else
switch(matchingN)
{
case 5:
cout << "Congratilations, You've guessed 5
winning numbers!!!! PRIZE: New Yacht filled with naked chicks!" << endl;
break;
case 4:
cout << "Congratulations, You've guessed 4
winning numbers!! PRIZE: Vacation to Siberian Gulag! :P" << endl;
break;
case 3:
cout << "Congratulations, You've guessed 3
winning numbers!! PRIZE: Bubble Gum that sticks to your shoes!" << endl;
break;
default:
cout << "You've guessed " << matchingN << "
winning number(s)!! Buy more tickets next time. Good luck!" << endl;
break;
}
cout << "\nBye!"; // all is done, good bye
cin.get();
cin.get();
return 0;
}
Ticket Lotto(int Tot, int Ran) // generate and return randomized & sorted
array of lottery numbers
{
Ticket temp; // create a ticket that will be returned once generated
with random lottery numbers with respect to arguments passed to function
int i = 0;
if (Tot < 5) // check for the first argument passed to function
{
cout << "Invalid number range, resetting to default: [1-5]" <<
endl; // if range of lottery number max is below 5, change it to min
allowed - 5
Tot = 5;
}
if (Ran < 2) // check the second argument, if less than 2, set it to
default value of 2, we need at least 2 winning numbers to play with
{
cout << "Invalid ticket request, setting number of winning
numbers to default - 2." << endl;
Ran = 2;
}
for (i = 0; i < Tot; i++) // generate non-random sequence of numbers
from 1 to Tot and store it in vector<int> array
temp.push_back(i+1);
for (i = 0; i < Ran; i++) // shuffle the numbers "Ran" many times to
have better randomization of numbers
random_shuffle(temp.begin(), temp.end());
temp.erase(temp.begin()+Ran, temp.end()); // erase unnecessary
numbers from Ran+, numbers from 1 to Ran are kept in.
sort(temp.begin(), temp.end()); // finally, sort the numbers
10
return temp; // and return the sorted and randomized array
8 }
10
9 void DisplayTicket(const Ticket & t) // function displays victor<int>
110 array or defined as Ticket
{
8. Mat and Pat want to invite their friends to a party. They ask you to write a
program that
does the following:
Allows Mat to enter a list of his friends names. The names are stored in a
container
and then displayed in sorted order.
Allows Pat to enter a list of her friends names. The names are stored in a
second
container and then displayed in sorted order.
Creates a third container that merges the two lists, eliminates duplicates, and
displays
the contents of this container.
cp16ex8.cpp
1 #include <iostream>
2 #include <set>
3 #include <string>
4 #include <iterator>
5 #include <algorithm>
6
7
8 using namespace std; // I don't like typing std:: all the time
9
1 int main()
0
{
1
string input; // keyboard input string
1
ostream_iterator<string, char> out(cout, "\n"); // output iterator to display
1
2 container elements
1
3
1
9
2
0
2
1
pats_friends.insert(input);
2
copy(pats_friends.begin(), pats_friends.end(), out);
2 friends
2
3
cin.get();
cin.get();
return 0;
3
2
3
3
3
4
3
5
3
6
3
7