Skip to content

Commit

Permalink
Combinatorics task
Browse files Browse the repository at this point in the history
  • Loading branch information
urmasa-tar committed Oct 21, 2024
1 parent ed9b07d commit 10e4410
Show file tree
Hide file tree
Showing 9 changed files with 318 additions and 0 deletions.
10 changes: 10 additions & 0 deletions CombinatoricAlgorithms/CombinatoricAlgorithms.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
<Project Sdk="Microsoft.NET.Sdk">

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

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

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.11.35312.102
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CombinatoricAlgorithms", "CombinatoricAlgorithms.csproj", "{95A17E6A-2902-41F4-9C83-89002AB7E505}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{95A17E6A-2902-41F4-9C83-89002AB7E505}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{95A17E6A-2902-41F4-9C83-89002AB7E505}.Debug|Any CPU.Build.0 = Debug|Any CPU
{95A17E6A-2902-41F4-9C83-89002AB7E505}.Release|Any CPU.ActiveCfg = Release|Any CPU
{95A17E6A-2902-41F4-9C83-89002AB7E505}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {6381A0F9-214C-406A-8034-F5B3DEEEB399}
EndGlobalSection
EndGlobal
59 changes: 59 additions & 0 deletions CombinatoricAlgorithms/Combinatorics.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CombinatoricAlgorithms
{
public class Combinatorics
{
// Вычисляет факториал числа n (n!)
public long Factorial(int n)
{
if (n < 0)
{
throw new ArgumentOutOfRangeException(nameof(n), "Факториал не определен для отрицательных чисел.");
}
else if (n == 0 || n == 1)
{
return 1;
}
else
{
long result = 1;
for (int i = 2; i <= n; i++)
{
result *= i;
}
return result;
}
}

// Вычисляет количество перестановок n элементов (n!)
public long Permutations(int n)
{
return Factorial(n);
}

// Вычисляет количество комбинаций из n элементов по k (C(n, k))
public long Combinations(int n, int k)
{
if (k < 0 || k > n)
{
return 0;
}
return Factorial(n) / (Factorial(k) * Factorial(n - k));
}

// Вычисляет количество размещений из n элементов по k (A(n, k))
public long Arrangements(int n, int k)
{
if (k < 0 || k > n)
{
return 0;
}
return Factorial(n) / Factorial(n - k);
}
}
}
86 changes: 86 additions & 0 deletions CombinatoricAlgorithms/KMP.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CombinatoricAlgorithms
{

public class KMP
{
private readonly string pattern;
private readonly int[] lps;

public KMP(string pattern)
{
this.pattern = pattern;
lps = BuildLPS(pattern);
}

// Метод для построения массива lps (Longest Prefix which is also Suffix)
private int[] BuildLPS(string pattern)
{
int length = 0; // Длина предыдущего самого длинного префикса
int m = pattern.Length;
int[] lps = new int[m];
lps[0] = 0; // lps[0] всегда равно 0

for (int i = 1; i < m; i++)
{
while (length > 0 && pattern[i] != pattern[length])
{
length = lps[length - 1];
}

if (pattern[i] == pattern[length])
{
length++;
lps[i] = length;
}
else
{
lps[i] = 0;
}
}

return lps;
}

// Метод для поиска подстроки в строке
public void Search(string text)
{
int n = text.Length;
int m = pattern.Length;
int i = 0; // Индекс для text
int j = 0; // Индекс для pattern

while (i < n)
{
if (pattern[j] == text[i])
{
i++;
j++;
}

if (j == m)
{
Console.WriteLine("Подстрока найдена в индексе: " + (i - j));
j = lps[j - 1]; // Продолжаем искать другие совпадения
}
else if (i < n && pattern[j] != text[i])
{
// Мismatch после j совпадений
if (j != 0)
{
j = lps[j - 1];
}
else
{
i++;
}
}
}
}
}
}
7 changes: 7 additions & 0 deletions CombinatoricAlgorithms/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
class Program
{
public static void Main(string[] args)
{

}
}
96 changes: 96 additions & 0 deletions CombinatoricAlgorithms/combGeneric.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CombinatoricAlgorithms
{
public class combGeneric
{
// Генерация всех перестановок
public static IEnumerable<IEnumerable<T>> Permutations<T>(IEnumerable<T> elements)
{
var list = new List<T>(elements);
int count = list.Count;
var indices = new int[count];
for (int i = 0; i < count; i++)
{
indices[i] = 0;
}

yield return new List<T>(list);

while (true)
{
int i;
for (i = count - 1; i >= 0; i--)
{
if (indices[i] < i)
{
int j = (i % 2) == 0 ? 0 : indices[i];
Swap(list, i, j);
yield return new List<T>(list);
indices[i]++;
break;
}
indices[i] = 0;
}

if (i < 0) yield break;
}
}

// Генерация всех комбинаций
public static IEnumerable<IEnumerable<T>> Combinations<T>(IEnumerable<T> elements, int k)
{
var list = new List<T>(elements);
int count = list.Count;

if (k > count)
{
yield break;
}

int[] indices = new int[k];
for (int i = 0; i < k; i++)
{
indices[i] = i;
}

while (true)
{
yield return GetCombination(list, indices);

int position = k - 1;
while (position >= 0 && indices[position] == count - k + position)
{
position--;
}

if (position < 0) yield break;

indices[position]++;
for (int i = position + 1; i < k; i++)
{
indices[i] = indices[i - 1] + 1;
}
}
}

private static IEnumerable<T> GetCombination<T>(List<T> list, int[] indices)
{
foreach (var index in indices)
{
yield return list[index];
}
}

private static void Swap<T>(List<T> list, int i, int j)
{
T temp = list[i];
list[i] = list[j];
list[j] = temp;
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
// <autogenerated />
using System;
using System.Reflection;
[assembly: global::System.Runtime.Versioning.TargetFrameworkAttribute(".NETCoreApp,Version=v8.0", FrameworkDisplayName = ".NET 8.0")]
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
//------------------------------------------------------------------------------
// <auto-generated>
// Этот код создан программой.
// Исполняемая версия:4.0.30319.42000
//
// Изменения в этом файле могут привести к неправильной работе и будут потеряны в случае
// повторной генерации кода.
// </auto-generated>
//------------------------------------------------------------------------------

using System;
using System.Reflection;

[assembly: System.Reflection.AssemblyCompanyAttribute("CombinatoricAlgorithms")]
[assembly: System.Reflection.AssemblyConfigurationAttribute("Debug")]
[assembly: System.Reflection.AssemblyFileVersionAttribute("1.0.0.0")]
[assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0+ed9b07d3e30e763ad56a759b5b73e1e1043b2804")]
[assembly: System.Reflection.AssemblyProductAttribute("CombinatoricAlgorithms")]
[assembly: System.Reflection.AssemblyTitleAttribute("CombinatoricAlgorithms")]
[assembly: System.Reflection.AssemblyVersionAttribute("1.0.0.0")]

// Создано классом WriteCodeFragment MSBuild.

Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
// <auto-generated/>
global using global::System;
global using global::System.Collections.Generic;
global using global::System.IO;
global using global::System.Linq;
global using global::System.Net.Http;
global using global::System.Threading;
global using global::System.Threading.Tasks;

0 comments on commit 10e4410

Please sign in to comment.