01. Sorting Players
Здравейте,
упражнявам се върху стари изпити и попаднах на тази задача тук.
И написах това решение: https://pastebin.com/UY3F5kkD
Може би не е най-елегатното, но все пак мисля, че трябва да работи, а получавам само 40/100 :?
Ще съм благодарен, ако някой може да отдели време и погледне какво може би изпускам.
Поздрави,
Илиян Павлов
100/100 :)
Благодаря за отговора, възползвах се от коментарите и ще ги имам в предвид и за напред.
#include <iostream> #include <string> #include <sstream> #include <vector> #include <algorithm> bool isItADuplicate(const std::string& nameOfPlayer, const std::vector<std::string>& names, int& index){ for (int i = 0; i < names.size(); ++i) { if (nameOfPlayer == names[i]) { index = i; return true; } } return false; } void readInput(std::vector<std::string>& names, std::vector<int>& score) { std::string nameOfPlayer; int winsOfPlayer = 0; int losesOfPlayer = 0; int index = 0; int result = 0; std::string text; getline(std::cin, text); while (text != "End") { std::istringstream istr(text); istr >> nameOfPlayer >> winsOfPlayer >> losesOfPlayer; result = winsOfPlayer - losesOfPlayer; if (isItADuplicate(nameOfPlayer, names, index)) { score[index] = score[index] + result; getline(std::cin, text); continue; } names.push_back(nameOfPlayer); score.push_back(result); getline(std::cin, text); } } std::vector<std::string> sortPlayers(const std::vector<std::string>& names, const std::vector<int>& score) { std::vector<std::string> forPrint; for (int i = 0; i < names.size(); ++i) { //combine name + score in order to sort them forPrint.push_back(names[i] + ' ' + std::to_string(score[i])); } std::sort(forPrint.begin(), forPrint.end()); return forPrint; } int main() { std::vector<std::string> names; std::vector<int> score; std::vector<std::string> results; readInput(names, score); results = sortPlayers(names, score); //print for (std::string player : results) { std::cout << player << std::endl; } }
Не съм на напълно доволен как го написах, но може би като вземем новите неща, ще намеря и по-удовлетворяващ начин за решение.
Отново благодаря!
Поздрави,
Илиян Павлов
Хе-хе, много хитро си подходил като си сортирал стринговете - браво!
Надявам се виждаш градацията от предишното до сегашното си решение.
Разлика от земята до небето!
Като вземем другите структури от данни ще видиш как задачата би се решила по-лесно.
Функциите ти isItADuplicate и readInput са повече от чудесни.
Бързи козметични добавки:
std::vector<std::string> results;
results = sortPlayers(names, score);
Можеше да стане на 1 ред и да бъде константа:
const std::vector<std::string> results = sortPlayers(names, score);
Също така при range based for-loop
//print
for (std::string player : results) {
std::cout << player << std::endl;
}
Няма нужда да копираш стринга. Можеше player да бъде const reference