Skip to content

Comments

LZW#4

Open
Andrw-404 wants to merge 5 commits intomainfrom
LZW
Open

LZW#4
Andrw-404 wants to merge 5 commits intomainfrom
LZW

Conversation

@Andrw-404
Copy link
Owner

No description provided.

public class TrieTests
{
[Test]
public void Initialization_Create256Nodes()

Choose a reason for hiding this comment

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

Одного теста недостаточно. В идеале, должно быть по несколько тестов на каждую функцию: на обычное поведение и на граничные случаи.

{
public static class LZW
{
public static int[] Compress(byte[] input)

This comment was marked as resolved.

{
var trie = new Trie();
var codes = new List<int>();
trie.Reset();

Choose a reason for hiding this comment

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

Зачем вызывать Reset сразу после инициализации? Нельзя всё необходимое сделать в конструкторе?

}
}

if (trie.GetCurrentCode() != -1)

Choose a reason for hiding this comment

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

Если GetCurrentCode -- дорогая операция, нужно сохранить её результат во временную переменную, чтобы не вызывать дважды. А если дешёвая, то GetCurrentCode должен быть свойством.


foreach (byte b in input)
{
if (!trie.TryGetNextNode(b, out int code))

Choose a reason for hiding this comment

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

TryGetNextNode что-то кладёт в out int code только когда возвращает false? Странное решение. Название функции и аргументы очень похожи на TryGet у Dictionary, но он делает наоборот -- out-параметр действителен только если TryGet вернул true. И не только TryGet так делает -- это довольно ожидаемое поведение для всех функций, которые начинаются с Try.

return Array.Empty<byte>();
}

var dictionary = new Dictionary<int, List<byte>>();

Choose a reason for hiding this comment

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

Ключи этого словаря -- int, заполняются все ключи сразу, других не добавляется, размер известен заранее. Почему бы не использовать массив?

И не называйте, пожалуйста, переменную dictionary. Думаю, о ней известно больше, чем просто "это словарь". В конце концов, то, что это Dictionary видно из объявления.

break;
}

string decompressedFile = filePath[..^".zipped".Length] + "chgd";

Choose a reason for hiding this comment

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

С помощью System.Path это можно сделать проще, ну или хотя бы понятнее.

int[] codes = LZW.Compress(inputBytes);

using FileStream fs = new (outputPath, FileMode.Create);
byte[] buffer = new byte[codes.Length * 4];

Choose a reason for hiding this comment

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

Что означает число 4?


byte[] outputBytes = LZW.Decompress(codes);
File.WriteAllBytes(outputPath, outputBytes);
} No newline at end of file

Choose a reason for hiding this comment

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

nit: Файл должен заканчиваться символом новой строки.

FileInfo original = new (inputPath);
FileInfo compressed = new (outputPath);
double ratio = (double)original.Length / compressed.Length;
Console.WriteLine($"Коэффициент сжатия: {ratio:F2}");

Choose a reason for hiding this comment

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

По-моему здесь неправильно посчитан коэффициент сжатия:
изображение
изображение

P.S. Это очень маленький файл, на нём мог получиться любой коэффициент, и это не страшно. Но точно не бесконечность.

Copy link

@p-senichenkov p-senichenkov left a comment

Choose a reason for hiding this comment

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

LGTM

Comment on lines +20 to +25
Assert.Multiple(() =>
{
Assert.That(result, Is.True);
Assert.That(code, Is.EqualTo(-1));
Assert.That(trie.CurrentCode, Is.EqualTo(existingByte));
});

Choose a reason for hiding this comment

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

Не думаю, что здесь сильно нужен Multiple, но дело ваше. Только лучше использовать новый синтаксис.

Comment on lines +22 to +25
using FileStream fs = new (outputPath, FileMode.Create);
byte[] buffer = new byte[codes.Length * sizeof(int)];
Buffer.BlockCopy(codes, 0, buffer, 0, buffer.Length);
fs.Write(buffer, 0, buffer.Length);

Choose a reason for hiding this comment

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

nit: При таком использовании using этот FileStream будет жить до конца метода, хотя он нужен только ближайшие 4 строчки. Конкретно для FileStream это не очень страшно, но лучше использовать using с фигурными скобками. И открывать файл раньше времени тоже смысла мало.

/// <summary>
/// Resets the current node pointer to the root node.
/// </summary>
public void Reset() => this.current = this.root;

Choose a reason for hiding this comment

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

Я правильно понимаю, что Reset теперь нигде не вызывается?

}

/// <summary>
/// Gets the number of children nodes in the root (always 256 after initialization).

Choose a reason for hiding this comment

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

Если это свойство всегда 256 после инициализации, а до инициализации оно вызвано быть не может, так ли оно нужно?

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.

2 participants