Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth
Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

42,771 questions

55,537 answers

573 users

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
...