diff --git a/a2/pig_latin.h b/a2/pig_latin.h new file mode 100644 index 0000000..af0fb0e --- /dev/null +++ b/a2/pig_latin.h @@ -0,0 +1,6 @@ +#ifndef PIG_LATIN_H +#define PIG_LATIN_H + +char *translate(const char *phrase); + +#endif diff --git a/a2/program.c b/a2/program.c new file mode 100644 index 0000000..2145cf7 --- /dev/null +++ b/a2/program.c @@ -0,0 +1,72 @@ +#include +#include +#include +#include "pig_latin.h" + +static int is_vowel(char c) { + return c=='a' || c=='e' || c=='i' || c=='o' || c=='u'; +} + +static int is_consonant(char c) { + return c >= 'a' && c <= 'z' && !is_vowel(c); +} + +static void translate_word(const char *word, char *buf) { + int len = (int)strlen(word); + + if (is_vowel(word[0]) || + (len >= 2 && word[0]=='x' && word[1]=='r') || + (len >= 2 && word[0]=='y' && word[1]=='t')) { + sprintf(buf, "%say", word); + return; + } + + int i = 0; + while (i < len && is_consonant(word[i]) && word[i] != 'y') { + if (word[i] == 'q' && i + 1 < len && word[i+1] == 'u') break; + i++; + } + + int split; + + if (i < len - 1 && word[i] == 'q' && word[i+1] == 'u') { + split = i + 2; + } + else if (i > 0 && i < len && word[i] == 'y') { + split = i; + } + else { + split = i > 0 ? i : 1; + } + + strncpy(buf, word + split, len - split); + buf[len - split] = '\0'; + strncat(buf, word, split); + strcat(buf, "ay"); +} + +char *translate(const char *phrase) { + if (!phrase) return NULL; + + int plen = (int)strlen(phrase); + char *result = malloc(plen * 2 + 16); + if (!result) return NULL; + result[0] = '\0'; + + char *copy = malloc(plen + 1); + strcpy(copy, phrase); + + char word_buf[512]; + int first = 1; + char *token = strtok(copy, " "); + while (token != NULL) { + translate_word(token, word_buf); + if (!first) strcat(result, " "); + strcat(result, word_buf); + first = 0; + token = strtok(NULL, " "); + } + + free(copy); + return result; +} \ No newline at end of file