Skip to content

Instantly share code, notes, and snippets.

@antvconst
Created September 8, 2016 16:23
Show Gist options
  • Select an option

  • Save antvconst/904921782b06df8f5308774402d4f468 to your computer and use it in GitHub Desktop.

Select an option

Save antvconst/904921782b06df8f5308774402d4f468 to your computer and use it in GitHub Desktop.
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;
class Coding {
// Определяет, является ли символом разделителем
public static boolean isDelimiter(char c) {
return (c == '#') ||
(c == ',') ||
(c == ';') ||
(c == '.') ||
(c == ':');
}
// Определяет, состоит ли строка полностью из больших латинских букв
public static boolean isUpperCase(String s) {
for (char c : s.toCharArray())
if (!Character.isUpperCase(c))
return false;
return true;
}
// Определяет, состоит ли строка полностью из маленьких латинских букв
public static boolean isLowerCase(String s) {
for (char c : s.toCharArray())
if (!Character.isLowerCase(c))
return false;
return true;
}
public static void main(String[] args) throws IOException {
Map<String, Integer> codeTable = new HashMap<>(); // В качестве таблицы используем ассоциативный массив типа HashMap
// Переменные, хранящие значение текущего кода для соответствующих типов слов
int curNonterminalCode = 11;
int curTerminalCode = 51;
int curSemanticCode = 101;
// Инициализируем постоянную часть кодовой таблицы
codeTable.put(":", 1);
codeTable.put("(", 2);
codeTable.put(")", 3);
codeTable.put(".", 4);
codeTable.put("!", 5);
codeTable.put(";", 6);
codeTable.put(",", 7);
codeTable.put("#", 8);
codeTable.put("[", 9);
codeTable.put("]", 10);
codeTable.put("Eofgram", 1000);
String input = new String(Files.readAllBytes(Paths.get("/home/falceeffect/G.txt"))); // Читаем из файла все содержимое
String word = ""; // Буфер текущего слова
for (char c : input.toCharArray()) {
if ((!Character.isSpaceChar(c)) && (c != '\n') && (c != '\r')) { // Отбрасываем пробелы и переводы строк\кареток
if (isDelimiter(c)) { // Если текущий символ - разделитель, то классифицируем и кодируем слово
if (codeTable.containsKey(word)) // Проверяем, не встречалось ли уже такое слово
System.out.println(word + " <- Not new: " + codeTable.get(word)); // Если встречалось, берем существующий код
else {
int code = -1;
// Слева от пробела или большие латинские - нетерминал
if ((c == ':') || (isUpperCase(word))) {
code = curNonterminalCode++;
System.out.println(word + " <- new nonterminal: " + code);
}
// Начинается с знака доллара - семантика
else if (word.charAt(0) == '$') {
code = curSemanticCode++;
System.out.println(word + " <- new semantic: " + code);
}
// Маленькие латинские или в кавычках - терминал
else if ((isLowerCase(word)) || ((word.charAt(0) == '\'') && (word.charAt(word.length() - 1) == '\''))) {
code = curTerminalCode++;
System.out.println(word + " <- new terminal: " + curTerminalCode);
}
codeTable.put(word, code); // Добавляем в таблицу
}
System.out.println(c + " <- delimiter: " + codeTable.get(""+c)); // Не забываем вывести код разделителя
word = ""; // Очищаем буфер слова
} else {
word += c; // Если текущий символ - не разделитель, то добавляем его в буфер слова
}
}
}
System.out.println(word + " <- eof: " + codeTable.get(word)); // Не забываем про конец
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment