Generating a sequence of numbers - C++
Results 1 to 4 of 4

Thread: Generating a sequence of numbers - C++

  1. #1
    Senior Member
    Join Date
    Jan 2004
    Location
    Hawaii
    Posts
    351

    Generating a sequence of numbers - C++

    I'm trying to generate a sequence of random numbers where each number in the sequence is random. The language of choice is C++.

    Example:
    Generate 100 different numbers between 1-100.

    I plan to store them in a respectively-size array. I know I could generate a number and check the whole array for it, if so...then eliminate it...but I'm not sure if that's the best/easiest way to go about it.


    A_T
    Geek isn't just a four-letter word; it's a six-figure income.

  2. #2
    Senior Member
    Join Date
    Jan 2004
    Location
    Hawaii
    Posts
    351
    my best idea so far is to put 1-100 in that array, and use rand () and swap() to just move the numbers around

    A_T
    Geek isn't just a four-letter word; it's a six-figure income.

  3. #3
    Senior Member
    Join Date
    Feb 2005
    Posts
    188
    Hi

    Well what you can do is that generate a random number from the function rand().
    Now you have a number that you want to limit between 100 then take the remainder of the number after dividing by 100. This way the numbers will always be between under 100.

    Alternatively there may be a situation that the remainder of two numbers generated by rand() is same so if you want totally distinct numbers then you can compare them from previously generated numbers.

    This way you dont have to store the numbers in array.

    Code for generating 10 random numbers is
    for(i=0;i<10;i++)
    { printf("%d\n",rand()%100);
    }

    Hope it helps.
    \"The Smilie Wars\" ... just arrived after the great crusades

    .... computers come to the rescue .... ah technology at last has some use.

  4. #4
    Banned
    Join Date
    Nov 2005
    Posts
    63
    Code:
    #include <cstdlib>
    ...
    int limiter = 100;
    int limited;
    srand(time(NULL));
    limited = (int) (limiter * rand() / (RAND_MAX + 1.0)); // RAND_MAX = the max value that rand() can return, (int) casts it to an int, thus dropping whatever decimal there is
    std::cout << limited << endl;
    ...
    srand(time(NULL)); sets the initial seed of rand() to the current time via the time(NULL) function (passing in a null pointer). you should generate non-repeating "random" numbers if there was an unlimited range. but you want 1-100, thus you will get some repeats using this method. thus i would initialize a system of checks. store the numbers in an array, vector, etc. and then compare incoming "random" numbers to those stored in the data structure.

Posting Permissions

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

 Security News

     Patches

       Security Trends

         How-To

           Buying Guides