Skip to content

Instantly share code, notes, and snippets.

@Aaron8052
Last active December 12, 2023 02:29
Show Gist options
  • Save Aaron8052/f71ebff49da0cb14826fcb8cf07fb695 to your computer and use it in GitHub Desktop.
Save Aaron8052/f71ebff49da0cb14826fcb8cf07fb695 to your computer and use it in GitHub Desktop.
【DL 7周年抽奖活动】GiveawayWinnersGenerator
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <ctime>
#include <cstdlib>
using namespace std;
bool ReadFileLines(char* fileName, vector<string> &results);
void PrintAllNames(vector<string> nickNames);
int GetRandomNumber(int min, int max);
void GetWinners(int prizes, vector<string> nickNames);
int main(int argc, char* argv[])
{
if(argc != 2)
{
cout << "Please directly drag the name list txt into this exe file!" << endl;
system("pause");
return 1;
}
vector<string> nickNames = {};
if(!ReadFileLines(argv[1], nickNames))
{
system("pause");
return 1;
}
PrintAllNames(nickNames);
cout << endl << "Number of prizes: ";
int prizes = 0;
cin >> prizes;
GetWinners(prizes, nickNames);
system("pause");
return 0;
}
bool ReadFileLines(char* fileName, vector<string> &results)
{
ifstream file(fileName);
if (!file.is_open())
{
cout << "Error: Unable to open file: " <<fileName << endl;
return false;
}
string line = "";
while (getline(file, line)) {
results.push_back(line);
}
file.close();
return true;
}
void PrintAllNames(vector<string> nickNames)
{
cout << "====== Participants ======" << endl;
int size = nickNames.size();
for(int i = 0; i < size; i++)
{
cout << nickNames[i] << endl;
}
}
static bool seeded = false;
int GetRandomNumber(int min, int max)
{
if(!seeded)
{
unsigned seed = time(0);
srand(seed);
seeded = true;
}
int range = max - min;
return (rand() % range) + min;
}
void GetWinners(int prizes, vector<string> nickNames)
{
int size = nickNames.size();
prizes = min(prizes, size);
cout << "====== Winners ======" << endl;
if(prizes < 1)
{
cout << "No Winners";
return;
}
for(int i = 1; i <= prizes; i++)
{
if(size <= 0)
{
break;
}
int currentRollWinner = GetRandomNumber(0, size);
cout << "[" << i << "] " << nickNames[currentRollWinner] << endl;
nickNames.erase(nickNames.begin() + currentRollWinner);
size --;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment