Skip to content
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

Муканов Арман #223

Open
wants to merge 18 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
99 changes: 99 additions & 0 deletions cs/TagsCloudVisualization/CircularCloudLayouter.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
using System;
using System.Drawing;

namespace TagsCloudVisualization;

public class CircularCloudLayouter : ILayouter
{
private readonly List<Rectangle> rectangles;
private Point center;
private double spiralStep;
private double angle;
private const double DefaultAngleStep = Math.PI / 10;
private const double DefaultSpiralStep = 1;
private const double FullCircle = Math.PI * 2;
private const int SpiralStepThreshold = 10;

public CircularCloudLayouter(Point center)
{
this.center = center;
rectangles = new List<Rectangle>();
spiralStep = 1;
}

public IReadOnlyList<Rectangle> AddedRectangles => rectangles;

public Rectangle PutNextRectangle(Size rectangleSize)
{
if (rectangleSize.Width == 0 || rectangleSize.Height == 0)
throw new ArgumentException($"{nameof(rectangleSize)} should be with positive width and height");
var location = GetPosition(rectangleSize);
var rectangle = new Rectangle(location, rectangleSize);
rectangles.Add(rectangle);
return rectangle;
}

private Point GetPosition(Size rectangleSize)
{
if (rectangles.Count == 0)
{
center.Offset(new Point(rectangleSize / -2));
return center;
}

return FindApproximatePosition(rectangleSize);
}

private Point FindApproximatePosition(Size rectangleSize)
{
var currentAngle = angle;
while (true)
{
var candidateLocation = new Point(center.X + (int)(spiralStep * Math.Cos(currentAngle)),
center.Y + (int)(spiralStep * Math.Sin(currentAngle)));
var candidateRectangle = new Rectangle(candidateLocation, rectangleSize);

if (!IntersectsWithAny(candidateRectangle))
{
rectangles.Add(candidateRectangle);
angle = currentAngle;
return candidateRectangle.Location;
}

currentAngle = CalculateAngle(currentAngle);
}
}

private bool IntersectsWithAny(Rectangle candidateRectangle)
{
return rectangles
.Any(candidateRectangle.IntersectsWith);
}

private double CalculateAngle(double currentAngle)
{
currentAngle += GetAngleStep();
if (currentAngle > FullCircle)
{
currentAngle %= FullCircle;
UpdateSpiral();
}

return currentAngle;
}

private void UpdateSpiral()
{
spiralStep += DefaultSpiralStep;
}

private double GetAngleStep()
{
var angleStep = DefaultAngleStep;
var stepCount = (int)spiralStep / SpiralStepThreshold;
if (stepCount > 0)
angleStep /= stepCount;

return angleStep;
}
}
14 changes: 14 additions & 0 deletions cs/TagsCloudVisualization/ILayouter.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace TagsCloudVisualization
{
public interface ILayouter
{
public Rectangle PutNextRectangle(Size rectangleSize);
}
}
80 changes: 80 additions & 0 deletions cs/TagsCloudVisualization/LayouterVisualizer.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
using Microsoft.VisualBasic;
using NUnit.Framework;
using System.Drawing;
using System.Drawing.Imaging;

namespace TagsCloudVisualization;

public class LayouterVisualizer: IDisposable
{
private bool isDisposed;

public LayouterVisualizer(Size imageSize)
{
Bitmap = new Bitmap(imageSize.Width, imageSize.Height);
Pen = new Pen(Color.White, 3);
}

public Bitmap Bitmap { get; }

public Pen Pen { get; set; }

public void VisualizeRectangle(Rectangle rectangle)
{
using var g = Graphics.FromImage(Bitmap);
g.DrawRectangle(Pen, rectangle);
}

public void VisualizeRectangles(IEnumerable<Rectangle> rectangles)
{
foreach (var rect in rectangles)
{
VisualizeRectangle(rect);
}
}

public void SaveImage(string file, ImageFormat format)

Choose a reason for hiding this comment

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

Как считаешь нужен ли тут String?

Copy link
Author

Choose a reason for hiding this comment

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

Думаю, что нужен, потому что будет неочевидно, куда сохраняется изображение

Choose a reason for hiding this comment

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

Речь про string vs String

Copy link
Author

Choose a reason for hiding this comment

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

string - это же просто alias для String. Поэтому я не вижу преимуществ в использовании String

{
if (TrySaveImage(file, format))
{
Console.WriteLine($"Tag cloud visualization saved to {file}");
}
}

private bool TrySaveImage(string file, ImageFormat format)
{
try
{
Bitmap.Save(file, format);
return true;
}
catch (Exception ex)
{
Console.WriteLine("An error occurred while saving the image: " + ex.Message);
return false;
}
}

~LayouterVisualizer()
{
Dispose(false);
}

public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}

private void Dispose(bool fromDisposeMethod)
{
if (isDisposed) return;

Choose a reason for hiding this comment

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

Как считаешь что лучше?

if (isDisposed)
{
  return;
}

или

if (isDisposed) return;

или

if (!isDisposed) 
{
  ...
}

Copy link
Author

Choose a reason for hiding this comment

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

2 вариант, на мой взгляд лучше. Более читаемый, отсутствует вложенность.

if (fromDisposeMethod)
{
Bitmap.Dispose();
Pen.Dispose();
}

isDisposed = true;
}
}
13 changes: 13 additions & 0 deletions cs/TagsCloudVisualization/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
# Примеры визуализации облака тегов

| ![Облако с квадратными тегами](./Assets/Images resources/25_rect.jpeg) |
|:----------------------------------------------------------------------:|
| *Визуализация облака с квадратными тегами* |

| ![Облако с прямоугольными тегами](./Assets/Images resources/70_squares.jpeg) |
|:----------------------------------------------------------------------------:|
| *Визуализация облака с прямоугольными тегами* |

| ![Облако с различными тегам](./Assets/Images resources/75_rect.jpeg) |
|:--------------------------------------------------------------------:|
| *Визуализация облака с различными тегами* |
19 changes: 19 additions & 0 deletions cs/TagsCloudVisualization/TagsCloudVisualization.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net7.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="FluentAssertions" Version="7.0.0-alpha.3" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.9.0-preview-23531-01" />
<PackageReference Include="NUnit" Version="4.0.1" />
<PackageReference Include="NUnit.Console" Version="3.16.3" />
<PackageReference Include="NUnit3TestAdapter" Version="4.5.0" />
<PackageReference Include="System.Drawing.Common" Version="7.0.0" />
</ItemGroup>

</Project>
152 changes: 152 additions & 0 deletions cs/TagsCloudVisualization/Tests/CircularCloudLayouter_Should.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,152 @@
using System.Drawing;
using System.Drawing.Imaging;
using FluentAssertions;
using NUnit.Framework;
using NUnit.Framework.Interfaces;
using NUnit.Framework.Internal;

namespace TagsCloudVisualization.Tests;

[TestFixture]
public class CircularCloudLayouter_Should
{
private readonly string path = Path.Combine(TestContext.CurrentContext.TestDirectory, "TestsResults");
private CircularCloudLayouter cloudLayouter;
private Point center;
private Size canvasSize;

private Randomizer Random => TestContext.CurrentContext.Random;

[OneTimeSetUp]
public void OneTimeSetUp()
{
canvasSize = new Size(900, 900);
center = new Point(450, 450);

DeleteTestResults();
}

[SetUp]
public void SetUp()
{
cloudLayouter = new CircularCloudLayouter(center);
}

[TearDown]
public void TearDown()
{
var status = TestContext.CurrentContext.Result.Outcome.Status;
var test = TestContext.CurrentContext.Test;
if (status != TestStatus.Failed) return;
SaveFailedTestResult(test);
}

[Test]
public void PutNextRectangle_ShouldThrow_WhenSizeNotPositive()
{
var action = () => cloudLayouter.PutNextRectangle(new Size(0, 0));

action.Should().Throw<ArgumentException>();
}

[Test]
public void PutNextRectangle_ShouldReturnRectangleWithGivenSize()
{
var size = new Size(10, 10);

var rectangle = cloudLayouter.PutNextRectangle(size);

rectangle.Size.Should().Be(size);
}

[Test]
public void PutNextRectangle_ShouldPlaceFirstRectangleInCenter()
{
var size = new Size(50, 50);
var offsettedCenter = center - size / 2;

var rectangle = cloudLayouter.PutNextRectangle(size);

rectangle.Location.Should().Be(offsettedCenter);
}

[Test]
public void PutNextRectangle_ShouldReturnNotIntersectingRectangles()
{
var sizes = GetRandomSizes(70);

var actualRectangles = sizes.Select(x => cloudLayouter.PutNextRectangle(x)).ToList();

for (var i = 0; i < actualRectangles.Count - 1; i++)
{
for (var j = i + 1; j < actualRectangles.Count; j++)
{
actualRectangles[i].IntersectsWith(actualRectangles[j]).Should().BeFalse();
}
}
}

[Test]
public void PutNextRectangle_ShouldCreateLayoutCloseToCircle()
{
var sizes = GetRandomSizes(50);

var rectangles = sizes.Select(size => cloudLayouter.PutNextRectangle(size)).ToList();
var rectanglesSquare = rectangles
.Select(x => x.Width * x.Height)
.Sum();
var circleSquare = CalculateBoundingCircleSquare(rectangles);

rectanglesSquare.Should().BeInRange((int)(circleSquare * 0.8), (int)(circleSquare * 1.2));
}

private void DeleteTestResults()
{
var di = new DirectoryInfo(path);
foreach (var file in di.GetFiles())
{
file.Delete();
}
}

private void SaveFailedTestResult(TestContext.TestAdapter test)
{
Directory.CreateDirectory(Path.Combine(TestContext.CurrentContext.TestDirectory, "TestsResults"));
var pathToImage = Path.Combine(path, test.Name + ".jpeg");

var visualizer = new LayouterVisualizer(canvasSize);
visualizer.VisualizeRectangles(cloudLayouter.AddedRectangles);

visualizer.SaveImage(pathToImage, ImageFormat.Jpeg);
visualizer.Dispose();
}

private Size GetRandomSize()
{
//return new Size(Random.Next(30, 40), Random.Next(30, 40));
return new Size(Random.Next(100, 120), Random.Next(30, 90));
}

private List<Size> GetRandomSizes(int count)
{
var sizes = new List<Size>(count);
for (var i = 0; i < count; i++)
sizes.Add(GetRandomSize());
return sizes;
}

private double CalculateBoundingCircleSquare(List<Rectangle> rectangles)
{
var rect = rectangles
.Where(x => x.Contains(x.X, center.Y))
.MaxBy(x => Math.Abs(x.X - center.X));
var width = Math.Abs(rect.X - center.X);

rect = rectangles
.Where(x => x.Contains(center.X, x.Y))
.MaxBy(x => Math.Abs(x.Y - center.Y));
var height = Math.Abs(rect.Y - center.Y);

return Math.Max(width, height) * Math.Max(width, height) * Math.PI;
}
}
Loading