C++ (Qt)class URandGen{public: URandGen(int lim) : limit(lim) {} int operator()() { while (true) { int i = rand()%limit; if (used.find(i) == used.end()) { used.insert(i); return i; } } }private: std::set<int> used; int limit;}; ... URandGen uRand(100);std::cout << uRand() << std::endl;
C++ (Qt)int i. limit = data.size();for (i = 0; i < limit / 2; ++i) qSwap(data[qRand() % limit], data[qRand() % limit]);
C++ (Qt)qsrand (QDateTime::currentMSecsSinceEpoch());QList<int> src; // исходный массивQSet<int> dst; // наша выборкаint n; // количество элементов выборкиwhile (dst.size() < n) dst.insert(src.at(qrand() % src.size()));
C++ (Qt)template <unsigned long N>class URandGen{public: typedef unsigned long size_type; URandGen() { m_arr = new int[N]; for (size_type i = 0; i < N; ++i) m_arr[i] = i; reset(); } ~URandGen() { delete []m_arr; } void reset() { for (size_type i = 0; i < N; ++i) { std::swap(m_arr[i], m_arr[rand()%N]); } } int operator()() { static size_type i = 0; if (i == N) { reset(); i = 0; } return m_arr[i++]; }private: int *m_arr;};
C++ (Qt)int main(){ const int N = 10; int arr[N]; URandGen<N> r; std::copy(arr, arr+N, std::ostream_iterator<int>(std::cout, " ")); return 0;}
C++ (Qt)int URandGen::Rand( int index = -1 ){ if (index >= 0) m_count = index; m_count %= N; return m_arr[m_count++];}