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!

>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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.