GfG QA is closing soon... Please refer PRACTICE or GfG now on wards !!

C - Finding path

I have to find a combination of groups of letters, second letter in first group should be the same as first letter in second group etc. First letter in first group should be the same as second letter in last group. I can't use each group more than once and I have to use all of given groups.

For example, solution for this group: AA, CB, AC, BA, BD, DB is this: CB, BD, DB, BA, AA, AC

I have this code so far, it works, but if there is a lot of groups, it takes hours to compute. I need to make it more efficient. I am very new to programming so I need some advice how to do that.

In the input file, I have for example this. The first number indicates number of groups in the file.

10
C D
B C
B B
B B
D B
B B
C A
A B
B D
D C

Code

#include <stdio.h>
#include <stdlib.h>

void permutation(char group[][2], int buffer, int sum) {
    int i, j;
    char temp;

    if (buffer == sum && group[1][1] == group[sum][2]) {
        for (i = 1; i < sum; i++)
            if (group[i][2] != group[i+1][1]) break;

        if (i == sum) {
            FILE *output;
            output = fopen("output.txt", "a");
            for (j = 1; j <= sum; j++) {
                fprintf(output, "%c %c\n", group[j][1], group[j][2]);
            }
            exit(1);
        }
    } else {
        for (i = buffer; i <= sum; i++) {
            temp = group[buffer][1];
            group[buffer][1] = group[i][1];
            group[i][1] = temp;
            temp = group[buffer][2];
            group[buffer][2] = group[i][2];
            group[i][2] = temp;

            permutation(group, buffer + 1, sum);

            temp = group[buffer][1];
            group[buffer][1] = group[i][1];
            group[i][1] = temp;
            temp = group[buffer][2];
            group[buffer][2] = group[i][2];
            group[i][2] = temp;
        }
    }
}

int main() {
    FILE *input;

    input = fopen("input.txt", "r");

    int sum, i;

    fscanf(input, "%d", &sum);

    char group[sum][2];

    for (i = 1; i <= sum; i++) {
        fscanf(input, "%s", &group[i][1]);
        fscanf(input, "%s", &group[i][2]);
    }

    permutation(group, 1, sum);
}

 

asked Jan 1, 2016 by anonymous
...