Reputation: 89
i'm currently programming a Bulls and Cows program and I'm trying to figure out how to compare a given string with the result I have. I'm pasting my code here so you'll understand better. On the code: I have a char test that is the given string and i have several results. around 1296 results. What i want it to do is to compare the result to the char test and tell me if it's the same or not.(equal or not). I hope i didn't miss any additional information. Please let me know if I did. Thanks :)
#include <stdio.h>
#include <string.h>
void initialize(int poss[1296][4]);
int main()
{
int table[1296][4];
char str[5];
char tmp[5];
int i, j, k;
int bull = 0;
int cow = 0;
char test[7]={"2 B 0 C"};
initialize(table);
printf("Enter 4 digits: ");
scanf("%s", str);
for (i=0; i<1296; i++) // building this table
{
strcpy(tmp, str); // copying string
for (j=0; j<4; j++)
{
for (k=0; k<4; k++)
{
if (table[i][j]==tmp[k]-'0' && j==k) // gets the string as an integer
{
tmp[k] = -1;
bull++;
break;
}
else if (table[i][j]==tmp[k]-'0' && j!=k)
{
tmp[k] = -1;
cow++;
break;
}
}
}
//printf ("Number: %d%d%d%d, Input: %s\n",table[i][0], table[i][1], table[i][2], table[i][3], str);
printf ("%d B %d C\n\n", bull, cow);
bull = 0;
cow = 0;
}
}
void initialize(int poss[1296][4])
{
int i=0;
int j, k=0;
int m;
while (i<=5)
{
for (j=0; j<216 ; j++)
{
poss[k][0]=i;
k++;
}
i++;
}
k=0;
i=0;
j=0;
while (k<1296)
{
for (m=0; m<6; m++)
{
for (j=0; j<6; j++)
{
for (i=0; i<36 ; i++)
{
poss[k][1]=j;
k++;
}
}
}
}
k=0;
i=0;
j=0;
m=0;
while (k<1296)
{
for (j=0; j<6; j++)
{
for (i=0; i<6; i++)
{
poss[k][2]=j;
k++;
}
}
}
k=0;
i=0;
j=0;
m=0;
while (k<1296)
{
for (i=0; i<6; i++)
{
poss[k][3]=i;
k++;
}
}
}
Upvotes: 0
Views: 110
Reputation: 1144
If I understand right, I think there are 2 easy ways to test:
1.
if ((bull == test[0] - '0') && (cow == test[4] - '0'))
// strings are equal
2.
char buffer[8];
sprintf(tempString, "%d B %d C", bull, cow);
if (strcmp(tempString, test) == 0)
// strings are equal
printf("%s\n\n", buffer);
I would suggest the first method, however or even better, add these:
int testBull = test[0] - '0';
int testCow = test[4] - '0';
And test with them rather than calculating them at each step.
Upvotes: 1