Last active
September 7, 2020 06:06
-
-
Save komasaru/0054bf03b781b62874c69476e40056a1 to your computer and use it in GitHub Desktop.
C++ source code to rank, considering same ranks.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/*************************************************************** | |
Rank of numbers (integer) | |
$ g++ -std=c++17 -Wall -O2 --pedantic-errors -o rank rank.cpp | |
DATE AUTHOR VERSION | |
2020.08.31 mk-mode.com 1.00 新規作成 | |
Copyright(C) 2020 mk-mode.com All Rights Reserved. | |
***************************************************************/ | |
#include <iostream> // for cout | |
#include <regex> // for regex_search | |
namespace funcs { | |
bool is_int(std::string s) { | |
std::smatch m; | |
std::regex re("^[+-]?\\d+$"); | |
try { | |
if (!std::regex_search(s, m, re)) return false; | |
} catch (std::regex_error& e) { | |
return false; | |
} | |
return true; | |
} | |
bool rank_int(std::vector<int>& ns, std::vector<int>& rs) { | |
unsigned int s; | |
unsigned int i; | |
unsigned int j; | |
unsigned int c; | |
try { | |
s = ns.size(); | |
for (i = 0; i < s; i++) { | |
c = 0; | |
for (j = 0; j < s; j++) { | |
if (ns[i] < ns[j]) c++; | |
} | |
rs.push_back(c + 1); | |
} | |
} catch (...) { | |
return false; | |
} | |
return true; | |
} | |
void display(std::vector<int>& ns, std::vector<int>& rs) { | |
std::vector<int>::iterator it; // イテレータ | |
try { | |
std::cout << "---" << std::endl; | |
std::cout << "VALS = ["; | |
for (it = ns.begin(); it != ns.end(); ++it) { | |
std::cout << *it; | |
if (it != ns.end() - 1) std::cout << ", "; | |
} | |
std::cout << "]" << std::endl; | |
std::cout << "RANK = ["; | |
for (it = rs.begin(); it != rs.end(); ++it) { | |
std::cout << *it; | |
if (it != rs.end() - 1) std::cout << ", "; | |
} | |
std::cout << "]" << std::endl; | |
} catch (...) { | |
throw; | |
} | |
} | |
} | |
int main(int argc, char* argv[]) { | |
std::string buf; // 入力バッファ | |
std::vector<int> ns; // 入力値 | |
std::vector<int> rs; // ランク | |
try { | |
// 値入力 | |
while (true) { | |
std::cout << "n? "; | |
getline(std::cin, buf); | |
if (buf.empty()) break; | |
if (!funcs::is_int(buf)) { | |
std::cout << "NOT INTEGER !!" << std::endl; | |
continue; | |
} | |
ns.push_back(stoi(buf)); | |
} | |
// ランク計算 | |
if (!funcs::rank_int(ns, rs)) { | |
std::cout << "[ERROR] Failed to rank!" << std::endl; | |
return EXIT_FAILURE; | |
} | |
// 結果出力 | |
funcs::display(ns, rs); | |
} catch (...) { | |
std::cerr << "EXCEPTION!" << std::endl; | |
return EXIT_FAILURE; | |
} | |
return EXIT_SUCCESS; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment