Skip to content

Instantly share code, notes, and snippets.

@leotada
Created November 22, 2019 19:45
Show Gist options
  • Save leotada/568010d9a46929100b93d8b8d0ed3e7f to your computer and use it in GitHub Desktop.
Save leotada/568010d9a46929100b93d8b8d0ed3e7f to your computer and use it in GitHub Desktop.
Sorteio amigo secreto/oculto em C++ 11
// Autor Leonardo Antunes, 2019
#include <algorithm> // std::shuffle
#include <chrono> // std::chrono::system_clock
#include <iostream>
#include <random> // std::default_random_engine
#include <string>
#include <vector>
using namespace std;
vector<string> shuffle_names(vector<string> &names) {
// create a copy of names vector and shuffle
vector<string> selecteds(names);
// obtain a time-based seed:
unsigned seed = std::chrono::system_clock::now().time_since_epoch().count();
auto rng = std::default_random_engine(seed);
shuffle(selecteds.begin(), selecteds.end(), rng);
return selecteds;
}
int main() {
int n;
vector<string> names;
cout << "Digite a quantidade de pessoas do Amigo Secreto? ";
cin >> n;
// clear input buffer
cin.clear();
cin.ignore(10000, '\n');
if (n % 2 == 0) {
cout << "\nO número de participantes é: " << n;
} else {
cout << "\nO número impar inviabiliza o sorteio! Digite um número par.\n";
return 0;
}
// get names
for (int count = 0; count < n; ++count) {
cout << "\nDigite o nome de um amigo: ";
string name;
getline(cin, name);
names.push_back(name);
}
vector<string> selecteds = shuffle_names(names);
// verify
int verified = 0;
while (verified != n) {
verified = 0;
for (int count = 0; count < n; ++count) {
if (names[count] != selecteds[count]) {
verified++;
} else {
selecteds = shuffle_names(names);
break;
}
}
}
// print
for (int count = 0; count < n; ++count) {
cout << "Convidado: " << names[count] << ", Amigo: " << selecteds[count] << endl;
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment