Merge branch 'main' into UG

pull/185/head
Ujjwal 2021-04-15 11:04:36 +05:30 committed by GitHub
commit cf1bc4692f
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
29 changed files with 1172 additions and 199 deletions

25
.github/workflows/dotnet.yml vendored 100644
View File

@ -0,0 +1,25 @@
name: .NET
on:
push:
branches: [ main ]
pull_request:
branches: [ main ]
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Setup .NET
uses: actions/setup-dotnet@v1
with:
dotnet-version: 3.1.x
- name: Restore dependencies
run: dotnet restore algorithms/CSharp
- name: Build
run: dotnet build algorithms/CSharp --no-restore
- name: Test
run: dotnet test algorithms/CSharp --no-build --verbosity normal

View File

@ -1,4 +1,5 @@
# Data Structures and Algorithm # Data Structures and Algorithm
Data structure and Algorithm (DSA) Data structure and Algorithm (DSA)
## Contribution Guidelines ## Contribution Guidelines
@ -10,10 +11,12 @@ The problem being contributed must either be a simple **file** (**Eg.** [`kruska
The directory tree has the following convention of `category/language/problem`, where `category` is the topic or category of the problem being contributed (**Eg.** `strings`, `sorting`, `linked-lists` etc.), `language` represents the language code of the problem (**Eg.** `c-or-cpp` for C/C++, `python` for Python, `java` for Java etc.), and `problem` is a conforming name to the problem (**Eg.** `linear-search.cpp`, `palindrome`, `queue-linked-list.cpp` etc.) The directory tree has the following convention of `category/language/problem`, where `category` is the topic or category of the problem being contributed (**Eg.** `strings`, `sorting`, `linked-lists` etc.), `language` represents the language code of the problem (**Eg.** `c-or-cpp` for C/C++, `python` for Python, `java` for Java etc.), and `problem` is a conforming name to the problem (**Eg.** `linear-search.cpp`, `palindrome`, `queue-linked-list.cpp` etc.)
A unit `problem` must conform to the following specifications: A unit `problem` must conform to the following specifications:
- The name should be in lowercase. (**Eg.** `palindrome/`, `binary-search.cpp` etc.). - The name should be in lowercase. (**Eg.** `palindrome/`, `binary-search.cpp` etc.).
- Each word must be separated by a **dash** or a **hyphen** (`-`). - Each word must be separated by a **dash** or a **hyphen** (`-`).
**If you have a problem that belongs to a new *topic* or *category* than one which are present:** **If you have a problem that belongs to a new _topic_ or _category_ than one which are present:**
1. Create a new folder and an index for it inside (a readme, `README.md` file). 1. Create a new folder and an index for it inside (a readme, `README.md` file).
2. To each new index file, write the readme with your `problem` in it ([Markdown Documentation](https://guides.github.com/features/mastering-markdown/)). 2. To each new index file, write the readme with your `problem` in it ([Markdown Documentation](https://guides.github.com/features/mastering-markdown/)).
3. The folder name can also only contain **lowercase characters** and **dashes** or **hyphens** (`-`) (Eg. `strings` `sorting` etc.) 3. The folder name can also only contain **lowercase characters** and **dashes** or **hyphens** (`-`) (Eg. `strings` `sorting` etc.)
@ -29,6 +32,7 @@ The project and folder-based contributions have a bit more stricter contribution
The folder should conform to the `problem` specification, along with the following specifications The folder should conform to the `problem` specification, along with the following specifications
**Folder Structure** **Folder Structure**
```bash ```bash
problem-name\ problem-name\
| - .gitignore | - .gitignore
@ -40,7 +44,7 @@ problem-name\
#### `README.md` Specification / Template #### `README.md` Specification / Template
```markdown ````markdown
# <Title of the Problem> # <Title of the Problem>
< description of the problem > < description of the problem >
@ -57,12 +61,14 @@ problem-name\
```bash ```bash
make # or 'cargo run', or 'dotnet run' or 'mvn exec:java' etc. make # or 'cargo run', or 'dotnet run' or 'mvn exec:java' etc.
``` ```
## Test Cases & Output < if exists> ## Test Cases & Output < if exists>
< If you can provide test cases, describe it here, else remove this section > < If you can provide test cases, describe it here, else remove this section >
``` ````
#### `.gitignore` File #### `.gitignore` File
```gitignore ```gitignore
# add all output files and build files to be excluded from git tracking # add all output files and build files to be excluded from git tracking
main # executable file also must have the project name main # executable file also must have the project name
@ -70,7 +76,9 @@ target/ # the build file, for example for rust
``` ```
#### Build File / Specification File / Configuration File #### Build File / Specification File / Configuration File
It can be any of the following ones It can be any of the following ones
- **C/C++**: `Makefile` - **C/C++**: `Makefile`
- **Python**: `requirements.txt` - **Python**: `requirements.txt`
- **JavaScript**: `package.json` and `package-lock.json` - **JavaScript**: `package.json` and `package-lock.json`
@ -88,24 +96,30 @@ Again, the source codes must conform to a valid file structure convention that t
The programming should keep the naming convention rule of each programming language. The programming should keep the naming convention rule of each programming language.
### Other topic ### Other topic
- [First-time contribution](CONTRIBUTING.md) - [First-time contribution](CONTRIBUTING.md)
## Contributors ## Contributors
<a href="https://github.com/MakeContributions/DSA/graphs/contributors"> <a href="https://github.com/MakeContributions/DSA/graphs/contributors">
<img src="https://contrib.rocks/image?repo=MakeContributions/DSA" /> <img src="https://contrib.rocks/image?repo=MakeContributions/DSA" />
</a> </a>
### Reviewers ### Reviewers
|Programming Language| Users |
|-------------------|---------------| | Programming Language | Users |
| C or C++ |@Arsenic-ATG, @UG-SEP | | -------------------- | ------------------------------------------------- |
| Java |@TawfikYasser, @cyberwizard1001 | | C or C++ | @Arsenic-ATG, @UG-SEP, @aayushjain7 |
| Java | @TawfikYasser, @cyberwizard1001, @aayushjain7 |
| C# | @ming-tsai | | C# | @ming-tsai |
| Go |@atin | | Go | @atin |
| Python | @Arsenic-ATG, @atin, @sridhar-5, @cyberwizard1001 | | Python | @Arsenic-ATG, @atin, @sridhar-5, @cyberwizard1001 |
| JavaScript | @paulsonjpaul | | JavaScript | @paulsonjpaul |
## Open Graph ## Open Graph
<img src="https://opengraph.github.com/3b128f0e88464a82a37f2daefd7d594c6f41a3c22b3bf94c0c030135039b5dd7/MakeContributions/DSA" /> <img src="https://opengraph.github.com/3b128f0e88464a82a37f2daefd7d594c6f41a3c22b3bf94c0c030135039b5dd7/MakeContributions/DSA" />
## License ## License
[MIT](./LICENSE) [MIT](./LICENSE)

362
algorithms/CSharp/.gitignore vendored 100644
View File

@ -0,0 +1,362 @@
## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.
##
## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore
# User-specific files
*.rsuser
*.suo
*.user
*.userosscache
*.sln.docstates
# User-specific files (MonoDevelop/Xamarin Studio)
*.userprefs
# Mono auto generated files
mono_crash.*
# Build results
[Dd]ebug/
[Dd]ebugPublic/
[Rr]elease/
[Rr]eleases/
x64/
x86/
[Ww][Ii][Nn]32/
[Aa][Rr][Mm]/
[Aa][Rr][Mm]64/
bld/
[Bb]in/
[Oo]bj/
[Ll]og/
[Ll]ogs/
# Visual Studio 2015/2017 cache/options directory
.vs/
# Uncomment if you have tasks that create the project's static files in wwwroot
#wwwroot/
# Visual Studio 2017 auto generated files
Generated\ Files/
# MSTest test Results
[Tt]est[Rr]esult*/
[Bb]uild[Ll]og.*
# NUnit
*.VisualState.xml
TestResult.xml
nunit-*.xml
# Build Results of an ATL Project
[Dd]ebugPS/
[Rr]eleasePS/
dlldata.c
# Benchmark Results
BenchmarkDotNet.Artifacts/
# .NET Core
project.lock.json
project.fragment.lock.json
artifacts/
# ASP.NET Scaffolding
ScaffoldingReadMe.txt
# StyleCop
StyleCopReport.xml
# Files built by Visual Studio
*_i.c
*_p.c
*_h.h
*.ilk
*.meta
*.obj
*.iobj
*.pch
*.pdb
*.ipdb
*.pgc
*.pgd
*.rsp
*.sbr
*.tlb
*.tli
*.tlh
*.tmp
*.tmp_proj
*_wpftmp.csproj
*.log
*.vspscc
*.vssscc
.builds
*.pidb
*.svclog
*.scc
# Chutzpah Test files
_Chutzpah*
# Visual C++ cache files
ipch/
*.aps
*.ncb
*.opendb
*.opensdf
*.sdf
*.cachefile
*.VC.db
*.VC.VC.opendb
# Visual Studio profiler
*.psess
*.vsp
*.vspx
*.sap
# Visual Studio Trace Files
*.e2e
# TFS 2012 Local Workspace
$tf/
# Guidance Automation Toolkit
*.gpState
# ReSharper is a .NET coding add-in
_ReSharper*/
*.[Rr]e[Ss]harper
*.DotSettings.user
# TeamCity is a build add-in
_TeamCity*
# DotCover is a Code Coverage Tool
*.dotCover
# AxoCover is a Code Coverage Tool
.axoCover/*
!.axoCover/settings.json
# Coverlet is a free, cross platform Code Coverage Tool
coverage*.json
coverage*.xml
coverage*.info
# Visual Studio code coverage results
*.coverage
*.coveragexml
# NCrunch
_NCrunch_*
.*crunch*.local.xml
nCrunchTemp_*
# MightyMoose
*.mm.*
AutoTest.Net/
# Web workbench (sass)
.sass-cache/
# Installshield output folder
[Ee]xpress/
# DocProject is a documentation generator add-in
DocProject/buildhelp/
DocProject/Help/*.HxT
DocProject/Help/*.HxC
DocProject/Help/*.hhc
DocProject/Help/*.hhk
DocProject/Help/*.hhp
DocProject/Help/Html2
DocProject/Help/html
# Click-Once directory
publish/
# Publish Web Output
*.[Pp]ublish.xml
*.azurePubxml
# Note: Comment the next line if you want to checkin your web deploy settings,
# but database connection strings (with potential passwords) will be unencrypted
*.pubxml
*.publishproj
# Microsoft Azure Web App publish settings. Comment the next line if you want to
# checkin your Azure Web App publish settings, but sensitive information contained
# in these scripts will be unencrypted
PublishScripts/
# NuGet Packages
*.nupkg
# NuGet Symbol Packages
*.snupkg
# The packages folder can be ignored because of Package Restore
**/[Pp]ackages/*
# except build/, which is used as an MSBuild target.
!**/[Pp]ackages/build/
# Uncomment if necessary however generally it will be regenerated when needed
#!**/[Pp]ackages/repositories.config
# NuGet v3's project.json files produces more ignorable files
*.nuget.props
*.nuget.targets
# Microsoft Azure Build Output
csx/
*.build.csdef
# Microsoft Azure Emulator
ecf/
rcf/
# Windows Store app package directories and files
AppPackages/
BundleArtifacts/
Package.StoreAssociation.xml
_pkginfo.txt
*.appx
*.appxbundle
*.appxupload
# Visual Studio cache files
# files ending in .cache can be ignored
*.[Cc]ache
# but keep track of directories ending in .cache
!?*.[Cc]ache/
# Others
ClientBin/
~$*
*~
*.dbmdl
*.dbproj.schemaview
*.jfm
*.pfx
*.publishsettings
orleans.codegen.cs
# Including strong name files can present a security risk
# (https://github.com/github/gitignore/pull/2483#issue-259490424)
#*.snk
# Since there are multiple workflows, uncomment next line to ignore bower_components
# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
#bower_components/
# RIA/Silverlight projects
Generated_Code/
# Backup & report files from converting an old project file
# to a newer Visual Studio version. Backup files are not needed,
# because we have git ;-)
_UpgradeReport_Files/
Backup*/
UpgradeLog*.XML
UpgradeLog*.htm
ServiceFabricBackup/
*.rptproj.bak
# SQL Server files
*.mdf
*.ldf
*.ndf
# Business Intelligence projects
*.rdl.data
*.bim.layout
*.bim_*.settings
*.rptproj.rsuser
*- [Bb]ackup.rdl
*- [Bb]ackup ([0-9]).rdl
*- [Bb]ackup ([0-9][0-9]).rdl
# Microsoft Fakes
FakesAssemblies/
# GhostDoc plugin setting file
*.GhostDoc.xml
# Node.js Tools for Visual Studio
.ntvs_analysis.dat
node_modules/
# Visual Studio 6 build log
*.plg
# Visual Studio 6 workspace options file
*.opt
# Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
*.vbw
# Visual Studio LightSwitch build output
**/*.HTMLClient/GeneratedArtifacts
**/*.DesktopClient/GeneratedArtifacts
**/*.DesktopClient/ModelManifest.xml
**/*.Server/GeneratedArtifacts
**/*.Server/ModelManifest.xml
_Pvt_Extensions
# Paket dependency manager
.paket/paket.exe
paket-files/
# FAKE - F# Make
.fake/
# CodeRush personal settings
.cr/personal
# Python Tools for Visual Studio (PTVS)
__pycache__/
*.pyc
# Cake - Uncomment if you are using it
# tools/**
# !tools/packages.config
# Tabs Studio
*.tss
# Telerik's JustMock configuration file
*.jmconfig
# BizTalk build output
*.btp.cs
*.btm.cs
*.odx.cs
*.xsd.cs
# OpenCover UI analysis results
OpenCover/
# Azure Stream Analytics local run output
ASALocalRun/
# MSBuild Binary and Structured Log
*.binlog
# NVidia Nsight GPU debugger configuration file
*.nvuser
# MFractors (Xamarin productivity tool) working folder
.mfractor/
# Local History for Visual Studio
.localhistory/
# BeatPulse healthcheck temp database
healthchecksdb
# Backup folder for Package Reference Convert tool in Visual Studio 2017
MigrationBackup/
# Ionide (cross platform F# VS Code tools) working folder
.ionide/
# Fody - auto-generated XML schema
FodyWeavers.xsd

View File

@ -0,0 +1,27 @@
{
"version": "0.2.0",
"configurations": [
{
// Use IntelliSense to find out which attributes exist for C# debugging
// Use hover for the description of the existing attributes
// For further information visit https://github.com/OmniSharp/omnisharp-vscode/blob/master/debugger-launchjson.md
"name": ".NET Core Launch (console)",
"type": "coreclr",
"request": "launch",
"preLaunchTask": "build",
// If you have changed target frameworks, make sure to update the program path.
"program": "${workspaceFolder}/test/bin/Debug/netcoreapp3.1/Algorithms.Tests.dll",
"args": [],
"cwd": "${workspaceFolder}/test",
// For more information about the 'console' field, see https://aka.ms/VSCode-CS-LaunchJson-Console
"console": "internalConsole",
"stopAtEntry": false
},
{
"name": ".NET Core Attach",
"type": "coreclr",
"request": "attach",
"processId": "${command:pickProcess}"
}
]
}

View File

@ -0,0 +1,42 @@
{
"version": "2.0.0",
"tasks": [
{
"label": "build",
"command": "dotnet",
"type": "process",
"args": [
"build",
"${workspaceFolder}/test/Algorithms.Tests.csproj",
"/property:GenerateFullPaths=true",
"/consoleloggerparameters:NoSummary"
],
"problemMatcher": "$msCompile"
},
{
"label": "publish",
"command": "dotnet",
"type": "process",
"args": [
"publish",
"${workspaceFolder}/test/Algorithms.Tests.csproj",
"/property:GenerateFullPaths=true",
"/consoleloggerparameters:NoSummary"
],
"problemMatcher": "$msCompile"
},
{
"label": "watch",
"command": "dotnet",
"type": "process",
"args": [
"watch",
"run",
"${workspaceFolder}/test/Algorithms.Tests.csproj",
"/property:GenerateFullPaths=true",
"/consoleloggerparameters:NoSummary"
],
"problemMatcher": "$msCompile"
}
]
}

View File

@ -0,0 +1,48 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 15
VisualStudioVersion = 15.0.26124.0
MinimumVisualStudioVersion = 15.0.26124.0
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Algorithms", "src\Algorithms.csproj", "{EDD3C753-58A5-4844-81EA-3E9BD6A1D2F6}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Algorithms.Tests", "test\Algorithms.Tests.csproj", "{8E5D96D1-0618-4A33-9AF6-95D1D8F14E5A}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Debug|x64 = Debug|x64
Debug|x86 = Debug|x86
Release|Any CPU = Release|Any CPU
Release|x64 = Release|x64
Release|x86 = Release|x86
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{EDD3C753-58A5-4844-81EA-3E9BD6A1D2F6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{EDD3C753-58A5-4844-81EA-3E9BD6A1D2F6}.Debug|Any CPU.Build.0 = Debug|Any CPU
{EDD3C753-58A5-4844-81EA-3E9BD6A1D2F6}.Debug|x64.ActiveCfg = Debug|Any CPU
{EDD3C753-58A5-4844-81EA-3E9BD6A1D2F6}.Debug|x64.Build.0 = Debug|Any CPU
{EDD3C753-58A5-4844-81EA-3E9BD6A1D2F6}.Debug|x86.ActiveCfg = Debug|Any CPU
{EDD3C753-58A5-4844-81EA-3E9BD6A1D2F6}.Debug|x86.Build.0 = Debug|Any CPU
{EDD3C753-58A5-4844-81EA-3E9BD6A1D2F6}.Release|Any CPU.ActiveCfg = Release|Any CPU
{EDD3C753-58A5-4844-81EA-3E9BD6A1D2F6}.Release|Any CPU.Build.0 = Release|Any CPU
{EDD3C753-58A5-4844-81EA-3E9BD6A1D2F6}.Release|x64.ActiveCfg = Release|Any CPU
{EDD3C753-58A5-4844-81EA-3E9BD6A1D2F6}.Release|x64.Build.0 = Release|Any CPU
{EDD3C753-58A5-4844-81EA-3E9BD6A1D2F6}.Release|x86.ActiveCfg = Release|Any CPU
{EDD3C753-58A5-4844-81EA-3E9BD6A1D2F6}.Release|x86.Build.0 = Release|Any CPU
{8E5D96D1-0618-4A33-9AF6-95D1D8F14E5A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{8E5D96D1-0618-4A33-9AF6-95D1D8F14E5A}.Debug|Any CPU.Build.0 = Debug|Any CPU
{8E5D96D1-0618-4A33-9AF6-95D1D8F14E5A}.Debug|x64.ActiveCfg = Debug|Any CPU
{8E5D96D1-0618-4A33-9AF6-95D1D8F14E5A}.Debug|x64.Build.0 = Debug|Any CPU
{8E5D96D1-0618-4A33-9AF6-95D1D8F14E5A}.Debug|x86.ActiveCfg = Debug|Any CPU
{8E5D96D1-0618-4A33-9AF6-95D1D8F14E5A}.Debug|x86.Build.0 = Debug|Any CPU
{8E5D96D1-0618-4A33-9AF6-95D1D8F14E5A}.Release|Any CPU.ActiveCfg = Release|Any CPU
{8E5D96D1-0618-4A33-9AF6-95D1D8F14E5A}.Release|Any CPU.Build.0 = Release|Any CPU
{8E5D96D1-0618-4A33-9AF6-95D1D8F14E5A}.Release|x64.ActiveCfg = Release|Any CPU
{8E5D96D1-0618-4A33-9AF6-95D1D8F14E5A}.Release|x64.Build.0 = Release|Any CPU
{8E5D96D1-0618-4A33-9AF6-95D1D8F14E5A}.Release|x86.ActiveCfg = Release|Any CPU
{8E5D96D1-0618-4A33-9AF6-95D1D8F14E5A}.Release|x86.Build.0 = Release|Any CPU
EndGlobalSection
EndGlobal

View File

@ -0,0 +1,9 @@
# C#
## Strings
- [Palindrome](src/Strings/palindrome.cs)
## Sorts
1. [Bubble Sort](src/Sorts/bubble-sort.cs)
2. [Insertion Sort](src/Sorts/insertion-sort.cs)
3. [Selection Sort](src/Sorts/selection-sort.cs)

View File

@ -0,0 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netcoreapp3.1</TargetFramework>
</PropertyGroup>
</Project>

View File

@ -0,0 +1,31 @@
using System;
namespace Algorithms.Sorts
{
public class BubbleSort
{
public static void Main()
{
int[] arr = { 800, 11, 50, 771, 649, 770, 240, 9 };
Sort(arr);
var result = string.Join(" ", arr);
Console.WriteLine(result);
}
public static void Sort(int[] source)
{
for (int write = 0; write < source.Length; write++)
{
for (int sort = 0; sort < source.Length - 1; sort++)
{
if (source[sort] > source[sort + 1])
{
var temp = source[sort + 1];
source[sort + 1] = source[sort];
source[sort] = temp;
}
}
}
}
}
}

View File

@ -0,0 +1,36 @@
using System;
namespace Algorithms.Sorts
{
public class InsertionSort
{
public static void Main()
{
int[] arr = { 800, 11, 50, 771, 649, 770, 240, 9 };
Sort(arr);
var result = string.Join(" ", arr);
Console.WriteLine(result);
}
public static void Sort(int[] source)
{
int n = source.Length;
for (int i = 1; i < n; ++i)
{
int key = source[i];
int j = i - 1;
// Move elements of arr[0..i-1],
// that are greater than key,
// to one position ahead of
// their current position
while (j >= 0 && source[j] > key)
{
source[j + 1] = source[j];
j = j - 1;
}
source[j + 1] = key;
}
}
}
}

View File

@ -0,0 +1,40 @@
using System;
namespace Algorithms.Sorts
{
public class SelectionSort
{
public static void Main()
{
int[] arr = { 800, 11, 50, 771, 649, 770, 240, 9 };
Sort(arr);
var result = string.Join(" ", arr);
Console.WriteLine(result);
}
public static void Sort(int[] source)
{
int n = source.Length;
// One by one move boundary of unsorted subarray
for (int i = 0; i < n - 1; i++)
{
// Find the minimum element in unsorted array
int min_idx = i;
for (int j = i + 1; j < n; j++)
{
if (source[j] < source[min_idx])
{
min_idx = j;
}
}
// Swap the found minimum element with the first
// element
int temp = source[min_idx];
source[min_idx] = source[i];
source[i] = temp;
}
}
}
}

View File

@ -0,0 +1,28 @@
using System;
using System.Linq;
using System.Text.RegularExpressions;
namespace Algorithms.Strings
{
public class Palindrome
{
public static void Main()
{
bool result = false;
result = IsPalindrome("abba");
Console.WriteLine(result);
result = IsPalindrome("abbccbbA");
Console.WriteLine(result);
result = IsPalindrome("Mr. Owl ate my metal worm");
Console.WriteLine(result);
}
public static bool IsPalindrome(string source)
{
source = source.ToLower();
source = Regex.Replace(source, @"[^0-9A-Za-z]", "");
string reverse = new string(Enumerable.Range(1, source.Length).Select(i => source[source.Length - i]).ToArray());
return reverse == source;
}
}
}

View File

@ -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="..\src\Algorithms.csproj" />
</ItemGroup>
</Project>

View File

@ -0,0 +1,17 @@
using NUnit.Framework;
namespace algorithms.CSharp.Test.Sorts
{
[TestFixture]
internal class BubbleSort
{
[Test]
public void SortTheArray_ShouldGetExpectedString()
{
int[] array = { 800, 11, 50, 771, 649, 770, 240, 9 };
Algorithms.Sorts.BubbleSort.Sort(array);
var result = string.Join(" ", array);
Assert.AreEqual("9 11 50 240 649 770 771 800", result);
}
}
}

View File

@ -0,0 +1,17 @@
using NUnit.Framework;
namespace algorithms.CSharp.Test.Sorts
{
[TestFixture]
internal class InsertionSort
{
[Test]
public void SortTheArray_ShouldGetExpectedString()
{
int[] array = { 800, 11, 50, 771, 649, 770, 240, 9 };
Algorithms.Sorts.InsertionSort.Sort(array);
var result = string.Join(" ", array);
Assert.AreEqual("9 11 50 240 649 770 771 800", result);
}
}
}

View File

@ -0,0 +1,17 @@
using NUnit.Framework;
namespace algorithms.CSharp.Test.Sorts
{
[TestFixture]
internal class SelectionSort
{
[Test]
public void SortTheArray_ShouldGetExpectedString()
{
int[] array = { 800, 11, 50, 771, 649, 770, 240, 9 };
Algorithms.Sorts.SelectionSort.Sort(array);
var result = string.Join(" ", array);
Assert.AreEqual("9 11 50 240 649 770 771 800", result);
}
}
}

View File

@ -0,0 +1,18 @@
using NUnit.Framework;
namespace Algorithms.CSharp.Test.Strings
{
[TestFixture]
internal class Palindrome
{
[TestCase("abba", true)]
[TestCase("abbccbbA", true)]
[TestCase("Mr. Owl ate my metal worm", true)]
[TestCase("asdfgasdfg", false)]
public void PassString_ShouldGetExpectedResult(string text, bool expected)
{
var result = Algorithms.Strings.Palindrome.IsPalindrome(text);
Assert.AreEqual(expected, result);
}
}
}

View File

@ -5,3 +5,7 @@
1. [Kruskal Algorithm](c-or-cpp/kruskal-algorithm.cpp) 1. [Kruskal Algorithm](c-or-cpp/kruskal-algorithm.cpp)
2. [Bellman Ford Algorithm](c-or-cpp/bellman-ford.cpp) 2. [Bellman Ford Algorithm](c-or-cpp/bellman-ford.cpp)
3. [Prim's Algorithm](c-or-cpp/Prim's-algorithm.c) 3. [Prim's Algorithm](c-or-cpp/Prim's-algorithm.c)
### Java
1. [Dijkstras Algorithm](java/Dijkstras.java)

View File

@ -0,0 +1,133 @@
import java.util.*;
class AdjListNode
{
int dest;
int weight;
AdjListNode(int dest,int weight)
{
this.dest=dest;
this.weight=weight;
}
}
class NodeComparator implements Comparator<AdjListNode>
{
@Override
public int compare(AdjListNode node1, AdjListNode node2)
{
if (node1.weight < node2.weight)
return -1;
if (node1.weight > node2.weight)
return 1;
return 0;
}
}
class Dijkstras
{
public int[] dijkstras(List<List<AdjListNode>> adj_list,int source)
{
int[] distance = new int[adj_list.size()];
Set<Integer> completed = new HashSet<Integer>();
for(int i=0;i<distance.length;++i)
{
distance[i] = Integer.MAX_VALUE;
}
PriorityQueue<AdjListNode> pq = new PriorityQueue<>(adj_list.size(),new NodeComparator());
AdjListNode source_node = new AdjListNode(source,0);
for(int i=0;i<distance.length;++i)
{
pq.add(new AdjListNode(i,Integer.MAX_VALUE));
}
pq.add(source_node);
distance[source]=0;
while(!pq.isEmpty())
{
AdjListNode current = pq.remove();
if(!completed.contains(current.dest))
{
completed.add(current.dest);
for(AdjListNode n :adj_list.get(current.dest) )
{
if( distance[n.dest] > (distance[current.dest]+n.weight))
{
distance[n.dest] = distance[current.dest]+n.weight;
pq.add(new AdjListNode(n.dest, distance[n.dest]));
}
}
}
}
return distance;
}
public static void main(String args[])
{
/*
SAMPLE INPUT AND OUTPUT
___________________________
Input:
__________
Please enter the number of nodes N. Vertices will be [0,N-1]
6
Please Enter the number of Edges
9
Please enter each edge in the sequence <starting node> <destination node> <weight>
0 1 1
0 2 5
1 2 2
1 4 1
1 3 2
2 4 2
3 5 1
3 4 3
4 5 2
Please enter source vertex
0
Output:
___________
Distances from source 0
Node0--->0
Node1--->1
Node2--->3
Node3--->3
Node4--->2
Node5--->4
*/
List<List<AdjListNode>> adj_list = new ArrayList<List<AdjListNode>>();
System.out.println("Please enter the number of nodes N. Vertices will be [0,N-1]");
Scanner sc = new Scanner(System.in);
int v = sc.nextInt();
for(int i=0;i<v;++i)
adj_list.add(new ArrayList<AdjListNode>());
System.out.println("Please enter the number of edges");
int e = sc.nextInt();
System.out.println("Please enter each edge in the sequence <starting node> <destination node> <weight>");
// Sample Data: 0 2 5 (edge from 0 to 2 with weight 5)
for(int i=0;i<e;++i)
{
int startnode = sc.nextInt();
int destnode = sc.nextInt();
int weight = sc.nextInt();
adj_list.get(startnode).add(new AdjListNode(destnode,weight));
}
int source;
System.out.println("Please enter source vertex");
source = sc.nextInt();
Dijkstras d = new Dijkstras();
int[] distances = d.dijkstras(adj_list, source); //source vertex is taken as 0
System.out.println("Distances from source "+source);
for(int i=0;i<distances.length;++i)
{
if(distances[i]==Integer.MAX_VALUE)
System.out.println("Node"+i+"--->"+"infinity");
else
System.out.println("Node"+i+"--->"+distances[i]);
}
}
}

View File

@ -1,58 +1,90 @@
# A simple Python program to create a singly linked list # Create a singly linked list
# Node class
class Node: class Node:
# Function to initialise the node object
def __init__(self, data): def __init__(self, data):
self.data = data # Assign data self.data = data
self.next = None # Initialize next as null self.next = None
def __repr__(self):
"""
>>> Node(77)
Node(77)
"""
return f"Node({self.data})"
# Linked List class contains a Node object
class LinkedList: class LinkedList:
# Function to initialize head
def __init__(self): def __init__(self):
self.head = None self.head = None
def __iter__(self):
"""
>>> ll = LinkedList()
>>> list(ll)
[]
>>> ll.push(88)
>>> tuple(ll)
(88,)
>>> ll.push(89)
>>> tuple(ll)
(89, 88)
"""
node = self.head
while node:
yield node.data # `yield node` would also be possible
node = node.next
# Function to insert a new node at the beginning def __len__(self):
def insertAtHead(self, new_data): return len(tuple(iter(self)))
# 1 & 2: Allocate the Node & def __repr__(self):
# Put in the data """
new_node = Node(new_data) >>> ll = LinkedList()
>>> repr(ll)
'LinkedList()'
>>> ll.push(99)
>>> ll.push(100)
>>> repr(ll)
'LinkedList(100, 99)'
>>> str(ll)
'LinkedList(100, 99)'
"""
return f"LinkedList({', '.join(str(node) for node in self)})"
# 3. Make next of new Node as head def push(self, data):
new_node.next = self.head node = Node(data)
node.next = self.head
self.head = node
# 4. Move the head to point to new Node def pop(self):
self.head = new_node """
def removeAtHead(self): >>> ll = LinkedList()
temp = self.head >>> len(ll)
0
# If head node itself holds the key to be deleted >>> ll.push("push/pop")
if (temp is not None): >>> len(ll)
self.head = temp.next 1
temp = None >>> ll.pop()
return 'push/pop'
else: >>> len(ll)
return('underflow') 0
def printList(self): >>> ll.pop()
temp = self.head Traceback (most recent call last):
while(temp): ...
print (temp.data) IndexError: pop from empty LinkedList
temp = temp.next """
node = self.head
if not node:
raise IndexError("pop from empty LinkedList")
self.head = node.next
return node.data
if __name__ == '__main__':
# Code execution starts here ll = LinkedList()
if __name__=='__main__': ll.push(1)
l=LinkedList() ll.push('xyz')
l.insertAtHead(1) ll.push(1.1)
l.insertAtHead('xyz') ll.pop()
l.insertAtHead(1.1) print(ll)
l.removeAtHead() print(list(ll))
l.printList()

View File

@ -15,14 +15,6 @@
11. [Comb Sort](c-or-cpp/comb-sort.cpp) 11. [Comb Sort](c-or-cpp/comb-sort.cpp)
12. [3 Way Quick Sort](c-or-cpp/3way_quick_sort.cpp) 12. [3 Way Quick Sort](c-or-cpp/3way_quick_sort.cpp)
### C#
1. [Bubble Sort](csharp/bubble-sort.cs)
2. [Insertion Sort](csharp/insertion-sort.cs)
3. [Selection Sort](csharp/selection-sort.cs)
### Python ### Python
1. [Bubble Sort](python/bubble-sort.py) 1. [Bubble Sort](python/bubble-sort.py)

View File

@ -1,28 +0,0 @@
using System;
public class Program
{
public static void Main()
{
int[] arr = { 800, 11, 50, 771, 649, 770, 240, 9 };
Sort(arr);
var result = string.Join(" ", arr);
Console.WriteLine(result);
}
public static void Sort(int[] source)
{
for (int write = 0; write < source.Length; write++)
{
for (int sort = 0; sort < source.Length - 1; sort++)
{
if (source[sort] > source[sort + 1])
{
var temp = source[sort + 1];
source[sort + 1] = source[sort];
source[sort] = temp;
}
}
}
}
}

View File

@ -1,33 +0,0 @@
using System;
public class Program
{
public static void Main()
{
int[] arr = { 800, 11, 50, 771, 649, 770, 240, 9 };
Sort(arr);
var result = string.Join(" ", arr);
Console.WriteLine(result);
}
private static void Sort(int[] source)
{
int n = source.Length;
for (int i = 1; i < n; ++i)
{
int key = source[i];
int j = i - 1;
// Move elements of arr[0..i-1],
// that are greater than key,
// to one position ahead of
// their current position
while (j >= 0 && source[j] > key)
{
source[j + 1] = source[j];
j = j - 1;
}
source[j + 1] = key;
}
}
}

View File

@ -1,37 +0,0 @@
using System;
public class Program
{
public static void Main()
{
int[] arr = { 800, 11, 50, 771, 649, 770, 240, 9 };
Sort(arr);
var result = string.Join(" ", arr);
Console.WriteLine(result);
}
private static void Sort(int[] source)
{
int n = source.Length;
// One by one move boundary of unsorted subarray
for (int i = 0; i < n - 1; i++)
{
// Find the minimum element in unsorted array
int min_idx = i;
for (int j = i + 1; j < n; j++)
{
if (source[j] < source[min_idx])
{
min_idx = j;
}
}
// Swap the found minimum element with the first
// element
int temp = source[min_idx];
source[min_idx] = source[i];
source[i] = temp;
}
}
}

View File

@ -25,6 +25,7 @@
2. [All subsequences](java/sequence.java) 2. [All subsequences](java/sequence.java)
3. [KMP String Searching](java/kmp.cpp) 3. [KMP String Searching](java/kmp.cpp)
4. [Rabin Karp String Searching](java/rabin-karp.cpp) 4. [Rabin Karp String Searching](java/rabin-karp.cpp)
5. [String Tokenizer](java/tokenizer.java)
### Python ### Python

View File

@ -1,24 +0,0 @@
using System;
using System.Linq;
using System.Text.RegularExpressions;
public class Program
{
public static void Main()
{
bool result = false;
result = IsPalindrome("abba");
Console.WriteLine(result);
result = IsPalindrome("abbccbbA");
Console.WriteLine(result);
result = IsPalindrome("Mr. Owl ate my metal worm");
Console.WriteLine(result);
}
private static bool IsPalindrome(string source) {
source = source.ToLower();
source = Regex.Replace(source, @"[^0-9A-Za-z]", "");
string reverse = new string(Enumerable.Range(1, source.Length).Select(i => source[source.Length - i]).ToArray());
return reverse == source;
}
}

View File

@ -0,0 +1,96 @@
import java.util.ArrayList;
import java.util.List;
public class tokenizer{
public static boolean charIsDelimiter(char c, char [] delimiters){
//verrify if a character is a delimiter
for(char d: delimiters)
if(c == d) return true;
return false;
}
public static List<String> tokenize(String str, char... delimiters){
//by default the delimiter is white space ' '
if(delimiters.length <= 0) delimiters = new char [] {' '};
List<String> tokens = new ArrayList<String>();
String token = "";
for(int i = 0; i < str.length(); i++) {
char pos = str.charAt(i);
if(!charIsDelimiter(pos, delimiters)) {
//if the character is not a delimiter add it into the current token
token += pos;
}else {
//avoid an empty token before adding to the list
if(!token.equals(""))
tokens.add(token);
token = "";
}
}
//add the last token to the list
tokens.add(token);
return tokens;
}
public static void printTokens(List<String> tokens){
if(tokens == null) return;
System.out.print("[ ");
for(String token : tokens){
System.out.print("'" + token + "', ");
}
System.out.println("]");
}
public static void main(String [] args){
String myString = "Hello I like pasta & pizza--hut";
System.out.println("myString = '" + myString + "'");
System.out.print("\ntokenize(myString) = ");
printTokens(tokenize(myString));
System.out.print("\ntokenize(myString, ' ', 'z') = ");
printTokens(tokenize(myString, ' ', 'z'));
System.out.print("\ntokenize(myString, 'p','l', 'u') = ");
printTokens(tokenize(myString, 'p','l', 'u'));
System.out.print("\ntokenize(myString, ' ', '&', '-') = ");
printTokens(tokenize(myString, ' ', '&', '-'));
}
}
/*
to call the function:
tokenize(str, delimiters)
str is a text
delimiters is a list of char which is by default white space : ' '
example:
tokenize("hello world") = tokenize("hello world", ' ') = [ 'hello', 'world' ]
tokenize("hello world", ' ', 'l') = [ 'he', 'o', 'wor', 'd' ]
to run this file:
javac tokenizer.java
java tokenizer
result:
myString = 'Hello I like pasta & pizza--hut'
tokenize(myString) = [ 'Hello', 'I', 'like', 'pasta', '&', 'pizza--hut', ]
tokenize(myString, ' ', 'z') = [ 'Hello', 'I', 'like', 'pasta', '&', 'pi', 'a--hut', ]
tokenize(myString, 'p','l', 'u') = [ 'He', 'o I ', 'ike ', 'asta & ', 'izza--h', 't', ]
tokenize(myString, ' ', '&', '-') = [ 'Hello', 'I', 'like', 'pasta', 'pizza', 'hut', ]
*/

View File

@ -5,3 +5,7 @@
1. [Pre, In & Post Order Traversals](c-or-cpp/pre-in-post-traversal.cpp) 1. [Pre, In & Post Order Traversals](c-or-cpp/pre-in-post-traversal.cpp)
2. [Level Order Traversal](c-or-cpp/level-order-traversal.cpp) 2. [Level Order Traversal](c-or-cpp/level-order-traversal.cpp)
3. [Build Binary Tree using Pre,In & Post Order](c-or-cpp/build-binary-tree.cpp) 3. [Build Binary Tree using Pre,In & Post Order](c-or-cpp/build-binary-tree.cpp)
### Java
1. [Pre, In & Post Order Traversals](java/pre_in_post_traversal.java)

View File

@ -0,0 +1,76 @@
class Node{
int value;
Node left;
Node right;
public Node(int value) {
this.value = value;
}
}
public class pre_in_post_traversal{
public static void preOrder(Node node){
if (node == null) return;
System.out.print(node.value + ", ");
preOrder(node.left);
preOrder(node.right);
}
public static void inOrder(Node node){
if(node == null) return;
inOrder(node.left);
System.out.print(node.value + ", ");
inOrder(node.right);
}
public static void postOrder(Node node){
if(node == null) return;
postOrder(node.left);
postOrder(node.right);
System.out.print(node.value + ", ");
}
public static void main(String [] args){
Node root = new Node(4);
root.left = new Node(2);
root.right = new Node(7);
root.left.right = new Node(6);
root.left.left = new Node(1);
root.right.right = new Node(9);
System.out.print("pre order: ");
preOrder(root);
System.out.println("\n");
System.out.print("in order: ");
inOrder(root);
System.out.print("\n\npost order: ");
postOrder(root);
}
}
/*
tree structure:
4
/ \
2 7
/ \ \
1 6 9
to run the file:
javac .\pre_in_post_traversal.java
java pre_in_post_traversal
results:
pre order: 4, 2, 1, 6, 7, 9,
in order: 1, 2, 6, 4, 7, 9,
post order: 1, 6, 2, 9, 7, 4,
*/