473,836 Members | 2,123 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Combinations/permutations algorithm in C++

Hi,

I want to write a function of four parameters. Each parameter can be
of type long, double or string. For example:

f(long, long, long, long);
f(long, long, long, double);
f(long, long, long, const string &);
f(long, long, double, long);
f(long, long, string, long);
f(long, long, double, double);
f(long, long, double, string);
f(long, long, string, long);

. . .

I would like write this code automaticaly. I know the next_permutatio n
STL algorithm, but I think that it is not useful in this case.

Any idea ?

Thanks,
Jose Luis.
Jul 22 '05 #1
4 2287
On 13 Apr 2004 03:44:18 -0700, jo************* *********@yahoo .es (jose luis
fernandez diaz) wrote:
Hi,

I want to write a function of four parameters. Each parameter can be
of type long, double or string. For example:

f(long, long, long, long);
f(long, long, long, double);
f(long, long, long, const string &);
f(long, long, double, long);
f(long, long, string, long);
f(long, long, double, double);
f(long, long, double, string);
f(long, long, string, long);

. . .

I would like write this code automaticaly. I know the next_permutatio n
STL algorithm, but I think that it is not useful in this case.

Any idea ?


Sounds like you're thinking in terms of applying an STL algorithm to the
process of /code generation/, as in having something create the source code
for all those functions for you, with the right adjustments for the
different parameter ordering?

I suppose it might be possible to do something in terms of writing a C++
program that uses next_permutatio n for something like that, but I'm not
sure that's your best solution.

When I looked at your problem, I asked myself "What does he /do/ in those
functions"? IOW, are you converting all the arguments to a single
"standard" type for use within the function? If you are, and that type is
the same across all the functions (say, double in order to be able to
represent all the possible "values" supplied as arguments, more or less),
then you can do something like this with templates:

#include <iostream>
#include <string>
#include <typeinfo>
#include <cstdlib>
using namespace std;

template<typena me T>
double toDouble(const T &t)
{
cerr << "Invalid type supplied to toDouble: " <<
typeid(t).name( ) << endl;
return 99999.9999; // I did this as a quick-and-dirty /
// example, but it would be much better to
// do something different with compile-time
// assertions
}

template<>
inline double toDouble(const double &d) { return d; }

template<>
inline double toDouble(const long &d) { return d; }

template<>
inline double toDouble(const std::string &d)
{ return std::atof(d.c_s tr()); }

// and so on, for each type you wish to support...

// This version of f just returns the sum, as a double:
template<typena me T1, typename T2, typename T3, typename T4>
double f(T1 v1, T2 v2, T3 v3, T4 v4)
{
return toDouble(v1) + toDouble(v2) + toDouble(v3) + toDouble(v4);
}
int main()
{
cout << f(1L,2L,3L,4L) << endl << endl;
cout << f(1.0,2L,3L,str ing("4.5")) << endl << endl;
cout << f(1.5,2L,3,stri ng("4.5")) << endl << endl;
cout << f('a', 2L, 35.7, 4.3) << endl << endl;
cout << f("abc", 2L, 3.5f, 45.5) << endl << endl;
return 0;
}
Output:
10

10.5

Invalid type supplied to toDouble: int
100008

Invalid type supplied to toDouble: char
100042

Invalid type supplied to toDouble: const char *
Invalid type supplied to toDouble: float
200047
-leor

--
Leor Zolman --- BD Software --- www.bdsoft.com
On-Site Training in C/C++, Java, Perl and Unix
C++ users: download BD Software's free STL Error Message Decryptor at:
www.bdsoft.com/tools/stlfilt.html
Jul 22 '05 #2

"jose luis fernandez diaz" <jo************ **********@yaho o.es> wrote in message
news:c2******** *************** ***@posting.goo gle.com...
Hi,

I want to write a function of four parameters. Each parameter can be
of type long, double or string. For example:

f(long, long, long, long);
f(long, long, long, double);
f(long, long, long, const string &);
f(long, long, double, long);
f(long, long, string, long);
f(long, long, double, double);
f(long, long, double, string);
f(long, long, string, long);

. . .

I would like write this code automaticaly. I know the next_permutatio n
STL algorithm, but I think that it is not useful in this case.

Any idea ?

Thanks,
Jose Luis.

Something like this : (?)

--------- permut.cpp ---------
#include <cassert>
#include <string>
#include <vector>
#include <iostream>
#include <sstream>
#include <iterator>
using namespace std;

template<typena me T>
vector<vector<T > > get_permut (size_t n, const vector<T>& abt_i)
{
vector<vector<T > > ret_vect;

if (n > 1)
{
vector<vector<T > > prev_vect (get_permut (n - 1, abt_i));
for (size_t i = 0; i < prev_vect.size( ); i++)
{
for (size_t j = 0; j < abt_i.size(); j++)
{
vector<T> tmp_vect (prev_vect[i]);
tmp_vect.push_b ack (abt_i[j]);
ret_vect.push_b ack (tmp_vect);
}
}
}
else
{
for (size_t j = 0; j < abt_i.size(); j++)
{
vector<T> tmp_vect (1, abt_i[j]);
ret_vect.push_b ack (tmp_vect);
}
}

return ret_vect;
}
int main (int argc, char** argv)
{
const bool condition_argc = (argc == 2);
if (!condition_arg c)
{
cout << endl
<< " USAGE : "
<< argv[0]
<< " <size of permutation>"
<< endl;
return 1;
}

assert (condition_argc );

vector<string> abt1;
abt1.push_back ("long");
abt1.push_back ("double");
abt1.push_back ("string");
abt1.push_back ("const string&");
vector<vector<s tring> > res1_vect (get_permut (atoi(argv[1]), abt1));
for (size_t i = 0; i < res1_vect.size( ); i++)
{
ostringstream oss;
copy (res1_vect[i].begin(), res1_vect[i].end(), ostream_iterato r<string>(oss, ", "));
cout << "f(" << oss.str().subst r (0, oss.str().size( ) - 2) << ");" << endl;
}

return 0;
}

------------------------------

--------- Compilation & Run ---------

$ g++ permut.cpp

$ a
USAGE : a <size of permutation>

$ a 4
<See news://news.individual .net/c5**********@ne ws.wplus.net
or
news://news.wplus.net/c5**********@ne ws.wplus.net
via NNTP server>

-------------------------------------
--
Alex Vinokur
mailto:al****@c onnect.to
http://mathforum.org/library/view/10978.html

Jul 22 '05 #3
"jose luis fernandez diaz" <jo************ **********@yaho o.es> wrote in
message news:c2******** *************** ***@posting.goo gle.com...
Hi,

I want to write a function of four parameters. Each parameter can be
of type long, double or string. For example:

f(long, long, long, long);
f(long, long, long, double);
f(long, long, long, const string &);
f(long, long, double, long);
f(long, long, string, long);
f(long, long, double, double);
f(long, long, double, string);
f(long, long, string, long);

. . .

I would like write this code automaticaly. I know the next_permutatio n
STL algorithm, but I think that it is not useful in this case.

Any idea ?

template<class A, class B, class C, class D>
void f(A a, B b, C c, D d)
{
// ...
}
template<>
void f(long a, long b, long c, const string &d)
{
// ...
}


Ioannis Vranos

Jul 22 '05 #4
Hello,

jose luis fernandez diaz wrote:
I want to write a function of four parameters. Each parameter can be
of type long, double or string. For example:

Let the compiler generate it for you on the fly via templates. This
looks a bit complicated at first, but templates are invaluable to get
the desired effect of compile-time polymorphism.

// handling parameter 1

template <class T>
handle_param_1 (T); // default, may not be used

template <>
handle_param_1 (long l)
{
// what to do, when parameter 1 is long
}

template <>
handle_param_1 (double d)
{
// what to do, when parameter 1 is double
}

// handling parameter 2

template <class T>
handle_param_2 (T); // default, may not be used

template <>
handle_param_2 (long l)
{
// what to do, when parameter 2 is long
}

template <>
handle_param_2 (double d)
{
// what to do, when parameter 2 is double
}

// handling more parameters same way

// ...

template <class P1, class P2>
void f(P1 p1, P2 p2)
{
handle_param_1( p1);
handle_param_2( p2);
}

// Now f(long,double), f(long,long), f(double,long), f(double,double ),
// all have a defined meaning

If you want to learn more about C++ templates, consider the book about
templates from Vandewoorde and Josuttis.

Bernd Strieder

Jul 22 '05 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

20
2305
by: John Trunek | last post by:
I have a set of X items, but want permutations of length Y (X > Y). I am aware of the permutation functions in <algorithm>, but I don't believe this will do what I want. Is there a way, either through the STL or some other library to do this, or do I need to write my own code?
6
606
by: jose luis fernandez diaz | last post by:
Hi, I want to write a function of four parameters. Each parameter can be of type long, double or string. For example: f(long, long, long, long); f(long, long, long, double); f(long, long, long, const string &); f(long, long, double, long); f(long, long, string, long);
2
6038
by: deancoo | last post by:
I've seen an algorithm for permutations, but I need to find combinations. Is there an STL equivalent to next_permutation for combinations? The material I'm finding is kinda light, if anyone would like to offer advice on how to approach this problem, it would be much appreciated. Thanks, d
3
1706
by: spakka | last post by:
I'm useless at templates, but, inspired by this post: <hinnant-074D8A.11281207032005@syrcnyrdrs-01-ge0.nyroc.rr.com>, I'm trying to write an algorithm template <class BidirectionalIterator, class Function, class Size> Function for_each_combination(BidirectionalIterator first, BidirectionalIterator last, Size k,
3
5413
by: Ryan | last post by:
I've been trying to find an algorithm that will output all of the possible combinations of items in an array. I know how to find the number of combinations for each set using nCr=n!/(r!(n-r)!) set being possible combinations of r objects from a group of n objects. e.g. n=5 r=3 using A,B,C,D,E as items ABC ABD ABE ACD ACE
16
6776
by: a | last post by:
We are writing an app that assigns people to teams based on their curent score. Teams are 8 people, there are 2 teams. (i would like it to be flexible, but this is a start). I need an algorithm that creates the 2 teams such that the total score for each team is as close as possible. Any ideas?? Thanks!
0
12599
by: JosAH | last post by:
Greetings, last week I stated that a lot of topics in a lot of forums mention all sorts of sorting problems. Last week's tip gave an answer to quite a bit of those sorting problems. Another "favourite" (mind the quotes) topic is about permutations and combinations. This week's tip shows how permutations can be generated in an efficient way. A next tip talks about how combinations can be generated efficiently. First here's an...
1
10940
by: JosAH | last post by:
Greetings, last week we talked a bit about generating permutations and I told you that this week will be about combinations. Not true; there's a bit more to tell about permutations and that's what this Tip Of The Week is about. Maybe later we'll talk a bit about combinations (if anyone's interested). The little utility class we implemented last week was able to generate a next permutation (if any) given a current permutation. But what...
2
2276
by: zgfareed | last post by:
Can anyone suggest an algorithm or function to generate combinations/ permutations of a group of substrings stored in a vector. The substrings consists of 3 letters and the resulting string combinations should be of a size that is a multiple of 3.
0
9657
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10823
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10577
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10243
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9359
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7775
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6975
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5642
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5812
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.