64,282
社区成员
发帖
与我相关
我的任务
分享
1. #include <iostream>
2. #include <algorithm>
3. #include <iterator>
4. #include <string>
5. #include <time.h>
6. using namespace std;
7.
8. class GuessColor{
9. private:
10. typedef string colorlist_t;
11. colorlist_t m_cl;
12. public:
13. // 从字符串初始化颜色表
14. void fromString(const string &str){
15. m_cl = str;
16. }
17.
18. // 从gc随机取颜色
19. void sampleFrom( const GuessColor& gc ) {
20. m_cl.resize(gc.m_cl.size());
21. for(colorlist_t::iterator i=m_cl.begin(); i!=m_cl.end(); ++i){
22. *i = gc.m_cl[ random( m_cl.size() ) ];
23. }
24. }
25. // 显示颜色表
26. friend ostream& operator<< (ostream& os, const GuessColor& gc){
27. copy(gc.m_cl.begin(), gc.m_cl.end(),
28. ostream_iterator<char>(os));
29. return os;
30. }
31. // 对比另一个GuessColor,得到nA和mB(other会被改变)
32. void nAmB(GuessColor& other, int *nA, int *nB) const{
33. *nA = 0, *nB = 0;
34.
35. colorlist_t A = other.m_cl;
36. colorlist_t B = m_cl;
37.
38. colorlist_t::iterator itr,itrOth;
39. for(itr=A.begin(), itrOth = B.begin();
40. itr!=A.end() && itrOth!=B.end(); ++itr,++itrOth)
41. if(*itr == *itrOth) {
42. ++*nA;
43. *itrOth = '\0';
44. *itr = '\0';
45. }
46.
47. for(itr=A.begin();itr!=A.end(); ++itr)
48. {
49. if(*itr != '\0')
50. {
51. colorlist_t::iterator itrFind=find(B.begin(),B.end(), *itr);
52. if(itrFind != B.end()){
53. ++*nB;
54. *itrFind = '\0';
55. }
56. }
57. }
58. }
59. public:
60. static void randomize(){
61. srand( (unsigned)time(NULL));
62. }
63. static size_t random(size_t max){
64. return (double)rand() / (RAND_MAX + 1) * max;
65. }
66. };
67.
68. int main(int argc, char* argv[])
69. {
70. const char szAllColor[] = "RGYW";
71. const size_t nColorNumber = sizeof(szAllColor)-1;
72.
73. GuessColor::randomize();
74. GuessColor gcAll;
75. GuessColor gcRand;
76. GuessColor gcInput;
77.
78. gcAll.fromString(szAllColor);
79.
80. gcRand.sampleFrom(gcAll);
81. for(int gt=0; gt<8; gt++) {
82. string s;
83. cout << endl << "输入颜色组合["<<gcAll<<"]:";
84. getline(cin, s);
85. transform(s.begin(), s.end(), s.begin(), (int (*)(int))toupper);
86. if(s == "X"){
87. char c;
88. cout << endl << "确认退出吗?(Y/N)";
89. cin >> c;
90. if(c == 'Y' || c == 'y')
91. break;
92. else{
93. gt--; //这次不算次数
94. continue;
95. }
96. }
97. else if(s == "E"){
98. break;
99. }
100.
101. s.resize(nColorNumber, '\0');
102. gcInput.fromString(s);
103. int nA, nB;
104. gcRand.nAmB(gcInput, &nA, &nB);
105.
106. cout << endl << nA << 'A' << nB << 'B';
107. if(nA == 4){
108. cout << endl << "猜对啦~~聪明!!!";
109. break;
110. }
111. }
112.
113. cout << endl << "答案:" << gcRand << endl;
114. system("pause");
115. return 0;
116. }