Created
October 14, 2016 16:00
-
-
Save antvconst/628a8d9639a97ff4dc2f3382f21fcbe3 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.IOException; | |
import java.nio.file.Files; | |
import java.nio.file.Paths; | |
import java.util.HashMap; | |
import java.awt.*; | |
import java.awt.event.*; | |
import javax.swing.*; | |
// Класс кодовой таблицы, являющийся небольшой надстройкой над стандартной хэш-таблицей | |
class CodeTable extends HashMap<String, Integer> { | |
// Переменные, хранящие значение текущего кода для соответствующих типов слов | |
int curNonTerminalCode = 11; | |
int curTerminalCode = 51; | |
int curSemanticCode = 101; | |
} | |
// Класс окона | |
class Window extends JFrame { | |
JTextArea inputF, outputF; | |
JScrollPane inputS, outputS; | |
public Window(String input, String output) { | |
super("Coding"); | |
Container container = getContentPane(); | |
container.setLayout(new FlowLayout()); | |
inputF = new JTextArea(input, 20, 40); | |
outputF = new JTextArea(output, 20, 40); | |
outputF.setLineWrap(true); | |
inputS = new JScrollPane(inputF); | |
outputS = new JScrollPane(outputF); | |
inputF.setEditable(false); | |
outputF.setEditable(false); | |
container.add(inputS); | |
container.add(outputS); | |
pack(); | |
//setSize(850, 650); | |
setVisible(true); | |
} | |
} | |
class Coding { | |
// Определяет, является ли символ разделителем | |
public static boolean isDelimiter(char c) { | |
return (c == '#') || | |
(c == ',') || | |
(c == ';') || | |
(c == '.') || | |
(c == ':') || | |
(c == '*') || | |
(c == '(') || | |
(c == ')') || | |
(c == '[') || | |
(c == ']'); | |
} | |
// Возвращает код слова, либо находя его в таблице, либо добавляя в таблицу | |
public static int getCode(String word, char delim, CodeTable codeTable) { | |
int code = -1; | |
if (codeTable.containsKey(word)) { // Проверяем, не встречалось ли уже такое слово, иначе берем существующий код | |
code = codeTable.get(word); | |
System.out.println(word + " <- Existing: " + codeTable.get(word)); | |
} | |
else { | |
// Начинается с знака доллара - семантика | |
if (word.charAt(0) == '$') { | |
code = codeTable.curSemanticCode++; | |
System.out.println(word + " <- new semantic: " + code); | |
} | |
// В кавычках - терминал | |
else if (((word.charAt(0) == '\'') && (word.charAt(word.length() - 1) == '\''))) { | |
code = codeTable.curTerminalCode++; | |
System.out.println(word + " <- new terminal: " + code); | |
} | |
// В иных случая - нетерминал | |
else { | |
code = codeTable.curNonTerminalCode++; | |
System.out.println(word + " <- new nonterminal: " + code); | |
} | |
codeTable.put(word, code); // Добавляем в таблицу | |
} | |
return code; | |
} | |
public static String process(String input) { | |
CodeTable codeTable = new CodeTable(); // В качестве таблицы используем ассоциативный массив типа HashMap | |
// Инициализируем постоянную часть кодовой таблицы | |
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 output = ""; | |
String word = ""; // Буфер текущего слова | |
boolean qOpen = false; // Флаг открытой кавычки | |
for (char c : input.toCharArray()) { | |
if ((!Character.isSpaceChar(c)) && (c != '\n') && (c != '\r')) { // Отбрасываем пробелы и переводы строк/кареток | |
if (c == '$') { // Видим начало семантики, значит предыдущее слово точно кончилось и можно его закодировать | |
if (!word.isEmpty()) | |
output += getCode(word, c, codeTable) + " "; | |
word = ""; | |
} | |
if (c == '\'') // Видим кавычку | |
{ | |
if (!qOpen) { // Если кавычка открывается, то кодируем предыдущее слово | |
if (!word.isEmpty()) | |
output += getCode(word, c, codeTable) + " "; | |
word = "" + c; | |
qOpen = true; | |
} | |
else { // Если кавычка закрывается, то добавляем её к слову и кодируем его | |
word += c; | |
output += getCode(word, c, codeTable) + " "; | |
qOpen = false; | |
word = ""; | |
} | |
} | |
else if (isDelimiter(c) && !qOpen) { // Если текущий символ - разделитель, находящийся не в кавычках, то кодируем слово | |
if (!word.isEmpty()) { | |
output += getCode(word, c, codeTable) + " "; | |
} | |
output += codeTable.get("" + c) + " "; // Не забываем вывести код разделителя | |
if (c == '.') | |
output += "\n"; | |
System.out.println(c + " <- delimiter: " + codeTable.get("" + c)); | |
word = ""; | |
} | |
else | |
word += c; | |
} | |
} | |
output += codeTable.get(word) + "\n"; // Не забываем про последнее слово, оставшееся без разделителя | |
System.out.println(word + " <- eof: " + codeTable.get(word)); | |
return output; | |
} | |
public static void main(String[] args) throws IOException { | |
FileDialog fd = new FileDialog(new JFrame(), "Choose a file", FileDialog.LOAD); | |
fd.setVisible(true); | |
String input = new String(Files.readAllBytes(Paths.get(fd.getDirectory() + fd.getFile()))); // Читаем из файла все содержимое | |
String output = process(input); | |
Window win = new Window(input, output); | |
win.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment