Skip to content

Conversation

@evgenykuzin
Copy link

No description provided.

@evgenykuzin evgenykuzin changed the title Trie Евгений Кузин, Trie Mar 11, 2018

static class TrieNode {
Map<Character, TrieNode> children = new TreeMap<>();
boolean leaf;
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Лист - это узел с нулевым количеством дочерних узлов. То есть лист можно определить по пустому children. Зачем в таком случае нужна отдельная переменная - непонятно. В Trie нужно отмечать, соответствует ли узел какому-либо слову, или просто является промежуточным, но тогда и название у переменной должно быть другое.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

не понял, нужно изменить название переменной leaf на другое или удалить эту переменную вообще?

Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Я не понял, зачем нужна эта переменная. Если она обозначает лист (узел без дочерних узлов), то её нужно удалить, потому что узел можно легко вычислить с помощью переменной children. Если она обозначает что-то другое, то её нужно переименовать.

}

TrieNode root = new TrieNode();
List existedChars = new ArrayList<Character>();
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Указывайте тип хранящихся в List элементов.

Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Зачем вообще нужна переменная existedChars? Имя не очень помогает понять её смысл.

public void insert(String str) {
int i = 0;
TrieNode v = root;
boolean bro = false;
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

bro? Не очень понятное имя переменной.

TrieNode v = root;
boolean bro = false;
for (char ch : str.toLowerCase().toCharArray()) {
i++;
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Зачем вам нужна переменная i, если она нигде не используется?

if (!v.children.containsKey(ch)){
v.children.put(ch, new TrieNode());
}
else {
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Можно писать без фигурной скобки и на одной строке, т.е. else if.

}
}
return result;
}
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Не хватает поиска всех строк в дереве с заданным префиксом - это было в задании. Кроме того, нужно написать стандартные методы, такие как toString, equals, hashCode.

TrieNode v = root;
boolean broExist = false;
String str2 = str;
System.out.println(str2);
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Используйте логирование вместо println. Логирование вы всегда можете отключить одной командой, а println придется вручную убирать из кода.

for (char ch : str.toLowerCase().toCharArray()) {
if ( v != root && !existedChars.contains(ch) ) {
System.out.println(v.children.keySet());
//v.children.remove(ch);
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Не оставляйте комментарии в коде. Если понадобится вернуться к предыдущему варианту, то все старые версии вашего кода, которые вы коммитили, есть в гите и на GitHub-е.

if ( v != root && !existedChars.contains(ch) ) {
System.out.println(v.children.keySet());
//v.children.remove(ch);
v.children.put('@', v.children.remove(ch));
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Что значит @?

Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Желательно не выполнять опасные действия, такие как удаление элемента, при вычислении аргументов вызова. Легко забыть про это при чтении кода. Выполните удаление в отдельной строке кода, а результат выполнения сохраните в переменную.

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import javax.xml.crypto.Data;
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Лишний импорт. Он вам в коде точно не нужен, лучше его удалить.

}

TrieNode root = new TrieNode();

Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Много лишних пустых строк. Касается всего кода.

node.children.get(ch).brunch = true;
}

} else if (node.brunch) node.brunch = false;
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Если ставите фигурные скобки у одной ветви if-а, то ставьте и у другой.


searchHelp(word, prefix, node);

System.out.println("_________________");
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Если в описании метода не сказано, что он должен выводить что-то на экран, то не стоит писать в нем println. Метод должен возвращать полученное значение, а не выводить на экран. Исключение - логирование.

static class TrieNode {
Map<Character, TrieNode> children = new TreeMap<>();
boolean leaf;
boolean brunch;
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

😞
Imgur

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

упс


@Test
void exampleTest() {
logger.info("Test started");
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Не все методы протестированы.

@h31
Copy link
Owner

h31 commented Mar 15, 2018

Не реализованы стандартные методы, некоторые старые замечания ещё не исправлены. Пока что 3.

@h31 h31 added the mediocre Удовлетворительно label Mar 15, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

mediocre Удовлетворительно

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants