How to make a random array to not repeat?
CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 2 of 2

Thread: How to make a random array to not repeat?

  1. #1
    Join Date
    Feb 2013
    Posts
    5

    Unhappy How to make a random array to not repeat?

    Here is my code for a simple game. paste it and try it.

    #include <iostream>
    #include <string>
    #include <ctime>
    #include <cstdlib>
    using namespace std;

    int main (void)
    {
    string g[4],
    b[4],
    a[4],
    l[4];

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

    cout << "Welcome!\n\n";
    cout << "Type 4 girl names.\n";
    for (int gi = 0; gi < 4; gi++)
    cin >> g[gi];

    cout << "Type 4 boy names.\n";
    for (int bi = 0; bi < 4; bi++)
    cin >> b[bi];

    cout << "\nWhat they do (enter 4 actions)?\n";
    for (int ai = 0; ai < 4; ai++)
    getline(cin, a[ai]);

    cout << "\nWhere is happening (enter 4 locations)?\n";
    for (int li = 0; li < 4; li++)
    getline(cin, l[li]);

    for (int c = 0; c < 4; c++)
    cout << g[rand() % 4] << " and " << b[rand() % 4] << " are " << a[rand() % 4] << " from a " << l[rand() % 4] << endl;

    return (0);
    }

    At the end in the 4 lines some of the names, actions and locations repeat. How do I make them to not repeat and use every name that you will enter? do I need random_shuffle? How can I integrate it in my code?

  2. #2
    Join Date
    Aug 2000
    Location
    West Virginia
    Posts
    7,619

    Re: How to make a random array to not repeat?

    You can use random_shuffle ...

    Code:
    #include <algorithm>
    
    // after entering the data ...
    
    random_shuffle(g,g+4);
    random_shuffle(b,b+4);
    random_shuffle(a,a+4);
    random_shuffle(l,l+4);
    
    for (int c = 0; c < 4; c++)
    {
     cout << g[c] << " and " << b[c] << " are " << a[c] << " from a " << l[c] << endl;
    }
    Also, there is a bug when entering the data. It happens when you use operator >>
    followed by getline() [ a google search should describe the problem in detail ].

    Between the operator >> and the getline(), use the ignore() function:

    Code:
     cin >> b[bi];
    
     cin.ignore(10000,'\n');

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

This is a CodeGuru survey question.


Featured


HTML5 Development Center