DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

C++ Way To Randomly Select M Numbers

07.16.2007
| 5319 views |
  • submit to reddit
        This will randomly select M numbers from the interval [1, NMAX].

Note the extensive use of STL.

const short NMAX = 49;
const short M = 6;

std::vector<short> v;
for (short i(0); i < NMAX; ++i)
	v.push_back(i + 1);

random_shuffle(v.begin(), v.end());
copy(v.begin(), v.begin() + M, std::ostream_iterator<short>(std::cout, " "));