Adding counter to bubblesort function - c++

I need to calculate the total number of swapping process and sorting running time for my bubble sort function. For running time, I was successful. But for the total number of swapping processes, I couldn't really understand what to do. I thought of initializing "count" and then tried to call it into the main function. That was a failure.
This if my bubble sort function:
void bubbleSort(T patient[], int size)
{
bool noChange = true; // stop when a pass causes no change
for(int i = size; i > 0; i--)
{
noChange = true;
for(int j = 1; j < i; j++)
{
if(patient[j] < patient[j - 1])
{
swap(patient[j], patient[j-1]);
count = count + 1;
noChange = false;
} // end if
} // end for(j)
if (noChange)
return; // sorted--no need to continue
} // end for(i)
}
"count" seems to show no value when called into the main function. Any tips on what I should try so that I could get the total number of swapping process in this?
EDIT 3:
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <time.h>
#include <string>
#include <ctime>
using namespace std;
const int SIZE = 5;
template <class T>
void printArray(T ar[], int sz);
template <class T>
int bubbleSort(T ar[], int sz);
//////////////////////////////////////////////////////////////////////////
// Main Function Implementation
//////////////////////////////////////////////////////////////////////////
int main() {
int numOfData = 50000;
string line, temp;
ofstream resultFile;
string patient[numOfData];
ifstream dataFile("shufflePatient.txt");
int times,i,count;
cout << "Program to shuffle data" << endl << endl;
cout << "This program will calculate swapping processes and running time.";
/*Storing data*/
cout << "Reading data in process.." << endl;
if (dataFile.is_open()) {
i=-1;
while (dataFile.good()) {
getline (dataFile, line);
if (i>=0) patient[i] = line;
i++;
}
dataFile.close();
}
double start_s=clock();
bubbleSort(patient,SIZE);
double stop_s=clock();
cout << "time: " << (stop_s-start_s)/double(CLOCKS_PER_SEC) << endl;
count = bubbleSort(patient,SIZE) ;
cout << "swapping process : " << count ;
cin.get(); // hold window open
/*Writing to file*/
cout << "Writing to file.." << endl;
resultFile.open ("test.txt");
for (int i=0 ; i<numOfData ; i++) {
resultFile << patient[i] << "\n";
}
resultFile.close();
system("pause");
return 0;
}
//----------------------------------------------------------------------------
// prints array of size size
//----------------------------------------------------------------------------
template <class T>
void printArray(T patient[], int size)
{
for(int i = 0; i < size; i++)
cout << patient[i] << " ";
cout << endl;
}
//----------------------------------------------------------------------------
// sorts array of size size by Bubble Sort method
//----------------------------------------------------------------------------
template <class T>
int bubbleSort(T patient[], int size) //returning an int
{
int count = 0; //initializing count
bool noChange = true;
for(int i = size; i > 0; i--)
{
noChange = true;
for(int j = 1; j < i; j++)
{
if(patient[j] < patient[j - 1])
{
swap(patient[j], patient[j-1]);
count = count + 1;
noChange = false;
}
}
if (noChange)
return count; // returning count
}
return count; // returning count
}
This is my updated code. Count value returns to 0. I don't know if the code I've used is right or wrong (where i call the return value of count). Any thoughts?
PS
Also, after changing my functions from void to int, for some reason my code stops sorting the data alphabetically when its written into the "text" file. Whats up with this?

You are not using the return value from the function, why don't you make the function return int - and return the count of number of swaps:
int bubbleSort(T patient[], int size) //returning an int
{
int count = 0; //initializing count
bool noChange = true;
for(int i = size; i > 0; i--)
{
noChange = true;
for(int j = 1; j < i; j++)
{
if(patient[j] < patient[j - 1])
{
swap(patient[j], patient[j-1]);
count = count + 1;
noChange = false;
}
}
if (noChange)
return count; // returning count
}
return count; // returning count
}
PS
The problem in the original code could be where you declared or initialized count (which is not shown in the code snap).
Also, using local variable is usually a better practice than using global ones.

Related

Having issues eliminating duplicates and sorting from C++ array outfile

Trying to create a list of unique grades from a text file. Having issues with the output eliminating duplicates. Currently, I am trying to compare the value of each previous array entry to the next and if they are different, output the result to the outfile, but is just outputs an empty file.
I am also curious if there is an easy fix to change the sorting from 'low to high' into 'high to low'. Thank you in advance.
#include <iostream>
#include <string>
#include <limits>
#include <cmath>
#include <iomanip>
#include <fstream>
using namespace std;
int testScoreArray[100];
void selectSort(int testScoreArray[], int n);
void fileOutput(int testScoreArray[]);
int main()
{
int n = 100;
ifstream infile;
infile.open("testscoresarrayhomework.txt");
for (int i = 0; i < 100; i++) {
infile >> testScoreArray[i];
}
selectSort(testScoreArray, n);
fileOutput(testScoreArray);
infile.close();
return 0;
}
void selectSort(int testScoreArray[], int n)
{
//pos_min is short for position of min
int pos_min, temp;
for (int i = 0; i < n - 1; i++) {
pos_min = i; //set pos_min to the current index of array
for (int j = i + 1; j < n; j++) {
if (testScoreArray[j] < testScoreArray[pos_min])
pos_min = j;
//pos_min will keep track of the index that min is in, this is needed when a swap happens
}
//if pos_min no longer equals i than a smaller value must have been found, so a swap must occur
if (pos_min != i) {
temp = testScoreArray[i];
testScoreArray[i] = testScoreArray[pos_min];
testScoreArray[pos_min] = temp;
}
}
};
void fileOutput(int testScoreArray[])
{
ofstream outfile;
int gradeEvent = 0;
int previousGrade = 0;
outfile.open("testscoresoutput.txt");
outfile << "Test Score Breakdown: ";
outfile << endl
<< "Score / Occurance";
for (int i = 0; i < 100; i++) {
previousGrade = i;
if (previousGrade && previousGrade != i) {
outfile << '\n' << testScoreArray[i] << " / " << gradeEvent;
}
}
outfile.close();
};
You have declared a global variable testScoreArray and the function names use the same variable name for their parameters. It's best to avoid using global variables when possible. You can remove global declaration, then declare testScoreArray in main, and pass it to your functions. Example:
//int testScoreArray[100]; <=== comment out
void selectSort(int *testScoreArray, int n);
void fileOutput(int *testScoreArray, int n); //add array size
int main()
{
int testScoreArray[100]; //<== add testScoreArray in here
int n = sizeof(testScoreArray) / sizeof(testScoreArray[0]);
selectSort(testScoreArray, n);
fileOutput(testScoreArray, n);
...
}
In fileOutput you are basically checking to see if i != i, you need to examine the array, not indexing in the loop:
void fileOutput(int *testScoreArray, int n)
{
ofstream outfile("testscoresoutput.txt");
for(int i = 0; i < n; i++)
if(i && testScoreArray[i] != testScoreArray[i-1])
outfile << testScoreArray[i] << "\n";
};
To revers the sort, simply change the condition in this comparison
if (testScoreArray[j] < testScoreArray[pos_min])
pos_min = j;
To:
if(testScoreArray[j] > testScoreArray[pos_min])
pos_min = j;
Technically you would rename the variable to pos_max

Identical .txt files w/ different outputs

Using codeblocks, I have written a code that displays an adjacency matrix, BFS and DFS search order, and whether or not graph is bipartite.
The graph is passed as a program argument through main as a .txt file.
I have two identical .txt files with different names and drastically different outputs. I have absolutely no idea why.
for graph0.txt
I have this output
For graphNull.txt
I have this output
With the exception of the file name, the files are identical. I even typed them the exact same way just to make sure. Why is this happening?
#include <iostream>
using namespace std;
#include "Graph.h"
int main(int argc, char *argv[])
{
Graph g;
g.load(argv[1]);
cout << endl << "Adjacency Matrix" << endl;
g.display();
g.displayDFS(0);
g.displayBFS(0);
cout << "Bipartite: ";
if (g.isBipartite())
cout << "TRUE";
else
cout << "FALSE";
cout << endl;
return 0;
}
Graph.h
#ifndef GRAPH_H
#define GRAPH_H
#include "QueueInt.h"
#include "StackInt.h"
class Graph {
public:
Graph(); // constructor
~Graph(); // destructor
// Load the graph from a file
void load(char *filename);
// Display the adjacency matrix
void display() const;
// Display the depth first search from the given vertex
void displayDFS(int vertex) const;
// Display the breadth first search from the given vertex
void displayBFS(int vertex) const;
// Determine whether the graph is bipartite or not
bool isBipartite() const;
private:
string fName;
int numVert;
int** mat;
int* visited;
int* dfs;
void helperDFS(int vertex, int &counter, int* visited, int* dfs) const;
};
#endif
Graph.cpp
#include <iostream>
#include <fstream>
#include <cstdlib>
using namespace std;
#include "Graph.h"
#include "QueueInt.h"
#include "StackInt.h"
// Constructor
Graph::Graph()
{
fName = "";
numVert = 0;
}
// Destructor
Graph::~Graph()
{
delete mat;
delete visited;
delete dfs;
}
// Load the graph from a file
void Graph::load(char* filename)
{
int numStore;
fName = filename;
fstream fin;
fin.open(filename);
fin >> numStore;
numVert = numStore;
mat = new int *[numVert];
int a;
int b;
for (int i = 0; i < numVert ; i++){
//matrix is created
mat[i] = new int[numVert];
for (int j = 0; j < numVert; j++){
mat[i][j] = 0;
}
}
while (fin >> a >> b){
mat[a][b] = 1;
mat[b][a] = 1;
}
}
// Display the adjacency matrix
void Graph::display() const
{
for (int i = 0; i < numVert; i++){
for (int j = 0; j < numVert; j++){
cout << mat[i][j] << " ";
}
cout << "\n";
}
}
// Displays the depth first search starting at the given vertex
void Graph::helperDFS(int vertex, int &counter, int* visited, int* dfs) const {
visited[vertex] = 1;
dfs[counter] = vertex;
counter++;
for (int j = 0; j < numVert; j++){
if (mat[vertex][j] == 1 && visited[j] != 1){
helperDFS(j, counter, visited, dfs);
}
}
}
void Graph::displayDFS(int vertex) const
{
int counter = 0;
int* visited = new int [numVert];
for(int i = 0; i < numVert; i++){
visited[i] = 0;
}
int* dfs = new int [numVert];
helperDFS(vertex, counter, visited, dfs);
cout << "DFS at vertex " << vertex << ": ";
for (int i = 0; i < numVert; i++){
cout << dfs[i] << " ";
}
}
// Perform breadth first search starting at the given vertex
void Graph::displayBFS(int vertex) const
{
int v = vertex;
int vert;
int bfs[numVert];
int counter = 0;
int* visited = new int [numVert];
QueueInt q; //empty q
//create visited array initizalized to false for each vertex
for (int i = 0; i < numVert; i++){
visited[i] = 0;
}
cout << endl;
//mark v as visited
visited[vertex] = 1;
//add v to queue
q.enqueue(vertex);
//process v to array for output
bfs[counter] = vertex;
counter ++;
while(!q.isEmpty()){
vert = q.dequeue();
for (int j = 0; j < numVert; j++){
if (mat[vert][j] == 1 && visited[j]!=1){
visited[j] = 1;
q.enqueue(j);
bfs[counter] = j;
counter ++;
}
}
}
cout << "BFS at vertex " << v << ": ";
for (int i = 0; i < numVert; i++){
cout << bfs[i] << " ";
}
cout << "\n";
}
// Determine whether the graph is bipartite or not
bool Graph::isBipartite() const
{
bool flag = true;
int color[numVert];
//ASSIGN COLOR ELEMENTS TO 0
for (int i = 0; i < numVert; i++){
color[i] = 0;
}
//ASSIGN CURRENT ELEMENT COLOR 1
for (int i =0; i < numVert; i++){
if (color[i] == 0){
color[i] = 1;
}
//ASSIGN ADJACENT ELEMENTS COLOR 2
for (int j = 0; j < numVert; j++){
if (mat[i][j] == 1){
color[j] = 2;
}
}
//FOR ELEMENTS WITH COLOR TWO, CHECK FOR ADJACENCY
for (int j = 0; j < numVert; j++){
if (color[j] == 2){
for (int k = 0; k < numVert; k++){ //will have a self check, but thats not a problem given no self loops
if (color[k] == 2){
if (mat[j][k] == 1){
flag = false;
return flag;
}
}
}
}
}
//RESET COLORS, RUN AGAIN
for (int h = 0; h < numVert; h++){
color[h] = 0;
}
}
return flag;
}
QueueInt.h
#ifndef QUEUEINT_H
#define QUEUEINT_H
#include <queue>
using namespace std;
class QueueInt
{
public:
// Add an integer to the back of the queue.
void enqueue(int val);
// Removes and returns an integer from the front of the queue. Aborts the
// program is the queue is empty.
int dequeue();
// Returns but does not remove the integer at the front of the queue. Aborts the
// program is the queue is empty.
int front() const;
// Returns true if the queue is empty.
bool isEmpty() const;
private:
queue<int> queueObj; // underyling STL queue object
};
#endif // QUEUE_H
QueueInt.cpp
#include <iostream>
#include <cstdlib>
using namespace std;
#include "QueueInt.h"
// Add an integer to the back of the queue.
void QueueInt::enqueue(int val)
{
queueObj.push(val);
}
// Removes and returns an integer from the front of the queue. Aborts the
// program is the queue is empty.
int QueueInt::dequeue()
{
int val = front();
queueObj.pop();
return val;
}
// Returns but does not remove the integer at the front of the queue. Aborts the
// program is the queue is empty.
int QueueInt::front() const
{
if (isEmpty()) {
cerr << "Tried to access empty queue --> aborting program" << endl;
exit(-1);
}
return queueObj.front();
}
// Returns true if the queue is empty.
bool QueueInt::isEmpty() const
{
return queueObj.empty();
}

Function to stall for time with <Windows.h> and continue to other functions

My waitSeconds() functions takes an integer for the number of seconds to wait. I am using the to use Sleep(msec)and converting to seconds at this point I want to try doing it like this and know it's not elegant. However my programs does not execute the rest of my functions calls and I am head banging.
Ultimately, what I want to use this functions call for is to call it with my slowTriangle() function and distressCall() that loops forever with a pause of what the parameter of waitSeconds has been passed through. I hope this last part is making sense. Anyways thank you for any guidance any of you experienced members can provide.
#include <iostream>
#include <Windows.h>
using namespace std;
int dots(int count);
int dashes(int count);
void sendSOS();
void waitSeconds(int seconds2Wait);
int triangle(int rows);
int slowTriangle();
void distressCall();
int main()
{
dots(3);
dashes(3);
sendSOS();
cout << "\n\n ";
waitSeconds(1);
int triangle(4);
int slowTriangle();
void distressCall();
return 0;
}
int dots(int count) // counts DOWN the number of dots that the int is set as a parameter
{
for (; count >= 1; count--)
{
cout << "." ;
}
return 0;
}
int dashes(int count) // counts UP the number of dots that the int is set as a parameter
{
int i;
for (; count >= 1; count--)
{
cout << "-";
}
return 0;
}
void sendSOS()
{
dots(3);
dashes(3);
dots(3);
}
void waitSeconds(int seconds2Wait) //Sleeps for time specified
{
Sleep(1000 * seconds2Wait); //converts miliseconds to seconds
seconds2Wait = 2;
}
int triangle(int rows) //Prints a dot triangle
{
int i, j;
for (i = 1; i <= rows; ++i)
{
for (j = 1; j <= i; ++j)
{
cout << ". ";
}
cout << "\n";
}
return 0;
}
int slowTriangle(int rows) //Prints a dot triangle with sleep paramter passed in
{
int i, j, seconds2Wait;
for (i = 1; i <= rows; ++i)
{
for (j = 1; j <= i; ++j)
waitSeconds(3);
{
cout << ". ";
}
cout << "\n";
}
return 0;
}
void distressCall()
{
sendSOS();
waitSeconds(2);
}
The correct C++ answer is already in the comments: std::this_thread::sleep_for
The WinAPI method (Sleep) is also possible.
The real reason why your "functions" appear to fail is because int triangle(4) defines a new variable in main, initialized to 4. This variable hides the global triangle function.
#include <ctime>
void pause (unsigned int seconds)
{
time_t goal = seconds + time(0);
while (goal > time(0));
}
#include <iostream>
#include <ctime>
using namespace std;
int dots(int count);
int dashes(int count);
void sendSOS();
void waitSeconds(int seconds2Wait);
int triangle(int rows);
int slowTriangle(int rows);
void distressCall();
int main()
{
dots(3);
dashes(3);
sendSOS();
cout << "\n\n";
waitSeconds(1);
triangle(4);
slowTriangle(4);
distressCall();
return 0;
}
int dots(int count) // counts DOWN the number of dots that the int is set as a parameter
{
for (; count >= 1; count--)
{
cout << "." ;
}
return 0;
}
int dashes(int count) // counts UP the number of dots that the int is set as a parameter
{
for (; count >= 1; count--)
{
cout << "-";
}
return 0;
}
void sendSOS()
{
dots(3);
dashes(3);
dots(3);
}
void waitSeconds(int seconds2Wait) //Sleeps for time specified
{
time_t goal = seconds2Wait + time(0);
while (goal > time(0));
}
int triangle(int rows) //Prints a dot triangle
{
int i, j;
for (i = 1; i <= rows; ++i)
{
for (j = 1; j <= i; ++j)
{
cout << ". ";
}
cout << "\n";
}
return 0;
}
int slowTriangle(int rows) //Prints a dot triangle with sleep paramter passed in
{
int i, j;
for (i = 1; i <= rows; ++i)
{
for (j = 1; j <= i; ++j)
{
waitSeconds(3);
cout << ". ";
}
cout << "\n";
}
return 0;
}
void distressCall()
{
sendSOS();
waitSeconds(2);
}
Implemented pause function as suggested and it works as intended now. Kudos to our other friend who wrote the ctime pause function. I also fixed some of your syntax errors :)
If you want distressCall() to run forever make it like this:
void distressCall()
{
while(true)
{
sendSOS();
waitSeconds(2);
}
}
Strongly recommend that you implement an escape mechanism though :).

quicksort string array help c++

This is my code. I don't know how to get the code to run. Im having problems with quicksorting for string.
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <time.h>
#include <string>
#include <ctime>
#include <stdio.h>
using namespace std;
int count;
template <class T>
void printArray(T ar[], int sz);
template <class T>
void bubbleSort(T ar[], int sz);
void quickSortMain(string items[], int ct);
void quickSort(string items[], int left, int right);
//////////////////////////////////////////////////////////////////////////
// Main Function Implementation
//////////////////////////////////////////////////////////////////////////
int main() {
int numOfData = 50000;
string line, temp;
ofstream resultFile;
ofstream tableFile;
double data[100][2];
string patient[numOfData];
ifstream dataFile("shufflePatient.txt");
int i;
int SIZE = 0;
cout << "Program to shuffle data" << endl << endl;
cout << "This program will calculate swapping processes and running time.";
/*Storing data*/
cout << "Reading data in process.." << endl;
if (dataFile.is_open()) {
i=-1;
while (dataFile.good()) {
getline (dataFile, line);
if (i>=0) patient[i] = line;
i++;
}
dataFile.close();
}
SIZE = 5;
quickSortMain(patient, 5);
/*Writing to file*/
cout << "Writing to file.." << endl;
resultFile.open ("test.txt");
for (int i=0 ; i<numOfData ; i++) {
resultFile << patient[i] << "\n";
}
resultFile.close();
system("pause");
return 0;
}
void quickSortMain(string items[], int ct)
{
quickSort(items, 0, ct-1);
}
void quickSort(string items[], int left, int right)
{
int i, j;
char *x;
string temp[10];
i = left;
j = right;
x = items[(left+right)/2];
do {
while((strcmp(items[i],x) < 0) && (i < right)) {
i++;
}
while((strcmp(items[j],x) > 0) && (j > left)) {
j--;
}
if(i <= j) {
strcpy(temp, items[i]);
strcpy(items[i], items[j]);
strcpy(items[j], temp);
i++;
j--;
}
} while(i <= j);
if(left < j) {
quickSort(items, left, j);
}
if(i < right) {
quickSort(items, i, right);
}
}
//----------------------------------------------------------------------------
// prints array of size size
//----------------------------------------------------------------------------
template <class T>
void printArray(T patient[], int size)
{
for(int i = 0; i < size; i++)
cout << patient[i] << " ";
cout << endl;
}
//----------------------------------------------------------------------------
// sorts array of size size by Bubble Sort method
//----------------------------------------------------------------------------
template <class T>
void bubbleSort(T patient[], int size) //returning an int
{
bool noChange = true;
for(int i = size; i > 0; i--)
{
noChange = true;
for(int j = 1; j < i; j++)
{
if(patient[j] < patient[j - 1])
{
swap(patient[j], patient[j-1]);
count = count + 1;
noChange = false;
}
}
if (noChange)
return ;
}
}
The error i got was in this line:
x = items[(left+right)/2];
I changed
char x*; to string x;
I don't know if that was correct. Now the error im getting is that strcmp and strcpy are not declared. Any help on what i should do next?
That's correct, now change
strcmp(items[i],x) < 0
to
items[i] < x
and
strcmp(items[j],x) > 0
to
items[j] > x
and
strcpy(temp, items[i]);
to
temp = items[i];
etc.
But really this is a case of RTFM. If you're competent enough to write a quicksort routine you should be competent enough to look up how std::string works. Being able to access reference information is a very important skill for a programmer.

c++ permutations high numbers (convert code)

I am trying to convert this code that works for '0' - '3' strings to integer so that it will work for higher numbers
#include <string>
#include <iostream>
using namespace std;
void permutate(char[], int );
bool recurse(char[], int );
int main()
{
int strLength;
cout << "Enter your desired length: ";
cin >> strLength;
char strArray[strLength];
for (int i = 0; i<strLength; i++)
strArray[i] = '0';
permutate(strArray, sizeof(strArray));
return 0;
}
void permutate(char charArray[], int length)
{
string wait;
length--;
bool done = false;
while(!done)
{
for (int i = 0; i <= length; i++)
cout << charArray[i];
cout << endl;
if (charArray[length] == '3')
done = recurse(charArray, length);
else
charArray[length] = (char)(charArray[length]+1);
}
}
bool recurse(char charArray[], int length)
{
bool done = false;
int temp = length;
if (temp > 1)
{
charArray[temp] = '0';
if (charArray[temp-1] == '3')
{
temp--;
done = recurse(charArray, temp);
}
else
(charArray[temp-1] = (char)(charArray[temp-1] + 1));
}
else
{
charArray[temp] = '0';
if (charArray[temp-1] == '3')
done = true;
else
charArray[temp-1] = (char)(charArray[temp-1]+1);
}
return done;
}
I changed every char to int,
every '0' = 0, '3' = 3
every (charArray[temp-1] = (char)(charArray[temp-1] + 1)); to charArray[temp-1]++;
I tried to debug but I still can`t make it work :(
Manged to fix it( works for high numbers):
#include <string>
#include <iostream>
using namespace std;
void permutate(int[], int, int );
bool recurse(int[], int, int );
int main()
{
int strLength, nrElem;
cout << "Enter your desired length: ";
cin >> strLength;
cout << "Enter nr elem: ";
cin >> nrElem;
int strArray[strLength];
for (int i = 0; i<strLength; i++)
strArray[i] = 0;
permutate(strArray, strLength, nrElem );
cout << "\nSTOP";
return 0;
}
void permutate(int charArray[], int length, int nrElem)
{
// length--;
bool done = false;
while(!done)
{
for (int i = 0; i < length; i++)
cout << charArray[i] << " ";
cout << endl;
if (charArray[length - 1] == nrElem)
//done = true;
done = recurse(charArray, length, nrElem);
else
charArray[length - 1]++;
}
}
bool recurse(int charArray[], int length, int nrElem)
{
bool done = false;
int temp = length ;
if (temp > 1)
{
charArray[temp] = 0;
if (charArray[temp-1] == nrElem)
{
temp--;
done = recurse(charArray, temp, nrElem);
}
else
charArray[temp-1]++;
}
else
{
charArray[temp] = 0;
if (charArray[temp-1] == nrElem)
done = true;
else
charArray[temp-1]++;
}
return done;
}
In your permutate function, you're incrementing charArray[length] but checking to see if charArray[length - 1] is equal to nrElem, so you never end up calling recurse.
Here is a short piece of code to do the same (not an answer, however it did not look right in a comment field), not sure if you need the recursion, if you do not this code may be of interest:
#include <iostream>
#include <sstream>
using namespace std;
string output(int firstIntSize, int secondIntSize)
{
std::ostringstream oss;
for (int i = 0; i<firstIntSize; i++)
{
for (int j = 0; j< secondIntSize; j++)
{
oss << i << j << " ";
}
}
return oss.str();
}
int main()
{
cout << output(2,3);
return 0;
}
hmmm... Why not simply make a Permutations algorithm and then use a generic function to print whatever you are permutating. Here's how I would do it for strings:
#include <iostream>
#include <string>
template<class T>
void print(T * A, unsigned n){ //for printing purposes
for(unsigned i=0;i<n;i++){
std::cout<<A[i]<<" ";
}
std::cout<<std::endl;
}
void generate_permutations(unsigned k, std::string str, char *A, bool *U){
// k is the position that we need to fill, starts from 0 and goes to the end.
if(k<str.size()) //if k==str.size() then we will print it
for(unsigned i=0;i<str.size();i++){
if(U[i]==0){
A[k]=str[i]; U[i]=1;
generate_permutations(k+1, str, A,U);
U[i]=0; //after the recursion is finished and printed, we can release the letter.
}
}
else
print(A,str.size());
}
int main(){
std::string str;
std::cout<<"Enter the string to be permutated: \n";
std::cin>>str;
int n;
n = str.length(); // You don't really need to ask the user the size of the string he/she wants to enter.
bool *U; // we will keep track of the used letters with the help of this boolean vector
char *A; // we will copy the contents of str here, so that we keep the str intact
U = new bool[n];
for (int i=0;i<n;i++) U[i]=false;
A = new char[n];
for (int i=0;i<n;i++) A[i]=str[i];
generate_permutations(0,str,A,U);
return 0;
}
Now if you want to convert to numbers (ints), it's almost the same:
#include <iostream>
template<class T>
void print(T * A, int n){
for(int i=0;i<n;i++){
std::cout<<A[i]<<" ";
}
std::cout<<std::endl;
}
void generate_permutations(int k, int *A, bool *U, int n){
if(k==n)
print(A,n);
else {
for(int i=0;i<n;i++){
if(U[i]==0){
A[k]=i; U[i]=1;
generate_permutations(k+1,A,U,n);
U[i]=0;
}
}
}
}
int main(){
int n;
std::cout<<"Permutations of how many objects? \n";
std::cin>>n;
int * A;
bool *U;
A = new int[n];
U = new bool[n];
for (int i=0;i<n;i++) U[i]=false;
print(U, n);
generate_permutations(0,A,U,n);
return 0;
}