程序仅循环最后一个输入

时间:2016-02-14 01:05:13

标签: c loops

现在我正在编写一个能够获取mastermind线索的东西,并返回应该留下多少猜测才能使密码正确无误。我有一个小问题,因为它只适用于输入的最后一个猜测,所以如果输入只有一个猜测,那么它是正确的,但是更多而且它不是......

这是我现在的代码:

#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);
        }
    }
}

以下是一些示例输入/输出: 输入:

1
10 2 1
1 0 1 0 1 0 1 0 1 5 4

输出:

200

这是正确的,举个例子:

输入:

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

应该给:

1

但确实给出了:

8

我无法弄清楚如何设置它不仅仅是一条线索......任何帮助都会很棒。

1 个答案:

答案 0 :(得分:1)

主读取循环似乎不正确:

        for (j = 0; j < slots + 2; j++) {
            scanf("%d", &guess[j]);
        }

你的意思是:

input