CodeNewbie Community 🌱

Aaron McCollum
Aaron McCollum

Posted on • Edited on

Pig Latin gets me everytime

Posted originally on my personal blog

Pig Latin gets me every time. Or should I say…everytimeyay? I’ve come across the Pig Latin challenge a few times on different platforms, and it’s always a challenge for me (although it’s getting better).

On App Academy Open, the challenge is this: words that start with a vowel must have ‘yay’ added to the end, and all other words must have all letters before the first vowel moved to the end of the word with ‘ay’ tacked on at the end. For example, the word “trash” would turn into “ashtray”, while “apple” turns into “appleyay.”

How should I go about writing this function? My design (while not the most efficient) can be split into three parts:

  1. Handling the words starting with a vowel
  2. Writing a helper method to rotate letters from the front to the back
  3. Handling the words not starting with a vowel

The first step is easy. Basically, in pseudocode, if the first letter of a word is included in the string “aeiou” then we just return that word and add “yay” to it. So the first thing is to create a vowels variable and have it equal “aeiou”, then write the following code:

Alt Text

The next part is the tricky part. If the word does not start with a vowel, we need to identify where the first vowel is at in the word. Everything before the first vowel needs to be removed and pushed to the end of the word (adding the “ay” will be easy once we restructure the word).

My method to solve this is:

  1. Create a helper method called rotate_arr(str) that will send the first letter to the back of the string one time.
  2. Iterate through the word until you find the first vowel and record the index number (i) of the vowel
  3. Call rotate_arr(str) for i times to rotate the letters until you’ve reached the first vowel
  4. Return the updated word + “ay”

The helper function:

Alt Text

Iterating through the word to find the first vowel, then calling rotate_arr the necessary amount of times.

Alt Text

All in all, this code satisfies the requirements for pig latin! This took me a while, and several incorrect attempts, to get right. Having a do statement inside an if statement inside another do statement can be tricky to keep track of! Constant testing and reading helped me figure out the right order of things. Below is the whole code in its entirety.

Alt Text

Top comments (0)