Skip to content

Головнев Максим#270

Open
maximka200 wants to merge 11 commits intokontur-courses:masterfrom
maximka200:TagCloud
Open

Головнев Максим#270
maximka200 wants to merge 11 commits intokontur-courses:masterfrom
maximka200:TagCloud

Conversation

@maximka200
Copy link

No description provided.

- написал основную структуру логику CircularCloudLayouter и Spiral
@maximka200
Copy link
Author

maximka200 commented Nov 28, 2025

@Dimques

const double radiusStep = 1.0;

angle += angleStep;
var radius = radiusStep * angle;

This comment was marked as resolved.

}

private bool IntersectsWithAny(Rectangle rect) =>
Rectangles.Any(r => r.IntersectsWith(rect));
Copy link

Choose a reason for hiding this comment

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

Будет очень дорого, если будет, например, много мелких квадратов. Попробуй эвристику похитрее придумать. Или посмотри в сторону геометрических алгоритмов.


namespace TagCloud;

public class Spiral(Point center)

This comment was marked as resolved.

private bool IntersectsWithAny(Rectangle rect) =>
Rectangles.Any(r => r.IntersectsWith(rect));

private Rectangle MoveToCenter(Rectangle rect)

This comment was marked as resolved.

public Rectangle PutNextRectangle(Size rectangleSize)
{
if (rectangleSize.Width <= 0 || rectangleSize.Height <= 0)
throw new ArgumentException("Размер прямоугольника должен быть положительным");

This comment was marked as resolved.


namespace TagCloud;

public class CircularCloudLayouter(Point center)

This comment was marked as resolved.

if (rectangleSize.Width <= 0 || rectangleSize.Height <= 0)
throw new ArgumentException("Размер прямоугольника должен быть положительным");

return RectangleSpiral.TryAddRectangleInCenter(rectangleSize, out var rectangle)

This comment was marked as resolved.


public Rectangle AddRectangle(Size rectangleSize)
{
while (true)

This comment was marked as resolved.

return false;
}

#region Helpers

This comment was marked as resolved.

EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Samples", "Samples\Samples.csproj", "{B5108E20-2ACF-4ED9-84FE-2A718050FC94}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TagsCloudVisualization", "TagsCloudVisualization\TagsCloudVisualization.csproj", "{6580A616-7832-45F4-8A9A-E9A5D4FE64A8}"

This comment was marked as resolved.

- доп. проект с примерами использования библиотеки
- визуализация упавших тестов
- переделал логику
@@ -0,0 +1,129 @@
using System.Drawing;
using ArgumentOutOfRangeException = System.ArgumentOutOfRangeException;

This comment was marked as resolved.

Copy link
Author

Choose a reason for hiding this comment

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

у меня ломается почему то

Вроде бы без этого работает

изображение изображение

Copy link
Author

Choose a reason for hiding this comment

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

а, все понял о чем ты

private readonly List<Rectangle> rectangles = [];
public IReadOnlyCollection<Rectangle> Rectangles => rectangles.AsReadOnly();

private int failureStreak;

This comment was marked as resolved.

private int failureStreak;
private int currentStep = DefaultStep;

private const int DefaultStep = 1;

This comment was marked as resolved.

public IReadOnlyCollection<Rectangle> Rectangles => rectangles.AsReadOnly();

private int failureStreak;
private int currentStep = DefaultStep;

This comment was marked as resolved.

}
}

private Rectangle MoveAtTheWay(Rectangle rectangle, int dx, int dy, bool toCenter, int maxStep)

This comment was marked as resolved.


var boundingWidth = maxX - minX;
var boundingHeight = maxY - minY;
var boundingArea = (double)boundingWidth * boundingHeight;

This comment was marked as resolved.

[SetUp]
public void Setup()
{
center = new Point(0, 0);

This comment was marked as resolved.

namespace TagCloudTests;

[TestFixture]
public class CloudVisualizationConfigBuilderTests
Copy link

Choose a reason for hiding this comment

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

Хвалю за попытку хорошо сделать, но кажется, что тесты на билдер излишни - как-будто присваивание в этих тестах проверяешь, не? :)

}

[Test]
public void ConfigIsNull_ShouldThrowArgumentNullException()

This comment was marked as resolved.

}

[Test]
public void GetNextPoint_ShouldReturnDifferentPoints()

This comment was marked as resolved.

return Math.Sqrt(halfW * halfW + halfH * halfH);
}

private static bool CirclesIntersect(Point c1, double r1, Point c2, double r2)

This comment was marked as resolved.

var distX = Math.Abs(center.X - shiftedCenter.X);
var distY = Math.Abs(center.Y - shiftedCenter.Y);

if (dx != 0 && distX >= bestDistX ||
Copy link

Choose a reason for hiding this comment

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

В строчку норм будет смотреться

};

var shiftedCenter = GetCenter(shifted);
var distX = Math.Abs(center.X - shiftedCenter.X);

This comment was marked as resolved.

private Rectangle FindBestPositionWithExponentialStep(Rectangle rectangle, int dx, int dy)
{
var best = rectangle;
var bestCenter = GetCenter(best);
Copy link

Choose a reason for hiding this comment

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

Хороший кандидат на метод-расширение для Rectangle.

Copy link
Author

Choose a reason for hiding this comment

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

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

private void AddRectangle(Rectangle rect)
{
rectangles.Add(rect);
var c = GetCenter(rect);

This comment was marked as resolved.

{
placementFailureStreak++;

currentAngleStepMultiplier =

This comment was marked as resolved.

[Repeat(100)]
public void PutNextRectangle_CloudForManyRectangles_ShouldBeDense()
{
var random = new Random(42);

This comment was marked as resolved.

This comment was marked as resolved.

return this;
}

public CloudVisualizationConfigBuilder WithBackground(Rgba32 color)
Copy link

Choose a reason for hiding this comment

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

Никогда, никогда, никогда, НИКОГДА в публичных методах своих интерфейсов НЕ ИСПОЛЬЗУЙ ТИПЫ ИЗ БИБЛИОТЕК-ЗАВИСИМОСТЕЙ! Во-первых, если пользователь на них завяжется, то ты не сможешь сменить библиотеку для отрисовки под капотом у конфиг-билдера без поломки обратной совместимости с кодом пользователя, а во-вторых если он тоже использует ту же зависимость, но другой версии, могут быть очень дурацкие конфликты с зависимостями. В целом нюгет неплохо их разрешает, но всё-равно от пользователя надо стараться прятать транзитивные зависимости, для этого есть специальные инструкции в *.csproj файлах - если интересно, гугли про PrivateAssets и другие похожие инструкции.

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