Question: I'm trying to create a program that prints permutations of a string (in lexicographical order) given a number of permutations but my program does not
I'm trying to create a program that prints permutations of a string (in lexicographical order) given a number of permutations but my program does not seem to be working correctly, I need some help in debugging. It works for certain cases like if I input 2 chpt it will print out permutations correctly (chpt, chtp) but if I try a larger permutation number like 20 024789 it won't print out the permutations correctly. This program uses John trotter algorithm which is required for the assignment. 


#include "csce310hw01pt02.h"
#include
#include
using namespace std;
bool LEFT_TO_RIGHT = true;
bool RIGHT_TO_LEFT = false;
//utility function to find the largest k element.
int getMobile(string word, bool direction[]) {
int k = 0 , prevK = 0;
for(int i = 0; i
//if direction of arrow is pointing to the left and an element is larger than last element and that element is larger than what k was last, k becomes that new larger element. Thus, we found largest k.
if(direction[word[i]-1] == RIGHT_TO_LEFT && i != 0) {
if(word[i] > word[i-1] && word[i] > prevK) {
k = word[i];
prevK = k;
}
}
//same idea with arrow pointing opposite direction
if(direction[word[i]-1] == LEFT_TO_RIGHT && i != word.length() - 1) {
if(word[i] > word[i+1] && word[i] > prevK) {
k = word[i];
prevK = k;
}
}
}
return k;
}
//function to find position of k in the string
int mobilePosition(string word, int k) {
int r = 0;
for(int i = 0; i
if(word[i] == k) {
r = i+1;
}
}
return r;
}
void printPermutations(string word, int permutations) {
//store current direction
bool direction[word.length()];
for(int i = 0; i
cout
}
cout
//set initial arrow direction from right to left
for(int i = 0; i
direction[i] = RIGHT_TO_LEFT;
}
for(int j = 1; j
int k = getMobile(word, direction);
int positionK = mobilePosition(word, k);
if(direction[word[positionK - 1] - 1] == RIGHT_TO_LEFT) {
swap(word[positionK - 1], word[positionK - 2]);
} else if(direction[word[positionK - 1] - 1] == LEFT_TO_RIGHT) {
swap(word[positionK], word[positionK - 1]);
}
//swapping elements based on the direction of arrow
for(int m = 0; m
if(word[m] > k) {
if(direction[word[m] - 1] == LEFT_TO_RIGHT) {
direction[word[m] - 1] = RIGHT_TO_LEFT;
} else if(direction[word[m] - 1] == RIGHT_TO_LEFT) {
direction[word[m] - 1] = LEFT_TO_RIGHT;
}
}
}
for(int i = 0; i cout } cout } }
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
