src/main/java/PigLatin.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class PigLatin {
    private static final Pattern VOWELISH = Pattern.compile("^([aeiou]|yt|xr)");
    private static final Pattern CONSONANTISH = Pattern.compile("^(ch|qu|thr?|sch|[a-z](qu)?)");

    public static String translate(String input) {
        return Pattern.compile(" ").splitAsStream(input)
                .map(PigLatin::translateWord)
                .collect(Collectors.joining(" "));
    }

    private static String translateWord(String word) {
        return rotateLetters(word, numberOfLettersToMove(word)) + "ay";
    }

    private static int numberOfLettersToMove(String word) {
        if (VOWELISH.matcher(word).find())
            return 0;
        else
            return Stream.of(CONSONANTISH)
                    .map(pattern -> pattern.matcher(word))
                    .filter(Matcher::find)
                    .mapToInt(Matcher::end)
                    .findFirst()
                    .orElse(0);
    }

    private static String rotateLetters(String word, int num) {
        return word.substring(num) + word.substring(0, num);
    }
}

@abo64 and @dariograziotto think this looks great

Comments


You're not logged in right now. Please login via GitHub to comment