Невозможно преобразовать Pig Latin в Engli sh просто так - вам нужен человек, программа с доступом к базе данных слов или нейронный net или что-то, что было обучено на базе данных слов. Без этого вы будете преобразовывать слова обратно в английский sh только в том случае, если они изначально начинались с гласной буквы или их первая буква была согласной, а вторая буква - гласной. В противном случае у машины буквально нет возможности определить, где слово закончилось.
По этой причине вам нужно создать метод, который выдает List<String>
, например:
public static List<String> allPossibleSentences(String inPigLatin) {
List<String> pigWords = Arrays.asList(inPigLatin.split("\\s"));
//You can also use a method reference here
List<List<String>> possSentences = cartesianProduct(pigWords.stream().map(word -> possibleEnglishWords(word)).collect(Collectors.toList()));
return possSentences.stream().map(words -> String.join(" ", words)).collect(Collectors.toList());
}
Но так как вам нужен метод fromPig в вашем коде, вы можете написать его следующим образом:
public static String fromPig(String inPigLatin) {
return allPossibleSentences(inPigLatin).get(0);
}
Это по сравнению с ответом Арвинда Кумара Авина sh, поскольку он генерирует все перестановки , но я думаю, что будет более полезно, если у вас есть наиболее вероятный случай и все возможные предложения.
Пример основного метода
public static void main(String[] args) {
String inPigLatin="avajay isyay ayay onderfulway ogrammingpray " +
"anguagelay andyay objectyay orientedyay ogrammingpray " +
"isyay hetay estbay ingthay afteryay icedslay eadbray";
System.out.println(fromPig(inPigLatin));
inPigLatin = "icedslay eadbray";
System.out.println("\nExpected = sliced bread, gotten = " + fromPig(inPigLatin));
System.out.println(String.join("\n", allPossibleSentences(inPigLatin)));
}
Пример вывода
java is a wonderful rogrammingp language and object oriented rogrammingp is the best hingt after liceds readb
Expected = sliced bread, gotten = liceds readb
liceds readb
liceds bread
liceds dbrea
sliced readb
sliced bread //Here you have the right answer, but your method has no way to confirm that
sliced dbrea
dslice readb
dslice bread
dslice dbrea
Ваш класс PigLatin теперь
import java.util.Arrays;
import java.util.List;
import java.util.ArrayList;
import java.util.stream.Collectors;
class PigLatin {
//Put your toPig and toPigWord methods here (I couldn't find them)
public static String fromPig(String inPigLatin) {
return allPossibleSentences(inPigLatin).get(0);
}
/* Methods that above code relies on */
private static List<String> possibleEnglishWords(String word) {
List<String> possibilities = new ArrayList<>();
if (word.matches(".*yay$")) {
possibilities.add(word.substring(0, word.length() - 3));
return possibilities;
}
//Remove the pig latin part
word = word.substring(0, word.length() - 2);
for (int i = word.length() - 1; i >= 0; i --) {
if (isVowel(word.charAt(i))) break;
if (word == "anguagel") System.out.println("char = " + word.charAt(i));
possibilities.add(word.substring(i) + word.substring(0, i));
}
return possibilities;
}
//Put all the words together
public static List<List<String>> cartesianProduct(List<List<String>> possWordArr) {
if (possWordArr.size() == 1) {
List<List<String>> possSentencesAsWords = new ArrayList<>();
possSentencesAsWords.add(possWordArr.get(0));
return possSentencesAsWords;
}
return _cartesianProduct(0, possWordArr);
}
//Helper method
private static List<List<String>> _cartesianProduct(int index, List<List<String>> possWordArr) {
List<List<String>> ret = new ArrayList<>();
if (index == possWordArr.size()) {
ret.add(new ArrayList<>());
} else {
for (String word : possWordArr.get(index)) {
for (List<String> words : _cartesianProduct(index + 1, possWordArr)) {
words.add(0, word);
ret.add(words);
}
}
}
return ret;
}
private static boolean isVowel(char c) {
c = toUppercase(c);
switch (c) {
case 'A':
case 'E':
case 'I':
case 'O':
case 'U':
return true;
default:
return false;
}
}
private static char toUppercase(char c) {
if (c >= 'a') return (char) (((char) (c - 'a')) + 'A');
else return c;
}
}