mur7ay
mur7ay

Reputation: 833

Displaying content with a for loop

I'm trying to write a program that randomly selects three items from an array that contains five different fruits or vegetables and then display this randomly selected content to the user. Now I'm having trouble understanding why my output is not consistent because sometimes when I run it I'll get something like this:

This bundle contains the following: 


Broccoli

With the first two items missing and sometimes I'll get this:

This bundle contains the following: 
Tomato
Tomato
Tomato

This is the portion of the code I'm currently having trouble with:

void BoxOfProduce::output() {

        cout << "This bundle contains the following: " << endl;

        // Use this so it will be truly random
        srand(time(0));

        for (int f = 0; f < 3; f++) {

            // Here were making the random number
            int boxee = rand() % 5;

            // Adding the content to the box
            Box[f] = Box[boxee];

            // Now were calling on the function to display the content
            displayWord(boxee);

        } // End of for loop

    } // End of output()


    void BoxOfProduce::displayWord(int boxee) {

        cout << Box[boxee] << endl;

    }


int main() {

    BoxOfProduce b1;
    b1.input();
    b1.output();

Can someone help me understand why i'm getting this output? Thanks!

Upvotes: 1

Views: 57

Answers (3)

Rorschach
Rorschach

Reputation: 764

Don't do it like you are doing it :) Like @John3136 pointed out, you are messing up your Box variable..

void BoxOfProduce::output()
{

  srand(time(NULL)); //keep in mind that this is NOT entirely random!
  int boxee = rand() % 5;
  int i = 0;
  while(i<5)
  {
    boxee = rand() % 5;
    cout<<Box[boxee]<<endl;  //this line might be wrong, my point is to print element of your array with boxee index
    i++;
  }

}

Upvotes: 1

wrangler
wrangler

Reputation: 3576

You are overwriting the elements of your array with randomly selected item.

Box[f] = Box[boxee];

For eg: If boxee=1 and f=0, it will overwrite element at index 0 with 1, while at same time element at index 1 is same leaving two copies of same item.

Use :std:random_shuffle instead.

Upvotes: 1

John3136
John3136

Reputation: 29266

Box[f] = Box[boxee]; is changing the contents of the "Box" you are picking things out of. If the first random number is 3, item 3 gets copied to item 0, so now you have twice as much chance of getting that item the next time through the loop...

Upvotes: 1

Related Questions