You are here:

C++/random number

Advertisement


Question
how to select a random number from any set like:
1,4,7,10,13,16
(programming language c++)

Answer
Place your set of numbers into an array then select entries from the array based on a random index value from 0 to number-of-elements - 1.

You do not mention if you are familiar with (pseudo) random number generation at all in C++ (or C) and it is only how to select from a set of values that has you stumped or you have no idea about such things at all.

So in brief: in C++11[1] and later we can use the new random number support provided by the C++ standard library[2]. In pre C++11[3] (C++03, C++98, pre-standard C++) we have to use the C random number support[4] (which we can do in C++11 of course but why bother when the new facilities are better?). Or of course you can use some third party library.

You can look up the nitty gritty details at you own convenience if you are interested - especially for the new C++11 random number support as it is quite extensive and this is not really the forum to reproduce such detail in bulk - and random numbers are not my area of expertise in any case. However, I can give simple example usage for both the new C++11 random number support and pre-C++11 C-library style support.

C++11 (and later) example:

   # include <iostream>  // for std::cout
   # include <random>    // for std::uniform_distribution, std::random_device, std::mt19937 et al.
   # include <array>     // for std::array

   void cxx11_example()
   {
       std::cout << "C++11 style random number selection from set of values:\n";

   // Use C++11 array-wrapper type to define set of required numbers to select randomly
       std::array<int,6> random_set{{1,4,7,10,13,16}};

   // Use a C++11 random number uniform distribution to define type and range
   // of random values. Other distributions are available.
       std::uniform_int_distribution<int>  distribution(0, random_set.size()-1);

   // Use a random device random number generator to seed a (faster) pseudo
   // random number generator (PRNG). std::random_device generally wraps some
   // form of system random number generation device, but is usually quite slow.
       std::random_device rd_seeder;

   // Use a Mersenne Twister type of PRNG. Note value from the random device
   // is passed as a single seed value. A sequence of values can also be
   // provided to perform fuller PRNG state initialisation.
   // Other PRNG types are available.
       std::mt19937 prng(rd_seeder());

   // Print sample of 20 random values from random_set:
   // Use the distribution to produce index values in the required range from
   // raw PRNG output values:
       for (int i=0; i<20; ++i)
       {
         std::cout << random_set[distribution(prng)] << ' ';
       }
       std::cout << std::endl;
   }

I have also used another C++11 feature - std::array[5] - which is a lightweight wrapper around built in arrays, to show its availability. It would be quite simple to use a built in array in this case, as per the pre-C++11 example below.

You will need a C++ implementation which has C++11 language and, particularly, library support. You may need to tell the compiler to turn on such support (for example the to-hand version of g++ I tried the code on - g++ 4.7.3 - requires the --std=c++11 option).

If you are using a compiler without C++11 library support for random numbers you could as an alternative use the Boost[6] implementation of the C++11 random number generation support[7]. It was also available pre-C++11 as part of the C++ standard TR1 release of additional and optional library support[3].

Or you can revert to the C style of random number generation using srand and rand - and using something like the value from time as a seed value to the PRNG:

   # include <iostream>  // for std::cout
   # include <cstdlib>   // for std::srand and std::rand
   # include <ctime>     // for std::time

   void pre_cxx11_example()
   {
       std::cout << "Pre-C++11 style random number selection from set of values:\n";

   // Use built in array to define set of required numbers to select randomly
       int random_set[] = {1,4,7,10,13,16};
       int random_set_size = sizeof random_set/sizeof(int);

   // Use std::time to seed global C random number generator using srand:
       std::srand(std::time(NULL));

   // Print sample of 20 random values from random_set:
   // Use std::rand to get raw pseudo random number, scale it using modulus
   // of size of random set of numbers to produce an index into random_set:
       for (int i=0; i<20; ++i)
       {
         std::cout << random_set[rand()%random_set_size] << ' ';
       }
       std::cout << std::endl;
   }

Hope this helps.

References:
-----------
[1] ISO C++2011: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2012/n3337.pdf
   This document is the working draft just after the C++2011 standard release so has very few differences from the standard document.
[2] C++11 Random number library support: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2012/n3337.pdf , section 26.5.8
[3] C++ standardisation: http://en.wikipedia.org/wiki/C%2B%2B#Standardization - section Standardisation
[4] C++ library random number support from C: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2012/n3337.pdf ,
   section 26.8, paragraph 5, table 120
[5] C++11 std::array: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2012/n3337.pdf , section 23.3.2
[6] Boost: http://www.boost.org/
[7] Boost random: http://www.boost.org/doc/libs/1_56_0/doc/html/boost_random.html

C++

All Answers


Answers by Expert:


Ask Experts

Volunteer


Ralph McArdell

Expertise

I am a software developer with more than 15 years C++ experience and over 25 years experience developing a wide variety of applications for Windows NT/2000/XP, UNIX, Linux and other platforms. I can help with basic to advanced C++, C (although I do not write just-C much if at all these days so maybe ask in the C section about purely C matters), software development and many platform specific and system development problems.

Experience

My career started in the mid 1980s working as a batch process operator for the now defunct Inner London Education Authority, working on Prime mini computers. I then moved into the role of Programmer / Analyst, also on the Primes, then into technical support and finally into the micro computing section, using a variety of 16 and 8 bit machines. Following the demise of the ILEA I worked for a small company, now gone, called Hodos. I worked on a part task train simulator using C and the Intel DVI (Digital Video Interactive) - the hardware based predecessor to Indeo. Other projects included a CGI based train simulator (different goals to the first), and various other projects in C and Visual Basic (er, version 1 that is). When Hodos went into receivership I went freelance and finally managed to start working in C++. I initially had contracts working on train simulators (surprise) and multimedia - I worked on many of the Dorling Kindersley CD-ROM titles and wrote the screensaver games for the Wallace and Gromit Cracking Animator CD. My more recent contracts have been more traditionally IT based, working predominately in C++ on MS Windows NT, 2000. XP, Linux and UN*X. These projects have had wide ranging additional skill sets including system analysis and design, databases and SQL in various guises, C#, client server and remoting, cross porting applications between platforms and various client development processes. I have an interest in the development of the C++ core language and libraries and try to keep up with at least some of the papers on the ISO C++ Standard Committee site at http://www.open-std.org/jtc1/sc22/wg21/.

Education/Credentials

©2016 About.com. All rights reserved.