fork(1) download
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. class UniqueGenerator;
  5. UniqueGenerator getUniqueGenerator(int);
  6.  
  7. class UniqueGeneratorException
  8. {
  9. };
  10.  
  11. class UniqueGenerator
  12. {
  13. private:
  14. int *_list;
  15. int *_stack;
  16. int _size;
  17. int _i, _j, _p;
  18. UniqueGenerator();
  19. public:
  20. UniqueGenerator(int size) : _size(size), _i(1), _j(0), _p(0) {
  21. if (_size < 2) {
  22. throw UniqueGeneratorException();
  23. }
  24. _list = new int[_size];
  25. _stack = new int[_size];
  26. }
  27. ~UniqueGenerator() {
  28. delete [] _list;
  29. delete [] _stack;
  30. }
  31.  
  32. void init(int size) {
  33. if (size < 2) {
  34. throw UniqueGeneratorException();
  35. }
  36. if (size > _size) {
  37. delete [] _list;
  38. delete [] _stack;
  39. _list = new int[size];
  40. _stack = new int[size];
  41. }
  42. _size = size;
  43. }
  44.  
  45. void reset() {
  46. for (_j = 0; _j < _size; _j++) {
  47. _list[_j] = 0;
  48. }
  49. _i = 1;
  50. _j = 0;
  51. _p = 0;
  52. }
  53.  
  54. const int* next() {
  55. if (_i > _size) {
  56. _list[_j] = 0;
  57. _j++;
  58. _i--;
  59. }
  60. for (;;) {
  61. while (_j == _size) {
  62. _i--;
  63. if (_i < 1) {
  64. _i = 1;
  65. _j = 0;
  66. _p = 0;
  67. } else {
  68. _p--;
  69. _j = _stack[_p];
  70. _list[_j] = 0;
  71. _j++;
  72. }
  73. }
  74. if (_list[_j] == 0) {
  75. _list[_j] = _i;
  76. _i++;
  77. if (_i > _size) {
  78. break;
  79. } else {
  80. _stack[_p] = _j;
  81. _p++;
  82. _j = 0;
  83. }
  84. } else {
  85. _j++;
  86. }
  87. }
  88. return _list;
  89. }
  90.  
  91. int size() const {
  92. return _size;
  93. }
  94. };
  95.  
  96.  
  97. int main() {
  98.  
  99. try {
  100. UniqueGenerator gen(4);
  101.  
  102. for (int j = 0; j < 25; j++) {
  103. const int *k = gen.next();
  104. for (int i = 0; i < gen.size(); i++) {
  105. cout << k[i];
  106. }
  107. cout << endl;
  108. }
  109.  
  110. } catch (UniqueGeneratorException ex) {
  111. cout << "error" << endl;
  112. }
  113.  
  114. return 0;
  115. }
Success #stdin #stdout 0s 3476KB
stdin
Standard input is empty
stdout
1234
1243
1324
1423
1342
1432
2134
2143
3124
4123
3142
4132
2314
2413
3214
4213
3412
4312
2341
2431
3241
4231
3421
4321
1234