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

Ренат Зубакин #222

Open
wants to merge 9 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
6 changes: 6 additions & 0 deletions cs/TagsCloudVisualization/App.config
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.8" />
</startup>
</configuration>
90 changes: 90 additions & 0 deletions cs/TagsCloudVisualization/CircularCloudLayouter.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;

namespace TagsCloudVisualization
{
public class CircularCloudLayouter
SolarHunger marked this conversation as resolved.
Show resolved Hide resolved
Copy link

Choose a reason for hiding this comment

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

И тут нет интерфейса

{
public CircularCloudLayouter(Point center, IDistribution distribution)
{
if (center != distribution.Center)
throw new ArgumentException();

Center = center;
SolarHunger marked this conversation as resolved.
Show resolved Hide resolved
Distribution = distribution;
WordPositions = new List<Rectangle>();
}

public Point Center { get; }
public List<Rectangle> WordPositions { get; }
public IDistribution Distribution { get; private set; }


public Rectangle PutNextRectangle(Size rectangleSize)
{
if (rectangleSize.Width < 1 || rectangleSize.Height < 1)
throw new ArgumentException();

var rectanglePosition = Distribution.GetNextPoint();
var currRectangle = new Rectangle(rectanglePosition, rectangleSize);

while (CheckIntersection(currRectangle))
{
rectanglePosition = Distribution.GetNextPoint();
currRectangle.Location = rectanglePosition;
}

currRectangle = ComperessRectangle(currRectangle);
WordPositions.Add(currRectangle);
return currRectangle;
}


private bool CheckIntersection(Rectangle currRectangle)
{
return WordPositions.Any(rec => currRectangle.IntersectsWith(rec));
}


private Rectangle ComperessRectangle(Rectangle rectangle)
{
var changes = 1;
while (changes > 0)
{
rectangle = CompressByAxis(rectangle, true, out changes);
rectangle = CompressByAxis(rectangle, false, out changes);
}

return rectangle;
}


private Rectangle CompressByAxis(Rectangle rectangle, bool isByX, out int changes)
{
changes = 0;
var stepX = rectangle.X < Center.X ? 1 : -1;
var stepY = rectangle.Y < Center.Y ? 1 : -1;

while ((isByX && rectangle.X != Center.X) ||
(!isByX && rectangle.Y != Center.Y))
{
var newRectangle = isByX
? new Rectangle(new Point(rectangle.X + stepX, rectangle.Y), rectangle.Size)
: new Rectangle(new Point(rectangle.X, rectangle.Y + stepY), rectangle.Size);

if (!CheckIntersection(newRectangle))
{
rectangle = newRectangle;
changes++;
continue;
}

break;
}

return rectangle;
}
}
}
72 changes: 72 additions & 0 deletions cs/TagsCloudVisualization/CloudLayouterDrawer.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;

namespace TagsCloudVisualization
Copy link

Choose a reason for hiding this comment

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

Нет абстракции - какого-то интерфейса

{
public class CloudLayouterDrawer
{
private readonly Random random;
Copy link

@gisinka gisinka Dec 12, 2023

Choose a reason for hiding this comment

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

В одном файле поля и свойства до конструктора, в другом после, как-то уж определись)

public int Margin { get; private set; }


public CloudLayouterDrawer(int margin)
Copy link

Choose a reason for hiding this comment

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

Цвет фона можно сделать параметром рисовальщика

{
this.Margin = margin;
random = new Random();
}

public void DrawCloud(string filename, IEnumerable<Rectangle> rectangles)
{

if (!rectangles.Any() || string.IsNullOrEmpty(filename))
throw new ArgumentException();

int imageWidth,imageHeight;
SetImageSize(rectangles, out imageWidth, out imageHeight);

var newRectanglesPositions = GetNewRectanglesPositions(rectangles,imageWidth,imageHeight);

using (var bitmap = new Bitmap(imageWidth, imageHeight))
Copy link

@gisinka gisinka Dec 10, 2023

Choose a reason for hiding this comment

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

можно упростить до using var bitmap = new Bitmap(imageWidth, imageHeight)

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

Choose a reason for hiding this comment

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

Поднять - никто не запрещал)

{
using (var graphics = Graphics.FromImage(bitmap))
{
foreach (var rectangle in newRectanglesPositions)
{
var color = Color.FromArgb(random.Next(256), random.Next(256), random.Next(256));
var brush = new SolidBrush(color);
graphics.FillRectangle(brush, rectangle);
}
SaveImageToFile(bitmap,filename);
}
}
}


private void SaveImageToFile(Bitmap bitmap,string filename)
{
var projectDirectory = Directory.GetParent(Environment.CurrentDirectory).Parent.FullName;
var filePath = Path.Combine(projectDirectory, "images", filename);
bitmap.Save(filePath, ImageFormat.Png);
}
private void SetImageSize(IEnumerable<Rectangle> rectangles,out int imageWidth,out int imageHeight)
{
var maxX = rectangles.Select(rec => rec.X + rec.Width / 2).Max();
var minX = rectangles.Select(rec => rec.X - rec.Width / 2).Min();
var maxY = rectangles.Select(rec => rec.Y + rec.Height / 2).Max();
var minY = rectangles.Select(rec => rec.Y - rec.Height / 2).Min();

imageWidth = maxX - minX + Margin;
imageHeight = maxY - minY + Margin;
}

private IEnumerable<Rectangle> GetNewRectanglesPositions(IEnumerable<Rectangle> rectangles,int imageWidth, int imageHeight)
{
return rectangles.Select(rec =>
new Rectangle(rec.X + imageWidth / 2, rec.Y + imageHeight / 2, rec.Width, rec.Height));
}
}
}
11 changes: 11 additions & 0 deletions cs/TagsCloudVisualization/IDistribution.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
using System.Drawing;

namespace TagsCloudVisualization
{
public interface IDistribution
{
Point Center { get; }
Point GetNextPoint();

}
}
13 changes: 13 additions & 0 deletions cs/TagsCloudVisualization/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
using System;
using System.Drawing;

namespace TagsCloudVisualization
{
public class Program
{
private static void Main()
{

}
}
}
36 changes: 36 additions & 0 deletions cs/TagsCloudVisualization/Properties/AssemblyInfo.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;

// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("CircularCloudLayouter")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("CircularCloudLayouter")]
[assembly: AssemblyCopyright("Copyright © 2023")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]

// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("80edaa6b-8db4-4a7e-8d3d-7032262731b6")]

// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
3 changes: 3 additions & 0 deletions cs/TagsCloudVisualization/Readme.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
!["������ 1"](./images/example3.png)
!["������ 2"](./images/example1.png)
!["������ 3"](./images/example2.png)
40 changes: 40 additions & 0 deletions cs/TagsCloudVisualization/SpiralDistribution.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
using System;
using System.Drawing;

namespace TagsCloudVisualization
{
public class SpiralDistribution : IDistribution
{
public SpiralDistribution(Point center = new Point(), double angleStep = 0.1, double radiusStep = 0.1)
{
if (radiusStep <= 0 || angleStep == 0) throw new ArgumentException();
Center = center;

This comment was marked as resolved.

Copy link

Choose a reason for hiding this comment

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

throw new ArgumentException(); должен жить на отдельной строчке

Copy link

Choose a reason for hiding this comment

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

Считаю, что конструктор должен быть максимально простым, никаких проверок внутри не должно быть, его задача - инициализировать объект, если хочешь сделать проверку на входные параметры, то лучше сделать статичный метод который это будет проверять, и потом сам вызовет тебе приватный конструктор,
Ну и декомпозиция, все дела
Да и тесты так как то приятнее писать когда вызываешь какой нибудь метод Create вместо new

Как вариант валидацию выносить в отдельный приватный метод

Radius = 0;
Angle = 0;
AngleStep = angleStep - 2 * Math.PI * (int)(angleStep / 2 * Math.PI);
RadiusStep = radiusStep;
}

public double Angle { get; private set; }
public double AngleStep { get; }
public double RadiusStep { get; }
public Point Center { get; }
public double Radius { get; private set; }

public Point GetNextPoint()
{
var x = Radius * Math.Cos(Angle) + Center.X;
var y = Radius * Math.Sin(Angle) + Center.Y;

Angle += AngleStep;

if (Angle >= Math.PI * 2)
{
Angle -= 2 * Math.PI;
Radius += RadiusStep;
}

return new Point((int)x, (int)y);
}
}
}
96 changes: 96 additions & 0 deletions cs/TagsCloudVisualization/TagsCloudVisualization.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="..\packages\Microsoft.NET.Test.Sdk.16.7.1\build\net40\Microsoft.NET.Test.Sdk.props" Condition="Exists('..\packages\Microsoft.NET.Test.Sdk.16.7.1\build\net40\Microsoft.NET.Test.Sdk.props')" />
<Import Project="..\packages\Microsoft.CodeCoverage.16.7.1\build\netstandard1.0\Microsoft.CodeCoverage.props" Condition="Exists('..\packages\Microsoft.CodeCoverage.16.7.1\build\netstandard1.0\Microsoft.CodeCoverage.props')" />
<Import Project="..\packages\NUnit.3.12.0\build\NUnit.props" Condition="Exists('..\packages\NUnit.3.12.0\build\NUnit.props')" />
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{80EDAA6B-8DB4-4A7E-8D3D-7032262731B6}</ProjectGuid>
<OutputType>Exe</OutputType>
<RootNamespace>TagsCloudVisualization</RootNamespace>
<AssemblyName>TagsCloudVisualization</AssemblyName>
<TargetFrameworkVersion>v4.8</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
<Deterministic>true</Deterministic>
<NuGetPackageImportStamp>
</NuGetPackageImportStamp>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="FluentAssertions, Version=5.10.3.0, Culture=neutral, PublicKeyToken=33f2691a05b67b6a, processorArchitecture=MSIL">
<HintPath>..\packages\FluentAssertions.5.10.3\lib\net47\FluentAssertions.dll</HintPath>
</Reference>
<Reference Include="Microsoft.VisualStudio.CodeCoverage.Shim, Version=15.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.CodeCoverage.16.7.1\lib\net45\Microsoft.VisualStudio.CodeCoverage.Shim.dll</HintPath>
</Reference>
<Reference Include="nunit.framework, Version=3.12.0.0, Culture=neutral, PublicKeyToken=2638cd05610744eb, processorArchitecture=MSIL">
<HintPath>..\packages\NUnit.3.12.0\lib\net45\nunit.framework.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.Configuration" />
<Reference Include="System.Core" />
<Reference Include="System.Drawing" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Net.Http" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="CircularCloudLayouter.cs" />
<Compile Include="CloudLayouterDrawer.cs" />
<Compile Include="IDistribution.cs" />
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="TagsCloudVisualizationTests\CircularCloudLayouterTests.cs" />
<Compile Include="SpiralDistribution.cs" />
<Compile Include="TagsCloudVisualizationTests\CloudLayouterDrawerTests.cs" />
<Compile Include="TagsCloudVisualizationTests\SpiralDistributionTests.cs" />
</ItemGroup>
<ItemGroup>
<None Include="App.config" />
<None Include="packages.config" />
<None Include="Readme.md" />
</ItemGroup>
<ItemGroup />
<ItemGroup>
<Content Include="images\example1.png" />
<Content Include="images\example2.png" />
<Content Include="images\example3.png" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">
<PropertyGroup>
<ErrorText>This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}.</ErrorText>
</PropertyGroup>
<Error Condition="!Exists('..\packages\NUnit.3.12.0\build\NUnit.props')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\NUnit.3.12.0\build\NUnit.props'))" />
<Error Condition="!Exists('..\packages\Microsoft.CodeCoverage.16.7.1\build\netstandard1.0\Microsoft.CodeCoverage.props')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\Microsoft.CodeCoverage.16.7.1\build\netstandard1.0\Microsoft.CodeCoverage.props'))" />
<Error Condition="!Exists('..\packages\Microsoft.CodeCoverage.16.7.1\build\netstandard1.0\Microsoft.CodeCoverage.targets')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\Microsoft.CodeCoverage.16.7.1\build\netstandard1.0\Microsoft.CodeCoverage.targets'))" />
<Error Condition="!Exists('..\packages\Microsoft.NET.Test.Sdk.16.7.1\build\net40\Microsoft.NET.Test.Sdk.props')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\Microsoft.NET.Test.Sdk.16.7.1\build\net40\Microsoft.NET.Test.Sdk.props'))" />
<Error Condition="!Exists('..\packages\Microsoft.NET.Test.Sdk.16.7.1\build\net40\Microsoft.NET.Test.Sdk.targets')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\Microsoft.NET.Test.Sdk.16.7.1\build\net40\Microsoft.NET.Test.Sdk.targets'))" />
</Target>
<Import Project="..\packages\Microsoft.CodeCoverage.16.7.1\build\netstandard1.0\Microsoft.CodeCoverage.targets" Condition="Exists('..\packages\Microsoft.CodeCoverage.16.7.1\build\netstandard1.0\Microsoft.CodeCoverage.targets')" />
<Import Project="..\packages\Microsoft.NET.Test.Sdk.16.7.1\build\net40\Microsoft.NET.Test.Sdk.targets" Condition="Exists('..\packages\Microsoft.NET.Test.Sdk.16.7.1\build\net40\Microsoft.NET.Test.Sdk.targets')" />
</Project>
Loading