0

Hi dudes! And thanks for reading this.

So I want rand() to generate random number and again, but the second number can´t be same as the first one.

So far my code is:

int kortti1, kortti2;
     
     srand ( time(NULL) );
         
         kortti1 = rand() % 5 + 1;
         kortti2 = rand() % 5 + 1;

I´m pretty sure I should use this string:

kortti1 != kortti2;

But I have no idea where to place it :angry:

So a small advice would be great!


Thanks a lot!

2
Contributors
1
Reply
2
Views
9 Years
Discussion Span
Last Post by Narue
0

>but the second number can´t be same as the first one.
That's not very random. :icon_rolleyes: Assuming you want the full range of rand minus the numbers already selected, you're pretty much stuck with re-selecting if you pick the same number:

#include <algorithm>
#include <cstdlib>
#include <iostream>
#include <iterator>
#include <set>

int main()
{
  std::set<int> numbers;

  for ( int i = 0; i < 10; i++ ) {
    int r = rand();

    while ( numbers.find( r ) != numbers.end() )
      r = rand();

    numbers.insert( r );
  }

  std::copy ( numbers.begin(), numbers.end(), 
    std::ostream_iterator<int> ( std::cout, "\n" ) );
}

But beware, that could run forever depending on the range of rand and the amount of numbers you want in the final set. It can also potentially be slow if you have to re-select many times. So you might want to place a limit on the number of selections before failing.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.