fork download
  1. #include <array>
  2. #include <cstddef>
  3. #include <vector>
  4. #include <iostream>
  5.  
  6. template<typename T, int K, int N>
  7. void generate_all_multisets(
  8. std::array<T, K> const& alphabet,
  9. std::vector< std::vector<T> >& all_words,
  10. std::vector<T>& current_word,
  11. int current_letter
  12. )
  13. {
  14. if (current_letter == N) {
  15. all_words.push_back(current_word);
  16. for (auto k = 0; k != N; ++k)
  17. std::cout << current_word[k];
  18. std::cout << "\n";
  19. return;
  20. }
  21.  
  22. auto const tmp = current_word[current_letter];
  23. for (auto letter = alphabet.begin(); letter != alphabet.end(); ++letter) {
  24. current_word[current_letter] = *letter;
  25. generate_all_multisets<T, K, N>(alphabet, all_words, current_word, current_letter + 1);
  26. }
  27. current_word[current_letter] = tmp;
  28. }
  29.  
  30. template<typename T, int K, int N>
  31. void generate_all_words(
  32. std::array<T, K> const& alphabet,
  33. std::vector< std::vector<T> >& all_words
  34. )
  35. {
  36. // first word
  37. std::vector<T> word(N, alphabet.front());
  38. generate_all_multisets<T, K, N>(alphabet, all_words, word, 0);
  39. }
  40.  
  41. int main()
  42. {
  43. std::array<int, 4> alphabet = { 1, 2, 3, 4};
  44. auto const word_length = 3;
  45.  
  46. std::vector< std::vector<int> > all_words;
  47. generate_all_words<int, 4, 3>(alphabet, all_words);
  48. }
Success #stdin #stdout 0s 3064KB
stdin
Standard input is empty
stdout
111
112
113
114
121
122
123
124
131
132
133
134
141
142
143
144
211
212
213
214
221
222
223
224
231
232
233
234
241
242
243
244
311
312
313
314
321
322
323
324
331
332
333
334
341
342
343
344
411
412
413
414
421
422
423
424
431
432
433
434
441
442
443
444