genRandom.h
#pragma once
#include <random>
#include <vector>
#include <string>
#include <map>
class getRandom
{
public:
getRandom(std::vector<size_t> &weight, std::vector<std::string> &names);
~getRandom();
std::vector<std::string> getName();
private:
std::vector<std::pair<std::string, size_t>> _sortMap(std::map<std::string, size_t> &m);
std::discrete_distribution<size_t> weight;
std::default_random_engine e;
std::vector<std::string> names;
};
genRandom.cpp
#include "stdafx.h"
#include "getRandom.h"
#include <functional>
#include <set>
#include <algorithm>
getRandom::getRandom(std::vector<size_t> &v, std::vector<std::string> &n)
: weight(v.begin(), v.end()), names(n)
{
}
getRandom::~getRandom()
{
}
std::vector<std::string> getRandom::getName() {
std::map<size_t, size_t> results; // Store the results of throws
for (size_t go{}; go < 5000; ++go) // 5000 throws of the die
++results[weight(e)];
std::map<std::string, size_t> pairs;
for (size_t i = 0; i < names.size(); ++i) {
pairs.emplace(names[i], results[i]);
}
std::vector<std::pair<std::string, size_t>> tmp = _sortMap(pairs);
std::vector<std::string> expectVtr;
for (size_t i = 0; i < 3; ++i) {
expectVtr.push_back(tmp[i].first);
}
return expectVtr;
}
std::vector<std::pair<std::string, size_t>> getRandom::_sortMap(std::map<std::string, size_t> &m) {
auto compFunctor =
[](std::pair<std::string, size_t> elem1, std::pair<std::string, size_t> elem2)
{
return elem1.second > elem2.second;
};
std::vector<std::pair<std::string, size_t>> tmp;
for (auto curr = m.begin(); curr != m.end(); curr++)
tmp.push_back(make_pair(curr->first, curr->second));
std::sort(tmp.begin(), tmp.end(), compFunctor);
return tmp;
}
main.cpp
// EatMatter.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "getRandom.h"
#include <iostream>
#include <fstream>
#include <sstream>
using namespace std;
int main()
{
ifstream f("shop name.txt");
if (f) {
string line, word;
vector<size_t> rate;
vector<string> names;
while (getline(f, line)) {
size_t foodRate;
string foodName;
istringstream info(line);
info >> foodRate;
rate.push_back(foodRate);
info >> foodName;
names.push_back(foodName);
}
getRandom g(rate, names);
std::vector<string> genNames = g.getName();
for (auto i : genNames) {
cout << i << endl;
}
}
else {
cout << "Cannot open file" << endl;
exit(1);
}
getchar();
return 0;
}
15 fish
10 shaokao
10 jiaozi
15 chuanchuan
10 maidanglao
5 dongbei
10 malatang
5 mianbao
10 shenghao
10 chancai