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;
}
Related
I'm trying to rotate my string with 'r' places but facing some problem.The following is my code(function).Please help.
For eg: hello coding. after r=3 should become ng.hello codi.
void fnc(){
char a[100],key;
int n,r,i,t=1,total=0,count,x;
cin>>n; //no. of test cases
while(t<=n){
cin>>r; //no. of rotations
cin.get();
cin.get(a,100);
for(i=0; a[i]!= '\0'; i++){
//cout<<a[i];
total++;
}
cout<<total;
for(i=0; i<r; i++){
key = a[total-1];
cout<<"key: "<<key<<endl;
for(i=total-2; i>=0; i--){
a[i+1] = a[i];
}
a[0] = key;
}
for(i=0; a[i]!= '\0'; i++){
cout<<a[i];
}
///cout<<a<<endl;
t++;
}
}
Here is a way of doing this using only iterators:
#include <string>
#include <iostream>
using namespace std;
int mod(int a, unsigned int b) {
int ret = a % b;
return ret>=0 ? ret : b + ret;
}
string rotate(const string sentence, int rotation) {
rotation = mod(rotation, sentence.size());
string rotatedSentence;
for(auto itr=sentence.begin(); itr < sentence.end(); ++itr) {
if (distance(sentence.begin(), itr) < rotation) {
rotatedSentence.push_back(*(itr + sentence.size() - rotation));
} else {
rotatedSentence.push_back(*(itr - rotation));
}
}
return rotatedSentence;
}
int main() {
const string sentence = "hello coding.";
cout << sentence << endl;
cout << rotate(sentence, 3) << endl; //prints ng.hello codi
return 0;
}
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.
I have an array, and the user can insert a string.
And I have this code:
int main(){
char anagrama[13];
cin >> anagrama;
for(int j = 0; j < strlen(anagrama); j++){
cout << anagrama[j];
for(int k = 0; k < strlen(anagrama); k++){
if(j != k)
cout << anagrama[k];
}
cout << endl;
}
}
The problem is that I need all permutations of the string in sorted order.
For example if the user write: abc, the output must to be:
abc
acb
bac
bca
cab
cba
and my code doesn't show all permutations, and not sorted
Can you help me?
I need do the implementation without a function already implemented.
I think with a recursive function, but I do not know how.
This is an example:
http://www.disfrutalasmatematicas.com/combinatoria/combinaciones-permutaciones-calculadora.html without repetition and sorted
In C++ you can use std::next_permutation to go through permutations one by one. You need to sort the characters alphabetically before calling std::next_permutation for the first time:
cin>>anagrama;
int len = strlen(anagrama);
sort(anagrama, anagrama+len);
do {
cout << anagrama << endl;
} while (next_permutation(anagrama, anagrama+len));
Here is a demo on ideone.
If you must implement permutations yourself, you could borrow the source code of next_permutation, or choose a simpler way of implementing a permutation algorithm recursively.
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
void permute(string select, string remain){
if(remain == ""){
cout << select << endl;
return;
}
for(int i=0;remain[i];++i){
string wk(remain);
permute(select + remain[i], wk.erase(i, 1));
}
}
int main(){
string anagrama;
cout << "input character set >";
cin >> anagrama;
sort(anagrama.begin(), anagrama.end());
permute("", anagrama);
}
Another version
#include <iostream>
#include <string>
#include <vector>
#include <iterator>
#include <algorithm>
using namespace std;
void permute(string& list, int level, vector<string>& v){
if(level == list.size()){
v.push_back(list);
return;
}
for(int i=level;list[i];++i){
swap(list[level], list[i]);
permute(list, level + 1, v);
swap(list[level], list[i]);
}
}
int main(){
string anagrama;
vector<string> v;
cout << "input character set >";
cin >> anagrama;
permute(anagrama, 0, v);
sort(v.begin(), v.end());
copy(v.begin(), v.end(), ostream_iterator<string>(cout, "\n"));
}
#alexander the output of this programme is in exact order as requested by you:
HERE, is a simplest code for generating all combination/permutations of a given array without including some special libraries (only iostream.h and string are included) and without using some special namespaces than usual ( only namespace std is used).
void shuffle_string_algo( string ark )
{
//generating multi-dimentional array:
char** alpha = new char*[ark.length()];
for (int i = 0; i < ark.length(); i++)
alpha[i] = new char[ark.length()];
//populating given string combinations over multi-dimentional array
for (int i = 0; i < ark.length(); i++)
for (int j = 0; j < ark.length(); j++)
for (int n = 0; n < ark.length(); n++)
if( (j+n) <= 2 * (ark.length() -1) )
if( i == j-n)
alpha[i][j] = ark[n];
else if( (i-n)== j)
alpha[i][j] = ark[ ark.length() - n];
if(ark.length()>=2)
{
for(int i=0; i<ark.length() ; i++)
{
char* shuffle_this_also = new char(ark.length());
int j=0;
//storing first digit in golobal array ma
ma[v] = alpha[i][j];
//getting the remaning string
for (; j < ark.length(); j++)
if( (j+1)<ark.length())
shuffle_this_also[j] = alpha[i][j+1];
else
break;
shuffle_this_also[j]='\0';
//converting to string
string send_this(shuffle_this_also);
//checking if further combinations exist or not
if(send_this.length()>=2)
{
//review the logic to get the working idea of v++ and v--
v++;
shuffle_string_algo( send_this);
v--;
}
else
{
//if, further combinations are not possiable print these combinations
ma[v] = alpha[i][0];
ma[++v] = alpha[i][1];
ma[++v] = '\0';
v=v-2;
string disply(ma);
cout<<++permutaioning<<":\t"<<disply<<endl;
}
}
}
}
and main:
int main()
{
string a;
int ch;
do
{
system("CLS");
cout<<"PERMUNATING BY ARK's ALGORITH"<<endl;
cout<<"Enter string: ";
fflush(stdin);
getline(cin, a);
ma = new char[a.length()];
shuffle_string_algo(a);
cout<<"Do you want another Permutation?? (1/0): ";
cin>>ch;
} while (ch!=0);
return 0;
}
HOPE! it helps you! if you are having problem with understanding logic just comment below and i will edit.
/*Think of this as a tree. The depth of the tree is same as the length of string.
In this code, I am starting from root node " " with level -1. It has as many children as the characters in string. From there onwards, I am pushing all the string characters in stack.
Algo is like this:
1. Put root node in stack.
2. Loop till stack is empty
2.a If backtracking
2.a.1 loop from last of the string character to present depth or level and reconfigure datastruture.
2.b Enter the present char from stack into output char
2.c If this is leaf node, print output and continue with backtracking on.
2.d Else find all the neighbors or children of this node and put it them on stack. */
class StringEnumerator
{
char* m_string;
int m_length;
int m_nextItr;
public:
StringEnumerator(char* str, int length): m_string(new char[length + 1]), m_length(length) , m_Complete(m_length, false)
{
memcpy(m_string, str, length);
m_string[length] = 0;
}
StringEnumerator(const char* str, int length): m_string(new char[length + 1]), m_length(length) , m_Complete(m_length, false)
{
memcpy(m_string, str, length);
m_string[length] = 0;
}
~StringEnumerator()
{
delete []m_string;
}
void Enumerate();
};
const int MAX_STR_LEN = 1024;
const int BEGIN_CHAR = 0;
struct StackElem
{
char Elem;
int Level;
StackElem(): Level(0), Elem(0){}
StackElem(char elem, int level): Elem(elem), Level(level){}
};
struct CharNode
{
int Max;
int Curr;
int Itr;
CharNode(int max = 0): Max(max), Curr(0), Itr(0){}
bool IsAvailable(){return (Max > Curr);}
void Increase()
{
if(Curr < Max)
Curr++;
}
void Decrease()
{
if(Curr > 0)
Curr--;
}
void PrepareItr()
{
Itr = Curr;
}
};
void StringEnumerator::Enumerate()
{
stack<StackElem> CStack;
int count = 0;
CStack.push(StackElem(BEGIN_CHAR,-1));
char answerStr[MAX_STR_LEN];
memset(answerStr, 0, MAX_STR_LEN);
bool forwardPath = true;
typedef std::map<char, CharNode> CharMap;
typedef CharMap::iterator CharItr;
typedef std::pair<char, CharNode> CharPair;
CharMap mCharMap;
CharItr itr;
//Prepare Char Map
for(int i = 0; i < m_length; i++)
{
itr = mCharMap.find(m_string[i]);
if(itr != mCharMap.end())
{
itr->second.Max++;
}
else
{
mCharMap.insert(CharPair(m_string[i], CharNode(1)));
}
}
while(CStack.size() > 0)
{
StackElem elem = CStack.top();
CStack.pop();
if(elem.Level != -1) // No root node
{
int currl = m_length - 1;
if(!forwardPath)
{
while(currl >= elem.Level)
{
itr = mCharMap.find(answerStr[currl]);
if((itr != mCharMap.end()))
{
itr->second.Decrease();
}
currl--;
}
forwardPath = true;
}
answerStr[elem.Level] = elem.Elem;
itr = mCharMap.find(elem.Elem);
if((itr != mCharMap.end()))
{
itr->second.Increase();
}
}
//If leaf node
if(elem.Level == (m_length - 1))
{
count++;
cout<<count<<endl;
cout<<answerStr<<endl;
forwardPath = false;
continue;
}
itr = mCharMap.begin();
while(itr != mCharMap.end())
{
itr->second.PrepareItr();
itr++;
}
//Find neighbors of this elem
for(int i = 0; i < m_length; i++)
{
itr = mCharMap.find(m_string[i]);
if(/*(itr != mCharMap.end()) &&*/ (itr->second.Itr < itr->second.Max))
{
CStack.push(StackElem(m_string[i], elem.Level + 1));
itr->second.Itr++;
}
}
}
}
I wrote one without a function already implemented even any templates and containers. actually it was written in C first, but has been transform to C++.
easy to understand but poor efficiency, and its output is what you want, sorted.
#include <iostream>
#define N 4
using namespace std;
char ch[] = "abcd";
int func(int n) {
int i,j;
char temp;
if(n==0) {
for(j=N-1;j>=0;j--)
cout<<ch[j];
cout<<endl;
return 0;
}
for(i=0;i<n;i++){
temp = ch[i];
for(j=i+1;j<n;j++)
ch[j-1] = ch[j];
ch[n-1] = temp;
//shift
func(n-1);
for(j=n-1;j>i;j--)
ch[j] = ch[j-1];
ch[i] = temp;
//and shift back agian
}
return 1;
}
int main(void)
{
func(N);
return 0;
}
In case you have std::vector of strings then you can 'permute' the vector items as below.
C++14 Code
#include <iostream>
#include <algorithm>
#include <iostream>
#include <string>
#include <vector>
#include <boost/algorithm/string/join.hpp>
using namespace std;
int main() {
// your code goes here
std::vector<std::string> s;
s.push_back("abc");
s.push_back("def");
s.push_back("ghi");
std::sort(s.begin(), s.end());
do
{
std::cout << boost::algorithm::join(s,"_") << std::endl ;
} while(std::next_permutation(s.begin(), s.end()));
return 0;
}
Output:
abc_def_ghi
abc_ghi_def
def_abc_ghi
def_ghi_abc
ghi_abc_def
ghi_def_abc
I have an array, and the user can insert a string.
And I have this code:
int main(){
char anagrama[13];
cin >> anagrama;
for(int j = 0; j < strlen(anagrama); j++){
cout << anagrama[j];
for(int k = 0; k < strlen(anagrama); k++){
if(j != k)
cout << anagrama[k];
}
cout << endl;
}
}
The problem is that I need all permutations of the string in sorted order.
For example if the user write: abc, the output must to be:
abc
acb
bac
bca
cab
cba
and my code doesn't show all permutations, and not sorted
Can you help me?
I need do the implementation without a function already implemented.
I think with a recursive function, but I do not know how.
This is an example:
http://www.disfrutalasmatematicas.com/combinatoria/combinaciones-permutaciones-calculadora.html without repetition and sorted
In C++ you can use std::next_permutation to go through permutations one by one. You need to sort the characters alphabetically before calling std::next_permutation for the first time:
cin>>anagrama;
int len = strlen(anagrama);
sort(anagrama, anagrama+len);
do {
cout << anagrama << endl;
} while (next_permutation(anagrama, anagrama+len));
Here is a demo on ideone.
If you must implement permutations yourself, you could borrow the source code of next_permutation, or choose a simpler way of implementing a permutation algorithm recursively.
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
void permute(string select, string remain){
if(remain == ""){
cout << select << endl;
return;
}
for(int i=0;remain[i];++i){
string wk(remain);
permute(select + remain[i], wk.erase(i, 1));
}
}
int main(){
string anagrama;
cout << "input character set >";
cin >> anagrama;
sort(anagrama.begin(), anagrama.end());
permute("", anagrama);
}
Another version
#include <iostream>
#include <string>
#include <vector>
#include <iterator>
#include <algorithm>
using namespace std;
void permute(string& list, int level, vector<string>& v){
if(level == list.size()){
v.push_back(list);
return;
}
for(int i=level;list[i];++i){
swap(list[level], list[i]);
permute(list, level + 1, v);
swap(list[level], list[i]);
}
}
int main(){
string anagrama;
vector<string> v;
cout << "input character set >";
cin >> anagrama;
permute(anagrama, 0, v);
sort(v.begin(), v.end());
copy(v.begin(), v.end(), ostream_iterator<string>(cout, "\n"));
}
#alexander the output of this programme is in exact order as requested by you:
HERE, is a simplest code for generating all combination/permutations of a given array without including some special libraries (only iostream.h and string are included) and without using some special namespaces than usual ( only namespace std is used).
void shuffle_string_algo( string ark )
{
//generating multi-dimentional array:
char** alpha = new char*[ark.length()];
for (int i = 0; i < ark.length(); i++)
alpha[i] = new char[ark.length()];
//populating given string combinations over multi-dimentional array
for (int i = 0; i < ark.length(); i++)
for (int j = 0; j < ark.length(); j++)
for (int n = 0; n < ark.length(); n++)
if( (j+n) <= 2 * (ark.length() -1) )
if( i == j-n)
alpha[i][j] = ark[n];
else if( (i-n)== j)
alpha[i][j] = ark[ ark.length() - n];
if(ark.length()>=2)
{
for(int i=0; i<ark.length() ; i++)
{
char* shuffle_this_also = new char(ark.length());
int j=0;
//storing first digit in golobal array ma
ma[v] = alpha[i][j];
//getting the remaning string
for (; j < ark.length(); j++)
if( (j+1)<ark.length())
shuffle_this_also[j] = alpha[i][j+1];
else
break;
shuffle_this_also[j]='\0';
//converting to string
string send_this(shuffle_this_also);
//checking if further combinations exist or not
if(send_this.length()>=2)
{
//review the logic to get the working idea of v++ and v--
v++;
shuffle_string_algo( send_this);
v--;
}
else
{
//if, further combinations are not possiable print these combinations
ma[v] = alpha[i][0];
ma[++v] = alpha[i][1];
ma[++v] = '\0';
v=v-2;
string disply(ma);
cout<<++permutaioning<<":\t"<<disply<<endl;
}
}
}
}
and main:
int main()
{
string a;
int ch;
do
{
system("CLS");
cout<<"PERMUNATING BY ARK's ALGORITH"<<endl;
cout<<"Enter string: ";
fflush(stdin);
getline(cin, a);
ma = new char[a.length()];
shuffle_string_algo(a);
cout<<"Do you want another Permutation?? (1/0): ";
cin>>ch;
} while (ch!=0);
return 0;
}
HOPE! it helps you! if you are having problem with understanding logic just comment below and i will edit.
/*Think of this as a tree. The depth of the tree is same as the length of string.
In this code, I am starting from root node " " with level -1. It has as many children as the characters in string. From there onwards, I am pushing all the string characters in stack.
Algo is like this:
1. Put root node in stack.
2. Loop till stack is empty
2.a If backtracking
2.a.1 loop from last of the string character to present depth or level and reconfigure datastruture.
2.b Enter the present char from stack into output char
2.c If this is leaf node, print output and continue with backtracking on.
2.d Else find all the neighbors or children of this node and put it them on stack. */
class StringEnumerator
{
char* m_string;
int m_length;
int m_nextItr;
public:
StringEnumerator(char* str, int length): m_string(new char[length + 1]), m_length(length) , m_Complete(m_length, false)
{
memcpy(m_string, str, length);
m_string[length] = 0;
}
StringEnumerator(const char* str, int length): m_string(new char[length + 1]), m_length(length) , m_Complete(m_length, false)
{
memcpy(m_string, str, length);
m_string[length] = 0;
}
~StringEnumerator()
{
delete []m_string;
}
void Enumerate();
};
const int MAX_STR_LEN = 1024;
const int BEGIN_CHAR = 0;
struct StackElem
{
char Elem;
int Level;
StackElem(): Level(0), Elem(0){}
StackElem(char elem, int level): Elem(elem), Level(level){}
};
struct CharNode
{
int Max;
int Curr;
int Itr;
CharNode(int max = 0): Max(max), Curr(0), Itr(0){}
bool IsAvailable(){return (Max > Curr);}
void Increase()
{
if(Curr < Max)
Curr++;
}
void Decrease()
{
if(Curr > 0)
Curr--;
}
void PrepareItr()
{
Itr = Curr;
}
};
void StringEnumerator::Enumerate()
{
stack<StackElem> CStack;
int count = 0;
CStack.push(StackElem(BEGIN_CHAR,-1));
char answerStr[MAX_STR_LEN];
memset(answerStr, 0, MAX_STR_LEN);
bool forwardPath = true;
typedef std::map<char, CharNode> CharMap;
typedef CharMap::iterator CharItr;
typedef std::pair<char, CharNode> CharPair;
CharMap mCharMap;
CharItr itr;
//Prepare Char Map
for(int i = 0; i < m_length; i++)
{
itr = mCharMap.find(m_string[i]);
if(itr != mCharMap.end())
{
itr->second.Max++;
}
else
{
mCharMap.insert(CharPair(m_string[i], CharNode(1)));
}
}
while(CStack.size() > 0)
{
StackElem elem = CStack.top();
CStack.pop();
if(elem.Level != -1) // No root node
{
int currl = m_length - 1;
if(!forwardPath)
{
while(currl >= elem.Level)
{
itr = mCharMap.find(answerStr[currl]);
if((itr != mCharMap.end()))
{
itr->second.Decrease();
}
currl--;
}
forwardPath = true;
}
answerStr[elem.Level] = elem.Elem;
itr = mCharMap.find(elem.Elem);
if((itr != mCharMap.end()))
{
itr->second.Increase();
}
}
//If leaf node
if(elem.Level == (m_length - 1))
{
count++;
cout<<count<<endl;
cout<<answerStr<<endl;
forwardPath = false;
continue;
}
itr = mCharMap.begin();
while(itr != mCharMap.end())
{
itr->second.PrepareItr();
itr++;
}
//Find neighbors of this elem
for(int i = 0; i < m_length; i++)
{
itr = mCharMap.find(m_string[i]);
if(/*(itr != mCharMap.end()) &&*/ (itr->second.Itr < itr->second.Max))
{
CStack.push(StackElem(m_string[i], elem.Level + 1));
itr->second.Itr++;
}
}
}
}
I wrote one without a function already implemented even any templates and containers. actually it was written in C first, but has been transform to C++.
easy to understand but poor efficiency, and its output is what you want, sorted.
#include <iostream>
#define N 4
using namespace std;
char ch[] = "abcd";
int func(int n) {
int i,j;
char temp;
if(n==0) {
for(j=N-1;j>=0;j--)
cout<<ch[j];
cout<<endl;
return 0;
}
for(i=0;i<n;i++){
temp = ch[i];
for(j=i+1;j<n;j++)
ch[j-1] = ch[j];
ch[n-1] = temp;
//shift
func(n-1);
for(j=n-1;j>i;j--)
ch[j] = ch[j-1];
ch[i] = temp;
//and shift back agian
}
return 1;
}
int main(void)
{
func(N);
return 0;
}
In case you have std::vector of strings then you can 'permute' the vector items as below.
C++14 Code
#include <iostream>
#include <algorithm>
#include <iostream>
#include <string>
#include <vector>
#include <boost/algorithm/string/join.hpp>
using namespace std;
int main() {
// your code goes here
std::vector<std::string> s;
s.push_back("abc");
s.push_back("def");
s.push_back("ghi");
std::sort(s.begin(), s.end());
do
{
std::cout << boost::algorithm::join(s,"_") << std::endl ;
} while(std::next_permutation(s.begin(), s.end()));
return 0;
}
Output:
abc_def_ghi
abc_ghi_def
def_abc_ghi
def_ghi_abc
ghi_abc_def
ghi_def_abc
Firstly, this is for a class so there are limitations on what we can and can't do, plus I am extremely new to c++ and programming in general, so that is why the code is probably a little crap.
I am at my wits end trying to understand why when I display the item_list using the first set of cout lines within the first for loop, it displays each individual item as it should be (its a list of skyrim ingredients and their effects).
However, when the second for loop executes, the item_list is filled with nothing but the last item that should have been inserted (wisp wrappings and their effects).
Even just pointing me in the right direction would be GREATLY appreciated :)
cheers
int client::fill_list(int size_in, int h1size, int h2size)
{
char temp[ASIZE] = {'\0'};
int j = 0;
ifstream ifile;
ifile.open("test.txt");
if(ifile.is_open())
{
for(int i = 0; i < size_in; ++i)
{
if(ifile.good())
{
j = 0;
do
{
temp[j] = char(ifile.get());
++j;
}while(ifile.peek() != '*');
temp[j] = char(ifile.get());
copy(client_item.name, temp, j);
}
if(ifile.good())
{
j = 0;
do
{
temp[j] = char(ifile.get());
++j;
}while(ifile.peek() != '*');
temp[j] = char(ifile.get());
copy(client_item.effect1, temp, j);
}
if(ifile.good())
{
j = 0;
do
{
temp[j] = char(ifile.get());
++j;
}while(ifile.peek() != '*');
temp[j] = char(ifile.get());
copy(client_item.effect2, temp, j);
}
if(ifile.good())
{
j = 0;
do
{
temp[j] = char(ifile.get());
++j;
}while(ifile.peek() != '*');
temp[j] = char(ifile.get());
copy(client_item.effect3, temp, j);
}
if(ifile.good())
{
j = 0;
do
{
temp[j] = char(ifile.get());
++j;
}while(ifile.peek() != '*');
temp[j] = char(ifile.get());
copy(client_item.effect4, temp, j);
}
reference.into_list(i,client_item);
cout << reference.item_list[i].name;
cout << reference.item_list[i].effect1;
cout << reference.item_list[i].effect2;
cout << reference.item_list[i].effect3;
cout << reference.item_list[i].effect4;
getchar();
}
}
for(int k = 0; k < SIZE; ++k)
{
cout << reference.item_list[k].name;
cout << reference.item_list[k].effect1;
cout << reference.item_list[k].effect2;
cout << reference.item_list[k].effect3;
cout << reference.item_list[k].effect4;
}
getchar();
return 0;
}
...
int table::into_list(int index, item&item_in)
{
if(index < SIZE)
{
item_list[index] = item_in;
return 0;
}
else
return 1;
}
...
Header for the table class
#include "hash.h"
class table
{
public:
table()
{
item_list = new item [SIZE];
}
~table();
int fill(item*);
int insert(item&, nHash&);
int insert(item&, eHash&, int);
int retrieve(char*,item*,int);
int remove(int,item&);
int remove(int);
int check_hash(int,int,int);
int keygen(char*, int);
int from_list(int, item&);
int into_list(int, item&);
//private:
item * item_list;
nHash name_table;
eHash ef1_table;
eHash ef2_table;
eHash ef3_table;
eHash ef4_table;
};
....
Beginning of main
#include "client.h"
int main()
{
client program;
program.fill_list(SIZE,HNSIZE,HESIZE);
for(int i = 0; i < SIZE; ++i)
{
cout << program.reference.item_list[i].name;
cout << program.reference.item_list[i].effect1 << endl;
cout << program.reference.item_list[i].effect2 << endl;
cout << program.reference.item_list[i].effect3 << endl;
cout << program.reference.item_list[i].effect4 << endl;
}
....
item header
#include <iostream>
#include <fstream>
#include <cctype>
#include <cstdlib>
#include <cstring>
#include <cmath>
using namespace std;
const int ASIZE = 30;
const int SIZE = 92;
const int HNSIZE = 41;
const int HESIZE = 17;
struct item
{
item();
~item();
char * name;
char * effect1;
char * effect2;
char * effect3;
char * effect4;
int count;
//int keygen(int,int);
/*int name_key;
int ef1_key;
int ef2_key;
int ef3_key;
int ef4_key;*/
};
It's possible that part of the problem is how you make copies of client_item here:
reference.into_list(i,client_item);
This just assigns client_item to item_list like so:
item_list[index] = item_in;
...but since item is defined like this:
struct item
{
item();
~item();
char * name;
char * effect1;
...
...all of the items in item_list will have pointers (like name, etc.) that point to the same memory as the memory in client_item.
For example, after each assignment, the pointers item_list[index].name and item_in.name will have the same value. (You can check that by printing both pointers, if you're curious.) Since they both point to the same memory, if you change what's stored at that memory, both objects will appear to change at the same time.
That means that subsequent changes to client_item -- like copying a new string into one of the places that it points -- will affect all of the saved items as well.