Skip to content

Task 10#2

Open
YaroslavKomarov wants to merge 15 commits intomasterfrom
task_10
Open

Task 10#2
YaroslavKomarov wants to merge 15 commits intomasterfrom
task_10

Conversation

@YaroslavKomarov
Copy link
Owner

No description provided.

@Toxin65
Copy link

Toxin65 commented Dec 22, 2020

Определитесь, пожалуйста, что из этого мне смотреть.
Заявлено было 8,9. Вижу два ПР, и только в одном что-то про Таск 10...

@YaroslavKomarov
Copy link
Owner Author

Я, честно говоря, затрудняюсь ответить. Я проходил ревью у Елены Александровны и она мне сказала, внести последнюю правку, после чего она могла бы принять у меня task 8 и task 9. Однако к тому моменту я уже выполнили и task 10, который по просьбе Елены Александровны поместил в отдельный pull

@Toxin65
Copy link

Toxin65 commented Dec 22, 2020

Ну, я при просмотре 10го накидаю замечаний по всем трём, чует моё сердце...
Так что может разницы то и нет.
Тем не менее, мне нужны чёткие указания. Что мне смотреть и в какую графу потом писать, соответственно.

@YaroslavKomarov
Copy link
Owner Author

Елена Александровна мне сказала, что Вы будете проверять у меня 10 задание.

@YaroslavKomarov
Copy link
Owner Author

Также Елена Александровна сказала, что сможет зачесть мне 8 и 9 задание, если Вы зачтете мне 10)

@Toxin65
Copy link

Toxin65 commented Dec 25, 2020

Ок, гляжу.

Copy link

@Toxin65 Toxin65 left a comment

Choose a reason for hiding this comment

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

Исправьте то, что есть. Потом продолжим.
Извините, немного недочитал, надо уделить внимание всем, по возможности...

#pragma once

class MCell {
private:

This comment was marked as resolved.


MCell::MCell() {
m_down = false;
m_right = false;

This comment was marked as resolved.

m_right = false;
}

bool MCell::down() const { return m_down; }

This comment was marked as resolved.

@@ -0,0 +1,26 @@
#pragma once
#include <vector>
using namespace std;

This comment was marked as resolved.

private:
int m_i, m_j;
int m_distance;
MTreeNode* m_parent;

This comment was marked as resolved.

void PrintTreeInfo(const MTreeNode* tree, const int& width, const int& height);
vector<int> GetRandCoordinates(const int& width, const int& height);

void PrintTreeInfo(const MTreeNode* tree, const int& width, const int& height) {
Copy link

Choose a reason for hiding this comment

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

Ох, как плохо без комментариев.
Что делает эта функция? Зачем программист её написал?

Copy link
Owner Author

Choose a reason for hiding this comment

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

Функция для получения произвольных координат на границе рандомного лабиринта. Теперь этот комментарий прописал в коде

vector<vector<string>> to_print(height);
for (auto& vctr : to_print)
vctr = vector<string>(width);
while (true) {
Copy link

Choose a reason for hiding this comment

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

for(;;)

int i = tree->i();
int j = tree->j();
sum_weights += tree->distance();
max_weight = tree->distance() > max_weight ? tree->distance() : max_weight;
Copy link

Choose a reason for hiding this comment

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

std::max

}
for (auto& vctr : to_print) {
for (auto& str : vctr)
cout << setw(5) << str;
Copy link

Choose a reason for hiding this comment

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

Неплохо...

Copy link
Owner Author

Choose a reason for hiding this comment

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

Тоже забыл это поправить перед отправкой! В setw() теперь передаю длину строки, полученной от вершины с максимальным весом + 1 (const int max_len = size(to_string(max_weight) ....setw(max_len) << str...)

cout << setw(5) << str;
cout << endl;
}
int average_weight = sum_weights / (1. * width * height);
Copy link

Choose a reason for hiding this comment

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

const

Однострочные методы инициализированны в заголовочных файлах;
Убрал из заголовочников
Одностроные методы проинициализированны в заголовочных файлах;
В заголовочных больше не используются пространства имен;
const есть везде, где можно;
Исправлен нелепый метод searchNode;
Добавлен метод поиска корня в дереве searchRoot;
во всех заголовочниках сначала идет public-секция;
При живом родителе у дочернего элемента distance правильный;
Лишние ссылки при прохождении по векторам (и при int) убраны;
Перед добавлением ребенка происходит проверка на его наличие к родителя;
m_dict из класса Maze больще не член класса и он sctatic;
добавлены assert при попытке получения клетки лабиринта и где-то еще;
Добавлена проверка на соседство двух клеток для методов класса Maze;
Теперь, если звязи не было метод removeConnection возвращает корректное
значение;
Вообще, кажется, все исправил, что было прописано Вами.
Copy link

@Toxin65 Toxin65 left a comment

Choose a reason for hiding this comment

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

Давайте поправим...
Всё бы хорошо. Но есть непростительное!

@@ -0,0 +1,5 @@
//#include "MCell.h"
Copy link

Choose a reason for hiding this comment

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

Это можно было бы и остаивть. Тогда он откомпилится в отдельный объектный файл. А это неплохо!

const MTreeNode* searchNode(const int i, const int j);
const MTreeNode* searchRoot(const MTreeNode* node);
private:
int m_i, m_j = 0;
Copy link

Choose a reason for hiding this comment

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

Что-то тут копипастой запахло.
Где-то уже видел...

Copy link
Owner Author

Choose a reason for hiding this comment

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

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

Copy link

Choose a reason for hiding this comment

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

Дык не про то речь... Ну и ладно...


MTreeNode::MTreeNode(MTreeNode* parent) {
m_parent = parent;
m_distance = parent == nullptr ? 0 : parent->m_distance + 1;
Copy link

Choose a reason for hiding this comment

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

Можо не тернарным, а просто при наличии родителя у него спросить и +1...

if (child->m_i == i && child->m_j == j)
return false;
m_children.push_back(new MTreeNode(this));
m_children[m_children.size() - 1]->m_distance = this->m_distance + 1;

This comment was marked as resolved.

}

MTreeNode* MTreeNode::hasChild(int i, int j) const{
const int count = m_children.size();
Copy link

Choose a reason for hiding this comment

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

Это тут зачем. Осталось?

bool Maze::hasConnection(int i1, int j1, int i2, int j2) const {
if ((abs(i1 - i2) + abs(j1 - j2) != 1)) return false;
if (j2 < 0 || j2 >= m_width || i2 < 0 || i2 >= m_height)
return false;
Copy link

Choose a reason for hiding this comment

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

Может вынести эти штучки отдельно. А то дублирование получается. Ниже то же самое написано...

return m_field[ind1 * m_width + ind2].down();
}
else
return false;
Copy link

Choose a reason for hiding this comment

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

Тут вообще ассерт, такого быть то не должно в природе!
Ассерт -- хорошая проверка программиста, что он что-то накосячил...

if (j2 < 0 || j2 >= m_width || i2 < 0 || i2 >= m_height)
return false;
int ind1 = min(i1, i2);
int ind2 = min(j1, j2);
Copy link

Choose a reason for hiding this comment

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

const им всем же!

if (j + 1 == m_width)
cout << endl;
}
} No newline at end of file
Copy link

Choose a reason for hiding this comment

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

Пустая строка же!!!

int sum_weights = 0;
int max_weight = 0;
queue<const MTreeNode*> nodes;
vector<vector<string>> to_print(height);
Copy link

Choose a reason for hiding this comment

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

Да пусть будет...
Но предупреждение вы получили.
При приёме на работу я такую фигню не потерплю!!!

в конструкторе MTreeNode упразднил тернарный оператор;
заменил индексацию для вектора в методе addChild на .back;
убрал вычисление m_distance из addChild;
убрал лишнее вычисление длинные вектора детей в hasChild;
Вернул ссылку для итерирования по вектору в hasChild;
Прописал несколько комментариев для serchNode, searchRoot;
Убрал return nullptr у метода searchNode;
Уменшил вложенность для большей читаемости кода у searchRoot;
Исправил assert у метода cell класса Maze;
Вынес в отделный метод checkConnection проверку на вшивость для всех связей;
Добавил в метод checkConnecion проверку нереального случая;
добавли нужные const;
довил пустую строку в конце Maze.cpp.
Copy link

@Toxin65 Toxin65 left a comment

Choose a reason for hiding this comment

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

Беды с памятью... Большие беды! Разберитесь с new delete..

return nullptr;
}

const MTreeNode* MTreeNode::searchNode(const int i, const int j) {
Copy link

Choose a reason for hiding this comment

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

Доки надо в заголовках. Ну да ладно... На будущее...
Ну и кодировка похерилась...

#include <iostream>
#include <queue>
#include "MTreeNode.h"
using namespace std;

This comment was marked as resolved.


MTreeNode::~MTreeNode() {
for (auto ptr : m_children)
delete ptr;

This comment was marked as resolved.

Copy link
Owner Author

Choose a reason for hiding this comment

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

Речь о том, что я мог просто вызвать delete[] ? Или я оставляю в памяти висеть детей того родителя, у которого вызывается деструктор?

Copy link

Choose a reason for hiding this comment

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

Сорян, всё норм. Я уже обревьювился в конец...

using namespace std;

MTreeNode* MTreeNode::begintTree(int i, int j) {
MTreeNode* node = new MTreeNode(nullptr);

This comment was marked as resolved.

Copy link
Owner Author

Choose a reason for hiding this comment

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

Тут утечка, верно? Кстати говоря, я вызывал delete для корня дерева в practise_18.11.20.cpp в случае построения второго лабиринта (про третий благополучно забыл). Но я догадываюсь, что это не есть хорошо. Можете намекнуть на пример корректного поведения для beginTree?

Copy link

Choose a reason for hiding this comment

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

Извиняюсь, запутался... Всё норм.

Copy link

@Toxin65 Toxin65 left a comment

Choose a reason for hiding this comment

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

Не идеально... Но зачесть можно.

const MTreeNode* child(int i) const { return m_children[i]; }
static MTreeNode* begintTree(int i, int j);
const MTreeNode* searchNode(const int i, const int j);
const MTreeNode* searchRoot(const MTreeNode* node);
Copy link

Choose a reason for hiding this comment

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

Оба метода сами по себе const.

#include "MTreeNode.h"
using namespace std;

MTreeNode* MTreeNode::begintTree(int i, int j) {
Copy link

Choose a reason for hiding this comment

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

Ну ё-маё... А я его ищу. beginTree!!! А не begint...


MTreeNode::~MTreeNode() {
for (auto ptr : m_children)
delete ptr;
Copy link

Choose a reason for hiding this comment

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

Сорян, всё норм. Я уже обревьювился в конец...

}

MTreeNode* MTreeNode::hasChild(int i, int j) const{
for (auto &child : m_children){
Copy link

Choose a reason for hiding this comment

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

Нет смысла ссылку делать. Получается ссылка на указатель -- это тут лишнее...

int main()
{
const int maze_size = 5;
Maze maze1 = Maze(maze_size, maze_size);
Copy link

Choose a reason for hiding this comment

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

Maze maze1(maze_size, maze_size);

Конечно же исправил beginTree)));
убрал ссылку в hasChild;
Теперь корректно создаю экземпляры класса Maze.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants

Comments