Avatar of jkedgar

jkedgar's solution

to Pig Latin in the C# Track

Published at Jul 13 2018 · 2 comments
Instructions
Test suite
Solution

Note:

This solution was written on an old version of Exercism. The tests below might not correspond to the solution code, and the exercise may have changed since this code was written.

Implement a program that translates from English to Pig Latin.

Pig Latin is a made-up children's language that's intended to be confusing. It obeys a few simple rules (below), but when it's spoken quickly it's really difficult for non-children (and non-native speakers) to understand.

  • Rule 1: If a word begins with a vowel sound, add an "ay" sound to the end of the word.
  • Rule 2: If a word begins with a consonant sound, move it to the end of the word, and then add an "ay" sound to the end of the word.

There are a few more rules for edge cases, and there are regional variants too.

See http://en.wikipedia.org/wiki/Pig_latin for more details.

Source

The Pig Latin exercise at Test First Teaching by Ultrasaurus https://github.com/ultrasaurus/test-first-teaching/blob/master/learn_ruby/pig_latin/

Submitting Incomplete Solutions

It's possible to submit an incomplete solution so you can see how others have completed the exercise.

PigLatinTest.cs

// This file was auto-generated based on version 1.2.0 of the canonical data.

using Xunit;

public class PigLatinTest
{
    [Fact]
    public void Word_beginning_with_a()
    {
        Assert.Equal("appleay", PigLatin.Translate("apple"));
    }

    [Fact(Skip = "Remove to run test")]
    public void Word_beginning_with_e()
    {
        Assert.Equal("earay", PigLatin.Translate("ear"));
    }

    [Fact(Skip = "Remove to run test")]
    public void Word_beginning_with_i()
    {
        Assert.Equal("iglooay", PigLatin.Translate("igloo"));
    }

    [Fact(Skip = "Remove to run test")]
    public void Word_beginning_with_o()
    {
        Assert.Equal("objectay", PigLatin.Translate("object"));
    }

    [Fact(Skip = "Remove to run test")]
    public void Word_beginning_with_u()
    {
        Assert.Equal("underay", PigLatin.Translate("under"));
    }

    [Fact(Skip = "Remove to run test")]
    public void Word_beginning_with_a_vowel_and_followed_by_a_qu()
    {
        Assert.Equal("equalay", PigLatin.Translate("equal"));
    }

    [Fact(Skip = "Remove to run test")]
    public void Word_beginning_with_p()
    {
        Assert.Equal("igpay", PigLatin.Translate("pig"));
    }

    [Fact(Skip = "Remove to run test")]
    public void Word_beginning_with_k()
    {
        Assert.Equal("oalakay", PigLatin.Translate("koala"));
    }

    [Fact(Skip = "Remove to run test")]
    public void Word_beginning_with_x()
    {
        Assert.Equal("enonxay", PigLatin.Translate("xenon"));
    }

    [Fact(Skip = "Remove to run test")]
    public void Word_beginning_with_q_without_a_following_u()
    {
        Assert.Equal("atqay", PigLatin.Translate("qat"));
    }

    [Fact(Skip = "Remove to run test")]
    public void Word_beginning_with_ch()
    {
        Assert.Equal("airchay", PigLatin.Translate("chair"));
    }

    [Fact(Skip = "Remove to run test")]
    public void Word_beginning_with_qu()
    {
        Assert.Equal("eenquay", PigLatin.Translate("queen"));
    }

    [Fact(Skip = "Remove to run test")]
    public void Word_beginning_with_qu_and_a_preceding_consonant()
    {
        Assert.Equal("aresquay", PigLatin.Translate("square"));
    }

    [Fact(Skip = "Remove to run test")]
    public void Word_beginning_with_th()
    {
        Assert.Equal("erapythay", PigLatin.Translate("therapy"));
    }

    [Fact(Skip = "Remove to run test")]
    public void Word_beginning_with_thr()
    {
        Assert.Equal("ushthray", PigLatin.Translate("thrush"));
    }

    [Fact(Skip = "Remove to run test")]
    public void Word_beginning_with_sch()
    {
        Assert.Equal("oolschay", PigLatin.Translate("school"));
    }

    [Fact(Skip = "Remove to run test")]
    public void Word_beginning_with_yt()
    {
        Assert.Equal("yttriaay", PigLatin.Translate("yttria"));
    }

    [Fact(Skip = "Remove to run test")]
    public void Word_beginning_with_xr()
    {
        Assert.Equal("xrayay", PigLatin.Translate("xray"));
    }

    [Fact(Skip = "Remove to run test")]
    public void Y_is_treated_like_a_consonant_at_the_beginning_of_a_word()
    {
        Assert.Equal("ellowyay", PigLatin.Translate("yellow"));
    }

    [Fact(Skip = "Remove to run test")]
    public void Y_is_treated_like_a_vowel_at_the_end_of_a_consonant_cluster()
    {
        Assert.Equal("ythmrhay", PigLatin.Translate("rhythm"));
    }

    [Fact(Skip = "Remove to run test")]
    public void Y_as_second_letter_in_two_letter_word()
    {
        Assert.Equal("ymay", PigLatin.Translate("my"));
    }

    [Fact(Skip = "Remove to run test")]
    public void A_whole_phrase()
    {
        Assert.Equal("ickquay astfay unray", PigLatin.Translate("quick fast run"));
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

public static class PigLatinExtensions
{
    // Split the string (or any enumerable list of characters) into strings.
    // Similar to String.Split, but instead of a list of delimiters, this uses
    // a supplied function to determine if a character is a delimiter.
    public static IEnumerable<string> Split(this IEnumerable<char> source, Func<char, bool> isSeparator)
    {
        string currentWord = "";

        foreach (char elem in source)
        {
            if (!isSeparator(elem))
            {
                currentWord += elem;
            }
            else if (currentWord.Length > 0)
            {
                yield return currentWord;
                currentWord = "";
            }
        }

        if (currentWord.Length >= 0)
        {
            yield return currentWord;
        }
    }

    // Is the character a vowel?  Currently only 'a', 'e', 'i', 'o', and 'u'
    // return true;
    public static bool isVowel(char ch)
    {
        return ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u';
    }

    // Should a this consonant be treated as a vowel?  Look at the next
    // character to help decide.  Currently only 'yt' and 'xr' return true.
    public static bool isConsonantAsVowel(char ch, char next_ch)
    {
        return (ch == 'y' && next_ch == 't') || (ch == 'x' && next_ch == 'r');
    }

    // Should a vowel be treated as a consonant?  Look at the previous
    // character to help decide.  Currently only 'qu' returns true.
    public static bool isVowelAsConsonant(char ch, char prev_ch)
    {
        return ch == 'u' && prev_ch == 'q';
    }

    // Pull each character off of the word (from left to right) and see if it
    // should be treated as a vowel.  Once we get to a vowel, the rest of
    // the word (including the vowel) will be the first part of the output
    // word, the consonants will go next and then the characters "ay".
    public static string ToPigLatin(string word)
    {
        char lastConsonant = '\0';
        List<char> consonants = new List<char>();
        Stack<char> rest = new Stack<char>(word.ToLower().Reverse());

        while (rest.Count() > 0)
        {
            char nextChar = rest.Peek();

            // If we encounter a vowel and it shouldn't be treated like a
            // consonant exit the loop
            if (isVowel(nextChar) && !isVowelAsConsonant(nextChar, lastConsonant))
            {
                break;
            }

            // Check to see if the consonant we are at should be treated like
            // a vowel.
            nextChar = rest.Pop();
            if (rest.Count() > 0 && isConsonantAsVowel(nextChar, rest.Peek()))
            {
                rest.Push(nextChar);
                break;
            }

            consonants.Add(nextChar);
            lastConsonant = nextChar;
        }

        // 'consonants' now contains all the characters we want to add to the
        // end (with 'ay') and 'rest' contains all the rest.
        return new StringBuilder()
                        .Append(rest.ToArray())
                        .Append(consonants.ToArray())
                        .Append("ay")
                        .ToString();
    }

    // Convert each string in the list to piglatin
    public static IEnumerable<string> ToPigLatin(this IEnumerable<string> source)
    {
        foreach (string elem in source)
        {
            yield return ToPigLatin(elem);
        }
    }

    // Combine a list of strings into one string putting 'separator' between each.
    public static string Combine(this IEnumerable<string> source, string separator)
    {
        return String.Join(separator, source.ToList());
    }
}

public class PigLatin
{
    // Translate all the words in 'input' into piglatin.
    // Note:  Only handles words in lower case with no punctuation and at
    // least one vowel (not including the 'u' in 'qu').
    public static string Translate(string input)
    {
        if (input == null)
        {
            throw new ArgumentNullException("Invalid input string");
        }

        return input.Split(Char.IsWhiteSpace).ToPigLatin().Combine(" ");
    }
}

Community comments

Find this solution interesting? Ask the author a question to learn more.
Avatar of martinfreedman

Wow loong, try Linq or Regex

Avatar of ErikSchierboom

I agree with @martinfreedman that LINQ or a Regex could clean up the code. I'd recommend using a Regex, as that is ideally suited for this problem where you have to match strings.

What can you learn from this solution?

A huge amount can be learned from reading other people’s code. This is why we wanted to give exercism users the option of making their solutions public.

Here are some questions to help you reflect on this solution and learn the most from it.

  • What compromises have been made?
  • Are there new concepts here that you could read more about to improve your understanding?