This program supposes to print out all the possible solution of given the guess pattern, the number of black pegs, and the number of white pegs in a mastermind game.
In addition, it has to be done by using recursion, and it has to have a runtime less than 15 second with a pattern length of 15.
An example of the output of the code would look like below:
Code:
Enter the pattern length: 3
Input the guess pattern: abc
Enter the number of black pegs in the feedback: 2
Enter the number of white pegs in the feedback: 0
The possible key patterns are:
aac
aba
abb
abd
abe
abf
acc
adc
aec
afc
bbc
cbc
dbc
ebc
fbc
and here is the my code:
Code:
#include<stdio.h>
#include<stdlib.h>
#include<stdbool.h>
void scanIn(char *pattern, int length)
{
char input[length + 1];
scanf("%s", input);
int i;
for(i = 0; i < length; i++)
{
pattern[i] = input[i];
}
}
bool pegsTester1(char *guess, char *test, int black, int white, int length)
{
int i,j,k;
bool guess_Hit[length];
bool testHit[length];
int blackFeedBack;
int whiteFeedBack;
for(i = 0; i < length; i++)
{
guess_Hit[i] = false;
testHit[i] = false;
blackFeedBack = 0;
whiteFeedBack = 0;
}
if(black)
{
for(i = 0; i < length; i++)
{
if(guess[i] == test[i])
{
blackFeedBack++;
guess_Hit[i] = true;
testHit[i] = true;
}
}
}
if(white)
{
for(i = 0; i < length; i++)
{
for(j = 0; j < length && !testHit[i]; j++)
{
if(guess[i] == test[j] && !gues........[j])
{
whiteFeedBack++;
testHit[i] = true;
guess_Hit[j] = true;
}
}
}
}
if(blackFeedBack != black || whiteFeedBack != white)
return false;
else
return true;
}
void printresult(int length, int count, char *guess, int black, int white, char *test)
{
if(count == length)
{
bool rightGuess = pegsTester1(guess, test, black, white, length);
if(rightGuess)
{
int x;
for(x = 0; x < length; x++)
printf("%c", test[x]);
printf("\n");
}
return;
}
else
{
char t;
for (t = 'a'; t <= 'f'; t++)
{
test[count] = t;
printresult(length, count + 1, guess, black, white, test);
}
}
}
int main(void)
{
int length;
printf("Enter the pattern length: ");
scanf("%d", &length);
char guess[length];
printf("Input the guess pattern: ");
scanIn(guess, length);
int black, white;
printf("Enter the number of black pegs in the feedback: ");
scanf("%d", &black);
printf("Enter the number of white pegs in the feedback: ");
scanf("%d", &white);
char test[length+1];
int i;
for(i = 0; i < length; i++)
{
test[i]='a';
}
test[length] = '\0';
printf("The possible key patterns are: \n");
printresult(length, 0, guess, black, white, test);
return 0;
}
The only problem I have now is that it takes too long to generate all the possibility. What can I do to make it faster? Should I check for matches as the program generates the pattern? If so, how? Please help. You can either help by changing my code or make a brand new one.
Thank you!