Solved

# Generating a combination of strings

Posted on 2004-11-07
177 Views

I am looking for opitmal method of generating pair of numbers from string number.
For example string 12345
Should produce: 11 12 13 14 15 22 23 24 25 33 34 35 44 45 55
or
String 121256708
Should produce: 11 12 15 16 17 10 18 22 21 25 26 27 20 28 55 56 57 50 58 66 67 60 68 77 70 78 00 08 88

I've perused the STL algorithms but I'm coming up short on the right combination - if you will.
Idea.

0
Question by:forums_mp

LVL 1

Assisted Solution

Hey, try this:

#include <iostream>
#include <string>
#include <deque>
using namespace std;

int main()
{
string model;
cout << "enter string: ";
cin >> model;
deque<string> pairs;
string a;
for (int i=0; i< model.size(); i++)
for (int j=i; j< model.size(); j++)
{
a = "";
a+=model[i];
a+=model[j];
pairs.push_back(a);
}

for (int i=0; i< pairs.size(); i++)
cout << pairs[i] << " ";
cout << endl;
return 1;
}
0

Author Comment

Your approach doesnt remove duplicates, nonetheless, I had something similar.  I thought perhaps there was a more elegant approach in the form of STL algorithms.
0

LVL 1

Accepted Solution

well, if you want to remove duplicates, an easy way to do it would be to use a <set> instead of a <deque> ... A set is a collection of unique variables, so if you try to insert something that already exists, it won't get inserted twice...

the only difference in the code would be that you would need an iterator to go through the set

set<string> pairs;

... code to load up the set ...

for ( set<string>::iterator t = pairs.begin(), t!= pairs.end(); t++)
{
cout << *t << " ";
cout << endl;
return1;
}

Now, if you consider "21" and "12" a duplicate pair, and you want to watch out for that as well, what you could do is sort the string before you insert it into the set... this can be accomplished like this

#include <algorithm>

sort ( a );
pairs.push_back(a);

hope this helps,

Gustavo.
0

## Featured Post

### Suggested Solutions

In days of old, returning something by value from a function in C++ was necessarily avoided because it would, invariably, involve one or even two copies of the object being created and potentially costly calls to a copy-constructor and destructor. A…
Written by John Humphreys C++ Threading and the POSIX Library This article will cover the basic information that you need to know in order to make use of the POSIX threading library available for C and C++ on UNIX and most Linux systems.   [s…
The goal of the tutorial is to teach the user how to use functions in C++. The video will cover how to define functions, how to call functions and how to create functions prototypes. Microsoft Visual C++ 2010 Express will be used as a text editor an…
The viewer will be introduced to the member functions push_back and pop_back of the vector class. The video will teach the difference between the two as well as how to use each one along with its functionality.