#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;
}