Skip to content

Instantly share code, notes, and snippets.

@tbbooher
Created September 18, 2023 12:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tbbooher/7964fe80fef01e9629ba7107e99e8d72 to your computer and use it in GitHub Desktop.
Save tbbooher/7964fe80fef01e9629ba7107e99e8d72 to your computer and use it in GitHub Desktop.
wrote two code examples, one in java the other in python
public class PigLatinConverter {
public static void main(String[] args) {
String inputSentence = "Hello world this is a test";
String pigLatinSentence = convertSentenceToPigLatin(inputSentence);
System.out.println("Original: " + inputSentence);
System.out.println("Pig Latin: " + pigLatinSentence);
}
public static String convertSentenceToPigLatin(String sentence) {
String[] words = sentence.split(" ");
StringBuilder pigLatinSentence = new StringBuilder();
for (String word : words) {
pigLatinSentence.append(convertToPigLatin(word)).append(" ");
}
return pigLatinSentence.toString().trim();
}
public static String convertToPigLatin(String word) {
// Convert the word to lowercase
word = word.toLowerCase();
// Check if the word starts with a vowel
if (isVowel(word.charAt(0))) {
return word + "way";
} else {
// Find the index of the first vowel in the word
int firstVowelIndex = -1;
for (int i = 0; i < word.length(); i++) {
if (isVowel(word.charAt(i))) {
firstVowelIndex = i;
break;
}
}
// If there's no vowel in the word, return the word as is
if (firstVowelIndex == -1) {
return word;
}
// Construct the Pig Latin version of the word
return word.substring(firstVowelIndex) + word.substring(0, firstVowelIndex) + "ay";
}
}
public static boolean isVowel(char c) {
return "aeiou".indexOf(c) != -1;
}
}
def convert_to_pig_latin(word):
if word[0] in "aeiou":
return word + "way"
for i, char in enumerate(word):
if char in "aeiou":
return word[i:] + word[:i] + "ay"
return word
def convert_sentence_to_pig_latin(sentence):
return ' '.join([convert_to_pig_latin(word) for word in sentence.lower().split()])
if __name__ == "__main__":
input_sentence = "Hello world this is a test"
print(f"Original: {input_sentence}")
print(f"Pig Latin: {convert_sentence_to_pig_latin(input_sentence)}")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment