How to generate all unique 2-digit permutations from a given 3-digit number in C

1 Answer

0 votes
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MAX_PERMUTATIONS 128

typedef struct {
    char **permutations;
    int count;
} PermutationSet;

PermutationSet *generate_2_digit_permutations_from_3_digit_number(char *threeDigitNumber) {
    PermutationSet *twoDigitPermutations = (PermutationSet *)malloc(sizeof(PermutationSet));
    twoDigitPermutations->permutations = (char **)malloc(MAX_PERMUTATIONS * sizeof(char *));
    twoDigitPermutations->count = 0;

    // Generate all two_digit_permutations of three_digit_number
    for (int i = 0; i < strlen(threeDigitNumber); i++) {
        for (int j = 0; j < strlen(threeDigitNumber); j++) {
            if (i != j) {
                char *permutation = (char *)malloc(3 * sizeof(char));
                sprintf(permutation, "%c%c", threeDigitNumber[i], threeDigitNumber[j]);
                twoDigitPermutations->permutations[twoDigitPermutations->count++] = permutation;
            }
        }
    }

    return twoDigitPermutations;
}

int main() {
    char threeDigitNumber[] = "185";

    PermutationSet *twoDigitPermutations = generate_2_digit_permutations_from_3_digit_number(threeDigitNumber);

    for (int i = 0; i < twoDigitPermutations->count; i++) {
        printf("%s, ", twoDigitPermutations->permutations[i]);
    }
    printf("\n");

    // Free memory
    for (int i = 0; i < twoDigitPermutations->count; i++) {
        free(twoDigitPermutations->permutations[i]);
    }
    free(twoDigitPermutations->permutations);
    free(twoDigitPermutations);

    return 0;
}



/*
run:

18, 15, 81, 85, 51, 58,

*/

 



answered Jun 16, 2024 by avibootz
...