diff --git a/.github/workflows/dotnet.yml b/.github/workflows/dotnet.yml new file mode 100644 index 00000000..2414ed29 --- /dev/null +++ b/.github/workflows/dotnet.yml @@ -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 diff --git a/README.md b/README.md index aea147c8..a5dca766 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,5 @@ # Data Structures and Algorithm + Data structure and Algorithm (DSA) ## Contribution Guidelines @@ -7,13 +8,15 @@ Data structure and Algorithm (DSA) The problem being contributed must either be a simple **file** (**Eg.** [`kruskal-algorithm.cpp`](https://github.com/MakeContributions/DSA/blob/main/graphs/c-or-cpp/kruskal-algorithm.cpp), [`linear-search.java`](https://github.com/MakeContributions/DSA/blob/main/searching/java/linear-search.java)) or a more complex **directory** ([`palindrome/`](https://github.com/MakeContributions/DSA/tree/main/strings/rust/palindrome)). This is a unit `problem`. -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: + - The name should be in lowercase. (**Eg.** `palindrome/`, `binary-search.cpp` etc.). - 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). 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.) @@ -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 **Folder Structure** + ```bash problem-name\ | - .gitignore @@ -40,7 +44,7 @@ problem-name\ #### `README.md` Specification / Template -```markdown +````markdown # < description of the problem > @@ -54,15 +58,17 @@ problem-name\ - instructions to run the project - < Simple and reproducible commands to execute the project > - ```bash - make # or 'cargo run', or 'dotnet run' or 'mvn exec:java' etc. - ``` + ```bash + make # or 'cargo run', or 'dotnet run' or 'mvn exec:java' etc. + ``` + ## Test Cases & Output < if exists> < If you can provide test cases, describe it here, else remove this section > -``` +```` #### `.gitignore` File + ```gitignore # add all output files and build files to be excluded from git tracking 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 + It can be any of the following ones + - **C/C++**: `Makefile` - **Python**: `requirements.txt` - **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. ### Other topic + - [First-time contribution](CONTRIBUTING.md) ## Contributors + <a href="https://github.com/MakeContributions/DSA/graphs/contributors"> <img src="https://contrib.rocks/image?repo=MakeContributions/DSA" /> </a> ### Reviewers -|Programming Language| Users | -|-------------------|---------------| -| C or C++ |@Arsenic-ATG, @UG-SEP | -| Java |@TawfikYasser, @cyberwizard1001 | -| C# | @ming-tsai | -| Go |@atin | -| Python | @Arsenic-ATG, @atin, @sridhar-5, @cyberwizard1001 | -| JavaScript | @paulsonjpaul | + +| Programming Language | Users | +| -------------------- | ------------------------------------------------- | +| C or C++ | @Arsenic-ATG, @UG-SEP, @aayushjain7 | +| Java | @TawfikYasser, @cyberwizard1001, @aayushjain7 | +| C# | @ming-tsai | +| Go | @atin | +| Python | @Arsenic-ATG, @atin, @sridhar-5, @cyberwizard1001 | +| JavaScript | @paulsonjpaul | + ## Open Graph + <img src="https://opengraph.github.com/3b128f0e88464a82a37f2daefd7d594c6f41a3c22b3bf94c0c030135039b5dd7/MakeContributions/DSA" /> ## License + [MIT](./LICENSE) diff --git a/algorithms/CSharp/.gitignore b/algorithms/CSharp/.gitignore new file mode 100644 index 00000000..3a8542dc --- /dev/null +++ b/algorithms/CSharp/.gitignore @@ -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 \ No newline at end of file diff --git a/algorithms/CSharp/.vscode/launch.json b/algorithms/CSharp/.vscode/launch.json new file mode 100644 index 00000000..15f08e94 --- /dev/null +++ b/algorithms/CSharp/.vscode/launch.json @@ -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}" + } + ] +} \ No newline at end of file diff --git a/algorithms/CSharp/.vscode/tasks.json b/algorithms/CSharp/.vscode/tasks.json new file mode 100644 index 00000000..17a32f2e --- /dev/null +++ b/algorithms/CSharp/.vscode/tasks.json @@ -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" + } + ] +} \ No newline at end of file diff --git a/algorithms/CSharp/Algorithms.sln b/algorithms/CSharp/Algorithms.sln new file mode 100644 index 00000000..b1f09671 --- /dev/null +++ b/algorithms/CSharp/Algorithms.sln @@ -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 diff --git a/algorithms/CSharp/README.md b/algorithms/CSharp/README.md new file mode 100644 index 00000000..43795628 --- /dev/null +++ b/algorithms/CSharp/README.md @@ -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) \ No newline at end of file diff --git a/algorithms/CSharp/src/Algorithms.csproj b/algorithms/CSharp/src/Algorithms.csproj new file mode 100644 index 00000000..cb631906 --- /dev/null +++ b/algorithms/CSharp/src/Algorithms.csproj @@ -0,0 +1,7 @@ +<Project Sdk="Microsoft.NET.Sdk"> + + <PropertyGroup> + <TargetFramework>netcoreapp3.1</TargetFramework> + </PropertyGroup> + +</Project> diff --git a/algorithms/CSharp/src/Sorts/bubble-sort.cs b/algorithms/CSharp/src/Sorts/bubble-sort.cs new file mode 100644 index 00000000..b16248fb --- /dev/null +++ b/algorithms/CSharp/src/Sorts/bubble-sort.cs @@ -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; + } + } + } + } + } +} \ No newline at end of file diff --git a/algorithms/CSharp/src/Sorts/insertion-sort.cs b/algorithms/CSharp/src/Sorts/insertion-sort.cs new file mode 100644 index 00000000..c7c14982 --- /dev/null +++ b/algorithms/CSharp/src/Sorts/insertion-sort.cs @@ -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; + } + } + } +} \ No newline at end of file diff --git a/algorithms/CSharp/src/Sorts/selection-sort.cs b/algorithms/CSharp/src/Sorts/selection-sort.cs new file mode 100644 index 00000000..6dd53654 --- /dev/null +++ b/algorithms/CSharp/src/Sorts/selection-sort.cs @@ -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; + } + } + } +} \ No newline at end of file diff --git a/algorithms/CSharp/src/Strings/palindrome.cs b/algorithms/CSharp/src/Strings/palindrome.cs new file mode 100644 index 00000000..3c30ad33 --- /dev/null +++ b/algorithms/CSharp/src/Strings/palindrome.cs @@ -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; + } + } +} \ No newline at end of file diff --git a/algorithms/CSharp/test/Algorithms.Tests.csproj b/algorithms/CSharp/test/Algorithms.Tests.csproj new file mode 100644 index 00000000..e26afb5b --- /dev/null +++ b/algorithms/CSharp/test/Algorithms.Tests.csproj @@ -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> diff --git a/algorithms/CSharp/test/Sorts/bubble-sort.cs b/algorithms/CSharp/test/Sorts/bubble-sort.cs new file mode 100644 index 00000000..4da77fc1 --- /dev/null +++ b/algorithms/CSharp/test/Sorts/bubble-sort.cs @@ -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); + } + } +} \ No newline at end of file diff --git a/algorithms/CSharp/test/Sorts/insertion-sort.cs b/algorithms/CSharp/test/Sorts/insertion-sort.cs new file mode 100644 index 00000000..f8f8fa9c --- /dev/null +++ b/algorithms/CSharp/test/Sorts/insertion-sort.cs @@ -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); + } + } +} \ No newline at end of file diff --git a/algorithms/CSharp/test/Sorts/selection-sort.cs b/algorithms/CSharp/test/Sorts/selection-sort.cs new file mode 100644 index 00000000..5cb558b6 --- /dev/null +++ b/algorithms/CSharp/test/Sorts/selection-sort.cs @@ -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); + } + } +} \ No newline at end of file diff --git a/algorithms/CSharp/test/Strings/palindrome.cs b/algorithms/CSharp/test/Strings/palindrome.cs new file mode 100644 index 00000000..800074ee --- /dev/null +++ b/algorithms/CSharp/test/Strings/palindrome.cs @@ -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); + } + } +} \ No newline at end of file diff --git a/graphs/README.md b/graphs/README.md index b0806cc6..510a1ccc 100644 --- a/graphs/README.md +++ b/graphs/README.md @@ -5,3 +5,7 @@ 1. [Kruskal Algorithm](c-or-cpp/kruskal-algorithm.cpp) 2. [Bellman Ford Algorithm](c-or-cpp/bellman-ford.cpp) 3. [Prim's Algorithm](c-or-cpp/Prim's-algorithm.c) + +### Java + +1. [Dijkstras Algorithm](java/Dijkstras.java) diff --git a/graphs/java/Dijkstras.java b/graphs/java/Dijkstras.java new file mode 100644 index 00000000..9ac9fb16 --- /dev/null +++ b/graphs/java/Dijkstras.java @@ -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]); + } + } +} diff --git a/linked-lists/Python/singly.py b/linked-lists/Python/singly.py index de5037c1..270a2145 100644 --- a/linked-lists/Python/singly.py +++ b/linked-lists/Python/singly.py @@ -1,58 +1,90 @@ -# A simple Python program to create a singly linked list - -# Node class -class Node: - - # Function to initialise the node object - def __init__(self, data): - self.data = data # Assign data - self.next = None # Initialize next as null - - -# Linked List class contains a Node object -class LinkedList: - - # Function to initialize head - def __init__(self): +# Create a singly linked list + +class Node: + def __init__(self, data): + self.data = data + self.next = None + + def __repr__(self): + """ + >>> Node(77) + Node(77) + """ + return f"Node({self.data})" + + +class LinkedList: + def __init__(self): self.head = None - - # Function to insert a new node at the beginning - def insertAtHead(self, new_data): - - # 1 & 2: Allocate the Node & - # Put in the data - new_node = Node(new_data) - - # 3. Make next of new Node as head - new_node.next = self.head - - # 4. Move the head to point to new Node - self.head = new_node - def removeAtHead(self): - temp = self.head - - # If head node itself holds the key to be deleted - if (temp is not None): - self.head = temp.next - temp = None - return - else: - return('underflow') - def printList(self): - temp = self.head - while(temp): - print (temp.data) - temp = temp.next + 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 - - -# Code execution starts here -if __name__=='__main__': - l=LinkedList() - l.insertAtHead(1) - l.insertAtHead('xyz') - l.insertAtHead(1.1) - l.removeAtHead() - l.printList() + def __len__(self): + return len(tuple(iter(self))) + def __repr__(self): + """ + >>> 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)})" + + def push(self, data): + node = Node(data) + node.next = self.head + self.head = node + + def pop(self): + """ + >>> ll = LinkedList() + >>> len(ll) + 0 + >>> ll.push("push/pop") + >>> len(ll) + 1 + >>> ll.pop() + 'push/pop' + >>> len(ll) + 0 + >>> ll.pop() + Traceback (most recent call last): + ... + IndexError: pop from empty LinkedList + """ + node = self.head + if not node: + raise IndexError("pop from empty LinkedList") + self.head = node.next + return node.data + + +if __name__ == '__main__': + ll = LinkedList() + ll.push(1) + ll.push('xyz') + ll.push(1.1) + ll.pop() + print(ll) + print(list(ll)) diff --git a/sorting/README.md b/sorting/README.md index 63a1761f..8d53fc78 100644 --- a/sorting/README.md +++ b/sorting/README.md @@ -15,14 +15,6 @@ 11. [Comb Sort](c-or-cpp/comb-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 1. [Bubble Sort](python/bubble-sort.py) diff --git a/sorting/csharp/bubble-sort.cs b/sorting/csharp/bubble-sort.cs deleted file mode 100644 index 7346933c..00000000 --- a/sorting/csharp/bubble-sort.cs +++ /dev/null @@ -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; - } - } - } - } -} \ No newline at end of file diff --git a/sorting/csharp/insertion-sort.cs b/sorting/csharp/insertion-sort.cs deleted file mode 100644 index 02e4184f..00000000 --- a/sorting/csharp/insertion-sort.cs +++ /dev/null @@ -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; - } - } -} \ No newline at end of file diff --git a/sorting/csharp/selection-sort.cs b/sorting/csharp/selection-sort.cs deleted file mode 100644 index 8a44bac9..00000000 --- a/sorting/csharp/selection-sort.cs +++ /dev/null @@ -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; - } - } -} \ No newline at end of file diff --git a/strings/README.md b/strings/README.md index cf6130bb..b19e72dd 100644 --- a/strings/README.md +++ b/strings/README.md @@ -25,6 +25,7 @@ 2. [All subsequences](java/sequence.java) 3. [KMP String Searching](java/kmp.cpp) 4. [Rabin Karp String Searching](java/rabin-karp.cpp) +5. [String Tokenizer](java/tokenizer.java) ### Python diff --git a/strings/csharp/palindrome.cs b/strings/csharp/palindrome.cs deleted file mode 100644 index b01d70cb..00000000 --- a/strings/csharp/palindrome.cs +++ /dev/null @@ -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; - } -} \ No newline at end of file diff --git a/strings/java/tokenizer.java b/strings/java/tokenizer.java new file mode 100644 index 00000000..ce6c4dc6 --- /dev/null +++ b/strings/java/tokenizer.java @@ -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', ] + +*/ diff --git a/trees/README.md b/trees/README.md index 69807e1d..cf5eeaa6 100644 --- a/trees/README.md +++ b/trees/README.md @@ -5,3 +5,7 @@ 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) 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) diff --git a/trees/java/pre_in_post_traversal.java b/trees/java/pre_in_post_traversal.java new file mode 100644 index 00000000..8997e3e3 --- /dev/null +++ b/trees/java/pre_in_post_traversal.java @@ -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, + +*/