The Solution to the Instagram Challenge: Vowel-Consonant String Transformer
Hey Technophiles, I Hope you are all doing well.
Sunday (25/08/2024), we posted a challenge on our Instagram page! If you didn’t check the post, kindly follow us on Instagram.
Instagram Post: View Post
Stay connected with us:
The challenge was all about transforming words based on the number of vowels and consonants they contain. The twist? Instead of just handling single words, you had to work with entire sentences, applying the transformation to each word in the sentence.
In case you missed it or are curious about the solution, don’t worry—I’ve got you covered! Let’s dive into the solution, and I’ll walk you through how you can implement this challenge in C, Python, and Java.
Challenge Recap
Here’s a quick recap of the challenge:
- More Vowels: If a word contains more vowels than consonants, reverse the word.
- More Consonants: If a word contains more consonants than vowels, replace each vowel with the next vowel in the sequence:
a -> e, e -> i, i -> o, o -> u, u -> a
. - Equal Vowels and Consonants: If the word has an equal number of vowels and consonants, convert the word to uppercase.
And here’s the catch: this transformation should be applied to every word in a sentence!
1. Solution in C
// Optimized Code #include <stdio.h> #include <string.h> #include <ctype.h> int is_vowel(char ch) { ch = tolower(ch); return (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u'); } char next_vowel(char ch) { switch (tolower(ch)) { case 'a': return 'e'; case 'e': return 'i'; case 'i': return 'o'; case 'o': return 'u'; case 'u': return 'a'; default: return ch; } } void reverse_word(char* word) { int length = strlen(word); for (int i = 0; i < length / 2; i++) { char temp = word[i]; word[i] = word[length - i - 1]; word[length - i - 1] = temp; } } void replace_vowels(char* word) { for (int i = 0; i < strlen(word); i++) { if (is_vowel(word[i])) { word[i] = next_vowel(word[i]); } } } void transform_word(char* word) { int length = strlen(word); int vowel_count = 0, consonant_count = 0; for (int i = 0; i < length; i++) { if (is_vowel(word[i])) { vowel_count++; } else if (isalpha(word[i])) { consonant_count++; } } if (vowel_count > consonant_count) { reverse_word(word); } else if (consonant_count > vowel_count) { replace_vowels(word); } else { for (int i = 0; i < length; i++) { word[i] = toupper(word[i]); } } } void transform_sentence(char* sentence) { char* word = strtok(sentence, " \n"); while (word != NULL) { transform_word(word); printf("%s ", word); word = strtok(NULL, " \n"); } } int main() { char sentence[100]; printf("Enter a sentence: "); fgets(sentence, sizeof(sentence), stdin); size_t length = strlen(sentence); if (length > 0 && sentence[length - 1] == '\n') { sentence[length - 1] = '\0'; } printf("Transformed sentence: "); transform_sentence(sentence); printf("\n"); return 0; } // Time Complexity: O(n) // Space Complexity: O(n)
Function Definitions:
is_vowel(ch)
:- Checks if
ch
is a vowel: Comparesch
to vowel characters.
- Checks if
next_vowel(ch)
:- Finds the next vowel: Uses a
switch
statement to map each vowel to the next.
- Finds the next vowel: Uses a
reverse_word(word)
:- Reverses the word in-place: Swaps characters from start to end.
replace_vowels(word)
:- Replaces each vowel: Iterates over the word, replacing vowels using
next_vowel
.
- Replaces each vowel: Iterates over the word, replacing vowels using
transform_word(word)
:- Counts vowels and consonants: Iterates over
word
, counting vowels and consonants. - Applies transformation based on counts:
- More Vowels: Calls
reverse_word
. - More Consonants: Calls
replace_vowels
. - Equal: Converts word to uppercase.
- More Vowels: Calls
- Counts vowels and consonants: Iterates over
Main Function:
transform_sentence(sentence)
:- Tokenizes the sentence: Uses
strtok
to splitsentence
into words. - Transforms each word: Applies
transform_word
to each token. - Prints each transformed word.
- Tokenizes the sentence: Uses
2. Solution in Python
#Optimized Code def is_vowel(ch): return ch in 'aeiou' def next_vowel(ch): return { 'a': 'e', 'e': 'i', 'i': 'o', 'o': 'u', 'u': 'a' }.get(ch, ch) def transform_word(word): vowel_count = sum(1 for ch in word if is_vowel(ch)) consonant_count = len(word) - vowel_count if vowel_count > consonant_count: return word[::-1] # Reverse the word elif consonant_count > vowel_count: return ''.join(next_vowel(ch) if is_vowel(ch) else ch for ch in word) else: return word.upper() # Convert to uppercase def transform_sentence(sentence): words = sentence.split() return ' '.join(transform_word(word) for word in words) # Example usage sentence = input("Enter a sentence: ") print("Transformed sentence:", transform_sentence(sentence)) # Time Complexity: O(n) # Space Complexity: O(n)
Function Definitions:
is_vowel(ch)
:- Checks if
ch
is a vowel:ch
is compared against a set of vowel characters ('aeiou'
).
- Checks if
next_vowel(ch)
:- Finds the next vowel: Uses a dictionary to map each vowel to the next in sequence.
transform_word(word)
:- Counts vowels and consonants: Iterates over
word
, counting vowels and consonants. - Transforms based on counts:
- More Vowels: Reverses the word:
word[::-1]
. - More Consonants: Replaces vowels with the next vowel using
next_vowel
. - Equal: Converts word to uppercase:
word.upper().
- More Vowels: Reverses the word:
- Counts vowels and consonants: Iterates over
Main Function:
transform_sentence(sentence)
:- Splits the sentence:
sentence.split()
breaks the sentence into words. - Transforms each word: Applies
transform_word
to each word and joins them back together.
- Splits the sentence:
- Prints the transformed sentence.
3. Solution in Java
// Optimized Code import java.util.Scanner; public class VowelConsonantTransformer { private static boolean isVowel(char ch) { ch = Character.toLowerCase(ch); return "aeiou".indexOf(ch) != -1; } private static char nextVowel(char ch) { switch (Character.toLowerCase(ch)) { case 'a': return 'e'; case 'e': return 'i'; case 'i': return 'o'; case 'o': return 'u'; case 'u': return 'a'; default: return ch; } } private static String transformWord(String word) { int vowelCount = 0, consonantCount = 0; StringBuilder result = new StringBuilder(word.length()); for (char ch : word.toCharArray()) { if (isVowel(ch)) { vowelCount++; } else if (Character.isAlphabetic(ch)) { consonantCount++; } } if (vowelCount > consonantCount) { result.append(new StringBuilder(word).reverse()); } else if (consonantCount > vowelCount) { for (char ch : word.toCharArray()) { result.append(isVowel(ch) ? nextVowel(ch) : ch); } } else { result.append(word.toUpperCase()); } return result.toString(); } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter a sentence: "); String sentence = scanner.nextLine(); scanner.close(); String[] words = sentence.split("\\s+"); StringBuilder transformedSentence = new StringBuilder(); for (String word : words) { transformedSentence.append(transformWord(word)).append(" "); } System.out.println("Transformed sentence: " + transformedSentence.toString().trim()); } } // Time Complexity: O(n) // Space Complexity: O(n)
Function Definitions:
isVowel(ch)
:- Checks if
ch
is a vowel: Comparesch
to vowel characters.
- Checks if
nextVowel(ch)
:- Finds the next vowel: Uses a
switch
statement to determine the next vowel.
- Finds the next vowel: Uses a
transformWord(word)
:- Counts vowels and consonants: Iterates over
word
, counting vowels and consonants. - Applies transformation based on counts:
- More Vowels: Reverses the word using
StringBuilder
andreverse()
. - More Consonants: Replaces vowels using
nextVowel
. - Equal: Converts word to uppercase using
toUpperCase()
.
- More Vowels: Reverses the word using
- Counts vowels and consonants: Iterates over
Main Function:
- Reads user input: Takes a sentence from user input.
- Splits sentence into words: Uses
split("\\s+")
to divide the sentence. - Transforms each word: Applies
transformWord
to each word and concatenates the results. - Prints the transformed sentence.
Conclusion
This challenge is a great way to practice string manipulation and explore how programming languages handle common tasks like splitting strings, transforming text, and combining results.
Whether you prefer C’s manual handling, Python’s simplicity, or Java’s object-oriented approach, each solution gives you a clear path to tackle the problem effectively.
Try implementing these solutions yourself, and share your results! Whether you’re coding for fun, practice, or a serious project, these techniques will help you write cleaner, more efficient code.
If you enjoyed this article, let me know in the comments if you’d like to see more detailed and complex examples in future challenges! 🚀