contrib/mul/mbl/mbl_combination.h
Go to the documentation of this file.
00001 #ifndef mbl_combination_h
00002 #define mbl_combination_h
00003 //:
00004 // \file
00005 // \author Tim Cootes
00006 // \brief Functions to generate combinations of integers
00007 
00008 #include <vcl_cassert.h>
00009 #include <vcl_vector.h>
00010 #include <vcl_iostream.h>
00011 #include <vcl_algorithm.h>
00012 
00013 //: Generate first combination (n.size() zeros)
00014 inline
00015 vcl_vector<unsigned> mbl_combination_begin(const vcl_vector<unsigned>& n)
00016 {
00017   vcl_vector<unsigned> x(n.size());
00018   vcl_fill(x.begin(),x.end(),0);
00019   return x;
00020 }
00021 
00022 //: Moves x to next combination of integers.
00023 //  x[i] is a positive integer base n[i]
00024 //
00025 //  This allows stepping through all possible combinations of sets integers {x[i]}
00026 //  using
00027 // \code
00028 //  vcl_vector<unsigned> x = mbl_combination_begin(n);
00029 //  do { ...}  while (mbl_combination_next(x,n));
00030 // \endcode
00031 inline
00032 bool mbl_combination_next(vcl_vector<unsigned>& x, const vcl_vector<unsigned>& n)
00033 {
00034   assert(n.size()==x.size());
00035   for (unsigned i=0;i<n.size();++i)
00036   {
00037     x[i]=(x[i]+1)%n[i];
00038     if (x[i]>0) return true;
00039   }
00040   return false;
00041 }
00042 
00043 //: Number of possible combinations of n.size() values, drawing one from each of n[i] elements.
00044 inline
00045 unsigned mbl_n_combinations(const vcl_vector<unsigned>& n)
00046 {
00047   unsigned nc = 1;
00048   for (unsigned i=0;i<n.size();++i) if (n[i]>1) nc*=n[i];
00049   return nc;
00050 }
00051 
00052 //: Print combination as x3:x2:x1:x0
00053 inline
00054 void mbl_print_combination(vcl_ostream& os, const vcl_vector<unsigned>& x)
00055 {
00056   for (int i=x.size()-1;i>0;--i) os<<x[i]<<':';
00057   os<<x[0];
00058 }
00059 
00060 #endif // mbl_combination_h