CSC 123: C++ Programming
Assignment 3: Extra Credit
Many applications in Computer Science -- including games, statistical analysis, and simulation -- require
the use of randomized data. One way this can manifest is in the generation of random permutations of a
sequence of elements; i.e. a shuffling of these elements.
Shuffling can be achieved by the following algorithm, known as a Fisher–Yates shuffle. You can think of it
as a kind of Selection Sort, where instead of choosing the smallest element, you choose one at random!
for k = last position down to the second
choose a random position r between the first and k
swap the elements at positions k and r
Implement the shuffling algorithm in C++. The program should:
Request the desired number of elements n.
Initialize an array with the elements 0, 1, 2, ..., n – 1 and display it to the console.
Shuffle the elements randomly and display the new arrangement to the console.
You may assume that the user-given n is no greater than 100. Declare a constant to reflect this fact.
The following is a sample interaction. Note that since the shuffling is random, the result will change with each run.
How many elements would you like in the sequence? 10 [Enter]
Initial contents: 0 1 2 3 4 5 6 7 8 9
After shuffling: 2 5 9 4 6 7 0 3 1 8
In order to generate a random integer between 0 and n - 1, you can use the expression rand() % n. This
requires using #include <cstdlib>. Also, place the line srand(time(NULL)); somewhere at the
start of your code so that it is invoked only once. This will set the seed for the random number generator
based on the computer’s clock so the result is different with each run of the program. In order to use this
time function, be sure to #include <ctime>.
Make use of all elements of good programming style, including:
Comments, placing them liberally throughout your code to document it.
Helper functions as needed to break down the tasks into simpler ones using top-down design.
Remember to include a documentation comment for each function, describing what it does and the
role of all of its inputs and outputs. Refer to posted exercise solutions for examples.
The code you submit should be of your own creation. You may adapt code from the examples provided
in the course text, slides, and posted solutions. You may not, however, include code copied from other
sources, including classmates or the web. For more information on academic honesty, please refer to the