please help i'm stuck on something for a project i'm doing

i need to display the numbers 1 to 9 randomly but they cannot be repeated!
the code i have so far is this:

#include <iostream>
#include <ctime> 
#include <cstdlib>

using namespace std;
int main()
{     
    srand((unsigned)time(0));

    int random_integer;
    int lowest=1, highest=9;
    int range=(highest-lowest)+1;

    for(int index=0; index<9; index++)
    {         
        random_integer = lowest+int(range*rand()/(RAND_MAX + 1.0));
        cout << random_integer ;

    }
}

Recommended Answers

All 2 Replies

i need to display the numbers 1 to 9 randomly but they cannot be repeated!

you could save the random number in an array, when you create a new random number check the elements of the array if the random number generated is already given then create a new random number (use a loop so you can check every time if a number is given already)

i need to display the numbers 1 to 9 randomly but they cannot be repeated!

Then technically it's not random. ;) There are two ways to get a non-repeating set of random numbers:

  • Store the generated numbers and try again if you generate one that's already been generated.
    #include <algorithm>
    #include <iostream>
    #include <iterator>
    #include <vector>
    #include <cstdlib>
    #include <ctime>

    using namespace std;

    int main()
    {
        srand((unsigned)time(0));

        vector<int> rnum;

        while (rnum.size() < 9)
        {
            int r = 1 + rand() % 9;

            if (find(rnum.begin(), rnum.end(), r) == rnum.end())
            {
                rnum.push_back(r);
            }
        }

        copy(rnum.begin(), rnum.end(), ostream_iterator<int>(cout, " "));
        cout << endl;
    }
  • Fill an array (or other data structure) with the full range of numbers you want, then randomly shuffle it.
    #include <algorithm>
    #include <iostream>
    #include <iterator>
    #include <vector>
    #include <cstdlib>
    #include <ctime>

    using namespace std;

    int main()
    {
        srand((unsigned)time(0));

        vector<int> rnum(9);

        for (vector<int>::size_type i = 0; i < rnum.size(); i++)
        {
            rnum[i] = i + 1;
        }

        random_shuffle(rnum.begin(), rnum.end());

        copy(rnum.begin(), rnum.end(), ostream_iterator<int>(cout, " "));
        cout << endl;
    }
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.