Reputation: 11
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main() {
int cards[52];
srand(time(0));
for ( int i = 0; i < 52; i++ ) {
cards[i] = i + 1;
}
for ( int i = 0; i < 52; i++ ) {
int index = rand() % 52;
int tmp = cards[i];
cards[i] = cards[index];
cards[index] = tmp;
}
for ( int i = 0; i < 52; i++ ) {
cout << cards[i] << " ";
}
cout << endl;
return 0;
}
Hi everyone, this code generate random number 1-52. Is there a way to shuffle string for example string ("nick", "john", "mike"); and generate these names randomly each time I run the program.
Thanks.
Upvotes: 1
Views: 53
Reputation: 1099
To shuffle strings, you can use the exact same code that you have now.
You want to be able to change the number of items, so replace int cards[52] with a vector. Also rename it "indexes":
std::vector<int> indexes;
Resize it when you start the program, assuming you have a vector "names":
int main()
{
int n = names.size();
indexes.resize(n);
And number it from zero up, not from 1:
for ( int i = 0; i < n; i++ ) {
indexes[i] = i;
Shuffle the "n" ints:
for ( int i = 0; i < n; i++ ) {
int index = rand() % n;
int tmp = indexes[i];
indexes[i] = indexes[index];
indexes[index] = tmp;
}
Assuming the strings are in an array or vector "names", you can now use the randomized indexes to cycle through them:
for ( int i = 0; i < n; i++ ) {
cout << names[indexes[i]] << " ";
cout << endl;
This code will be much more efficient than trying to shuffle the strings, because it's only moving ints around, not the whole strings. You could also save several "sortings" separately, and have them all refer back to the same data.
Upvotes: 0
Reputation: 24946
Storing multiple objects can be done with std::array
or std::vector
where the first is statically sized while the latter can grow dynamically. Shuffling a collection of elements (with random iterators) can be done with std::shuffle
:
#include <vector>
#include <string>
#include <iostream>
#include <random>
#include <algorithm>
int main()
{
std::vector<std::string> v;
v.push_back("nick");
v.push_back("john");
v.push_back("mike");
std::mt19937_64 gen(std::random_device{}());
std::shuffle(v.begin(), v.end(), gen);
for(std::size_t i{}; i < v.size(); ++i) std::cout << v[i] << "\n";
}
Upvotes: 1