0

I searched and found some for randomizing numbers, but I don't think it applies for strings....For example I have a list like this in an array:

string restaurants[] = {"Texas Roadhouse,","On The Border,","Olive Garden,","Panda       Express,","Cracker Barrel,","IHOP,","Panda Express,","Pei Wei"};

How would I randomize this or just swap them all around and jumble them up?

3 Answers 3

4

Don't reinvent the wheel if you don't have to.

std::random_shuffle(std::begin(restaurants), std::end(restaurants));

In C++03, without implementing your own begin and end:

std::random_shuffle(restaurants, restaurants + sizeof restaurants / sizeof restaurants[0]);

Be aware that unless you use something such as std::vector, passing it into a function to do this not by reference will need to use the latter with an additional size argument.

Sign up to request clarification or add additional context in comments.

2 Comments

So what would I need to include or change given I am only have #include <iostream> #include <string> #include <ctime> #include <cstdlib> using namespace std; in my header
@user1751615, std::random_shuffle is part of <algorithm>, along with many other don't reinvent the wheel functions.
1

you could do like

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

int main ()
{
  static string numbers[] =  {"Texas Roadhouse,","On The Border,","Olive Garden,","Panda       Express,","Cracker Barrel,","IHOP,","Panda Express,","Pei Wei"};
  srand(time(0));
  int rand_index = rand() % 10;
  cout << numbers[rand_index] << endl;

  string input;
  getline(cin,input);
  cout << (((input=="even")==(rand_index+1)%2==0) ? "Right." : "Wrong.") << endl;
}

Comments

0

Just an alternative for fun (sort by random) :

std::sort(restaurants, restaurants + sizeof(restaurants) / sizeof(std::string), [](int x, int y) -> bool { return rand() % 100 >= 50; });

1 Comment

Sorry but this predicate doesn't satisfy a strict weak ordering so there's no guarantee it will work correctly or not crash. There's a reason the standard library has std::random_shuffle.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.