dcsimg
CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 6 of 6

Thread: Random number generator with one for-loop

  1. #1
    Join Date
    Mar 2018
    Posts
    37

    Random number generator with one for-loop

    According to the following code which can generate random binary numbers, how I can decrease these two for-loops to one for-loop?

    Code:
    #include <iostream>
    #include <string>
    #include <ctime>
    #include <vector>
    using namespace std;
    
    int main()
    {
      std::vector<int> b;
      srand(time(0));
      for (int i = 1; i <= 11; i++)
      {
        b.push_back(i);
      }
       for (int i = 1; i <= b.size(); i++)
       {
       b[i] = rand() % 2;
       std::cout << b[i] % 2 << " ";
       }
    }
    Last edited by Kmilano; March 27th, 2018 at 08:55 AM.

  2. #2
    2kaud's Avatar
    2kaud is offline Super Moderator Power Poster
    Join Date
    Dec 2012
    Location
    England
    Posts
    6,511

    Re: Random number generator with one for-loop

    This code is producing a vector of 11 elements which are randomly 0 or 1. The first loop can be eliminated by simply specifying the required size of the vector when it is defined. Also a range-based for could be used. Consider

    Code:
    #include <iostream>
    #include <ctime>
    #include <vector>
    using namespace std;
    
    int main()
    {
    	const size_t no_elems = 11;
    	vector<int> b(no_elems);
    
    	srand(time(0));
    
    	for (auto& v : b)
    		v = rand() % 2;
    
    	for (const auto& v : b)
    		cout << v  << " ";
    }
    Note that in this case the second for is purely to display the contents of the vector and could be combined with the first for if needed.

    Code:
    	for (auto& v : b) {
    		v = rand() % 2;
    		cout << v << " ";
    	}
    It could also be done using push_back() without first setting the vector size - although depending upon the size of the final vector, this may be less efficient if reallocations occur.

    Code:
    #include <iostream>
    #include <ctime>
    #include <vector>
    using namespace std;
    
    int main()
    {
    	const size_t no_elems = 11;
    	vector<int> b;
    
    	srand(time(0));
    
    	for (size_t i = 0; i < no_elems; ++i) {
    		b.push_back(rand() % 2);
    		cout << b.back() << " ";
    	}
    }
    Last edited by 2kaud; March 27th, 2018 at 10:55 AM.
    All advice is offered in good faith only. All my code is tested (unless stated explicitly otherwise) with the latest version of Microsoft Visual Studio (using the supported features of the latest standard) and is offered as examples only - not as production quality. I cannot offer advice regarding any other c/c++ compiler/IDE or incompatibilities with VS. You are ultimately responsible for the effects of your programs and the integrity of the machines they run on. Anything I post, code snippets, advice, etc is licensed as Public Domain https://creativecommons.org/publicdomain/zero/1.0/ and can be used without reference or acknowledgement. Also note that I only provide advice and guidance via the forums - and not via private messages!

    C++17 Compiler: Microsoft VS2017 (15.9.3)

  3. #3
    Join Date
    Feb 2017
    Posts
    370

    Re: Random number generator with one for-loop

    Quote Originally Posted by Kmilano View Post
    how I can decrease these two for-loops to one for-loop?
    You can decrease the for-loops to zero if you want.

    The rand function returns an integer between 0 and RAND_MAX and this usually is a 15 bit number. It means the number returned by rand holds 15 random bits. If they're loaded into an std::bitset you can access those bits conveniently just like you would an std::vector,
    Code:
    #include <iostream>
    #include <cstdlib>
    #include <ctime>
    #include <bitset>
    
    void test() {
    	const size_t no_elems = 11;
    
    	srand((unsigned)time(nullptr)); // seed rand() from system clock
    
    	std::cout << ((1<<no_elems) - 1) << " should smaller or equal to " << RAND_MAX << std::endl;
    
    	std::bitset<no_elems> bitset(rand()); // load random bits into bitset
    
    	for (size_t i=0; i<bitset.size(); ++i) { // print bits
    		std::cout << bitset[i] << " ";
    	}
    	std::cout << std::endl;
    }
    Using the new <random> library (which I recommend) it's be possible to generate up to 64 random bits in one go (fits in a long long unsigned int).
    Last edited by wolle; March 31st, 2018 at 05:41 AM.

  4. #4
    Join Date
    Mar 2018
    Posts
    37

    Re: Random number generator with one for-loop

    Hello and thank you for your perfect reply,
    could you please explain why you used const object? and there is no alternative way instead of const object?

  5. #5
    2kaud's Avatar
    2kaud is offline Super Moderator Power Poster
    Join Date
    Dec 2012
    Location
    England
    Posts
    6,511

    Re: Random number generator with one for-loop

    Quote Originally Posted by Kmilano View Post
    could you please explain why you used const object? and there is no alternative way instead of const object?
    ?? The only 'const' used is for no_elems which defines the required number of random elements. This is const as this value doesn't/shouldn't change duringthe program.
    All advice is offered in good faith only. All my code is tested (unless stated explicitly otherwise) with the latest version of Microsoft Visual Studio (using the supported features of the latest standard) and is offered as examples only - not as production quality. I cannot offer advice regarding any other c/c++ compiler/IDE or incompatibilities with VS. You are ultimately responsible for the effects of your programs and the integrity of the machines they run on. Anything I post, code snippets, advice, etc is licensed as Public Domain https://creativecommons.org/publicdomain/zero/1.0/ and can be used without reference or acknowledgement. Also note that I only provide advice and guidance via the forums - and not via private messages!

    C++17 Compiler: Microsoft VS2017 (15.9.3)

  6. #6
    Join Date
    Feb 2017
    Posts
    370

    Re: Random number generator with one for-loop

    Quote Originally Posted by Kmilano View Post
    Hello and thank you for your perfect reply,
    could you please explain why you used const object? and there is no alternative way instead of const object?
    The problem is that you hard-coded the number 11 in your example code in your first post.T hen no one really knows whether 11 is known and fixed at compile time or whether this is a number that is set at run-time. This is a difference that is paramount in C++. You must be very clear about this when you ask questions since C++ is strictly compiled before run-time.

    But regardless of which, my suggestion is worthwhile since it suggests you make use of all random bits you get from a call to a random number generator, not just one.
    Last edited by wolle; April 2nd, 2018 at 03:33 AM.

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  


Windows Mobile Development Center


Click Here to Expand Forum to Full Width




On-Demand Webinars (sponsored)