From 82dc7441133d28de257156df04f8c6e58b2b128d Mon Sep 17 00:00:00 2001 From: aedavelli <9965118+aedavelli@users.noreply.github.com> Date: Thu, 5 Jul 2018 22:03:30 -0700 Subject: [PATCH] Added code to check permutation --- .../Q1_02_Check_Permutation/QuestionA.c | 39 +++++++++++++++++++ .../Q1_02_Check_Permutation/QuestionB.c | 36 +++++++++++++++++ 2 files changed, 75 insertions(+) create mode 100644 Ch 01. Arrays and Strings/Q1_02_Check_Permutation/QuestionA.c create mode 100644 Ch 01. Arrays and Strings/Q1_02_Check_Permutation/QuestionB.c diff --git a/Ch 01. Arrays and Strings/Q1_02_Check_Permutation/QuestionA.c b/Ch 01. Arrays and Strings/Q1_02_Check_Permutation/QuestionA.c new file mode 100644 index 0000000..4ddef60 --- /dev/null +++ b/Ch 01. Arrays and Strings/Q1_02_Check_Permutation/QuestionA.c @@ -0,0 +1,39 @@ +#include +#include +#include +#include + +#define MAX_TEST_STRING_SIZE 10 + +static int cmpcharp(const void *p1, const void *p2) { + return *(char *)p1 - *(char *)p2; +} + +static bool is_permutation(const char *s1, const char *s2) { + bool result = false; + + char *word1copy = strdup(s1); + char *word2copy = strdup(s2); + + qsort(word1copy, strlen(word1copy), sizeof(char), cmpcharp); + qsort(word2copy, strlen(word2copy), sizeof(char), cmpcharp); + + result = strcmp(word1copy, word2copy) ? false : true; + + /* Need to free as strdup allocated memory */ + free(word1copy); + free(word2copy); + + return result; +} + +int main(int argc, char const *argv[]) { + char pairs[][2][MAX_TEST_STRING_SIZE] = { + {"apple", "papel"}, {"carrot", "tarroc"}, {"hello", "llloh"}}; + int number_of_pairs = sizeof(pairs) / sizeof(pairs[0]); + for (int i = 0; i < number_of_pairs; ++i) { + printf("%s, %s : %s\n", pairs[i][0], pairs[i][1], + is_permutation(pairs[i][0], pairs[i][1]) ? "true" : "false"); + } + return 0; +} \ No newline at end of file diff --git a/Ch 01. Arrays and Strings/Q1_02_Check_Permutation/QuestionB.c b/Ch 01. Arrays and Strings/Q1_02_Check_Permutation/QuestionB.c new file mode 100644 index 0000000..eb163f8 --- /dev/null +++ b/Ch 01. Arrays and Strings/Q1_02_Check_Permutation/QuestionB.c @@ -0,0 +1,36 @@ +#include +#include +#include + +#define MAX_TEST_STRING_SIZE 10 + +static bool is_permutation(const char *s1, const char *s2) { + char letters[128] = {0}; + + const char *tmp = s1; + while (*tmp) { + letters[(int)*tmp]++; + tmp++; + } + + tmp = s2; + while (*tmp) { + letters[(int)*tmp]--; + if (letters[(int)*tmp] < 0) { + return false; + } + tmp++; + } + return true; +} + +int main(int argc, char const *argv[]) { + char pairs[][2][MAX_TEST_STRING_SIZE] = { + {"apple", "papel"}, {"carrot", "tarroc"}, {"hello", "llloh"}}; + int number_of_pairs = sizeof(pairs) / sizeof(pairs[0]); + for (int i = 0; i < number_of_pairs; ++i) { + printf("%s, %s : %s\n", pairs[i][0], pairs[i][1], + is_permutation(pairs[i][0], pairs[i][1]) ? "true" : "false"); + } + return 0; +} \ No newline at end of file