Question : C++ permutation with replacement algorithm

I am looking for an algorithm that will generate, in any order, all permutations of 'n' items chosen from 'm' items WITH REPLACEMENT (i.e. m choose n with replacement).  There will be m^n permutations in total.

so all (3^2 = 9) permutations of 2 items with replacement from the 3 items 'a', 'b','c'  is:

aa
ab
ba
bb
cc
ac
ca
bc
cb

This issue was addressed without replacement in:

http://www.experts-exchange.com/Programming/Languages/CPP/Q_10291490.html

I need it with replacement.

Answer : C++ permutation with replacement algorithm

Here is an algorithm for permutations with replacement. I modified code from:
       http://en.wikipedia.org/wiki/Itoa

This boils down to a radix problem. If you have a set {a,b,c,d,e} and 3 slots, then you have 5^3 radix numbers: aaa, aab, aac, aad, aae, aba, ... . To get all possible unique outcomes, you can have a + operator so that a+1 --> b
...
e+1 --> a with a carry so that, for example:
abe + 1 --> aca


The output is:
Element #    Radix Number
    1                00
    2                10
    3                20
    4                01
    5                11
    6                21
    7                02
    8                12
    9                22
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
#include <stdio.h>
#include <math.h>
#include <string.h>

const int N_ITEMS = 8;
const int M_SLOTS = 3;
const unsigned int nPerms = int(  pow(float(N_ITEMS),float(M_SLOTS)) );

 void intToRadix(unsigned int n, char * str, int base)
 {
     int i=0;
     memset( str, '0', M_SLOTS);
     str[M_SLOTS] = '\0';
     do {
         str[i++] = n % base + '0';
     } while ((n /= base) > 0);
 }

int main()
{
   char strPerm[M_SLOTS+1];
   printf("Element #    Radix Number\n");
   for( unsigned int permNum = 0; permNum < nPerms; permNum++) {
      intToRadix( permNum, strPerm, N_ITEMS);
      printf("%5d    %10s\n", permNum+1,  strPerm );
   }
}
Random Solutions  
 
programming4us programming4us