Friday, 19 May 2017

Write a C Program to Permute All Letters of an Input String in Linux System.

A C Program to Permute All Letters of an Input String in Linux System. 


This algorithm finds all permutations of the letters of a given string. It is a recursive algorithm using concept of backtracking.

The source code for the C program to permute all letters of an input string. This program is successfully compiled and run on a Linux system.


    #include <stdio.h>

    #include <string.h>

    void swap (char *x, char *y)

    {

        char temp;

        temp = *x;

        *x = *y;

        *y = temp;

    }

    void permute(char *a, int i, int n) 

    {

       int j; 

       if (i == n)

         printf("%s\n", a);

       else

       {

            for (j = i; j <= n; j++)

           {

              swap((a + i), (a + j));

              permute(a, i + 1, n);

              swap((a + i), (a + j)); //backtrack

           }

       }

    } 

int main()

    {

       char str[21];

       int len;

       printf("\nEnter a string: ");

       scanf("%s", str);

       len = strlen(str);

       permute(str, 0, len - 1);

       return 0;

    }


OUTPUT

$ gcc permute.c -o permute
$ ./permute

Enter a string: SAN

All possible permutations are:
    SAN
    SNA
    ASN
    ANS
    NAS
    NSA



0 comments:

Post a Comment