Task 3: All permutations
Task
In this exercise, you are going to implement a function which computes the set of all permutations of a given string.
Note: This task naturally lends itself to a recursive implementation.
Example
The string "abc" has the following set of permutations:
{ abc, acb, bac, bca, cab, cba }
The Set class
A set class is implemented in set.h
and set.ipp
. This class
implements a number of useful operations on sets. For an overview of
its functionalities, please refer to the Power Set code example. Note
that you do not need to understand any of the code in set.h
and
set.ipp
in order to use it!
Input & Output
When the program starts, you are first prompted to enter a string.
Then, the program computes the set of all permutations using the function all_permutations. Finally, the resulting set is printed to the console.
Example
String: abc
Permutations:
{abc,acb,bac,bca,cab,cba}
Hint: You may find the substr method useful. The method is documented here.
Solution
#include "pair_sum.h"
#include <climits>
// PRE: for any two indices i and j, v[i] + v[j] ≤ INT_MAX
// POST: returns the number of indices (i,j), i<j of a vector v
// that corresponds to the given iterator range such that
// v[i] + v[j] == sum.
int pairs_with_sum(int sum, iterator begin, iterator end) {
int count = 0;
int size = end - begin;
for (int i = 0; i < size; ++i) {
for (int j = i + 1; j < size; ++j) {
iterator cur_begin = begin + i;
iterator cur_end = begin + j;
if (*cur_begin + *cur_end == sum)
++count;
}
}
return count;
}
Made by JirR02 in Switzerland 🇨🇭