
Wentworth Institute of Technology
Division of Professional and Continuing Studies
COMP385 Section 71 - Data Structures II - Fall, 2006
Homework 2 – Permutations
Instructor: Bob Goldstein (617) 912-2512
bobg@vision.eri.harvard.edu
http://webpages.charter.net/tlgcreations/Courses/index.html
http://goldstein.eri.harvard.edu/courses/index.html
http://myweb.wit.edu/goldsteinr/Courses/index.html
Due Date: September 19, 2006
Hand In: Printout of program code and dialogue of how it runs.
Purpose:
This homework is intended to use recursion to generate all possible permutations of an array-based list.
Description:
Write a recursive method, named permute, to calculate all permutations of an array of Character objects (use the
wrapper Character class). YOU MUST test your recursive method with the following main program:
Character testArray[] = {'a','b','c','d'};
Character allPermutations[][];
allPermutations = permute(testArray);
// print out the results, one row on a line
for(int i=0; i<allPermutations.length;i++)
{
for(int j=0;j<allPermutations[i].length;j++)
System.out.print(allPermutations[i][j]+ " ");
System.out.println();
}
Here is the output for a 3 item array and a 4 item array. Note that the number of permutations of n items is n factorial.
NOTE that the calling program does not need to know the size of the returned array, since it can determine it using the lengthe
property of arrays. ALSO note that permute does not do any printing. It just makes a large array and returns a reference to that
array so that the calling program can print it.
6 Permutations
of 3 items
24 permutations
of 4 items
a b c
a c b
b a c
b c a
c a b
c b a
a b c d
a b d c
a c b d
a c d b
a d b c
a d c b
b a c d
b a d c
b c a d
b c d a
b d a c
b d c a
c a b d
c a d b
c b a d
c b d a
c d a b
c d b a
d a b c
d a c b
d b a c
d b c a
d c a b
d c b a
The recursive algorithm is as follows: For an array of size n, make a 2D array within the method of size n factorial
rows by n columns, and return the reference to that array as the result.
- If n=2, then the permutations are { {a,b}, {b,a}}
- If n> 2, then call itself n times with arrays of size n-1. Construct the n arrays by removing 1 element at a time from
the input array. Build up the result by tacking on the removed item to the front of the returned elements. So, for
example, to calculate the permutations of [a,b,c,d], you would call permute 4 times as follows:
a + [the permutations of b,c,d] (there are 6 of these)
b + [the permutations of a,c,d] (there are 6 of these)
c + [the permuations of a,b,d] (there are 6 of these)
d + [the permuations of [a,b,c] (there are 6 of these)
Extra Credit:
Write permute as a generic method, so that you can permute lists of ANY object. IE, permute can then be called as
follows: permute( {“cat”, “dog”, “cow”, “rat”});
/app/work/qkdcmo-481263-2765056-homework2-doc.doc 1 12/4/2020 12/4/2020