分模块写比较繁琐,代码量较多,不过不容易出问题,也容易调试。
#include <iostream>
#include <cstring>
using namespace std;
void get_card(string &left, string &right) {
string s;
getline(cin, s);
int i = s.find('-');
left = s.substr(0, i);
right = s.substr(i+1, s.length());
}
typedef enum {
ONE = 0,
TWO,
THREE,
BOMB,
CONT,
JOKER
} CARD;
int card_value(string card) {
const string tb = "#34567891JQKA2";
string s;
for (auto i = card.begin(); i != card.end() && *i != ' '; i++) {
s.push_back(*i);
}
if (s.length() == 5) { /* 除JOKER牌,其他查表,索引表示牌的大小 */
return 0;
} else {
return tb.find(s[0]);
}
}
int card_type(string card) {
int cnt = 1;
for (auto i = card.begin(); i != card.end(); i++) {
if (' ' == *i) {
cnt++;
}
}
if (1 == cnt) {
return ONE;
} else if (2 == cnt) {
if (11 == card.length()) {
return JOKER;
} else {
return TWO;
}
} else if (3 == cnt) {
return THREE;
} else if (4 == cnt) {
return BOMB;
} else if (5 == cnt) {
return CONT;
}
}
int cmp_large(string &left, string &right) {
int l = card_value(left);
int r = card_value(right);
int type_left = card_type(left);
int type_right = card_type(right);
/* 如果是对王最大 */
if (JOKER == type_left) {
return 1;
} else if (JOKER == type_right) {
return -1;
}
/* 都不是对王,如果都是炸弹 */
if (BOMB == type_left && BOMB == type_right) {
if (l > r) {
return 1;
} else if (l < r) {
return -1;
} else {
return 0;
}
}
if (BOMB == type_left) {
return 1;
} else if (BOMB == type_right) {
return -1;
}
/* 剩下的同种类型才可相互比较 */
if (type_left == type_right) {
if (l > r) {
return 1;
} else if (l < r) {
return -1;
} else {
return 0;
}
} else {
return 0;
}
}
int main() {
string left;
string right;
get_card(left, right);
int res = cmp_large(left, right);
if (1 == res) {
cout << left;
} else if (-1 == res) {
cout << right;
} else {
cout << "ERROR";
}
return 0;
}