Skip to content

Instantly share code, notes, and snippets.

@rodchile
Created January 6, 2014 20:34
Show Gist options
  • Save rodchile/8289420 to your computer and use it in GitHub Desktop.
Save rodchile/8289420 to your computer and use it in GitHub Desktop.
Script to verify if a given C string is a permutation of other C string
#include <stdlib.h>
#include <stdio.h>
#include <stdbool.h>
#include <string.h>
char *sortString (char *stringToSort)
{
int stringLenght = strlen(stringToSort);
char *sortedString = strdup(stringToSort);
for (int i = 0; i < stringLenght; ++i)
{
for (int j = i; j < stringLenght; ++j)
{
int char1 = stringToSort[i];
int char2 = stringToSort[j];
if(char1 > char2)
{
sortedString[j] = stringToSort[i];
sortedString[i] = stringToSort[j];
stringToSort = strdup(sortedString);
}
}
}
printf("Sorted string: %s\n", sortedString);
return sortedString;
}
bool isPermutation (char *sourceString, char *stringToValidate)
{
int sourceStringLenght = strlen(sourceString);
int stringToValidateLenght = strlen(stringToValidate);
if(sourceStringLenght != stringToValidateLenght) return false;
sourceString = sortString(sourceString);
stringToValidate = sortString(stringToValidate);
return (strcmp(sourceString, stringToValidate) == 0);
}
int main(int argc, char const *argv[])
{
char *string1 = "abc";
char *string2 = "bac";
if(isPermutation(string1,string2))
{
printf("Omg it's a permutation");
}
else
{
printf("It isn't a permutation");
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment