Code:
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <math.h>
void userEnter(int*pattern, int n);
void print( int * s, int n);
void recurs( int * s, int * a, int n, int wpegs, int bpegs);
bool Done (int*s, int n);
bool bwPegs (int*a, int*s, int wpegs, int bpegs, int n);
int main(void)
{
int i, n, bpegs, wpegs;
printf("Enter the pattern length: ");
scanf("%d",&n);
int a[n];
printf("Input the guess pattern: ");
int pattern[n];
userEnter(pattern, n);
printf("Enter the number of black pegs in the feedback: ");
scanf("%d",&bpegs);
printf("Enter the number of white pegs in the feedback: ");
scanf("%d",&wpegs);
printf("The possible patterns are: ");
for(i=0; i<=n-1; i++)
{
a[i]=0;
}
if(bwPegs(a, pattern, wpegs, bpegs, n))
{
print(a,n);
}
recurs(a, pattern, n, wpegs, bpegs);
}
void userEnter(int*pattern, int n)
{
char input[n+1];
scanf("%s", input);
int i;
for(i = 0; i < n; i++)
{
pattern[i] = input[i]-97;
}
}
void print( int * s, int n)
{
int i;
printf( "\n" );
for( i = 0; i <n; i++ )
{
printf( "%c", ( s[ i ] + 97 ) );
}
}
void recurs( int * s, int * a, int n, int wpegs, int bpegs)
{
int i;
if(Done(s, n))
{
return;
}
else{
s[ 0 ] += 1;
for( i = 0; i <n-1; i++ )
{
if( s[ i ] == 6 )
{
s[ i ] = 0;
s[ i + 1 ] += 1;
}
}
if(bwPegs(a ,s, wpegs, bpegs, n))
{
print( s, n);
}
recurs(s, a, n, wpegs, bpegs);
}
}
bool Done (int*s, int n)
{
int i;
bool done=true;
for (i=0;i<n;i++)
{
if(s[i]!=5)
{
done=false;
}
}
return done;
}
bool bwPegs (int*a, int*s, int wpegs, int bpegs, int n)
{
int h, i, j, k, c=0 ,c2=0, a0=0, a1=0, a2=0, a3=0, a4=0, a5=0, s0=0,s1=0,s2=0,s3=0,s4=0,s5=0, ans0=0,ans1=0,ans2=0,ans3=0,ans4=0,ans5=0;
int dontcheck[n];
for(h=0;h<n;h++)
{
dontcheck[h]=0;
}
for(i=0;i<n;i++)
{
if(a[i]==s[i])
{
c++;
dontcheck[i]=1;
}
}
if(c==bpegs)
{
for(j=0;j<n;j++)/*checks a and s*/
{
if(dontcheck[j]==0)
{
if(a[j]==0)
{
a0++;
}
if(a[j]==1)
{
a1++;
}
if(a[j]==2)
{
a2++;
}
if(a[j]==3)
{
a3++;
}
if(a[j]==4)
{
a4++;
}
if(a[j]==5)
{
a5++;
}
if(s[j]==0)
{
s0++;
}
if(s[j]==1)
{
s1++;
}
if(s[j]==2)
{
s2++;
}
if(s[j]==3)
{
s3++;
}
if(s[j]==4)
{
s4++;
}
if(s[j]==5)
{
s5++;
}
}
}
if(a0>0&&s0>0)
{
if(a0<=s0)
{
ans0=a0;
}
else
{
ans0=s0;
}
}
if(a1>0&&s1>0)
{
if(a1<=s1)
{
ans1=a1;
}
else
{
ans1=s1;
}
}
if(a2>0&&s2>0)
{
if(a2<=s2)
{
ans2=a2;
}
else
{
ans2=s2;
}
}
if(a3>0&&s3>0)
{
if(a3<=s3)
{
ans3=a3;
}
else
{
ans3=s3;
}
}
if(a4>0&&s4>0)
{
if(a4<=s4)
{
ans4=a4;
}
else
{
ans4=s4;
}
}
if(a5>0&&s5>0)
{
if(a5<=s5)
{
ans5=a5;
}
else
{
ans5=s5;
}
}
c2=ans0+ans1+ans2+ans3+ans4+ans5;
}
if(c2==wpegs&&c==bpegs)
{
return true;
}
else
{
return false;
}
}