-
Notifications
You must be signed in to change notification settings - Fork 306
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Заколюкин Степан #255
Open
StepanZakolukin
wants to merge
12
commits into
kontur-courses:master
Choose a base branch
from
StepanZakolukin:TagsCloudVisualization
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Заколюкин Степан #255
Changes from all commits
Commits
Show all changes
12 commits
Select commit
Hold shift + click to select a range
3544016
Создал проект TagCloudVisualization в решение
StepanZakolukin 00e0c4b
Добавил тест на корректное создание экземпляра класса. Добавил код в …
StepanZakolukin b442385
Завершил реализацию класса расположения прямоугольников
StepanZakolukin bef6b80
Добавил модификаторы доступа для private методов
StepanZakolukin 2aa2d08
Сделал визуализацию
StepanZakolukin d40d671
Попытался добавить картинку в файл
StepanZakolukin bc219ac
Поправил markdown картинки
StepanZakolukin d5358bb
Добавил вторую картинку в README
StepanZakolukin 90aeca8
Добавил коментарии к картинкам
StepanZakolukin 93d54c5
Сделал рефакторинг
StepanZakolukin 0bffa4d
Добавил в тесты, проверяющие пересечение сгенерированнных прямоугольн…
StepanZakolukin 9830897
Отрефакторил код
StepanZakolukin File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains 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
This file contains 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
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,23 @@ | ||
using System.Drawing; | ||
using TagsCloudVisualization.Task_2; | ||
|
||
|
||
namespace TagsCloudVisualization; | ||
|
||
internal class Program | ||
{ | ||
private const string Path = "../../../../TagsCloudVisualization/Task 2"; | ||
|
||
static void Main() | ||
{ | ||
var colors = new[] { Color.Red, Color.Green, Color.Brown, Color.Yellow, Color.Blue }; | ||
|
||
var visual = new VisualizationCloudLayout(800, 600, Color.White, colors); | ||
|
||
visual.CreateImage(new CircularCloudLayouter(new Point(400, 300)), 175, new Size(30, 5), new Size(100, 25)) | ||
.Save($"{Path}/CentralСloud.png"); | ||
|
||
visual.CreateImage(new CircularCloudLayouter(new Point(250, 150)), 50, new Size(30, 5), new Size(80, 25)) | ||
.Save($"{Path}/SmalСloud.png"); | ||
} | ||
} |
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,19 @@ | ||
<Project Sdk="Microsoft.NET.Sdk"> | ||
|
||
<PropertyGroup> | ||
<OutputType>Library</OutputType> | ||
<TargetFramework>net8.0</TargetFramework> | ||
<ImplicitUsings>enable</ImplicitUsings> | ||
<GenerateProgramFile>false</GenerateProgramFile> | ||
<Nullable>enable</Nullable> | ||
</PropertyGroup> | ||
|
||
<ItemGroup> | ||
<PackageReference Include="FluentAssertions" Version="6.12.2" /> | ||
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.11.1" /> | ||
<PackageReference Include="NUnit" Version="4.2.2" /> | ||
<PackageReference Include="NUnit3TestAdapter" Version="4.6.0" /> | ||
<PackageReference Include="System.Drawing.Common" Version="9.0.0" /> | ||
</ItemGroup> | ||
|
||
</Project> |
64 changes: 64 additions & 0 deletions
64
cs/TagsCloudVisualization/Task 1,3/CircularCloudLayouter.cs
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,64 @@ | ||
using System.Drawing; | ||
|
||
|
||
namespace TagsCloudVisualization; | ||
|
||
public class CircularCloudLayouter | ||
{ | ||
private const double AngleChangeStep = Math.PI / 180; | ||
private int DistanceBetweenTurns { get; set; } | ||
private int InitialRadiusOfSpiral { get; set; } | ||
private double AngleOfRotationInRadians { get; set; } | ||
|
||
private readonly LinkedList<Rectangle> cloudOfRectangles; | ||
|
||
public readonly Point Center; | ||
|
||
public CircularCloudLayouter(Point center) | ||
{ | ||
Center = center; | ||
cloudOfRectangles = []; | ||
DistanceBetweenTurns = 30; | ||
} | ||
|
||
public Rectangle PutNextRectangle(Size rectangleSize) | ||
{ | ||
var halfOfMinSide = Math.Min(rectangleSize.Width, rectangleSize.Height) / 2; | ||
DistanceBetweenTurns = Math.Min(DistanceBetweenTurns, halfOfMinSide); | ||
|
||
if (cloudOfRectangles.Count == 0) InitialRadiusOfSpiral = halfOfMinSide; | ||
|
||
var rectangle = ChooseLocationForRectangle(rectangleSize); | ||
cloudOfRectangles.AddFirst(rectangle); | ||
|
||
return rectangle; | ||
} | ||
|
||
private Rectangle ChooseLocationForRectangle(Size rectangleSize) | ||
{ | ||
var currentPoint = GetNewPoint(); | ||
var rectangle = GetNewRectangle(currentPoint, rectangleSize); | ||
|
||
while (cloudOfRectangles.Any(rect => rect.IntersectsWith(rectangle))) | ||
{ | ||
AngleOfRotationInRadians += AngleChangeStep; | ||
currentPoint = GetNewPoint(); | ||
rectangle = GetNewRectangle(currentPoint, rectangleSize); | ||
} | ||
|
||
return rectangle; | ||
} | ||
|
||
private Rectangle GetNewRectangle(Point centerPoint, Size rectangleSize) => | ||
new(new(centerPoint.X - rectangleSize.Width / 2, | ||
centerPoint.Y - rectangleSize.Height / 2), rectangleSize); | ||
|
||
private Point GetNewPoint() | ||
{ | ||
var coefficient = InitialRadiusOfSpiral + AngleOfRotationInRadians * DistanceBetweenTurns; | ||
var x = coefficient * Math.Cos(AngleOfRotationInRadians) + Center.X; | ||
var y = coefficient * Math.Sin(AngleOfRotationInRadians) + Center.Y; | ||
|
||
return new((int)x, (int)y); | ||
} | ||
} |
82 changes: 82 additions & 0 deletions
82
cs/TagsCloudVisualization/Task 1,3/CircularCloudLayouterTests.cs
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,82 @@ | ||
using FluentAssertions; | ||
using NUnit.Framework; | ||
using NUnit.Framework.Interfaces; | ||
using System.Drawing; | ||
using TagsCloudVisualization.Task_2; | ||
|
||
|
||
namespace TagsCloudVisualization; | ||
|
||
|
||
[TestFixture] | ||
public class CircularCloudLayouterTests | ||
{ | ||
private readonly List<Rectangle> listRectangles = []; | ||
|
||
[Test] | ||
public void CircularCloudLayouter_CorrectInitialization_NoExceptions() | ||
{ | ||
var createAConstructor = () => new CircularCloudLayouter(new Point(960, 540)); | ||
|
||
createAConstructor | ||
.Should() | ||
.NotThrow(); | ||
} | ||
|
||
[Test] | ||
public void PutNextRectangle_RandomSizes_MustBeRightSize() | ||
{ | ||
var cloud = new CircularCloudLayouter(new Point(960, 540)); | ||
var random = new Random(); | ||
|
||
for (var i = 0; i < 50; i++) | ||
{ | ||
var width = random.Next(30, 200); | ||
var actualSize = new Size(width, random.Next(width / 6, width / 3)); | ||
|
||
var rectangle = cloud.PutNextRectangle(actualSize); | ||
|
||
actualSize | ||
.Should() | ||
.Be(rectangle.Size); | ||
} | ||
} | ||
|
||
[Test] | ||
public void PutNextRectangle_RandomSizes_ShouldNotIntersect() | ||
{ | ||
var cloudLayouter = new CircularCloudLayouter(new Point(960, 540)); | ||
var random = new Random(); | ||
|
||
for (int i = 0; i < 100; i++) | ||
{ | ||
var width = random.Next(30, 200); | ||
|
||
var rectangle = cloudLayouter.PutNextRectangle(new(width, random.Next(width / 6, width / 3))); | ||
|
||
listRectangles.Any(rect => rect.IntersectsWith(rectangle)) | ||
.Should() | ||
.BeFalse("Прямоугольники не должны пересекаться"); | ||
|
||
listRectangles.Add(rectangle); | ||
} | ||
} | ||
|
||
[TearDown] | ||
public void CreateReportInCaseOfAnError() | ||
{ | ||
if (TestContext.CurrentContext.Result.Outcome == ResultState.Failure) | ||
{ | ||
var colors = new[] { Color.Red, Color.Green, Color.Brown, Color.Yellow, Color.Blue }; | ||
var path = "../../../../TagsCloudVisualization/TestErrorReports/сloud.png"; | ||
var visual = new VisualizationCloudLayout(1920, 1080, Color.White, colors); | ||
|
||
visual.CreateImage(listRectangles) | ||
.Save(path); | ||
|
||
Console.WriteLine($"Tag cloud visualization saved to file {Path.GetFullPath(path)}"); | ||
} | ||
|
||
listRectangles.Clear(); | ||
} | ||
} |
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,33 @@ | ||
using System.Drawing; | ||
|
||
namespace TagsCloudVisualization.Task_2; | ||
|
||
public static class CloudLayout | ||
{ | ||
public static IEnumerable<Rectangle> GenerateCloudLayout( | ||
int amountRectangles, | ||
Size minSize, | ||
Size maxSize, | ||
CircularCloudLayouter cloudLayouter) | ||
=> GenerateRectangleSizes(amountRectangles, minSize, maxSize) | ||
.Select(cloudLayouter.PutNextRectangle); | ||
|
||
private static IEnumerable<Size> GenerateRectangleSizes( | ||
int amountData, | ||
Size minSize, | ||
Size maxSize) | ||
{ | ||
if (minSize.Width > maxSize.Width || minSize.Height > maxSize.Width) | ||
throw new ArgumentException("Минимальные размеры не могут быть больше максимальных"); | ||
|
||
var random = new Random(); | ||
|
||
for (var i = 0; i < amountData; i++) | ||
{ | ||
var width = random.Next(minSize.Width, maxSize.Width + 1); | ||
var height = random.Next(minSize.Height, maxSize.Height + 1); | ||
|
||
yield return new Size(width, height); | ||
} | ||
} | ||
} |
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,4 @@ | ||
Раскладка 1 | ||
![CentralСloud](CentralСloud.png) | ||
Раскладка 2 | ||
![SmalСloud](SmalСloud.png) |
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
59 changes: 59 additions & 0 deletions
59
cs/TagsCloudVisualization/Task 2/VisualizationCloudLayout.cs
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,59 @@ | ||
using Newtonsoft.Json.Linq; | ||
using System.Drawing; | ||
|
||
namespace TagsCloudVisualization.Task_2; | ||
|
||
public class VisualizationCloudLayout | ||
{ | ||
private readonly int width; | ||
private readonly int height; | ||
private readonly Color backgroundColor; | ||
private readonly Color[] rectanglePalette; | ||
|
||
public VisualizationCloudLayout(int width, int height, Color backgroundColor, IEnumerable<Color> rectanglePalette) | ||
{ | ||
this.width = width; | ||
this.height = height; | ||
this.backgroundColor = backgroundColor; | ||
this.rectanglePalette = rectanglePalette.ToArray(); | ||
} | ||
|
||
public Bitmap CreateImage(CircularCloudLayouter cloudLayouter, int amountRectangles, | ||
Size minSize, Size maxSize) | ||
{ | ||
var image = new Bitmap(width, height); | ||
var rectangles = CloudLayout.GenerateCloudLayout( | ||
amountRectangles, | ||
minSize, | ||
maxSize, | ||
cloudLayouter); | ||
|
||
DrawCloudLayout(Graphics.FromImage(image), rectangles); | ||
|
||
return image; | ||
} | ||
|
||
public Bitmap CreateImage(IEnumerable<Rectangle> rectangles) | ||
{ | ||
var image = new Bitmap(width, height); | ||
|
||
DrawCloudLayout(Graphics.FromImage(image), rectangles); | ||
|
||
return image; | ||
} | ||
|
||
private void DrawCloudLayout(Graphics graphics, IEnumerable<Rectangle> rectangles) | ||
{ | ||
var random = new Random(); | ||
|
||
graphics.FillRectangle(new SolidBrush(backgroundColor), 0, 0, width, height); | ||
|
||
foreach (var rect in rectangles) | ||
{ | ||
var color = rectanglePalette[random.Next(rectanglePalette.Length)]; | ||
|
||
graphics.FillRectangle(new SolidBrush(color), rect); | ||
graphics.DrawRectangle(new Pen(Color.Black, 1), rect); | ||
} | ||
} | ||
} |
This file contains 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
This file contains 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
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Я не знаю почему это 30, наверное, стоит это вынести в конструктор чтобы абстрактный клиент мог это настроить
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Вынести то можно, просто это значение потом все равно изменяется в методе PutNextRectangle в зависимости от самого маленького размера, который когда либо поступал в метод, это сделано для того чтобы увеличить кучность облака. Исходя из этого, я подумал, что наверное не будет смысла в возможности пользователя указать какое-то значение в конструкторе, т.к класс будет впоследствии его менять по определенному правилу
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
ну я так понял оно будет меняться только в меньшую сторону, и, как ты сказал, оно влияет на кучность. Может, пользователь захочет облако побольше и чтобы между тегами было расстояние
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
как бы в целом, для решения задачи создания облака слов это справедливо, но если говорить конкретно об задаче из домашки, то там был такой критерий: "Облако должно быть плотным, чем плотнее, тем лучше."
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Пон, пусть тогда будет так