Skip to content

Instantly share code, notes, and snippets.

@WindAzure
Created September 26, 2018 16:16
Show Gist options
  • Select an option

  • Save WindAzure/be7acacde84e0882395206bc9a72230b to your computer and use it in GitHub Desktop.

Select an option

Save WindAzure/be7acacde84e0882395206bc9a72230b to your computer and use it in GitHub Desktop.
UVa 489
#include <stdio.h>
#include <string.h>
#define MAX_ERROR_TIMES 7
char solutionStr[1000];
char guessStr[1000];
bool guessedCharacterTable[30];
auto solutionStrLen = 0;
auto guessStrLen = 0;
bool isCurrentWordGuessed(const char &singleCharacter)
{
return guessedCharacterTable[singleCharacter - 'a'];
}
void markCurrentWordGuessed(const char &singleCharacter)
{
guessedCharacterTable[singleCharacter - 'a'] = true;
}
bool isGameEnded(const int &restWordToGuess, const int &totalErrorTimes, const int &currentGuessStrPosition)
{
if (restWordToGuess == 0)
{
puts("You win.");
}
else if (totalErrorTimes >= MAX_ERROR_TIMES)
{
puts("You lose.");
}
else if (currentGuessStrPosition == guessStrLen)
{
puts("You chickened out.");
}
else
{
return false;
}
return true;
}
void judgeHangman(int currentGuessStrPosition, int &restWordToGuess, int totalErrorTimes)
{
if (isGameEnded(restWordToGuess, totalErrorTimes, currentGuessStrPosition))
{
return;
}
auto isMatched = false;
for (auto i = 0; i < solutionStrLen; i++)
{
if (guessStr[currentGuessStrPosition] == solutionStr[i])
{
isMatched = true;
if (!isCurrentWordGuessed(guessStr[currentGuessStrPosition]))
{
restWordToGuess--;
}
}
}
auto errorTimes = 1;
if (isMatched || isCurrentWordGuessed(guessStr[currentGuessStrPosition]))
{
errorTimes = 0;
}
markCurrentWordGuessed(guessStr[currentGuessStrPosition]);
judgeHangman(currentGuessStrPosition + 1, restWordToGuess, totalErrorTimes + errorTimes);
}
int main()
{
auto round = 0;
while (~scanf("%d", &round))
{
if (round == -1)
{
break;
}
memset(guessedCharacterTable, false, sizeof(bool) * 30);
scanf("%s%s", solutionStr, guessStr);
solutionStrLen = strlen(solutionStr);
guessStrLen = strlen(guessStr);
printf("Round %d\n", round);
auto restWordToGuess = solutionStrLen;
judgeHangman(0, restWordToGuess, 0);
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment