#include <iostream>
using namespace std;
class UniqueGenerator;
UniqueGenerator getUniqueGenerator(int);
class UniqueGeneratorException
{
};
class UniqueGenerator
{
private:
int *_list;
int *_stack;
int _size;
int _i, _j, _p;
UniqueGenerator();
public:
UniqueGenerator(int size) : _size(size), _i(1), _j(0), _p(0) {
if (_size < 2) {
throw UniqueGeneratorException();
}
_list = new int[_size];
_stack = new int[_size];
}
~UniqueGenerator() {
delete [] _list;
delete [] _stack;
}
void init(int size) {
if (size < 2) {
throw UniqueGeneratorException();
}
if (size > _size) {
delete [] _list;
delete [] _stack;
_list = new int[size];
_stack = new int[size];
}
_size = size;
}
void reset() {
for (_j = 0; _j < _size; _j++) {
_list[_j] = 0;
}
_i = 1;
_j = 0;
_p = 0;
}
const int* next() {
if (_i > _size) {
_list[_j] = 0;
_j++;
_i--;
}
for (;;) {
while (_j == _size) {
_i--;
if (_i < 1) {
_i = 1;
_j = 0;
_p = 0;
} else {
_p--;
_j = _stack[_p];
_list[_j] = 0;
_j++;
}
}
if (_list[_j] == 0) {
_list[_j] = _i;
_i++;
if (_i > _size) {
break;
} else {
_stack[_p] = _j;
_p++;
_j = 0;
}
} else {
_j++;
}
}
return _list;
}
int size() const {
return _size;
}
};
int main() {
try {
UniqueGenerator gen(4);
for (int j = 0; j < 25; j++) {
const int *k = gen.next();
for (int i = 0; i < gen.size(); i++) {
cout << k[i];
}
cout << endl;
}
} catch (UniqueGeneratorException ex) {
cout << "error" << endl;
}
return 0;
}
I2luY2x1ZGUgPGlvc3RyZWFtPgp1c2luZyBuYW1lc3BhY2Ugc3RkOwoKY2xhc3MgVW5pcXVlR2VuZXJhdG9yOwpVbmlxdWVHZW5lcmF0b3IgZ2V0VW5pcXVlR2VuZXJhdG9yKGludCk7CgpjbGFzcyBVbmlxdWVHZW5lcmF0b3JFeGNlcHRpb24Kewp9OwoKY2xhc3MgVW5pcXVlR2VuZXJhdG9yCnsKcHJpdmF0ZToKCWludCAqX2xpc3Q7CglpbnQgKl9zdGFjazsKC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