ISEbd-12 Rozhkov.I.E. Simple LabWork06 #6

Closed
RozhVan wants to merge 1 commits from lab06 into lab05
31 changed files with 334 additions and 735 deletions

View File

@ -1,25 +0,0 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.7.34031.279
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AiSD_Lab02", "AiSD Lab02\AiSD_Lab02.csproj", "{FA17B31D-8779-415E-B3A9-140812864D38}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{FA17B31D-8779-415E-B3A9-140812864D38}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{FA17B31D-8779-415E-B3A9-140812864D38}.Debug|Any CPU.Build.0 = Debug|Any CPU
{FA17B31D-8779-415E-B3A9-140812864D38}.Release|Any CPU.ActiveCfg = Release|Any CPU
{FA17B31D-8779-415E-B3A9-140812864D38}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {268E47D2-9C2D-4863-BCE2-130796952BAF}
EndGlobalSection
EndGlobal

View File

@ -1,55 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<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>{FA17B31D-8779-415E-B3A9-140812864D38}</ProjectGuid>
<OutputType>Exe</OutputType>
<RootNamespace>AiSD_Lab02</RootNamespace>
<AssemblyName>AiSD Lab02</AssemblyName>
<TargetFrameworkVersion>v4.7.2</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
<Deterministic>true</Deterministic>
</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="System" />
<Reference Include="System.Core" />
<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="EntityItem.cs" />
<Compile Include="FibNums.cs" />
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<ItemGroup>
<None Include="App.config" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
</Project>

View File

@ -1,6 +0,0 @@
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.2" />
</startup>
</configuration>

View File

@ -1,7 +0,0 @@
namespace AiSD_Lab02;
public class EntityItem
{
public int Weight { get; set; }
public int Value { get; set; }
}

View File

@ -1,64 +0,0 @@
namespace AiSD_Lab02;
public class FibNums
{
public int Fib(int num)
{
if (num < 2) return 1;
else return Fib(num - 1) + Fib(num - 2);
}
public void Merge(int[] array, int lowIndex, int middleIndex, int highIndex)
{
int left = lowIndex;
int right = middleIndex + 1;
int[] tempArray = new int[highIndex - lowIndex + 1];
int index = 0;
while ((left <= middleIndex) && (right <= highIndex))
{
if (array[left] < array[right])
{
tempArray[index] = array[left];
left++;
}
else
{
tempArray[index] = array[right];
right++;
}
index++;
}
for (int i = left; i <= middleIndex; i++)
{
tempArray[index] = array[i];
index++;
}
for (int i = right; i <= highIndex; i++)
{
tempArray[index] = array[i];
index++;
}
for (int i = 0; i < tempArray.Length; i++)
{
array[lowIndex + i] = tempArray[i];
}
}
public int[] MergeSort(int[] array, int lowIndex, int highIndex)
{
if (lowIndex < highIndex)
{
int middleInd = (lowIndex + highIndex) / 2;
MergeSort(array, lowIndex, middleInd);
MergeSort(array, middleInd + 1, highIndex);
Merge(array, lowIndex, middleInd, highIndex);
}
return array;
}
}

View File

@ -1,56 +0,0 @@
using System.Collections.Generic;
using System;
namespace AiSD_Lab02;
public class Program
{
public static void Main(string[] args)
{
List<EntityItem> items = new List<EntityItem>()
{
new EntityItem { Weight = 2, Value = 10 },
new EntityItem { Weight = 3, Value = 5 },
new EntityItem { Weight = 5, Value = 15 },
new EntityItem { Weight = 7, Value = 7 },
new EntityItem { Weight = 1, Value = 6 }
};
int capacity = 10;
for (int i = 0; i < items.Count - 1; i++)
{
for (int j = 0; j < items.Count - i - 1; j++)
{
double ratio1 = items[j].Value / (double)items[j].Weight;
double ratio2 = items[j + 1].Value / (double)items[j + 1].Weight;
if (ratio1 < ratio2)
{
EntityItem temp = items[j];
items[j] = items[j + 1];
items[j + 1] = temp;
}
}
}
int totalValue = 0;
int totalWeight = 0;
foreach (EntityItem item in items)
{
if (totalWeight + item.Weight <= capacity)
{
totalValue += item.Value;
totalWeight += item.Weight;
Console.WriteLine($"Предмет: вес={item.Weight}, значение={item.Value}");
}
}
Console.WriteLine($"Суммарное значение: {totalValue}");
Console.WriteLine($"Суммарный вес: {totalWeight}");
FibNums fibNums = new FibNums();
Console.WriteLine(fibNums.Fib(5));
}
}

View File

@ -1,36 +0,0 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// Общие сведения об этой сборке предоставляются следующим набором
// набора атрибутов. Измените значения этих атрибутов для изменения сведений,
// связанные с этой сборкой.
[assembly: AssemblyTitle("AiSD Lab02")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("AiSD Lab02")]
[assembly: AssemblyCopyright("Copyright © 2024")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Установка значения False для параметра ComVisible делает типы в этой сборке невидимыми
// для компонентов COM. Если необходимо обратиться к типу в этой сборке через
// из модели COM задайте для атрибута ComVisible этого типа значение true.
[assembly: ComVisible(false)]
// Следующий GUID представляет идентификатор typelib, если этот проект доступен из модели COM
[assembly: Guid("fa17b31d-8779-415e-b3a9-140812864d38")]
// Сведения о версии сборки состоят из указанных ниже четырех значений:
//
// Основной номер версии
// Дополнительный номер версии
// Номер сборки
// Номер редакции
//
// Можно задать все значения или принять номера сборки и редакции по умолчанию
// используя "*", как показано ниже:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]

View File

@ -1,25 +0,0 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.7.34031.279
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AiSD Lab02", "AiSD Lab02\AiSD Lab02.csproj", "{FA17B31D-8779-415E-B3A9-140812864D38}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{FA17B31D-8779-415E-B3A9-140812864D38}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{FA17B31D-8779-415E-B3A9-140812864D38}.Debug|Any CPU.Build.0 = Debug|Any CPU
{FA17B31D-8779-415E-B3A9-140812864D38}.Release|Any CPU.ActiveCfg = Release|Any CPU
{FA17B31D-8779-415E-B3A9-140812864D38}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {268E47D2-9C2D-4863-BCE2-130796952BAF}
EndGlobalSection
EndGlobal

View File

@ -1,55 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<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>{FA17B31D-8779-415E-B3A9-140812864D38}</ProjectGuid>
<OutputType>Exe</OutputType>
<RootNamespace>AiSD_Lab02</RootNamespace>
<AssemblyName>AiSD Lab02</AssemblyName>
<TargetFrameworkVersion>v4.7.2</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
<Deterministic>true</Deterministic>
</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="System" />
<Reference Include="System.Core" />
<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="EntityItem.cs" />
<Compile Include="KnapsackGreedy.cs" />
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<ItemGroup>
<None Include="App.config" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
</Project>

View File

@ -1,6 +0,0 @@
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.2" />
</startup>
</configuration>

View File

@ -1,14 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
public class EntityItem
{
public int Weight { get; set; }
public int Value { get; set; }
public EntityItem(int weight, int value)
{
Weight = weight;
Value = value;
}
}

View File

@ -1,12 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AiSD_Lab02
{
internal class FibNums
{
}
}

View File

@ -1,28 +0,0 @@
using System.Collections.Generic;
using System;
public class Program
{
public static void Main(string[] args)
{
List<EntityItem> items = new List<EntityItem>()
{
new EntityItem(2, 10),
new EntityItem(3, 5),
new EntityItem(5, 15),
new EntityItem(7, 7),
new EntityItem(1, 6)
};
int capacity = 10;
List<EntityItem> result = FillKnapsack(items, capacity);
Console.WriteLine("Предмет в рюкзаке:");
foreach (EntityItem item in result)
{
Console.WriteLine($"Вес: {item.Weight}, Стоимость: {item.Value}");
}
}
}
}

View File

@ -1,36 +0,0 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// Общие сведения об этой сборке предоставляются следующим набором
// набора атрибутов. Измените значения этих атрибутов для изменения сведений,
// связанные с этой сборкой.
[assembly: AssemblyTitle("AiSD Lab02")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("AiSD Lab02")]
[assembly: AssemblyCopyright("Copyright © 2024")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Установка значения False для параметра ComVisible делает типы в этой сборке невидимыми
// для компонентов COM. Если необходимо обратиться к типу в этой сборке через
// из модели COM задайте для атрибута ComVisible этого типа значение true.
[assembly: ComVisible(false)]
// Следующий GUID представляет идентификатор typelib, если этот проект доступен из модели COM
[assembly: Guid("fa17b31d-8779-415e-b3a9-140812864d38")]
// Сведения о версии сборки состоят из указанных ниже четырех значений:
//
// Основной номер версии
// Дополнительный номер версии
// Номер сборки
// Номер редакции
//
// Можно задать все значения или принять номера сборки и редакции по умолчанию
// используя "*", как показано ниже:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]

View File

@ -1,25 +0,0 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.7.34031.279
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AiSD_Lab1", "AiSD_Lab1\AiSD_Lab1.csproj", "{9015CE0F-B12D-4C87-9827-75FBDDB6AE48}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{9015CE0F-B12D-4C87-9827-75FBDDB6AE48}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{9015CE0F-B12D-4C87-9827-75FBDDB6AE48}.Debug|Any CPU.Build.0 = Debug|Any CPU
{9015CE0F-B12D-4C87-9827-75FBDDB6AE48}.Release|Any CPU.ActiveCfg = Release|Any CPU
{9015CE0F-B12D-4C87-9827-75FBDDB6AE48}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {F9A02028-472E-4A74-938E-A366C44E2A55}
EndGlobalSection
EndGlobal

View File

@ -1,10 +0,0 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net7.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
</Project>

View File

@ -1,67 +0,0 @@
using static System.Runtime.InteropServices.JavaScript.JSType;
namespace AiSD_Lab1;
public class Deque
{
Landmark first;
public Deque(string data)
{
Landmark newEl = new Landmark(data);
first = newEl;
}
public void AddFirst(string data)
{
Landmark newEl = new Landmark(data);
newEl.next = first;
first = newEl;
}
public Landmark RemoveFirst()
{
Landmark delEl = first;
first = delEl.next;
delEl.next = null;
return delEl;
}
public void RemoveLast()
{
Landmark delEl = first;
while (delEl.next.next != null)
{
delEl = delEl.next;
}
delEl.next = null;
}
public void AddLast(string data)
{
Landmark newEl = first;
while (newEl.next != null)
{
newEl = newEl.next;
}
newEl.next = new Landmark(data);
}
public string GetAll()
{
string Deque = "";
Landmark curr = first;
while (curr.next != null)
{
Deque += " " + curr.data;
curr = curr.next;
}
Deque += " " + curr.data;
return Deque;
}
}

View File

@ -1,12 +0,0 @@
namespace AiSD_Lab1;
public class Landmark
{
public String data;
public Landmark next;
public Landmark(String _data)
{
data = _data;
}
}

View File

@ -1,27 +0,0 @@
using System;
namespace AiSD_Lab1;
public class Program
{
public static void Main(String[] args)
{
Console.WriteLine("Сортировка слиянием");
Sort sort = new Sort();
sort.RandomArr();
sort.PrintArr();
sort.MergeSort(sort.arr, 0, sort.arr.Length - 1);
sort.PrintArr();
Deque deque = new Deque("Статуя свободы");
Console.WriteLine(deque.GetAll());
deque.AddFirst("Успенский собор");
Console.WriteLine(deque.GetAll());
deque.AddLast("Эйфелева башня");
Console.WriteLine(deque.GetAll());
deque.RemoveLast();
Console.WriteLine(deque.GetAll());
deque.RemoveFirst();
Console.WriteLine(deque.GetAll());
}
}

View File

@ -1,150 +0,0 @@
using System;
namespace AiSD_Lab1;
public class Sort
{
public int[] arr = new int[5];
/// <summary>
/// Заполняет массив рандомными значениями
/// </summary>
public void RandomArr()
{
for (int i = 0; i < arr.Length; i++)
{
Random random = new Random();
arr[i] = random.Next(-100, 100);
}
}
/// <summary>
/// Вывод массива в консоль
/// </summary>
public void PrintArr()
{
Console.WriteLine("Array:");
for (int i = 0; i < arr.Length; i++)
{
Console.WriteLine("[" + i + "]: " + arr[i]);
}
}
/// <summary>
/// Проверяет, отсортирован ли массив по возрастанию
/// </summary>
public void IsSortedUp()
{
for (int i = 0; i < arr.Length - 1; i++)
{
if (arr[i] > arr[i + 1])
{
Console.WriteLine("Массив НЕ отсортирован по возрастанию");
return;
}
}
Console.WriteLine("Массив отсортирован по возрастанию");
}
/// <summary>
/// Проверяет, отсортирован ли массив по убыванию
/// </summary>
public void IsSortedDown()
{
for (int i = 1; i < arr.Length; i++)
{
if (arr[i - 1] < arr[i])
{
Console.WriteLine("Массив НЕ отсортирован по убыванию");
return;
}
}
Console.WriteLine("Массив отсортирован по убыванию");
}
/// <summary>
/// Сортировка выбором
/// </summary>
public void Choise()
{
for(int i = 0; i < arr.Length; i++)
{
int min = i;
for(int j = i + 1; j < arr.Length; j++)
{
if (arr[j] < arr[min])
{
min = j;
}
int temp = arr[min];
arr[min] = arr[i];
arr[i] = temp;
}
}
}
/// <summary>
/// Метод для слияния массивов
/// </summary>
public void Merge(int[] array, int lowIndex, int middleIndex, int highIndex)
{
// Индекс первого элемента левой части массива
int left = lowIndex;
// Индекс первого элемента правой части массива
int right = middleIndex + 1;
// Массив для слияния
int[] tempArray = new int[highIndex - lowIndex + 1];
int index = 0;
// Проходимся по левой и правой половине массива
while ((left <= middleIndex) && (right <= highIndex))
{
if (array[left] < array[right])
{
tempArray[index] = array[left];
left++;
}
else
{
tempArray[index] = array[right];
right++;
}
index++;
}
for (int i = left; i <= middleIndex; i++)
{
tempArray[index] = array[i];
index++;
}
for (int i = right; i <= highIndex; i++)
{
tempArray[index] = array[i];
index++;
}
// Вносим в массив отсортированные элементы
for (int i = 0; i < tempArray.Length; i++)
{
array[lowIndex + i] = tempArray[i];
}
}
// Сортировка слиянием
public int[] MergeSort(int[] array, int lowIndex, int highIndex)
{
if (lowIndex < highIndex)
{
// Индекс середины массива
int middleInd = (lowIndex + highIndex) / 2;
MergeSort(array, lowIndex, middleInd);
MergeSort(array, middleInd + 1, highIndex);
Merge(array, lowIndex, middleInd, highIndex);
}
return array;
}
}

View File

@ -21,7 +21,7 @@ public abstract class AbstractCompany
_pictureWidth = picWidth; _pictureWidth = picWidth;
_pictureHeight = picHeight; _pictureHeight = picHeight;
_collection = collection; _collection = collection;
_collection.SetMaxCount = GetMaxCount; _collection.MaxCount = GetMaxCount;
} }
public static int operator +(AbstractCompany company, DrawningShip ship) public static int operator +(AbstractCompany company, DrawningShip ship)

View File

@ -1,12 +1,11 @@
 namespace ProjectPlane.CollectionGenericObjects;
namespace ProjectPlane.CollectionGenericObjects;
public interface ICollectionGenericObjects<T> public interface ICollectionGenericObjects<T>
where T : class where T : class
{ {
int Count { get; } int Count { get; }
int SetMaxCount { set; } int MaxCount { get; set; }
int Insert(T obj); int Insert(T obj);
@ -15,5 +14,10 @@ public interface ICollectionGenericObjects<T>
T? Remove(int position); T? Remove(int position);
T? Get(int position); T? Get(int position);
CollectionType GetCollectionType { get; }
IEnumerable<T?> GetItems();
} }

View File

@ -11,7 +11,9 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
public int Count => _collection.Count; public int Count => _collection.Count;
public int SetMaxCount { set { if (value > 0) { _maxCount = value; } } } public int MaxCount { get { return _collection.Count; } set { if (value > 0) { _maxCount = value; } } }
public CollectionType GetCollectionType => CollectionType.List;
public ListGenericObjects() public ListGenericObjects()
{ {
@ -62,4 +64,12 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
return obj; return obj;
} }
public IEnumerable<T?> GetItems()
{
for (int i = 0; i < Count; ++i)
{
yield return _collection[i];
}
}
} }

View File

@ -5,8 +5,12 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
{ {
private T?[] _collection; private T?[] _collection;
public int Count => _collection.Length; public int Count => _collection.Length;
public int SetMaxCount public int MaxCount
{ {
get
{
return _collection.Length;
}
set set
{ {
if (value > 0) if (value > 0)
@ -23,10 +27,13 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
} }
} }
public CollectionType GetCollectionType => CollectionType.Massive;
public MassiveGenericObjects() public MassiveGenericObjects()
{ {
_collection = Array.Empty<T?>(); _collection = Array.Empty<T?>();
} }
public T? Get(int position) public T? Get(int position)
{ {
if (position < 0 || position > Count) if (position < 0 || position > Count)
@ -48,6 +55,7 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
} }
return -1; return -1;
} }
public int Insert(T obj, int position) public int Insert(T obj, int position)
{ {
if (position < 0 || position > Count) if (position < 0 || position > Count)
@ -81,6 +89,7 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
return -1; return -1;
} }
public T? Remove(int position) public T? Remove(int position)
{ {
if (position < 0 || position > Count || _collection[position] == null) if (position < 0 || position > Count || _collection[position] == null)
@ -93,4 +102,12 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
return obj; return obj;
} }
public IEnumerable<T?> GetItems()
{
for (int i = 0; i < _collection.Length; ++i)
{
yield return _collection[i];
}
}
} }

View File

@ -1,12 +1,18 @@
using ProjectPlane.Drawnings; using ProjectPlane.Drawnings;
using ProjectPlane.CollectionGenericObjects; using System.Text;
using System.Xml.Linq;
namespace ProjectPlane.CollectionGenericObjects; namespace ProjectPlane.CollectionGenericObjects;
public class StorageCollection<T> public class StorageCollection<T>
where T : class where T : DrawningShip
{ {
private readonly string _collectionKey = "CollectionsStorage";
private readonly string _separatorForKeyValue = "|";
private readonly string _separatorItems = ";";
private Dictionary<string, ICollectionGenericObjects<T>> _storages; private Dictionary<string, ICollectionGenericObjects<T>> _storages;
public List<string> Keys => _storages.Keys.ToList(); public List<string> Keys => _storages.Keys.ToList();
@ -56,11 +62,117 @@ public class StorageCollection<T>
_storages.Remove(name); _storages.Remove(name);
} }
/// <summary> public bool SaveData(string filename)
/// Доступ к коллекции {
/// </summary> if (_storages.Count == 0)
/// <param name="name">Название коллекции</param> {
/// <returns></returns> return false;
}
if (File.Exists(filename))
{
File.Delete(filename);
}
StringBuilder sb = new();
sb.Append(_collectionKey);
foreach (KeyValuePair<string, ICollectionGenericObjects<T>> value in
_storages)
{
sb.Append(Environment.NewLine);
// не сохраняем пустые коллекции
if (value.Value.Count == 0)
{
continue;
}
sb.Append(value.Key);
sb.Append(_separatorForKeyValue);
sb.Append(value.Value.GetCollectionType);
sb.Append(_separatorForKeyValue);
sb.Append(value.Value.MaxCount);
sb.Append(_separatorForKeyValue);
foreach (T? item in value.Value.GetItems())
{
string data = item?.GetDataForSave() ?? string.Empty;
if (string.IsNullOrEmpty(data))
{
continue;
}
sb.Append(data);
sb.Append(_separatorItems);
}
}
using FileStream fs = new(filename, FileMode.Create);
byte[] info = new UTF8Encoding(true).GetBytes(sb.ToString());
fs.Write(info, 0, info.Length);
return true;
}
public bool LoadData(string filename)
{
if (!File.Exists(filename))
{
return false;
}
string bufferTextFromFile = "";
using (FileStream fs = new(filename, FileMode.Open))
{
byte[] b = new byte[fs.Length];
UTF8Encoding temp = new(true);
while (fs.Read(b, 0, b.Length) > 0)
{
bufferTextFromFile += temp.GetString(b);
}
}
string[] strs = bufferTextFromFile.Split(new char[] { '\n', '\r' },
StringSplitOptions.RemoveEmptyEntries);
if (strs == null || strs.Length == 0)
{
return false;
}
if (!strs[0].Equals(_collectionKey))
{
//если нет такой записи, то это не те данные
return false;
}
_storages.Clear();
foreach (string data in strs)
{
string[] record = data.Split(_separatorForKeyValue,
StringSplitOptions.RemoveEmptyEntries);
if (record.Length != 4)
{
continue;
}
CollectionType collectionType =
(CollectionType)Enum.Parse(typeof(CollectionType), record[1]);
ICollectionGenericObjects<T>? collection =
StorageCollection<T>.CreateCollection(collectionType);
if (collection == null)
{
return false;
}
collection.MaxCount = Convert.ToInt32(record[2]);
string[] set = record[3].Split(_separatorItems,
StringSplitOptions.RemoveEmptyEntries);
foreach (string elem in set)
{
if (elem?.CreateDrawningShip() is T ship)
{
if (collection.Insert(ship) == -1)
{
return false;
}
}
}
_storages.Add(record[0], collection);
}
return true;
}
public ICollectionGenericObjects<T>? this[string name] public ICollectionGenericObjects<T>? this[string name]
{ {
get get
@ -73,4 +185,14 @@ public class StorageCollection<T>
return null; return null;
} }
} }
private static ICollectionGenericObjects<T>? CreateCollection(CollectionType collectionType)
{
return collectionType switch
{
CollectionType.Massive => new MassiveGenericObjects<T>(),
CollectionType.List => new ListGenericObjects<T>(),
_ => null,
};
}
} }

View File

@ -0,0 +1,36 @@
using ProjectPlane.Entities;
using ProjectPlane.Drawnings;
namespace ProjectPlane.Drawnings;
public static class ExtentionDrawningShip
{
private static readonly string _separatorForObject = ":";
public static DrawningShip? CreateDrawningShip(this string info)
{
string[] strs = info.Split(_separatorForObject);
EntityShip? ship = EntityContainer.CreateEntityContainer(strs);
if (ship != null)
{
return new DrawCont(ship.Speed, ship.Weight, ship.ShipColor, (ship as EntityContainer).ContainerColor, (ship as EntityContainer).Container, (ship as EntityContainer).Crane);
}
ship = EntityShip.CreateEntityShip(strs);
if (ship != null)
{
return new DrawningShip(ship.Speed, ship.Weight, ship.ShipColor);
}
return null;
}
public static string GetDataForSave(this DrawningShip drawningShip)
{
string[]? array = drawningShip?.EntityShip?.GetStringRepresentation();
if (array == null)
{
return string.Empty;
}
return string.Join(_separatorForObject, array);
}
}

View File

@ -30,4 +30,20 @@ public class EntityContainer : EntityShip
{ {
ContainerColor = newColor; ContainerColor = newColor;
} }
public override string[] GetStringRepresentation()
{
return new[] { nameof(EntityContainer), Speed.ToString(), Weight.ToString(), ShipColor.Name, ContainerColor.Name, Container.ToString(), Crane.ToString()};
}
public static EntityContainer? CreateEntityContainer(string[] strs)
{
if (strs.Length != 7 || strs[0] != nameof(EntityContainer))
{
return null;
}
return new EntityContainer(Convert.ToInt32(strs[1]), Convert.ToDouble(strs[2]), Color.FromName(strs[3]), Color.FromName(strs[4]), Convert.ToBoolean(strs[5]), Convert.ToBoolean(strs[6]));
}
} }

View File

@ -26,4 +26,20 @@ public class EntityShip
{ {
ShipColor = newColor; ShipColor = newColor;
} }
public virtual string[] GetStringRepresentation()
{
return new[] { nameof(EntityShip), Speed.ToString(), Weight.ToString(), ShipColor.Name };
}
public static EntityShip? CreateEntityShip(string[] strs)
{
if (strs.Length != 4 || strs[0] != nameof(EntityShip))
{
return null;
}
return new EntityShip(Convert.ToInt32(strs[1]), Convert.ToDouble(strs[2]), Color.FromName(strs[3]));
}
} }

View File

@ -46,10 +46,17 @@
labelCollectionName = new Label(); labelCollectionName = new Label();
ComboBoxSelectorCompany = new ComboBox(); ComboBoxSelectorCompany = new ComboBox();
pictureBox = new PictureBox(); pictureBox = new PictureBox();
menuStrip = new MenuStrip();
файлToolStripMenuItem = new ToolStripMenuItem();
saveToolStripMenuItem = new ToolStripMenuItem();
loadToolStripMenuItem = new ToolStripMenuItem();
saveFileDialog = new SaveFileDialog();
openFileDialog = new OpenFileDialog();
groupBoxTools.SuspendLayout(); groupBoxTools.SuspendLayout();
panelCompanyTools.SuspendLayout(); panelCompanyTools.SuspendLayout();
panelStorage.SuspendLayout(); panelStorage.SuspendLayout();
((System.ComponentModel.ISupportInitialize)pictureBox).BeginInit(); ((System.ComponentModel.ISupportInitialize)pictureBox).BeginInit();
menuStrip.SuspendLayout();
SuspendLayout(); SuspendLayout();
// //
// groupBoxTools // groupBoxTools
@ -59,9 +66,9 @@
groupBoxTools.Controls.Add(panelStorage); groupBoxTools.Controls.Add(panelStorage);
groupBoxTools.Controls.Add(ComboBoxSelectorCompany); groupBoxTools.Controls.Add(ComboBoxSelectorCompany);
groupBoxTools.Dock = DockStyle.Right; groupBoxTools.Dock = DockStyle.Right;
groupBoxTools.Location = new Point(785, 0); groupBoxTools.Location = new Point(785, 24);
groupBoxTools.Name = "groupBoxTools"; groupBoxTools.Name = "groupBoxTools";
groupBoxTools.Size = new Size(200, 696); groupBoxTools.Size = new Size(200, 672);
groupBoxTools.TabIndex = 0; groupBoxTools.TabIndex = 0;
groupBoxTools.TabStop = false; groupBoxTools.TabStop = false;
groupBoxTools.Text = "Инструменты"; groupBoxTools.Text = "Инструменты";
@ -239,12 +246,44 @@
// pictureBox // pictureBox
// //
pictureBox.Dock = DockStyle.Fill; pictureBox.Dock = DockStyle.Fill;
pictureBox.Location = new Point(0, 0); pictureBox.Location = new Point(0, 24);
pictureBox.Name = "pictureBox"; pictureBox.Name = "pictureBox";
pictureBox.Size = new Size(785, 696); pictureBox.Size = new Size(785, 672);
pictureBox.TabIndex = 1; pictureBox.TabIndex = 1;
pictureBox.TabStop = false; pictureBox.TabStop = false;
// //
// menuStrip
//
menuStrip.Items.AddRange(new ToolStripItem[] { файлToolStripMenuItem });
menuStrip.Location = new Point(0, 0);
menuStrip.Name = "menuStrip";
menuStrip.Size = new Size(985, 24);
menuStrip.TabIndex = 2;
menuStrip.Text = "menuStrip";
//
// файлToolStripMenuItem
//
файлToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { saveToolStripMenuItem, loadToolStripMenuItem });
файлToolStripMenuItem.Name = айлToolStripMenuItem";
файлToolStripMenuItem.Size = new Size(48, 20);
файлToolStripMenuItem.Text = "Файл";
//
// saveToolStripMenuItem
//
saveToolStripMenuItem.Name = "saveToolStripMenuItem";
saveToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.S;
saveToolStripMenuItem.Size = new Size(181, 22);
saveToolStripMenuItem.Text = "Сохранение";
saveToolStripMenuItem.Click += SaveToolStripMenuItem_Click;
//
// loadToolStripMenuItem
//
loadToolStripMenuItem.Name = "loadToolStripMenuItem";
loadToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.L;
loadToolStripMenuItem.Size = new Size(181, 22);
loadToolStripMenuItem.Text = "Загрузка";
loadToolStripMenuItem.Click += LoadToolStripMenuItem_Click;
//
// FormShipCollection // FormShipCollection
// //
AutoScaleDimensions = new SizeF(7F, 15F); AutoScaleDimensions = new SizeF(7F, 15F);
@ -252,6 +291,8 @@
ClientSize = new Size(985, 696); ClientSize = new Size(985, 696);
Controls.Add(pictureBox); Controls.Add(pictureBox);
Controls.Add(groupBoxTools); Controls.Add(groupBoxTools);
Controls.Add(menuStrip);
MainMenuStrip = menuStrip;
Name = "FormShipCollection"; Name = "FormShipCollection";
Text = "Коллекция кораблей"; Text = "Коллекция кораблей";
groupBoxTools.ResumeLayout(false); groupBoxTools.ResumeLayout(false);
@ -260,7 +301,10 @@
panelStorage.ResumeLayout(false); panelStorage.ResumeLayout(false);
panelStorage.PerformLayout(); panelStorage.PerformLayout();
((System.ComponentModel.ISupportInitialize)pictureBox).EndInit(); ((System.ComponentModel.ISupportInitialize)pictureBox).EndInit();
menuStrip.ResumeLayout(false);
menuStrip.PerformLayout();
ResumeLayout(false); ResumeLayout(false);
PerformLayout();
} }
#endregion #endregion
@ -283,5 +327,11 @@
private ListBox listBoxCollection; private ListBox listBoxCollection;
private RadioButton radioButtonMassive; private RadioButton radioButtonMassive;
private Panel panelCompanyTools; private Panel panelCompanyTools;
private MenuStrip menuStrip;
private ToolStripMenuItem файлToolStripMenuItem;
private ToolStripMenuItem saveToolStripMenuItem;
private ToolStripMenuItem loadToolStripMenuItem;
private SaveFileDialog saveFileDialog;
private OpenFileDialog openFileDialog;
} }
} }

View File

@ -20,7 +20,7 @@ public partial class FormShipCollection : Form
panelCompanyTools.Enabled = false; panelCompanyTools.Enabled = false;
} }
private void ButtonAddShip_Click(object sender, EventArgs e) private void ButtonAddShip_Click(object sender, EventArgs e)
{ {
FormShipConfig form = new(); FormShipConfig form = new();
form.AddEvent(SetShip); form.AddEvent(SetShip);
@ -187,4 +187,39 @@ public partial class FormShipCollection : Form
panelCompanyTools.Enabled = true; panelCompanyTools.Enabled = true;
RerfreshListBoxItems(); RerfreshListBoxItems();
} }
private void SaveToolStripMenuItem_Click(object sender, EventArgs e)
{
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
if (_storageCollection.SaveData(saveFileDialog.FileName))
{
MessageBox.Show("Сохранение прошло успешно",
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
MessageBox.Show("Не сохранилось", "Результат",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
private void LoadToolStripMenuItem_Click(object sender, EventArgs e)
{
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
if (_storageCollection.LoadData(openFileDialog.FileName))
{
MessageBox.Show("Загрузка прошла успешно",
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
RerfreshListBoxItems();
}
else
{
MessageBox.Show("Не загрузилось", "Результат",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
} }

View File

@ -117,4 +117,13 @@
<resheader name="writer"> <resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value> <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader> </resheader>
<metadata name="menuStrip.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>17, 17</value>
</metadata>
<metadata name="saveFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>126, 17</value>
</metadata>
<metadata name="openFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>261, 17</value>
</metadata>
</root> </root>