SHARE
SPREAD
HELP

The Tradition of Sharing

Help your friends and juniors by posting answers to the questions that you know. Also post questions that are not available.


To start with, Sr2Jr’s first step is to reduce the expenses related to education. To achieve this goal Sr2Jr organized the textbook’s question and answers. Sr2Jr is community based and need your support to fill the question and answers. The question and answers posted will be available free of cost to all.

 

#
Authors:
Walter Savitch ,julia Lobur
Chapter:
Recursion
Exercise:
Programming Projects
Question:11 | ISBN:9780321531346 | Edition: 7

Question

Some problems require finding all permutations (different orderings) of

a set of items. For a set of n items { a1, a2, a3, . . . an } there are

n! permutations. For example, given the set {1, 2, 3} there are six

permutations:

{3, 2, 1} {2, 3, 1} {2, 1, 3} {3, 1, 2} {1, 3, 2} {1, 2, 3}

Write a recursive function that generates all the permutations of a set of

numbers. The general outline of a solution is given here, but the

implementation is up to you. The program will require storing a set of

permutations of numbers that you can implement in many ways (e.g.,

linked lists of nodes, linked lists of vectors, arrays, etc.) Your program

should call the recursive function with sets of several different sizes,

printing the resulting set of permutations for each.

One solution is to first leave out the nth item in the set. Recursively find

all permutations using the set of (n_1) items. If we insert the nth item

into each position for all of these permutations, then we get a new set of

permutations that includes the nth item. The base case is when there is

only one item in the set, in which case the solution is simply the

permutation with the single item.

For example, consider finding all permutations of {1, 2, 3}. We leave the

3 out and recursively find all permutations of the set {1, 2}. This consists

of the permutations:

{1, 2} {2, 1}

Next we insert the 3 into every position for these permutations. For the

first permutation, we insert the 3 in the front, between 1 and 2, and after

2. For the second permutation, we insert the 3 in the front, between 2

and 1, and after 1:

{3, 1, 2} {1, 3, 2} {1, 2, 3} {3, 2, 1} {2, 3, 1} {2, 1, 3}

The resulting six permutations comprise all permutations of the set

{1, 2, 3}.

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Sorry the answer is not available at the moment…

If you are able to find the answer, please make sure to post it here. So that your Juniors have smile on their lips and feel happy.

Spread the 'tradition of sharing'.