13.14. Coding PracticeΒΆ
Question
Create the enumerated type planet, which maps the planets in our solar system to integers starting at 1. Make sure to list the planets out in order! (Sadly, Pluto is not a planet :( )
1#include <iostream>
2
3// Write your code for the enumerated type planet.
Answer
Below is one way to implement the program. The planets in our solar system are Mercury, Venus, Earth, Mars, Jupiter, Saturn, Uranus, and Neptune.
1#include <iostream>
2
3enum planet { mercury = 1, venus, earth, mars, jupiter, saturn, uranus, neptune };
Question
A Bingo board has 25 Spaces in a matrix-like grid. A space has a number value randomly selected from 1 to 75 and can
either be filled or not. Write the struct definitions for space and bingo_board.
1#include <iostream>
2#include <vector>
3
4// Write your code for the struct space here.
5
6// Write your code for the struct bingo_board here.
Answer
Below is one way to implement the program. We declare the space and bingo_board struct
and create the instance variables in order. Make sure to set is_filled to false!
1#include <iostream>
2#include <vector>
3
4struct space {
5 int value;
6 bool is_filled;
7};
8
9struct bingo_board {
10 std::vector<std::vector<space> > board;
11};
Question
Now we need a way to swap the values at two indices in a vector. Write the function swap_values,
which takes a vector of ints and two indices as parameters.
1#include <iostream>
2#include <vector>
3
4// Write your code for the swap_values function here.
Answer
Below is one way to implement the program. We store the value at index1 in a temp
variable, replace the value at index1 with the value at index2, and then finally
replace the value at index2 with the value of temp. Make sure to pass
vec by reference!
1#include <cstddef>
2#include <iostream>
3#include <vector>
4
5void swap_values (std::vector<int> &vec, std::size_t index1, std::size_t index2) {
6 int temp = vec[index1];
7 vec[index1] = vec[index2];
8 vec[index2] = temp;
9}
Question
We can now fill our bingo_board with values! Write the bingo_board
member function make_board. Use the generate_rand_vec
function and select the first 25 values to fill up the board. Make sure
to create a free space in the middle of the board! Set the value of the
free space to 0 and is_filled to true. All other
spaces should have is_filled set to false.
1#include <cstddef>
2#include <random>
3#include <iostream>
4#include <vector>
5#include <cstdlib>
6#include <numeric>
7
8struct space {
9 int value;
10 bool is_filled;
11};
12
13struct bingo_board {
14 std::vector<std::vector<space> > board;
15 void make_board ();
16};
17
18std::size_t random_int(std::size_t low, std::size_t high);
19void swap_values (std::vector<int> &vec, std::size_t index1, std::size_t index2);
20std::vector<int> generate_rand_vec ();
21
22// Write your code for the make_board function here.
Answer
Below is one way to implement the program. First we need to initialize
the board to the correct dimensions. Then, we use generate_rand_vec
to create a vector of random values from 1 to 75. Afterwards, we set
the values of the 25 spaces to the first 25 values in the
random vector. Lastly, we set the middle space to 0 and
set its is_filled to true.
1#include <cstddef>
2#include <random>
3#include <iostream>
4#include <vector>
5#include <cstdlib>
6#include <numeric>
7
8struct space {
9 int value;
10 bool is_filled;
11};
12
13struct bingo_board {
14 std::vector<std::vector<space> > board;
15 void make_board ();
16};
17
18std::size_t random_int(std::size_t low, std::size_t high);
19void swap_values (std::vector<int> &vec, std::size_t index1, std::size_t index2);
20std::vector<int> generate_rand_vec ();
21
22void bingo_board::make_board() {
23 // Initialize board
24 space s = {0, false};
25 std::vector<space> cols(5, s);
26 for (std::size_t i = 0; i < 5; ++i) {
27 board.push_back(cols);
28 }
29
30 // Fill board with random values
31 std::vector<int> vec = generate_rand_vec();
32 std::size_t count = 0;
33 for (std::size_t row = 0; row < board.size(); ++row) {
34 for (std::size_t col = 0; col < board[row].size(); ++col) {
35 board[row][col].value = vec[count];
36 ++count;
37 }
38 }
39
40 // Create free space
41 board[2][2].value = 0;
42 board[2][2].is_filled = true;
43}
Question
Bubble sort is a method of sorting that involves repeatedly swapping the
adjacent elements if they are in the wrong order. For example, let's say
we have the vector with elements {3, 2, 4, 1}. On the first pass, we take
a look at the first two elements, 3 and 2. Since 3 is bigger than 2, we swap them.
Thus, the vector now looks like {2, 3, 4, 1}. Next, we look at the next two
elements, 3 and 4. Since 3 is less than 4, we don't swap. Lastly, we look at
the last two elements, 4 and 1. Since 4 is greater than 1, we swap the.
Thus the vector now looks like {2, 3, 1, 4}. Now we restart and look at the
first two elements again and the process continues. This way, the biggest elements
"bubble" to the back. Write the function bubble_sort,
which takes a vector as a parameter and sorts it. Feel free to use the provided
swap_values function.
1#include <cstddef>
2#include <iostream>
3#include <vector>
4
5void swap_values(std::vector<int> &vec, std::size_t index1, std::size_t index2) {
6 int temp = vec[index1];
7 vec[index1] = vec[index2];
8 vec[index2] = temp;
9}
10
11// Write your code for the bubble_sort function here.
12
13int main() {
14 std::vector<int> vec = { 5, 1, 4, 2, 8 };
15 bubble_sort (vec);
16 for (std::size_t i = 0; i < vec.size(); ++i) {
17 std::cout << vec[i] << ' ';
18 }
19}
Answer
Below is one way to implement the program. We must loop through all elements
in the vector. Since we know the last i elements are already in place,
our inner loop only goes up to vec.size() - 1 - i. If the next element
is greater than the current element, we swap the two elements.
1#include <cstddef>
2#include <iostream>
3#include <vector>
4
5void swap_values(std::vector<int> &vec, std::size_t index1, std::size_t index2) {
6 int temp = vec[index1];
7 vec[index1] = vec[index2];
8 vec[index2] = temp;
9}
10
11void bubble_sort(std::vector<int> &vec) {
12 for (std::size_t i = 0; i + 1 < vec.size(); ++i) {
13 for (std::size_t j = 0; j + 1 < vec.size() - i; ++j) {
14 if (vec[j] > vec[j + 1]) {
15 swap_values(vec, j, j + 1);
16 }
17 }
18 }
19}
20
21int main() {
22 std::vector<int> vec = { 5, 1, 4, 2, 8 };
23 bubble_sort (vec);
24 for (std::size_t i = 0; i < vec.size(); ++i) {
25 std::cout << vec[i] << ' ';
26 }
27}
13.14.1. Additional coding exercisesΒΆ
Question
How long is a year on other planets? Let's write a program that prints out the number of days in a year on each planet using a switch statement. These values are, in planetary order, 88 days, 225 days, 365 days, 687 days, 4333 days, 10759 days, 30687 days, and 60190 days. Print out this information in the following format: planet
planethasnum_daysnumber of days in a year! Use the code prompt to write your solution.
1#include <iostream>
2
3enum planet { mercury = 1, venus, earth, mars, jupiter, saturn, uranus, neptune };
4
5int main() {
6 planet p = jupiter;
7 // Write your code here.
8}
Question
Now let's generate a
bingo_board! We want to fill the 25spaces on thebingo_boardwith random values from 1 to 75 without repititon. To do this, we'll make avectorof numbers from 1 to 75 and shuffle it using the same method as shown in this chapter. Then we will select the first 25 values for the 25 spaces on thebingo_board. We will do this entire process in multiple steps. First, write the functionrandom_int, which generates a random value between low and high, inclusive. Be sure to include the relevant libraries! Use the code prompt to write your solution.
1#include <iostream>
2// Add any relevant libraries here.
3
4// Write your code for the random_int function here.
Question
Now that we have the functions
random_intandswap_values, we can write the functiongenerate_rand_vec.generate_rand_veccreates avectorwith values from 1 to 75, shuffles it usingrandom_intandswap_values, and returns the shuffledvector. Use the code prompt to write your solution.
1#include <iostream>
2#include <vector>
3#include <cstdlib>
4#include <numeric>
5
6// Write your code for the generate_rand_vec function here.
Question
Let's print out our
bingo_board! Write thebingo_boardmember functionprint_board. Insert tabs between each value in each row to make the board print out neater. Use the code prompt to write your solution.
1#include <cstddef>
2#include <random>
3#include <iostream>
4#include <vector>
5#include <cstdlib>
6#include <numeric>
7
8struct space {
9 int value;
10 bool is_filled;
11};
12
13struct bingo_board {
14 std::vector<std::vector<space> > board;
15 void make_board ();
16 void print_board ();
17};
18
19std::size_t random_int(std::size_t low, std::size_t high);
20void swap_values (std::vector<int> &vec, std::size_t index1, std::size_t index2);
21std::vector<int> generate_rand_vec ();
22
23// Write your code for the print_board function here.
24
25int main() {
26 bingo_board bingo;
27 bingo.make_board ();
28 bingo.print_board ();
29}
Question
You may have noticed that in some cases, our version of
bubble_sortdoes an unnecessary amount of work. For example, if ourvectorwas {1, 2, 3, 5, 4},bubble_sortwould swap 4 and 5, but then keep going even though ourvectoris already in order! We can save some work by including aboolcalledis_changed. If we swap values during a pass, we setis_changedto true. If nothing has been swapped, thenis_changedstays false, and we know to break out of the loop since ourvectoris already sorted. Write the functionfast_bubble_sort, which isbubble_sortwith this modification. Use the code prompt to write your solution.
1#include <cstddef>
2#include <iostream>
3#include <vector>
4
5void swap_values(std::vector<int> &vec, std::size_t index1, std::size_t index2) {
6 int temp = vec[index1];
7 vec[index1] = vec[index2];
8 vec[index2] = temp;
9}
10
11// Write your code for the fast_bubble_sort function here.
12
13int main() {
14 std::vector<int> vec = { 1, 3, 5, 4, 6, 8, 9 };
15 fast_bubble_sort (vec);
16 for (std::size_t i = 0; i < vec.size(); ++i) {
17 std::cout << vec[i] << ' ';
18 }
19}
Question
Write the enumerated type
Dayswhich maps days of the week to integers starting at 1. Use a switch statement to determine whether or not day is a weekend or not. Check for cases in numerical order.
1#include <iostream>
2// YOUR CODE HERE
Answer
Below is one way to use a switch statement to classify a day of the week.
1#include <iostream>
2
3enum m_day { mon = 1, tue, wed, thu, fri, sat, sun };
4
5int main () {
6 m_day m_day = sun;
7 switch (m_day > 5) {
8 case 0:
9 std::cout << "It is not the weekend :(" << '\n';
10 break;
11 case 1:
12 std::cout << "It is the weekend :)" << '\n';
13 break;
14 default:
15 std::cout << "Invalid input." << '\n';
16 break;
17 }
18}
Question
Use a switch statement to check and print out whether a number is divisible by two. Prompt and get input from the user. If input isn't valid, print out the default statement "Invalid input." Check for cases in numerical order.
1#include <iostream>
2// YOUR CODE HERE
Answer
Below is one way to use a switch statement to check and print out whether a number is divisible by two.
1#include <iostream>
2using std::cout;
3
4int main () {
5 int input;
6 cout << "Please enter an integer: ";
7 std::cin >> input;
8 switch (input % 2) {
9 case 0:
10 cout << input << " is even!" << '\n';
11 break;
12 case 1:
13 cout << input << " is odd!" << '\n';
14 break;
15 default:
16 cout << "Invalid input." << '\n';
17 break;
18 }
19}
Question
Use a switch statement to check and print out the maximum between two numbers. Prompt and get input from the user for two integers. If input isn't valid, print out the default statement "Invalid input." Check for cases in numerical order.
1#include <iostream>
2// YOUR CODE HERE
Answer
Below is one way to use a switch statement to check and print out the maximum between two numbers.
1#include <iostream>
2using std::cout;
3
4int main () {
5 int input1;
6 int input2;
7 cout << "Please enter first integer: ";
8 std::cin >> input1;
9 cout << "Please enter second integer: ";
10 std::cin >> input2;
11 switch (input1 > input2) {
12 case 0:
13 cout << "The maximum is " << input2 << '\n';
14 break;
15 case 1:
16 cout << "The maximum is " << input1 << '\n';
17 default:
18 cout << "Invalid input." << '\n';
19 break;
20 }
21}
Question
Write the pseudocode for the implementation of
merge_sort.
1// YOUR PSEUDOCODE HERE
Answer
Below is one way to write the pseudocode of
merge_sort.
1// card_deck card_deck::merge_sort () const {
2// find the midpoint of the deck
3// divide the deck into two subdecks
4// sort the subdecks using sort
5// merge the two halves and return the result
6// divide each subdeck into two more subdecks
7// }
Question
Let's revisit the dictionary data structure defined in the previous section. Write the struct definitions for
entry, which has member variables word and page, and fordictionary, which has a vector of Entries.
1#include <iostream>
2#include <vector>
3// YOUR CODE HERE
Answer
Below is one way to write the struct definition for
entryand fordictionary.
1#include <string>
2#include <iostream>
3#include <vector>
4
5struct entry {
6 std::string word;
7 int page;
8};
9
10struct dictionary {
11 std::vector<entry> entries;
12};
Question
Assume our dictionary is currently unsorted. Let's write a dictionary member function
findthat takes a string word as a parameter and returns the index of its corresponding entry. If the word isn't in the dictionary, return -1.
1#include <iostream>
2#include <vector>
3// YOUR CODE HERE
Answer
Below is one way to write the dictionary member function.
1#include <cstddef>
2#include <string>
3#include <iostream>
4#include <vector>
5
6struct entry {
7 std::string word;
8 int page;
9};
10
11struct dictionary {
12 std::vector<entry> entries;
13public:
14 std::ptrdiff_t find(std::string word);
15};
16
17std::ptrdiff_t dictionary::find (std::string word) {
18 for (std::size_t i = 0; i < entries.size(); ++i) {
19 if (entries[i].word == word) {
20 return static_cast<std::ptrdiff_t>(i);
21 }
22 }
23 return -1;
24}
Question
Of course, all dictionaries are in some sort of order. In order to do this, we must first write the dictionary member function
find_first_word, which takes a starting index as a parameter returns the index of the entry with the highest priority alphabetically (i.e. the entry with a word that would come first in the alphabet).
1#include <iostream>
2#include <vector>
3// YOUR CODE HERE
Answer
Below is one way to write the
find_first_wordmember function.
1#include <cstddef>
2#include <string>
3#include <iostream>
4#include <vector>
5
6struct entry {
7 std::string word;
8 int page;
9};
10
11struct dictionary {
12 std::vector<entry> entries;
13public:
14 std::size_t find_first_word(std::size_t start);
15};
16
17std::size_t dictionary::find_first_word (std::size_t start) {
18 std::size_t min = start;
19 for (std::size_t i = start; i < entries.size(); ++i) {
20 if (entries[i].word < entries[min].word) {
21 min = i;
22 }
23 }
24 return min;
25}
Question
We also need a swap function. Write the dictionary member function
swapwhich takes two indices as parameters and swaps the Entries at those indices.
1#include <iostream>
2#include <vector>
3// YOUR CODE HERE
Answer
Below is one way to write the
swapmember function
1#include <cstddef>
2#include <string>
3#include <iostream>
4#include <vector>
5
6struct entry {
7 std::string word;
8 int page;
9};
10
11struct dictionary {
12 std::vector<entry> entries;
13public:
14 void swap(std::size_t a, std::size_t b);
15};
16
17void dictionary::swap (std::size_t a, std::size_t b) {
18 entry temp = entries[a];
19 entries[a] = entries[b];
20 entries[b] = temp;
21}
Question
Now let's write the dictionary member function
alphabetize, which sorts the Entries in the dictionary in alphabetical order. Use thefind_first_wordandswapfunctions we defined earlier!
1#include <iostream>
2#include <vector>
3// YOUR CODE HERE
Answer
Below is one way to write the dictionary member function
alphabetize.
1#include <algorithm>
2#include <cstddef>
3#include <string>
4#include <vector>
5struct entry { std::string word; std::size_t page; };
6struct dictionary {
7 std::vector<entry> entries;
8 void alphabetize();
9 std::size_t find_first_word(std::size_t start) const {
10 std::size_t lowest = start;
11 for (std::size_t i = start; i < entries.size(); ++i) {
12 if (entries[i].word < entries[lowest].word) lowest = i;
13 }
14 return lowest;
15 }
16};
17void dictionary::alphabetize() {
18 for (std::size_t i = 0; i < entries.size(); ++i) {
19 const std::size_t lowest = find_first_word(i);
20 std::swap(entries[i], entries[lowest]);
21 }
22}
Question
Let's check to see if our sorting worked! Write the dictionary member function
print_dictionary, which prints out the word in each entry.
1#include <iostream>
2#include <vector>
3// YOUR CODE HERE
Answer
Below is one way to write the dictionary member function
print_dictionary.
1#include <cstddef>
2#include <string>
3#include <iostream>
4#include <vector>
5
6struct entry {
7 std::string word;
8 int page;
9};
10
11struct dictionary {
12 std::vector<entry> entries;
13public:
14 void print_dictionary();
15};
16
17void dictionary::print_dictionary () {
18 for (std::size_t i = 0; i < entries.size(); ++i) {
19 std::cout << entries[i].word << '\n';
20 }
21}