Click here to Skip to main content
Licence CPOL
First Posted 8 Oct 2008
Views 8,228
Downloads 85
Bookmarked 10 times

Combinatorial - A class to generate combinations of numbers

By | 8 Oct 2008 | Article
A combinatorial class and example code.

Introduction

This is a class to generate combinations of numbers. The generated sets of numbers can be utilized as indexes in your applications. The combinations are with repetition (the same index number can be found in more than one combination), but the combinations are unique.

Background

The code in this article is based on a permutations code originally created by Phillip Fuchs.

The reason I wrote this is that I couldn't find a class that could generate combinations of numbers. That was a year ago. So, I wrote a class to do it. And, here I want to share it.

The code to perform the permutations is not easy to follow, but the code creating the combinations is very easy: it receives the permutation numbers, and if they are found in the current set of combinations, it discards them; otherwise, it adds the combinations to the combinations vector.

Simple and silly, but it works.

Using the code

Just create an application and pass these as parameters: size, len, and combinations, where:

  • size: size of the set of numbers to combine
  • len: length of the resulting sets of combinations
  • combinations: how many sets we want to generate

The resulting sets of combinations can be used as indexes in your application.

Example:

#include "combinatorial.h"
#include <iterator> // for the copy on ostream
 
int main(int argc, char* argv[])
{
     ComboVector cv;
     if (argc != 4)
        return -1;

     int size = atoi(argv[1]);
     int len = atoi(argv[2]);
     int combin = atoi(argv[3]);

     if (len >= size)
     {
         cerr << " len cannot be >= size, exiting";
         return -2;
     }
 
     Comb::Combinations(size,len,combin,cv);
     copy(cv.begin(), cv.end(), ostream_iterator<string>(cout, "\n" ) );

     return 0;
}

Points of interest

An interesting point (beyond the combinatorial) is the printing of the values of the vector using an algorithm from iterators (copy).

History

  • 8 Oct 2008 - Version 1.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

jrivero

Software Developer

Canada Canada

Member

programmer interested in cooking and dogs..

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
-- There are no messages in this forum --
Permalink | Advertise | Privacy | Mobile
Web04 | 2.5.120517.1 | Last Updated 8 Oct 2008
Article Copyright 2008 by jrivero
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid