Reputation: 11
Right now I am programming a thing that takes clues to mastermind and return how many guesses should be left to get the secret code correct. I have a small problem however, as it only works on the last guess that is input, so if only one guess is input, it is correct, but any more and it is not...
Here is my code right now:
#include <stdio.h>
#include <stdlib.h>
int bPegs(int *secret, int *sarr);
void frequency(int *array, int *freq);
int tPegs(int *freqA, int *freqG);
void perm(int list[],int k, int n);
int check(int ba, int bb, int wa, int wb);
int slots, colors, guesses;
int *guess;
int counter = 0;
int main() {
int runs, k;
scanf("%d", &runs);
for (k = 0; k < runs; k++) {
int i, j;
scanf("%d", &slots);
scanf("%d", &colors);
scanf("%d", &guesses);
guess = malloc(sizeof(int) * slots + 2);
int *list = malloc(sizeof(int) * slots);
for (i = 0; i < guesses; i++) {
for (j = 0; j < slots + 2; j++) {
scanf("%d", &guess[j]);
}
}
perm(list, 0, slots);
printf("%d", counter);
}
return 0;
}
int bPegs(int *secrets, int *sarr) {
int i;
int black = 0;
for (i = 0; i < slots; i++) {
if (secrets[i] == sarr[i]) {
black++;
}
}
return black;
}
void frequency(int *array, int *freq) {
int i;
for (i = 0; i < slots; i++) {
freq[array[i]]++;
}
}
int tPegs(int *freqA, int *freqG) {
int i, total = 0;
for (i = 0; i < colors; i++) {
if (freqG[i] > freqA[i]) {
total += freqA[i];
}
if (freqG[i] < freqA[i] && freqG[i] != 0) {
total += freqG[i];
}
if (freqG[i] == freqA[i] && freqA[i] != 0) {
total+=freqG[i];
}
}
return total;
}
int check(int ba,int bb, int wa, int wb) {
if (ba == bb && wa == wb) {
return 1;
} else {
return 0;
}
}
void perm(int list[], int k, int n) {
int j;
int *freqA = calloc(colors, sizeof(int));
int *freqG = calloc(colors, sizeof(int));
if (k == n) {
frequency(list, freqA);
frequency(guess, freqG);
int ba = bPegs(list, guess);
int ta = tPegs(freqA, freqG);
int wa = ta - ba;
int bb = guess[slots];
int wb = guess[slots + 1];
if (check(ba, bb, wa, wb)) {
counter++;
}
} else {
int i;
for (i = 0; i < colors; i++) {
list[k] = i;
perm(list, k + 1, n);
}
}
}
Here is some sample input / output: input:
1
10 2 1
1 0 1 0 1 0 1 0 1 5 4
output:
200
this much is correct, for an example of it breaking:
input:
1
4 6 4
0 1 2 3 0 2
2 2 4 1 0 2
4 3 3 2 1 1
1 3 5 4 1 3
should give:
1
but it does give:
8
and I cannot figure out how to set this up for more than just one clue... any help would be great.
Upvotes: 0
Views: 70
Reputation: 145307
The main reading loop seems incorrect:
for (j = 0; j < slots + 2; j++) {
("%d", &guess[j]);
}
Did you mean this instead:
for (j = 0; j < slots + 2; j++) {
scanf("%d", &guess[j]);
}
Upvotes: 1