利用兩個布林陣列存放答案和猜測

因為猜中一個字時,不管有幾個都會顯現出來

這代表著我們只須關心有或沒有 (也就是 true or false)

而不用去管出現幾次

 

最後我們只要紀錄猜中及猜錯的次數

輸出相對應的結果即可

 

note:

answer[i] 為 true 代表 i 出現在 ans

guess[i] 為 true 代表 i 已經被猜過

 

 

#include <iostream>
#include <cstring>

using namespace std;

int main()
{
  bool answer[26], guess[26];

  int times;
  while(cin >> times && times != -1){

    cout << "Round " << times << endl;

    string ans, input;

    memset(answer, false, sizeof(answer));
    memset(guess, false, sizeof(guess));

    cin >> ans >> input;

    int ansLen = 0;
    for(int i = 0; ans[i]; i++){
      if(answer[ans[i] - 'a'] == false){
        answer[ans[i] - 'a'] = true;
        ansLen++;
      }
    }

    int correct = 0, error = 0;
    for(int i = 0; input[i]; i++){
      
      if(answer[input[i]-'a']){
        correct ++;
        answer[input[i]-'a'] = false;
        guess[input[i]-'a'] = true;
      }
      else if(answer[input[i]-'a'] == false && guess[input[i] - 'a'] == false){
        error++;
        guess[input[i]-'a'] = true;  
      }

      if(error == 7){
        cout << "You lose." << endl;
        break;
      }

      if(correct == ansLen){
        cout << "You win." << endl;
        break;
      }
    }

    if(correct < ansLen && error < 7)
      cout << "You chickened out." << endl;
  }

  return 0;
}

arrow
arrow
    全站熱搜

    大神(偽) 發表在 痞客邦 留言(0) 人氣()