Skip to content
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
61 changes: 61 additions & 0 deletions hw5Routers/hw5Routers.Test/AlgorithmTest.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
using NUnit.Framework;

namespace Hw5Routers.Test
{
public class Tests
{
[Test]
public void AlgorithmTestFirst()
{
int[,] graphFirst =
{
{0, 2, 4, 6 },
{2, 0, 0, 8 },
{4, 0, 0, 9 },
{6, 8, 9, 0 }
};
int[,] graphFirstResult =
{
{0, 0, 0, 6 },
{0, 0, 0, 8 },
{0, 0, 0, 9 },
{6, 8, 9, 0 }
};
Assert.AreEqual(AlgorithmPrima.Algorithm(graphFirst), graphFirstResult);
}

[Test]
public void AlgorithmTestSecond()
{
int[,] graphSecond =
{
{0, 0, 0, 3 },
{0, 0, 0, 6 },
{0, 0, 0, 9 },
{3, 6, 9, 0 }
};
int[,] graphSecondResult =
{
{0, 0, 0, 3 },
{0, 0, 0, 6 },
{0, 0, 0, 9 },
{3, 6, 9, 0 }
};
Assert.AreEqual(AlgorithmPrima.Algorithm(graphSecond), graphSecondResult);

This comment was marked as resolved.

}

[Test]
public void AlgorithmExceptionTest()
{
int[,] graph =
{
{0, 3, 0, 0},
{3, 0, 0, 0},
{0, 0, 0, 2},
{0, 0, 2, 0}
};
Assert.Throws<GraphDisconnectedException>(() => AlgorithmPrima.Algorithm(graph));
}

}
}
20 changes: 20 additions & 0 deletions hw5Routers/hw5Routers.Test/FileFunctionsTest.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
using NUnit.Framework;
using System.IO;

namespace Hw5Routers.Test
{
class FileFunctionsTest
{
[Test]
public void FileTest()
{
string[] result =
{
"1: 2 (10), 3 (5)"
};
FileFunctions.WriteInFile(AlgorithmPrima.Algorithm(FileFunctions.CreateGraph("..\\..\\..\\RoutersTest.txt")), "..\\..\\RoutersTestResult.txt");
var resultFromFile = File.ReadLines("..\\..\\RoutersTestResult.txt");
Assert.AreEqual(result, resultFromFile);
}
}
}
2 changes: 2 additions & 0 deletions hw5Routers/hw5Routers.Test/RoutersTest.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
1: 2 (10), 3 (5)
2: 3 (1)
1 change: 1 addition & 0 deletions hw5Routers/hw5Routers.Test/RoutersTestResult.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
1: 2 (10), 3 (5)
19 changes: 19 additions & 0 deletions hw5Routers/hw5Routers.Test/hw5Routers.Test.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>netcoreapp3.1</TargetFramework>

<IsPackable>false</IsPackable>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="NUnit" Version="3.12.0" />
<PackageReference Include="NUnit3TestAdapter" Version="3.16.1" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.5.0" />
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\hw5Routers\Hw5Routers.csproj" />
</ItemGroup>

</Project>
31 changes: 31 additions & 0 deletions hw5Routers/hw5Routers.sln
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 16
VisualStudioVersion = 16.0.31005.135
MinimumVisualStudioVersion = 10.0.40219.1
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Hw5Routers", "hw5Routers\Hw5Routers.csproj", "{55F17858-3620-46FF-BF81-AF2E7DD2595D}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "hw5Routers.Test", "hw5Routers.Test\hw5Routers.Test.csproj", "{B3DF091C-3CAD-4E6A-9401-94EFDBA9E0D2}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{55F17858-3620-46FF-BF81-AF2E7DD2595D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{55F17858-3620-46FF-BF81-AF2E7DD2595D}.Debug|Any CPU.Build.0 = Debug|Any CPU
{55F17858-3620-46FF-BF81-AF2E7DD2595D}.Release|Any CPU.ActiveCfg = Release|Any CPU
{55F17858-3620-46FF-BF81-AF2E7DD2595D}.Release|Any CPU.Build.0 = Release|Any CPU
{B3DF091C-3CAD-4E6A-9401-94EFDBA9E0D2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{B3DF091C-3CAD-4E6A-9401-94EFDBA9E0D2}.Debug|Any CPU.Build.0 = Debug|Any CPU
{B3DF091C-3CAD-4E6A-9401-94EFDBA9E0D2}.Release|Any CPU.ActiveCfg = Release|Any CPU
{B3DF091C-3CAD-4E6A-9401-94EFDBA9E0D2}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {054D180F-116B-4C02-B1C8-C947EB1CCD17}
EndGlobalSection
EndGlobal
112 changes: 112 additions & 0 deletions hw5Routers/hw5Routers/AlgorithmPrima.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
using System;
using System.Collections.Generic;
using System.Text;

namespace Hw5Routers
{
/// <summary>
/// Класс, реализующий алгоритм Прима
/// </summary>
public static class AlgorithmPrima

This comment was marked as resolved.

{
private static bool CheckGraph(int[,] matrix)
{
var vertexStatus = new int[matrix.GetLength(0)];
int number = 1;
vertexStatus[0] = number;
int count = 0;
while (count < matrix.GetLength(0) && !Check(vertexStatus))
{
for (int i = 0; i < matrix.GetLength(0); i++)
{
if (vertexStatus[i] == number)
{
for (int j = 0; j < matrix.GetLength(0); j++)
{
if (matrix[i, j] != 0 && vertexStatus[j] == 0)
{
vertexStatus[j] = number + 1;
}
}
}
}
number++;
count++;
}
return Check(vertexStatus);
}

private static bool Check(int[] vertexStatus)
{
for (int i = 0; i < vertexStatus.Length; i++)
{
if (vertexStatus[i] == 0)
{
return false;
}
}
return true;
}

This comment was marked as resolved.


private static int MaxKey(int[] key, bool[] isConsist)
{
int max = int.MinValue;
int indexMax = -1;
for (int i = 0; i < key.Length; i++)

This comment was marked as resolved.

{
if (!isConsist[i] && key[i] > max)
{
max = key[i];
indexMax = i;
}
}
return indexMax;
}

/// <summary>
/// алгоритм Прима
/// </summary>
/// <returns>новую матрицу</returns>
public static int[,] Algorithm(int[,] matrix)
{
if (!CheckGraph(matrix))
{
throw new GraphDisconnectedException();
}
int size = matrix.GetLength(0);
int[] parent = new int[size];
int[] key = new int[size];
bool[] isConsist = new bool[size];
for (int i = 0; i < size; i++)
{
key[i] = int.MinValue;
}
key[0] = 0;
parent[0] = -1;
for (int count = 0; count < size - 1; count++)
{
int indexFirst = MaxKey(key, isConsist);
isConsist[indexFirst] = true;
for (int indexSecond = 0; indexSecond < size; indexSecond++)
{
if (matrix[indexFirst, indexSecond] != 0 && !isConsist[indexSecond] && matrix[indexFirst, indexSecond] > key[indexSecond])
{
parent[indexSecond] = indexFirst;
key[indexSecond] = matrix[indexFirst, indexSecond];
}
}
}
return CreateMatrix(parent, matrix);
}

private static int[,] CreateMatrix(int[] parent, int[,] matrix)
{
var newMatrix = new int[matrix.GetLength(0), matrix.GetLength(0)];
for (int i = 1; i < matrix.GetLength(0); ++i)
{
newMatrix[parent[i], i] = newMatrix[i, parent[i]] = matrix[i, parent[i]];
}
return newMatrix;
}
}
}
112 changes: 112 additions & 0 deletions hw5Routers/hw5Routers/FileFunctions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
using System;
using System.IO;
using System.Collections.Generic;

namespace Hw5Routers
{
/// <summary>
/// класс для работы с файлами
/// </summary>
public static class FileFunctions
Copy link
Collaborator

Choose a reason for hiding this comment

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

И даже этому классу надо комментарий :)

{
/// <summary>
/// создает граф по файлу
/// </summary>
/// <returns>матрицу графа</returns>
public static int[,] CreateGraph(string filePath)
{
if (filePath == "")
{
throw new NoParametersException();
}
int vertices = CountVertexes(filePath);
var matrix = new int[vertices, vertices];
using var file = new StreamReader(filePath);
string stringLine = file.ReadLine();
while (stringLine != null)
{
string[] split = new string[] { " ", ",", ":" };
string[] lineDrop = stringLine.Split(split, StringSplitOptions.RemoveEmptyEntries);
var numberFirst = Int32.Parse(lineDrop[0]) - 1;
for (int i = 1; i < lineDrop.Length - 1; i += 2)
{
var numberSecond = Int32.Parse(lineDrop[i]) - 1;
var distance = Int32.Parse(lineDrop[i + 1].Substring(1, lineDrop[i + 1].Length - 2));
matrix[numberFirst, numberSecond] = matrix[numberSecond, numberFirst];
matrix[numberFirst, numberSecond] = distance;
}
stringLine = file.ReadLine();
}
return matrix;
}

private static int CountVertexes(string path)
{
using var file = new StreamReader(path);
string stringLine = file.ReadLine();
var list = new List<int>();
int vertice = 0;
while (stringLine != null)
{
stringLine = stringLine.Replace(':', ' ');
stringLine = stringLine.Replace(',', ' ');
string[] lineDrop = stringLine.Split(" ", StringSplitOptions.RemoveEmptyEntries);
var number = Int32.Parse(lineDrop[0]) - 1;
if (!list.Contains(number))
{
list.Add(number);
vertice++;
}
for (int i = 0; i < lineDrop.Length / 2; ++i)
{
number = Int32.Parse(lineDrop[2 * i + 1]) - 1;
if (!list.Contains(number))
{
list.Add(number);
vertice++;
}
}
stringLine = file.ReadLine();
}
return vertice;
}

/// <summary>
/// записывает итогую матрицу в файл
/// </summary>
public static void WriteInFile(int[,] matrix, string filePath)
{
if (filePath == "")
{
throw new NoParametersException();
}
var fileOut = new FileInfo(filePath);
if (fileOut.Exists)
{
fileOut.Delete();
}
using var newFile = new FileStream(filePath, FileMode.Create);
var file = new StreamWriter(newFile);
for (int i = 0; i < matrix.GetLength(0) - 1; i++)
{
var line = $"{i + 1}: ";
for (int j = i + 1; j < matrix.GetLength(0); ++j)
{
if (matrix[i, j] != 0)
{
line += $"{j + 1} ({matrix[i, j]}), ";
}
}
if (line != $"{i + 1}: ")
{
file.WriteLine(line.Substring(0, line.Length - 2));
}
}
file.Close();
if (fileOut.Exists)
{
fileOut.MoveTo(filePath);
}
}
}
}
21 changes: 21 additions & 0 deletions hw5Routers/hw5Routers/GraphDisconnectedException.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
using System;
using System.Collections.Generic;
using System.Text;

namespace Hw5Routers
{
/// <summary>
/// Исключение, когда граф несвязанный
/// </summary>
public class GraphDisconnectedException : Exception

This comment was marked as resolved.

{
public GraphDisconnectedException()
{
}

public GraphDisconnectedException(string message)
: base(message)
{
}
}
}
Loading