diff --git a/misc/algos-master/.bin/install_apt.sh b/misc/algos-master/.bin/install_apt.sh deleted file mode 100755 index cd980c5..0000000 --- a/misc/algos-master/.bin/install_apt.sh +++ /dev/null @@ -1,3 +0,0 @@ -#!/bin/bash -sudo apt-get update -sudo apt-get install -y $(grep -vE "^\s*#" apt-requirements.txt | tr "\n" " ") diff --git a/misc/algos-master/.bin/install_go.sh b/misc/algos-master/.bin/install_go.sh deleted file mode 100755 index 2143da8..0000000 --- a/misc/algos-master/.bin/install_go.sh +++ /dev/null @@ -1,4 +0,0 @@ -#!/bin/bash -go get -u github.com/golang/lint/golint -cd $GOPATH/src/github.com/golang/lint -go install . diff --git a/misc/algos-master/.bin/install_npm.sh b/misc/algos-master/.bin/install_npm.sh deleted file mode 100755 index 7027565..0000000 --- a/misc/algos-master/.bin/install_npm.sh +++ /dev/null @@ -1,2 +0,0 @@ -#!/bin/bash -npm install -g $(grep -vE "^\s*#" npm-requirements.txt | tr "\n" " ") diff --git a/misc/algos-master/.bin/install_pip2.sh b/misc/algos-master/.bin/install_pip2.sh deleted file mode 100755 index 5e86fbd..0000000 --- a/misc/algos-master/.bin/install_pip2.sh +++ /dev/null @@ -1,3 +0,0 @@ -#!/bin/bash -sudo -H pip2 install --upgrade pip -sudo -H pip2 install -Ur pip2-requirements.txt diff --git a/misc/algos-master/.bin/install_pip3.sh b/misc/algos-master/.bin/install_pip3.sh deleted file mode 100755 index 7c125c0..0000000 --- a/misc/algos-master/.bin/install_pip3.sh +++ /dev/null @@ -1,3 +0,0 @@ -#!/bin/bash -sudo -H pip3 install --upgrade pip -sudo -H pip3 install -Ur pip3-requirements.txt diff --git a/misc/algos-master/.bin/test_running.sh b/misc/algos-master/.bin/test_running.sh deleted file mode 100755 index 16eaa33..0000000 --- a/misc/algos-master/.bin/test_running.sh +++ /dev/null @@ -1,72 +0,0 @@ -#!/bin/bash -set -e - -echo "Testing C files..." -for i in $(ls -1 **/*.c); do - echo " Compiling $i - gcc $i -lm -std=c11" - gcc $i -lm -std=c11 - echo " Running $i - ./a.out > /dev/null" - ./a.out > /dev/null - rm -f a.out - echo "" -done - -echo "" -echo "Testing C++ files..." -for i in $(ls -1 **/*.cpp); do - echo " Compiling $i - g++ $i -lm -pthread -std=c++11" - g++ $i -lm -pthread -std=c++11 - echo " Running $i - ./a.out > /dev/null" - ./a.out > /dev/null - rm -f a.out - echo "" -done - -echo "" -echo "Testing Java files..." -for i in $(ls -1 **/*.java); do - echo " Compiling $i - javac -Werror -Xlint:all $i -d ." - javac -Werror -Xlint:all $i -d . - filename="${i##*/}" - classname="${filename%.*}" - echo " Running $i - java $classname > /dev/null" - java $classname > /dev/null - echo "" -done -rm -f *.class - -echo "Testing Python files..." -for i in $(ls -1 **/*.py); do - echo " Running $i - python2 $i > /dev/null" - python2 $i > /dev/null - echo " Running $i - python3 $i > /dev/null" - python3 $i > /dev/null - echo "" -done - -echo "" -echo "Running Go files..." -for i in $(ls -1 **/*.go); do - echo " Running $i - go run $i > /dev/null" - go run $i > /dev/null - echo "" -done - -echo "" -echo "Running JavaScript files..." -for i in $(ls -1 **/*.js); do - echo " Running $i - node --use-strict --harmony $i > /dev/null" - node --use-strict --harmony $i > /dev/null - echo "" -done - -echo "" -echo "Running C# files..." -for i in $(ls -1 **/*.cs); do - echo " Compiling $i - mcs $i" - mcs $i - excname="${i%.*}".exe - echo " Running $i - mono $excname > /dev/null" - mono $excname > /dev/null - echo "" -done diff --git a/misc/algos-master/.coafile b/misc/algos-master/.coafile deleted file mode 100644 index b908408..0000000 --- a/misc/algos-master/.coafile +++ /dev/null @@ -1,45 +0,0 @@ -# coafile for this project -# please add more settings beneath -# Local fixing -# coala --apply-patches -n - -# python files should only use spaces -[Python Spacing] -files = **/*.py -bears = SpaceConsistencyBear -use_spaces = True - -# golint -[Golint] -files = **/*.go -bears = GoLintBear - -# gofmt -[Gofmt] -files = **/*.go -bears = GofmtBear - -# python lint -[pep8] -files = **/*.py -bears = PEP8Bear - -# Haskell -[haskell] -files = **/*.hs -bears = HaskellLintBear - -# hlint -[hlint] -files = **/*.hs -bears = GhcModBear - -# JavaScript -[happiness] -files = **/*.js -bears = HappinessLintBear - -# CSharp -[csharp] -files = **/*.cs -bears = CSharpLintBear diff --git a/misc/algos-master/.codeclimate.yml b/misc/algos-master/.codeclimate.yml deleted file mode 100644 index 2d205f3..0000000 --- a/misc/algos-master/.codeclimate.yml +++ /dev/null @@ -1,23 +0,0 @@ ---- -engines: - duplication: - enabled: true - checks: - Similar code: - enabled: false # matches in different files - config: - languages: - - javascript - - python - fixme: - enabled: true - radon: - enabled: true - checks: - Complexity: - enabled: false -ratings: - paths: - - "**.js" - - "**.py" -exclude_paths: [] diff --git a/misc/algos-master/.editorconfig b/misc/algos-master/.editorconfig deleted file mode 100644 index c5c6c4f..0000000 --- a/misc/algos-master/.editorconfig +++ /dev/null @@ -1,31 +0,0 @@ -root = true - -[*] -charset = utf-8 -end_of_line = lf -insert_final_newline = true - -[*.{go,c,cpp}] -indent_style = tab -tab_width = 4 -trim_trailing_whitespace = true - -[*.js] -indent_style = tab -tab_width = 2 -trim_trailing_whitespace = true - -[*.{py,java,cs}] -indent_style = space -indent_size = 4 -trim_trailing_whitespace = true - -[*.{c,cpp,java,js}] -block_comment_start = /* -block_comment = * -block_comment_end = */ - -[*.yml] -indent_style = space -indent_size = 2 -trim_trailing_whitespace = true diff --git a/misc/algos-master/.gitignore b/misc/algos-master/.gitignore deleted file mode 100644 index d854879..0000000 --- a/misc/algos-master/.gitignore +++ /dev/null @@ -1,14 +0,0 @@ -# python -*.pyc -# C/CPP -*.exe -*.out -# Java -*.class -# MacOS -.DS_Store -# coala -*.orig - -# Jetbrains -.idea/ diff --git a/misc/algos-master/.travis.yml b/misc/algos-master/.travis.yml deleted file mode 100644 index f160272..0000000 --- a/misc/algos-master/.travis.yml +++ /dev/null @@ -1,21 +0,0 @@ -dist: trusty -sudo: required -language: node_js -node_js: - "7" - -env: - GOPATH: $HOME/go - PATH: $GOPATH/bin:$PATH - -install: - - ./.bin/install_apt.sh - - ./.bin/install_go.sh - - ./.bin/install_npm.sh - - ./.bin/install_pip2.sh - - ./.bin/install_pip3.sh - -script: - - ./.bin/test_running.sh - - coala --ci - - eclint check "**/*.{java,c,cpp,js,cs}" diff --git a/misc/algos-master/CODE_OF_CONDUCT.md b/misc/algos-master/CODE_OF_CONDUCT.md deleted file mode 100644 index 1df1961..0000000 --- a/misc/algos-master/CODE_OF_CONDUCT.md +++ /dev/null @@ -1,46 +0,0 @@ -# Contributor Covenant Code of Conduct - -## Our Pledge - -In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation. - -## Our Standards - -Examples of behavior that contributes to creating a positive environment include: - -* Using welcoming and inclusive language -* Being respectful of differing viewpoints and experiences -* Gracefully accepting constructive criticism -* Focusing on what is best for the community -* Showing empathy towards other community members - -Examples of unacceptable behavior by participants include: - -* The use of sexualized language or imagery and unwelcome sexual attention or advances -* Trolling, insulting/derogatory comments, and personal or political attacks -* Public or private harassment -* Publishing others' private information, such as a physical or electronic address, without explicit permission -* Other conduct which could reasonably be considered inappropriate in a professional setting - -## Our Responsibilities - -Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior. - -Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful. - -## Scope - -This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers. - -## Enforcement - -Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at codingclub.iiitv@gmail.com. The project team will review and investigate all complaints, and will respond in a way that it deems appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately. - -Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership. - -## Attribution - -This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [http://contributor-covenant.org/version/1/4][version] - -[homepage]: http://contributor-covenant.org -[version]: http://contributor-covenant.org/version/1/4/ diff --git a/misc/algos-master/CONTRIBUTING.md b/misc/algos-master/CONTRIBUTING.md deleted file mode 100644 index 7ddb405..0000000 --- a/misc/algos-master/CONTRIBUTING.md +++ /dev/null @@ -1,185 +0,0 @@ -## How to contribute an implementation (code)? - -* Have a look at open issues. They contain the list of algorithms/DS we plan to be implemented. Pick an unassigned issue. -* You can also create a new issue for an algorithm that is not in the list. -* Make sure you are assigned for the issue. -* Code the algorithm/DS following the styleguide defined below. -* Send a PR. -* Be sure to not include any compiled binaries in the patch. -* While sending a PR make sure you follow one issue per PR rule. - - - - -## Suggesting an algorithm / DS - -* First make sure you are not suggesting a duplicate. -* If not, proceed and create the issue. Make sure that you specify only one language in an issue. Create multiple issues for different languages. -* Title of issue should be of the following format - - ``` - Algorithm/DS Name [Language] - ``` -* Please include at least one external link for the algorithm/DS in the issue's body for each issue. The link should explain the algorithm/problem/DS in detail. - - - - -## Code Styleguide - -* Code submitted should be modular. -* Don't use global variables. -* Use separate folders for each concept. Folder name should be in full lowercase. If the algorithm/DS name has multiple words, separate them by underscores. (eg `longest_common_subsequence`) -* Filename should be derived from the folder name. (eg `longest_common_subsequence` becomes `longestCommonSubsequence.c` or `LongestCommonSubsequence.java`) -* Name of master function of the code should be kept same as filename to the best extent possible. -* Prefer classes instead of multiple helper functions (where applicable). -* Currently we are accepting contributions in C, C++, C#, Java, Python, Go and JavaScript but other languages may be considered after a discussion. -* Define `tester` code only in `main` routine. -* Use meaningful variable, method and function names and comments. -* No profanity. -* Use external libraries only when no other solution is possible/plausible. -* We have defined [skeleton codes](#samples) for some popular languages below. Please follow them whenever possible. - - - - -## Standalone points - -* In some cases, C and C++ implementation will be similar. In that case, only the C implementation must be done. - - - - -## Improving an implementation - -* If you feel you can improve upon an implementation, feel free to open an issue discussing the improvements. - - - - -## Samples - -#### C - -```c -void quicksort(int ar_size, int *ar) { - /* - Your implementation here... - */ -} - -int main() { - int ar_size = 4, i; - int a[4] = {2, 3, 0, 4}; - quicksort(ar_size, a); - - for (i=0; i - diff --git a/misc/algos-master/LICENSE b/misc/algos-master/LICENSE deleted file mode 100644 index 565272f..0000000 --- a/misc/algos-master/LICENSE +++ /dev/null @@ -1,7 +0,0 @@ -Copyright 2017 IIITV GitHub Group - -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/misc/algos-master/PULL_REQUEST_TEMPLATE.md b/misc/algos-master/PULL_REQUEST_TEMPLATE.md deleted file mode 100644 index bdf8a8e..0000000 --- a/misc/algos-master/PULL_REQUEST_TEMPLATE.md +++ /dev/null @@ -1,21 +0,0 @@ - - -Fixes #{ISSUE_NUMBER} - - -#### By submitting this pull request I confirm I've read and complied with the below declarations. - -- [ ] I have read the [Contribution guidelines](https://github.com/iiitv/algos/blob/master/CONTRIBUTING.md) and I am confident that my PR reflects them. -- [ ] I have followed the [coding guidelines](https://github.com/iiitv/algos/blob/master/CONTRIBUTING.md#cs) for this project. -- [ ] My code follows the [skeleton code structure](https://github.com/iiitv/algos/blob/master/CONTRIBUTING.md#sample). -- [ ] This pull request has a descriptive title. For example, `Added {Algorithm/DS name} [{Language}]`, not `Update README.md` or `Added new code`. -- [ ] This pull request will be closed if I fail to update it even once in a continuous time span of 7 days. -- [ ] This pull request shall only be reviewed and merged once the Travis build passes. No maintainer or supporter shall be obliged to review it before this condition is met. -- [ ] I have mentioned the issue number correctly (with hyperlink) in this pull request description. diff --git a/misc/algos-master/apt-requirements.txt b/misc/algos-master/apt-requirements.txt deleted file mode 100644 index 13191ba..0000000 --- a/misc/algos-master/apt-requirements.txt +++ /dev/null @@ -1,20 +0,0 @@ -# Go linting -golang-go -ghc-mod -hlint - -# Python 3 -python3-dev -python3-pip -python3-setuptools - -# More python 2 -python-setuptools -python-dev - -# CSharp Linting -mono-mcs - -# tkinter -python-tk -python3-tk diff --git a/misc/algos-master/bin_sort/BinSort.java b/misc/algos-master/bin_sort/BinSort.java deleted file mode 100644 index 78c1969..0000000 --- a/misc/algos-master/bin_sort/BinSort.java +++ /dev/null @@ -1,75 +0,0 @@ -import java.util.Random; - -class Node { - public double data; - public Node next; - - public Node(double data) { - this.data = data; - next = null; - } -} - -// Time Complexity O(n)-> avg case and O(n^2)-> Worst Case -// constraints:- 0<=A[i]<1 -public class BinSort { - public static void binSort(Node[] b, double[] a) { - for (int i = 0; i < a.length; i++) { - int ins = (int) (a[i] * b.length); - if (b[ins] == null) { - b[ins] = new Node(a[i]); - } else { - boolean check = true; - Node temp = b[ins]; - while (temp.next != null) { - if (a[i] > temp.next.data) { - temp = temp.next; - } else { - if (a[i] < temp.data) - break; - Node newNode = new Node(a[i]); - newNode.next = temp.next; - temp.next = newNode; - check = false; - break; - } - } - if (check) { - if (a[i] >= temp.data) { - Node newNode = new Node(a[i]); - temp.next = newNode; - } else { - double loc = temp.data; - temp.data = a[i]; - Node newNode = new Node(loc); - newNode.next = temp.next; - temp.next = newNode; - } - } - } - } - int j = 0; - for (int i = 0; i < b.length; i++) { - while (b[i] != null) { - a[j++] = b[i].data; - b[i] = b[i].next; - } - } - } - - public static void main(String[] args) { - Node[] b = new Node[10]; - Random ran = new Random(); - int n = 100; - double[] a = new double[n]; - for (int i = 0; i < n; i++) { - a[i] = ran.nextDouble(); - } - binSort(b, a); - for (int i = 0; i < n; i++) { - System.out.print(a[i] + " "); - } - System.out.println(" "); - } -} - diff --git a/misc/algos-master/bin_sort/bin_sort.go b/misc/algos-master/bin_sort/bin_sort.go deleted file mode 100644 index e0b876c..0000000 --- a/misc/algos-master/bin_sort/bin_sort.go +++ /dev/null @@ -1,73 +0,0 @@ -package main - -import ( - "fmt" - "math/rand" - "sort" -) - -// Bucket is a type alias of []float32. It is used in BucketSort() to represent -// individual buckets. -type Bucket []float32 - -// Methods required for sort.Sort() -func (b Bucket) Len() int { - return len(b) -} - -func (b Bucket) Swap(i, j int) { - b[i], b[j] = b[j], b[i] -} - -func (b Bucket) Less(i, j int) bool { - return b[i] < b[j] -} - -// BucketSort sorts provided slice of floats using Bucket Sort algorithm -// Time Complexity: O(n)-> Avg case and O(n^2)-> Worst Case -// Constraints: 0 <= arr[i] <= 1 -func BucketSort(arr []float32) []float32 { - n := len(arr) - - // Create n empty buckets, each can hold up to n elements - buckets := make([]Bucket, n) - for i := 0; i < n; i++ { - // Set length to 0, but allocate memory for n elements - buckets[i] = make([]float32, 0, n) - } - - // Place all the elements into corresponding buckets - for i := 0; i < n; i++ { - bi := int(float32(n) * arr[i]) - buckets[bi] = append(buckets[bi], arr[i]) - } - - // Sort elements in each bucket - for i := 0; i < n; i++ { - sort.Sort(buckets[i]) - } - - // Put sorted elements into the resulting array - sorted := make([]float32, 0, n) - for i := 0; i < n; i++ { - for j := 0; j < len(buckets[i]); j++ { - sorted = append(sorted, buckets[i][j]) - } - } - return sorted -} - -func makeRandomNumbers(n int) []float32 { - arr := make([]float32, n) - for i := range arr { - arr[i] = rand.Float32() - } - return arr -} - -func main() { - n := 10 - arr := makeRandomNumbers(n) - sorted := BucketSort(arr) - fmt.Println(sorted) -} diff --git a/misc/algos-master/exponentiation_by_squaring/ExponentiationBySquaring.java b/misc/algos-master/exponentiation_by_squaring/ExponentiationBySquaring.java deleted file mode 100644 index 5156ced..0000000 --- a/misc/algos-master/exponentiation_by_squaring/ExponentiationBySquaring.java +++ /dev/null @@ -1,27 +0,0 @@ -/* Algorithm to calculate base raised to power power very efficiently -* Can be used as a great alternative to normal pow function -* base - base of the expression -* power - power of expression -*/ - -public class ExponentiationBySquaring { - public static double exponentiationBySquaring(double base, int power) { - if (power < 0) { // Negative powers - return exponentiationBySquaring(1.0 / base, -power); - } else if (power == 0) { // Base case 1 - return 1; - } else if (power == 1) { // Base case 2 - return base; - } else if (power % 2 == 0){ // Even powers - return exponentiationBySquaring(base * base, power / 2); - } else { // Odd powers - return base * exponentiationBySquaring(base * base, (power - 1) / 2); - } - } - - public static void main(String[] args) { - double base = 2; - int power = -1; - System.out.println(base + " raised to " + power + " is: " + exponentiationBySquaring(base, power)); - } -} diff --git a/misc/algos-master/exponentiation_by_squaring/exponentiationBySquaring.js b/misc/algos-master/exponentiation_by_squaring/exponentiationBySquaring.js deleted file mode 100644 index 6108507..0000000 --- a/misc/algos-master/exponentiation_by_squaring/exponentiationBySquaring.js +++ /dev/null @@ -1,28 +0,0 @@ -function exponentiationBySquaring (base, power) { - /* - Performs Exponentiation By Squaring. - :param base: Base of expression. - :param power: Power of expression. - :return: Returns (base ^ power). - */ - if (power < 0) { // When Power is Negative - return exponentiationBySquaring(1 / base, -power); - } else if (power === 0) { // Power = 0 (Base Case 1) - return 1; - } else if (power === 1) { // Power = 1 (Base Case 2) - return base; - } else if (power % 2 === 0) { // When Power is Even - return exponentiationBySquaring(base * base, power >> 1); - } else { // When Power is Odd - return base * exponentiationBySquaring(base * base, (power - 1) >> 1); - } -} - -function main () { - let base = 3; - let power = 6; - let res = exponentiationBySquaring(base, power); - console.log('%d\n', res); -} - -main(); diff --git a/misc/algos-master/exponentiation_by_squaring/exponentiation_by_squaring.go b/misc/algos-master/exponentiation_by_squaring/exponentiation_by_squaring.go deleted file mode 100644 index 271123f..0000000 --- a/misc/algos-master/exponentiation_by_squaring/exponentiation_by_squaring.go +++ /dev/null @@ -1,23 +0,0 @@ -package main - -import "fmt" - -// ExponentiationBySquaring calculates base^power efficiently. -func ExponentiationBySquaring(base int, power int) int { - if power < 0 { // Negative power case - return ExponentiationBySquaring((1 / base), -power) - } else if power == 0 { // Base case1 - return 1 - } else if power == 1 { // Base case2 - return base - } else if power%2 == 0 { - return ExponentiationBySquaring(base*base, power/2) - } else { - return base * ExponentiationBySquaring(base*base, (power-1)/2) - } -} - -func main() { - base, power := 5, 10 - fmt.Println(ExponentiationBySquaring(base, power)) -} diff --git a/misc/algos-master/heap_sort/HeapSort.java b/misc/algos-master/heap_sort/HeapSort.java deleted file mode 100644 index ba2a186..0000000 --- a/misc/algos-master/heap_sort/HeapSort.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Following is the implementation of HeapSort algorithm. - * It will sort the input array with time complexity O(N*logN) - * N being the size of array. - * Space complexity is O(1). - */ - -public class HeapSort { - - public static void maxHeapify(int[] arr, int size, int parent) { // Build max-heap of subtree of parent index - int left = 2 * parent; - int right = left + 1; - int largest = parent; // Initially considering parent as largest - if (left < size && arr[left] > arr[largest]) // Left child is greater than parent - largest = left; - if (right < size && arr[right] > arr[largest]) // Right child is greater than parent - largest = right; - if (largest != parent) { // If parent is largest then subtree is max-heap - int temp = arr[parent]; - arr[parent] = arr[largest]; // Swap largest child with parent - arr[largest] = temp; - maxHeapify(arr, size, largest); // Convert upper subtree to max-heap - } - } - - public static void heapSort(int[] arr) { - for (int i = arr.length / 2 - 1; i >= 0; --i) - maxHeapify(arr, arr.length, i); // Create max-heap - - for (int i = arr.length - 1; i >= 0; --i) { - int temp = arr[0]; // Swap first and last element - arr[0] = arr[i]; - arr[i] = temp; - maxHeapify(arr, i, 0); // Create Max-Heap on reduced array - } - } - - public static void main(String[] args) { - int[] arr = new int[] {10, 4, 3, 13, 1, 123}; // Creating Test array - - heapSort(arr); // Sort the array - for (int element : arr) // Printing sorted array - System.out.print(element + " "); - } -} diff --git a/misc/algos-master/heap_sort/heapSort.js b/misc/algos-master/heap_sort/heapSort.js deleted file mode 100644 index 2f6be31..0000000 --- a/misc/algos-master/heap_sort/heapSort.js +++ /dev/null @@ -1,52 +0,0 @@ -/* -* Implementation of heap sort sorting algorithm. -* Time Complexity: O(N*logN), N being size of array -* Space Complexity: O(1) -*/ - -function maxHeapify (arr, size, parent) { - /* - * :param arr: input array. - * :param size: hypothetical size of input array. - * :param parent: index of current node to create max-heap from. - */ - let left = 2 * parent; - let right = left + 1; - let largest = parent; // Initially considering parent as largest - if (left < size && arr[left] > arr[largest]) { // Left child is greater than parent - largest = left; - } - if (right < size && arr[right] > arr[largest]) { // Right child is greater than parent - largest = right; - } - if (largest !== parent) { // If parent is largest then subtree is max-heap - let temp = arr[parent]; - arr[parent] = arr[largest]; // Swap largest child with parent - arr[largest] = temp; - maxHeapify(arr, size, largest); // Convert upper subtree to max-heap - } -} - -function heapSort (arr) { - /* - * :param arr: Input array to be sorted. - */ - for (let i = arr.length / 2 - 1; i >= 0; --i) { // Build max-heap - maxHeapify(arr, arr.length, i); - } - - for (let i = arr.length - 1; i >= 0; --i) { - let temp = arr[0]; // Swap first and last element - arr[0] = arr[i]; - arr[i] = temp; - maxHeapify(arr, i, 0); // Create Max-Heap on reduced array - } -} - -function main () { - let arr = [10, -4, 3, 13, 1, 123]; - heapSort(arr); - console.log(arr); -} - -main(); diff --git a/misc/algos-master/insertion_sort/InsertionSort.cs b/misc/algos-master/insertion_sort/InsertionSort.cs deleted file mode 100644 index efc5613..0000000 --- a/misc/algos-master/insertion_sort/InsertionSort.cs +++ /dev/null @@ -1,31 +0,0 @@ -using System; - -public class InsertionSort -{ - public static void Sort(int[] data) - { - int key; - for(int i = 1; i < data.Length; i++) - { - int j = i - 1; - key = data[i]; - while (j >= 0 && data[j] > key) - { - data[j + 1] = data[j]; - j = j - 1; - } - data[j + 1] = key; - } - } - - public static void Main() - { - int[] arr = new int[] {1000, 45, -45, 121, 47, 45, 65, 121, -1, 103, 45, 34}; - Sort(arr); - for(int i = 0; i < arr.Length; i++) - { - Console.Write(arr[i] + " "); - } - Console.WriteLine(""); - } -} diff --git a/misc/algos-master/insertion_sort/InsertionSort.java b/misc/algos-master/insertion_sort/InsertionSort.java deleted file mode 100644 index 7d8b2e0..0000000 --- a/misc/algos-master/insertion_sort/InsertionSort.java +++ /dev/null @@ -1,27 +0,0 @@ -public class InsertionSort { - - private static void insertionSort(int[] arr) { - for (int i = 1; i < arr.length; i++) { - int j = i - 1; - int key = arr[i]; // Element to be compared - - /* Move elements of arr[0...i-1], that are - greater than key, to one position ahead - of their current position */ - while(j >= 0 && arr[j] > key) { - arr[j+1] = arr[j]; - j--; - } - arr[j+1] = key; // Putting key to the position where all numbers before it are sorted - } - } - - public static void main(String[] args) { - int[] arr = {12, 11, 13, 5, 6}; - insertionSort(arr); - - for (int x: arr) { // Printing sorted array - System.out.print(x+" "); - } - } -} diff --git a/misc/algos-master/insertion_sort/insertionSort.js b/misc/algos-master/insertion_sort/insertionSort.js deleted file mode 100644 index 4772c09..0000000 --- a/misc/algos-master/insertion_sort/insertionSort.js +++ /dev/null @@ -1,30 +0,0 @@ -/* Following algorithm sorts the input array in ascending order -* Time Complexity : O(n^2) -* Auxiliary Space: O(1) -* n is the number of elements in the array to be sorted -*/ - -function insertionSort (arr) { - /* - : param arr : Array to be sorted - : return : Sorted Array - */ - for (let i = 1; i < arr.length; i++) { - let j = i - 1; - let temp = arr[i]; - while (j >= 0 && arr[j] > temp) { - arr[j + 1] = arr[j]; - j--; - } - arr[j + 1] = temp; - } - return arr; -} - -function main () { - let arr = [5, 9, 3, 1, 99]; - arr = insertionSort(arr); - console.log(arr); -} - -main(); diff --git a/misc/algos-master/insertion_sort/insertion_sort.go b/misc/algos-master/insertion_sort/insertion_sort.go deleted file mode 100644 index af795d1..0000000 --- a/misc/algos-master/insertion_sort/insertion_sort.go +++ /dev/null @@ -1,25 +0,0 @@ -package main - -import "fmt" - -// InsertionSort function returns sorted data -// Time complexity: O(n^2) -// Space complexity: O(1) -func InsertionSort(data []int) []int { - for i := 1; i < len(data); i++ { - key := data[i] - j := i - 1 - for j >= 0 && data[j] > key { - data[j+1] = data[j] - j-- - } - data[j+1] = key - } - return data -} - -func main() { - data := []int{1000, 45, -45, 121, 47, 45, 65, 121, -1, 103, 45, 34} - data = InsertionSort(data) - fmt.Println(data) -} diff --git a/misc/algos-master/largest_sum_contiguous_subarray/LargestSumContiguousSubarray.java b/misc/algos-master/largest_sum_contiguous_subarray/LargestSumContiguousSubarray.java deleted file mode 100644 index 74b08ee..0000000 --- a/misc/algos-master/largest_sum_contiguous_subarray/LargestSumContiguousSubarray.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Implementation of famous dynamic programming problem - * Largest Sum Contiguous Subarray - * Kadane Algorithm - * Time complexity O(n) - */ - -public class LargestSumContiguousSubarray { - - public static int largestSumContiguousSubarray(int[] array) { // maximum sum method implemention - int prevSum; - int currentSum; - int i; - prevSum = array[0]; // initialize current sum amd previous sum - currentSum = array[0]; - for (i = 1; i < array.length; i++) { - currentSum += array[i]; // add values in current sum - if (currentSum < 0) { // if current sum is negative , make it zero - currentSum = 0; - } else if (currentSum > prevSum) { // if current sum is greate than previous sum - prevSum = currentSum; // update previous sum - } - } - return prevSum; - } - - public static void main(String[] args) { - - int[] array = new int[] {-2, 1, -3, 4, -1, 2, 1, -5, 4}; - System.out.println("Largest Sum of Contiguous Subarray:" + "\t" + largestSumContiguousSubarray(array)); - } -} diff --git a/misc/algos-master/largest_sum_contiguous_subarray/largestSumContiguousSubarray.go b/misc/algos-master/largest_sum_contiguous_subarray/largestSumContiguousSubarray.go deleted file mode 100644 index 077d7e1..0000000 --- a/misc/algos-master/largest_sum_contiguous_subarray/largestSumContiguousSubarray.go +++ /dev/null @@ -1,25 +0,0 @@ -package main - -import "fmt" - -// largestSumContinousSubArray is main kadane's algorithm function -func largestSumContinousSubArray(arr []int) int { - maxTill := 0 - maxTemp := 0 - size := len(arr) - for i := 0; i < size; i++ { - maxTemp = maxTemp + arr[i] - if maxTill < maxTemp { - maxTill = maxTemp - } - if maxTemp < 0 { - maxTemp = 0 - } - } - return maxTill -} - -func main() { - array := []int{-2, -3, 3, -1, -2, 1, 5, -3} - fmt.Println(largestSumContinousSubArray(array)) -} diff --git a/misc/algos-master/largest_sum_contiguous_subarray/largestSumContiguousSubarray.js b/misc/algos-master/largest_sum_contiguous_subarray/largestSumContiguousSubarray.js deleted file mode 100644 index 3a56e8f..0000000 --- a/misc/algos-master/largest_sum_contiguous_subarray/largestSumContiguousSubarray.js +++ /dev/null @@ -1,22 +0,0 @@ -function largestSumContiguousSubarray (arr) { - /* - * Find the subarray with maximum sum from all subarrays. - * :param arr: List of numbers to form subarray from. - * :return: The maximum sum in all subarrays. - */ - let maxPrev = 0; - let maxNow = 0; - for (let x = 0; x < arr.length; x++) { - maxNow += arr[x]; - maxPrev = Math.max(maxPrev, maxNow); - maxNow = Math.max(0, maxNow); - } - return maxPrev; -} - -function main () { - let arr = [-2, -3, 4, -1, -2, 1, 5, -3]; - console.log('Maximum contiguous sum is : ' + largestSumContiguousSubarray(arr)); -} - -main(); diff --git a/misc/algos-master/linear_search/LinearSearch.cs b/misc/algos-master/linear_search/LinearSearch.cs deleted file mode 100644 index 05bd089..0000000 --- a/misc/algos-master/linear_search/LinearSearch.cs +++ /dev/null @@ -1,33 +0,0 @@ -/*Linear Search algorithm searches for a given number in array -Time complexity is O(n) , n is size of array*/ - -using System; - -public class LinearSearch -{ - public static int Search(int[] data, int target) - { - for (int i = 0; i < data.Length; i++) - if (data[i] == target) - return i; - return -1; - } - - public static void Main() - { - int[] array = new int[100]; - // Initializing array with 1,2,....,100 - for(int i = 1; i <= 100; i++) - array[i-1] = i; - // Elements to be searched in the array - int[] search = {12,55,34,102,78}; - for(int i = 0; i < 5; i++) - { - int index = Search(array, search[i]); - if(index >= 0) - Console.WriteLine(search[i] + " found at index " + index); - else - Console.WriteLine(search[i] + " not found in the list"); - } - } -} diff --git a/misc/algos-master/linear_search/LinearSearch.java b/misc/algos-master/linear_search/LinearSearch.java deleted file mode 100644 index bb54411..0000000 --- a/misc/algos-master/linear_search/LinearSearch.java +++ /dev/null @@ -1,30 +0,0 @@ -/* - * Linear Search algorithm searches for a given number in array - * Time complexity is O(n) , n is size of array - */ -public class LinearSearch { - - public static int linearSearch(int[] arr, int searchElement) { - for(int i = 0; i < arr.length; i++) { - if(arr[i] == searchElement) - return i; // Element found - } - return -1; // Element not found - } - - public static void main(String[] args) { - int[] array = new int[100]; - // Initializing array with 1,2,....,100 - for(int i = 1; i <= 100; i++) - array[i-1] = i; - // Elements to be searched in the array - int[] search = {12,55,34,102,78}; - for(int i = 0; i < 5; i++) { - int index = linearSearch(array, search[i]); - if(index >= 0) - System.out.println(search[i] + " found at index " + index); - else - System.out.println(search[i] + " not found in the list"); - } - } -} diff --git a/misc/algos-master/linear_search/linear-search.go b/misc/algos-master/linear_search/linear-search.go deleted file mode 100644 index 6408e10..0000000 --- a/misc/algos-master/linear_search/linear-search.go +++ /dev/null @@ -1,22 +0,0 @@ -package main - -import "fmt" - -func linearSearch(array []int, needle int) int { - for i, item := range array { - if item == needle { - return i - } - } - return -1 -} - -func main() { - array := []int{0, 2, 4, 6, 8, 10, 12, 14, 16, 18} - index := linearSearch(array, 10) - if index == -1 { - fmt.Println("Number not found") - } else { - fmt.Println("10 found at index", index) - } -} diff --git a/misc/algos-master/linear_search/linearSearch.js b/misc/algos-master/linear_search/linearSearch.js deleted file mode 100644 index 7321a5f..0000000 --- a/misc/algos-master/linear_search/linearSearch.js +++ /dev/null @@ -1,29 +0,0 @@ -function linearSearch (arr, x) { - /* - Performs a linear search - :param arr: List of elements to search from - :param x: Element to search for - :return: Index if element found else -1 - */ - for (let it = 0; it < arr.length; it++) { - if (x === arr[it]) { - return it; - } - } - return -1; -} - -function main () { - let data = []; - for (let i = 1; i <= 100; i++) { - data.push(i); - } - let index = linearSearch(data, 12); - if (index === -1) { - console.log('Element was not found'); - } else { - console.log('Element was found at %dth index', index); - } -} - -main(); diff --git a/misc/algos-master/linked_list/LinkedList.cs b/misc/algos-master/linked_list/LinkedList.cs deleted file mode 100644 index 51061e9..0000000 --- a/misc/algos-master/linked_list/LinkedList.cs +++ /dev/null @@ -1,240 +0,0 @@ -using System; - -public class RunLinkedList -{ - public static void Main(string[] args) - { - LinkedList list = new LinkedList(); - - try - { - Console.WriteLine(list.RemoveLast()); - } - catch (InvalidOperationException) - { - Console.WriteLine("The list is empty"); - } - - list.Add(2, 0); - Console.WriteLine(list); // [2] - - list.Remove(0); - Console.WriteLine(list); // Empty - - list.AddFront(2); - list.Add(5, 1); - list.Add(10, 2); - list.AddLast(3); - Console.WriteLine(list); // [2, 5, 10, 3] - - Console.WriteLine(list.Search(5)); // 1 - Console.WriteLine(list.Search(0)); // -1 - - list.RemoveLast(); - Console.WriteLine(list); // [2, 5, 10] - - list.RemoveFront(); - Console.WriteLine(list); // [5, 10] - - Console.WriteLine(list.IsEmpty()); // False - - while (!list.IsEmpty()) - { - list.RemoveLast(); - } - - Console.WriteLine(list.IsEmpty()); // True - - Console.ReadKey(); - } -} - -public class LinkedList -{ - public class Node - { - public U data; - public Node next; - - public Node(U obj) - { - this.data = obj; - this.next = null; - } - } - - private Node head; - public int size = 0; - - public LinkedList() - { - this.head = null; - } - - public void AddFront(T obj) - { - Node node = new Node(obj); - node.next = this.head; - this.head = node; - this.size++; - } - - public void AddLast(T obj) - { - if (this.head == null) - { - Node node = new Node(obj); - this.head = node; - this.size = 1; - } - else - { - Node temp = this.head; - while (temp.next != null) - { - temp = temp.next; - } - Node node = new Node(obj); - temp.next = node; - size++; - } - } - - public void Add(T obj, int index) - { - if (index < 0 || index > this.size) - { - throw new Exception("Invalid Index"); - } - Node temp = this.head; - if (index == 0) - { - AddFront(obj); - } - else - { - for (int i = 0; i < index - 1; i++) - { - temp = temp.next; - } - Node node = new Node(obj); - node.next = temp.next; - temp.next = node; - this.size++; - } - } - - public T RemoveFront() - { - if (IsEmpty()) - { - throw new InvalidOperationException(); - } - T objRemoved = this.head.data; - this.head = this.head.next; - this.size--; - return objRemoved; - } - - public T Remove(int index) - { - if (IsEmpty()) - { - throw new InvalidOperationException(); - } - else if (index < 0 || index > this.size) - { - throw new IndexOutOfRangeException("Invalid Index"); - } - else if (index > 0) - { - Node temp = this.head; - for (int i = 0; i < index - 1; i++) - { - temp = temp.next; - } - T objRemoved = temp.next.data; - temp.next = temp.next.next; - this.size--; - return objRemoved; - } - return RemoveFront(); - } - - public T RemoveLast() - { - if (IsEmpty()) - { - throw new InvalidOperationException(); - } - T objRemoved; - if (this.head.next == null) - { - objRemoved = this.head.data; - this.head = null; - } - else - { - Node temp = this.head; - while (temp.next.next != null) - { - temp = temp.next; - } - objRemoved = temp.next.data; - temp.next = null; - } - this.size--; - return objRemoved; - } - - public int Search(T obj) - { - Node temp = this.head; - for (int i = 0; i < this.size; i++) - { - if (temp.data.Equals(obj)) - { - return i; - } - else - { - temp = temp.next; - } - } - return -1; - } - - public int GetSize() - { - return this.size; - } - - public bool IsEmpty() - { - return size == 0; - } - - public override string ToString() - { - string returnString = ""; - Node temp = this.head; - if (temp != null) - { - returnString += "["; - while (temp != null) - { - if (temp.next == null) - { - return returnString += temp.data + "]"; - } - else - { - returnString += temp.data + ", "; - temp = temp.next; - } - } - return returnString; - } - return "[]"; - } -} diff --git a/misc/algos-master/linked_list/LinkedList.java b/misc/algos-master/linked_list/LinkedList.java deleted file mode 100644 index 014f9fa..0000000 --- a/misc/algos-master/linked_list/LinkedList.java +++ /dev/null @@ -1,215 +0,0 @@ -/* - * Following is the code for Linked List - * T defines the type of Linked List to be created - */ - -import java.util.NoSuchElementException; - -// Class to create a Node that contains data and pointer to next Node -class Node { - public T data; // Data of type T - public Node next; // Pointer to next Node - - // Constructor to create a Node - public Node(T input) { - this.data = input; - this.next = null; - } -} - -// Class containing methods to be performed on Linked List -class LinkedList { - - private Node head; // Pointer to first node of the Linked List - private int sizeOfList = 0; // Size of the Linked List - - // Constructor to create an empty Linked List - public LinkedList() { - head = null; - } - - // Method to add an element to the start of the Linked List - public void addFront(T input) { - Node newNode = new Node(input); - newNode.next = head; - head = newNode; - sizeOfList++; - } - - // Method to add an element to the end of the Linked List - public void addLast(T input) { - if (head == null) { - Node newNode = new Node(input); - head = newNode; - sizeOfList = 1; - } - else { - Node temp = head; - while (temp.next != null) - temp = temp.next; - Node newNode = new Node(input); - temp.next = newNode; - sizeOfList++; - } - } - - // Method to add an element at a given index - public void add(T input, int index) { - if (index < 0 || index > sizeOfList) - throw new IndexOutOfBoundsException("Invalid Index"); - Node temp = head; - if (index == 0) - addFront(input); - else { - for (int i = 0; i < index-1; i++) - temp = temp.next; - Node newNode = new Node(input); - newNode.next = temp.next; - temp.next = newNode; - sizeOfList++; - } - } - - // Method to remove the front element from the Linked List - public T removeFront() { - if (isEmpty()) - throw new NoSuchElementException(); - T removedElement = head.data; - head = head.next; - sizeOfList--; - return removedElement; - } - - // Method to remove the last element from the Linked List - public T removeLast() { - if (isEmpty()) - throw new NoSuchElementException(); - T removedElement; - if (head.next == null) { - removedElement = head.data; - head = null; - } - else { - Node temp = head; - while (temp.next.next != null) - temp = temp.next; - removedElement = temp.next.data; - temp.next = null; - } - sizeOfList--; - return removedElement; - } - - // Method to remove element at specific index from the Linked List - public T remove(int index) { - if (isEmpty()) - throw new NoSuchElementException(); - if (index < 0 || index > sizeOfList) - throw new IndexOutOfBoundsException("Invalid Index"); - if (index > 0) { - Node temp = head; - for (int i = 0; i < index-1; i++) - temp = temp.next; - T removedElement = temp.next.data; - temp.next = temp.next.next; - sizeOfList--; - return removedElement; - } - return removeFront(); - } - - // Method to search a element in the Linked List returns its index i - public int search(T input) { - Node temp = head; - for (int i = 0; i < sizeOfList; i++) { - if (temp.data == input) - return i; - else - temp = temp.next; - } - return -1; // Will return -1 if not found - } - - // Method to display the Linked List - public void display() { - Node temp = head; - if (temp != null) { - System.out.print("["); - while (temp != null) { - System.out.print(temp.data+", "); - temp = temp.next; - } - System.out.print("\b\b]\n"); - } - } - - // Method to display the size of Linked List - public int size() { - return sizeOfList; - } - - // Method to check whether the Linked List is empty - public boolean isEmpty() { - return sizeOfList == 0; - } - - public static void main(String[] args) { - - LinkedList list = new LinkedList(); // Creating an empty Linked List - - // Adding element to the list - list.addFront(3); - list.display(); - - // Adding elements at the end - list.addLast(5); - list.addLast(6); - list.display(); - - // Adding elements to front - list.addFront(2); - list.addFront(1); - list.display(); - - // Adding element at a given index (Adding 4 at index 3) - list.add(4, 3); - list.display(); - - // Removing First Element - list.removeFront(); - list.display(); - - // Removing Last Element - list.removeLast(); - list.display(); - - // Removing an element from a index - list.remove(2); - list.display(); - - // Searching for an element in the Linked List - int found = list.search(5); - if (found >= 0) - System.out.println("Element found at index: " + list.search(5)); - else - System.out.println("Element not found"); - - // Checking size of list and whether it is empty - if (list.isEmpty()) - System.out.println("List is empty"); - else - System.out.println("List is not empty, Size of list: " + list.size()); - - // Emptying the LinkedList - while (!list.isEmpty()) - list.removeLast(); - - // Testing Exceptions thrown - try { - list.removeLast(); - } catch (NoSuchElementException e) { - System.out.println("List Empty"); - } - } -} - diff --git a/misc/algos-master/linked_list/linkedList.js b/misc/algos-master/linked_list/linkedList.js deleted file mode 100644 index c200bf4..0000000 --- a/misc/algos-master/linked_list/linkedList.js +++ /dev/null @@ -1,270 +0,0 @@ -class Node { - // Constructs Node - constructor (data) { - this.data = data; - this.next = null; - } -} - -class LinkedList { - // Initialises Linked List - constructor (size = 0) { - this.head = null; - this.length = size; - } - - // Inserts Element with value at index - add (value, index) { - let temp = this.head; - if (index === 0) { - let n = new Node(value); - n.next = this.head; - this.head = n; - } else if (index < 0 || index >= this.length) { - throw new Error('Index Out of Bound'); - } else { - for (let i = 0; i < index - 1; i++) { - temp = temp.next; - } - let n = new Node(value); - n.next = temp.next; - temp.next = n; - } - this.length++; - } - - // Adds value at front of Linked List - addFirst (value) { - return this.add(value, 0); - } - - // Adds value at end of Linked List - addLast (value) { - if (this.head === null) { - this.addFirst(value); - } else { - let temp = this.head; - while (temp.next !== null) { - temp = temp.next; - } - let n = new Node(value); - temp.next = n; - this.length++; - } - } - - // Remove value from index in Linked List - remove (index) { - if (this.isEmpty()) { - throw new Error('List is Empty'); - } else if (index < 0 || index >= this.length) { - throw new Error('Index out of Bound'); - } else if (index === 0) { - this.head = this.head.next; - } else { - let temp = this.head; - if (temp.next == null) { - this.head = null; - } else { - for (let i = 0; i < index - 1; i++) { - temp = temp.next; - } - temp.next = temp.next.next; - } - } - this.length--; - } - - // Removes front element from Linked List - removeFront () { - this.remove(0); - } - - // Removes last element from Linked List - removeLast () { - this.remove(this.length - 1); - } - - // Searches and removes element with data = value. - removeByValue (value) { - this.remove(this.findFirst(value)); - } - - // Search and returns index. - search (input) { - let head = this.head; - for (let i = 0; i < this.length; i++) { - if (head.data === input) { - return i; - } else { - head = head.next; - } - } - throw new Error('Value not found'); - } - - // Search and return index of first occurence of input. - findFirst (input) { - return this.search(input); - } - - // Search and return index of last occurence of input. - findLast (input) { - let newList = new LinkedList(); - newList = this.clone(); - newList.reverse(); - return this.length - newList.search(input) - 1; - } - - // Sets Data of input at index. - setData (input, index) { - // If index is >= size of Linked List, It adds the value. - if (index >= this.length) { - this.add(input, index); - } else { - // If index already have some data it replaces it with input. - let head = this.head; - for (let i = 0; i < this.length; i++) { - if (i === index) { - head.data = input; - } - head = head.next; - } - } - } - - // Clones and returns a newList. - clone () { - let newList = new LinkedList(); - let temp = this.head; - while (temp.next) { - newList.addLast(temp.data); - temp = temp.next; - } - newList.addLast(temp.data); - return newList; - } - - // Reverses the existing Linked List. - reverse () { - let prev = null; - let current = this.head; - while (current) { - let next = current.next; - current.next = prev; - prev = current; - current = next; - } - this.head = prev; - } - - // Checks if Linked List is empty. - isEmpty () { - return (this.length === 0); - } - - // Clears the Linked List. - clear () { - this.head = null; - this.length = 0; - } - - // Returns the Linked List in List form. - show () { - let list = []; - let head = this.head; - while (head) { - list.push(head.data); - head = head.next; - } - return list; - } -} - -function main () { - let linkedList = new LinkedList(); - - linkedList.add(5, 0); - console.log(linkedList.show()); - console.log('Size : ' + linkedList.length); - - linkedList.addFirst(25); - linkedList.addFirst(251); - console.log(linkedList.show()); - console.log('Size : ' + linkedList.length); - - linkedList.addFirst(5); - console.log(linkedList.show()); - console.log('Size : ' + linkedList.length); - - try { - console.log('Fist Occurrence at index: ' + linkedList.findFirst(5)); - } catch (err) { - console.log('Value not found'); - } - - try { - console.log('Last Occurrence at index: ' + linkedList.findLast(5)); - } catch (err) { - console.log('Value not found'); - } - - try { - linkedList.setData(12325, 1); - console.log(linkedList.show()); - console.log('Size : ' + linkedList.length); - } catch (err) { - console.log('Index out of bound'); - } - - try { - linkedList.removeByValue(12325); - console.log(linkedList.show()); - console.log('Size : ' + linkedList.length); - } catch (err) { - console.log('Value not found'); - } - - linkedList.addLast(125); - linkedList.addLast(11); - console.log(linkedList.show()); - console.log('Size : ' + linkedList.length); - - try { - console.log('Element found at index: ' + linkedList.search(1125)); - } catch (err) { - console.log('Value not found'); - } - - console.log('Cloned : ', linkedList.clone().show()); - - try { - linkedList.remove(6); - console.log(linkedList.show()); - console.log('Size : ' + linkedList.length); - } catch (err) { - console.log('Index Out of Bound'); - } - - try { - linkedList.remove(2); - } catch (err) { - console.log('Index Out of Bound'); - } - console.log(linkedList.show()); - console.log('Size : ' + linkedList.length); - - linkedList.removeFront(); - console.log(linkedList.show()); - console.log('Size : ' + linkedList.length); - - linkedList.removeLast(); - console.log(linkedList.show()); - console.log('Size : ' + linkedList.length); - - linkedList.clear(); - console.log(linkedList.show()); - console.log('Size : ' + linkedList.length); -} - -main(); diff --git a/misc/algos-master/linked_list/linked_list.go b/misc/algos-master/linked_list/linked_list.go deleted file mode 100644 index b3f82ca..0000000 --- a/misc/algos-master/linked_list/linked_list.go +++ /dev/null @@ -1,115 +0,0 @@ -package main - -import ( - "errors" - "fmt" -) - -// List is a A general List interface -type List interface { - Add(newVal int) - Len() int - PeekLast() (int, error) - PeekFirst() (int, error) - ToSlice() []int -} - -type linkedListNode struct { - value int - next *linkedListNode -} - -// LinkedList is a singly-linked LinkedList -type LinkedList struct { - root *linkedListNode - tail *linkedListNode - length int -} - -// Len returns the length of the LinkedList -func (ll *LinkedList) Len() int { return ll.length } - -// Add adds a new element to the LinkedList Time Complexity: O(1) -func (ll *LinkedList) Add(newVal int) { - newNode := new(linkedListNode) - newNode.value = newVal - if ll.length == 0 { - ll.root = newNode - ll.root.next = nil - } else if ll.length == 1 { - ll.tail = newNode - ll.root.next = ll.tail - } else { - ll.tail.next = newNode - ll.tail = newNode - } - - ll.length++ -} - -// RemoveFirst removes the first element from the LinkedList Time Complexity: O(1) -func (ll *LinkedList) RemoveFirst() (val int, err error) { - if ll.length == 0 { - return 0, errors.New("there is nothing to remove") - } else if ll.length == 1 { - val = ll.root.value - ll.root = nil - } else if ll.length == 2 { - val = ll.root.value - ll.root = ll.tail - ll.tail = nil - } else { - val = ll.root.value - ll.root = ll.root.next - } - - ll.length-- - return -} - -// ToSlice converts the LinkedList to a Slice Time Complexity: O(n) -func (ll *LinkedList) ToSlice() []int { - var sliceList []int - - for currNode := ll.root; currNode != nil; currNode = currNode.next { - sliceList = append(sliceList, currNode.value) - } - - return sliceList -} - -// PeekLast returns the last element of the LinkedList, without removing it Time Complexity: O(1) -func (ll *LinkedList) PeekLast() (val int, err error) { - if ll.length == 0 { - return 0, errors.New("there is nothing to peek") - } else if ll.length == 1 { - val = ll.root.value - } else { - val = ll.tail.value - } - - return val, nil -} - -// PeekFirst returns the first element of the LinkedList, without removing it Time Complexity: O(1) -func (ll *LinkedList) PeekFirst() (val int, err error) { - if ll.length == 0 { - return 0, errors.New("there is nothing to peek") - } - - val = ll.root.value - - return val, nil -} - -func main() { - var ll LinkedList - ll.Add(10) - ll.Add(15) - ll.Add(25) - first, err := ll.RemoveFirst() - for err == nil { - fmt.Println(first) - first, err = ll.RemoveFirst() - } -} diff --git a/misc/algos-master/longest_common_subsequence/LongestCommonSubsequence.java b/misc/algos-master/longest_common_subsequence/LongestCommonSubsequence.java deleted file mode 100644 index 275202a..0000000 --- a/misc/algos-master/longest_common_subsequence/LongestCommonSubsequence.java +++ /dev/null @@ -1,41 +0,0 @@ -public class LongestCommonSubsequence { - //Function that returns Longest Common Subsequence of two strings - //Time Complexity - O( len(str1) * len(str2) ) - //Space Complexity - O( len(str1)*len(str2) ) - private static String longestCommonSubsequence(String str1, String str2) { - int[][] arr = new int[str1.length() + 1][str2.length() + 1]; - for (int i = str1.length() - 1; i >= 0; i--) { - for (int j = str2.length() - 1; j >= 0; j--) { - if (str1.charAt(i) == str2.charAt(j)) { - arr[i][j] = arr[i + 1][j + 1] + 1; - } - else { - arr[i][j] = Math.max(arr[i + 1][j], arr[i][j + 1]); - } - } - } - String res = ""; - int i = 0; - int j = 0; - while (i < str1.length() && j < str2.length()) { - if (str1.charAt(i) == str2.charAt(j)) { - res = res + str1.charAt(i); - i++; - j++; - } - else if (arr[i + 1][j] >= arr[i][j + 1]) { - i++; - } - else { - j++; - } - } - return res; - } - - public static void main(String[] args) { - String s1 = "applebanana"; - String s2 = "alphabet"; - System.out.println(longestCommonSubsequence(s1, s2)); - } -} diff --git a/misc/algos-master/longest_common_subsequence/longestCommonSubsequence.go b/misc/algos-master/longest_common_subsequence/longestCommonSubsequence.go deleted file mode 100644 index 0d61488..0000000 --- a/misc/algos-master/longest_common_subsequence/longestCommonSubsequence.go +++ /dev/null @@ -1,36 +0,0 @@ -package main - -import ( - "fmt" - "math" -) - -// Time complexity : O(len(str1)*len(str2)) -// longestCommonSubsequence returns length of the LCS -func longestCommonSubsequence(str1, str2 string) int { - len1 := len(str1) - len2 := len(str2) - lcs := make([][]int, len1+1) - for i := range lcs { - lcs[i] = make([]int, len2+1) - } - for i := 0; i <= len1; i++ { - for j := 0; j <= len2; j++ { - if i == 0 || j == 0 { - lcs[i][j] = 0 - } else if str1[i-1] == str2[j-1] { - lcs[i][j] = lcs[i-1][j-1] + 1 - } else { - lcs[i][j] = int(math.Max(float64(lcs[i-1][j]), float64(lcs[i][j-1]))) - } - } - } - return lcs[len1][len2] -} - -// Driver function to test above algorithm -func main() { - str1 := "mohit" - str2 := "mokyit" - fmt.Println(longestCommonSubsequence(str1, str2)) -} diff --git a/misc/algos-master/longest_common_subsequence/longestCommonSubsequence.js b/misc/algos-master/longest_common_subsequence/longestCommonSubsequence.js deleted file mode 100644 index 49953fe..0000000 --- a/misc/algos-master/longest_common_subsequence/longestCommonSubsequence.js +++ /dev/null @@ -1,49 +0,0 @@ -function longestCommonSubsequence (str1, str2) { - /* - * Time Complexity - O(len(str1) * len(str2)) - * Space Complexity - O(len(str1) * len(str2)) - * :param seq1: First sequence - * :param seq2: Second sequence - * :return: The longest common subsequence of two input sequences - */ - let len1 = str1.length; - let len2 = str2.length; - let lcs = new Array(len1 + 1); - for (let x = 0; x <= len1; x++) { - lcs[x] = new Array(len2 + 1); - } - for (let i = 0; i <= len1; i++) { - for (let j = 0; j <= len2; j++) { - if (i === 0 || j === 0) { - lcs[i][j] = 0; - } else if (str1[i - 1] === str2[j - 1]) { - lcs[i][j] = lcs[i - 1][j - 1] + 1; - } else { - lcs[i][j] = Math.max(lcs[i - 1][j], lcs[i][j - 1]); - } - } - } - let res = ''; - let i = len1; - let j = len2; - while (i > 0 && j > 0) { - if (str1[i - 1] === str2[j - 1]) { - res = str1[i - 1] + res; - i--; - j--; - } else if (lcs[i - 1][j] > lcs[i][j - 1]) { - i--; - } else { - j--; - } - } - return res; -} - -function main () { - let a = 'whattheheckman'; - let b = 'whatareyoudoinghere'; - console.log('Longest Common Subsequence : ' + longestCommonSubsequence(a, b)); -} - -main(); diff --git a/misc/algos-master/longest_palindromic_substring/LongestPalindromicSubstring.java b/misc/algos-master/longest_palindromic_substring/LongestPalindromicSubstring.java deleted file mode 100644 index 22bbfcf..0000000 --- a/misc/algos-master/longest_palindromic_substring/LongestPalindromicSubstring.java +++ /dev/null @@ -1,48 +0,0 @@ -public class LongestPalindromicSubstring { - - /* - This method is used to determine palindrome about a point in string. - @param test: Input string whose substrings are to be checked - @param left: Left end of result palindromic substring - @param right: Right end of result palindromic substring - @return: Length of palindromic substring - */ - private static int expandAroundCenter(String test, int left, int right) { - int lengthOfString = test.length(); - while (left >= 0 && right < lengthOfString && test.charAt(left) == test.charAt(right)) { - left -= 1; - right += 1; - } - return right - left - 1; - } - - /* - Method to find longest substring which is a palindrome. - @param test: Input string whose substrings are to be checked - @return: Longest substring of input string which is a palindrome - - Time complexity: O(lengthOfString^2) - Space complexity: O(1) - */ - public static String longestPalindromicSubstring(String test) { - String toTest = test.toLowerCase(); - int start = 0; - int end = 0; - int lengthOfString = test.length(); - for (int i = 0; i < lengthOfString; ++i) { - int length = Math.max(expandAroundCenter(toTest, i, i), expandAroundCenter(toTest, i, i + 1)); - if (length > end - start) { - start = i - (length - 1) / 2; - end = i + length / 2; - } - } - return test.substring(start, end + 1); - } - - public static void main(String[] args) { - String test = "Nitin"; - System.out.println("Longest Palindromic Substring of " + - test + " is " + - longestPalindromicSubstring(test)); - } -} diff --git a/misc/algos-master/longest_palindromic_substring/longestPalindromicSubstring.js b/misc/algos-master/longest_palindromic_substring/longestPalindromicSubstring.js deleted file mode 100644 index fc6c0c5..0000000 --- a/misc/algos-master/longest_palindromic_substring/longestPalindromicSubstring.js +++ /dev/null @@ -1,46 +0,0 @@ -function expandAroundCenter (test, left, right) { - /* - :param test: Input string whose substrings are to be checked - :param left: Left end of result palindromic substring - :param right: Right end of result palindromic substring - :return: Length of palindromic substring - */ - let n = test.length; - while (left >= 0 && right < n && test.charAt(left) === test.charAt(right)) { - left--; - right++; - } - return right - left - 1; -} - -function longestPalindromicSubstring (test) { - /* - Function to find longest substring which is a palindrome - - :param test: Input string whose substrings are to be checked - :return: Longest substring of input string which is a palindrome - - Time complexity: O(n^2) - Space complexity: O(1) - */ - let start = 0; - let end = 0; - - for (let i = 0; i < test.length; i++) { - let length = Math.max(expandAroundCenter(test, i, i), - expandAroundCenter(test, i, i + 1)); - if (length > end - start) { - start = i - Math.floor((length - 1) / 2); - end = i + Math.floor(length / 2); - } - } - return test.slice(start, end + 1); -} - -function main () { - let test = 'geeksforgeeks'; - console.log('Longest Palindromic Substring of', - test, 'is', longestPalindromicSubstring(test)); -} - -main(); diff --git a/misc/algos-master/longest_palindromic_substring/longest_palindromic_substring.go b/misc/algos-master/longest_palindromic_substring/longest_palindromic_substring.go deleted file mode 100644 index df233a9..0000000 --- a/misc/algos-master/longest_palindromic_substring/longest_palindromic_substring.go +++ /dev/null @@ -1,46 +0,0 @@ -package main - -import "fmt" - -// expandAroundCenter returns length of palindromic substring -func expandAroundCenter(runes []rune, left int, right int) int { - n := len(runes) - - for left >= 0 && right < n && runes[left] == runes[right] { - left-- - right++ - } - return right - left - 1 -} - -// LongestPalindromicSubstring returns the longest palindromic substring in -// provided string. -// Time complexity: O(n^2) -// Space complexity: O(1) -func LongestPalindromicSubstring(str string) string { - start, end := 0, 0 - runes := []rune(str) - - for i := 0; i < len(runes); i++ { - a := expandAroundCenter(runes, i, i) - b := expandAroundCenter(runes, i, i+1) - - length := 0 - if a > b { - length = a - } else { - length = b - } - - if length > end-start { - start = i - (length-1)/2 - end = i + length/2 - } - } - return string(runes[start : end+1]) -} - -func main() { - str := "And the longest palindrome is... neveroddoreven!" - fmt.Println(LongestPalindromicSubstring(str)) -} diff --git a/misc/algos-master/merge_sort/MergeSort.cs b/misc/algos-master/merge_sort/MergeSort.cs deleted file mode 100644 index 36cb97c..0000000 --- a/misc/algos-master/merge_sort/MergeSort.cs +++ /dev/null @@ -1,78 +0,0 @@ -/* -Time Complexity: O(n log(n)) -Space Complexity: O(n) -*/ - -using System; - -public class MergeSort -{ - /// - /// Merges two unsorted halves of an array into one sorted array - /// first half: from 'first' to 'mid' - /// second half: from 'mid' to 'last' - /// - /// The original unsorted array - /// The start index of the first half of the array a - /// The middle index of the two halves of the array - /// The end index of the second half of the array a - /// A temporary array for storing the sorted halves - public static void Merge(int[] a, int first, int mid, int last, int[] temp) - { - int currL = first; //left half pointer - int currR = mid; //right half pointer - int currT; //current sorted array pointer - - for (currT = first; currT < last; currT++) - { - //if left half is element is smaller or right pointer is out of bounds - if (currL < mid && (currR >= last || a[currL] < a[currR])) - temp[currT] = a[currL++]; - else - temp[currT] = a[currR++]; - } - - for (currT = first; currT < last; currT++) - a[currT] = temp[currT]; - } - - /// - /// Recursive method for sorting an array 'a' between two indexes - /// first and last by using merge sort - /// - /// The original unsorted array - /// The start index. The array will be sorted starting from this index - /// The end index. The array will be sorted untill this index - /// A temporary array for storing merge results - public static void DoMergeSort(int[] a, int first, int last, int[] temp) - { - if (last - first > 1) - { - int mid = first + (last - first) / 2; //find the middle - DoMergeSort(a, first, mid, temp); //sort left half - DoMergeSort(a, mid, last, temp); //sort right half - Merge(a, first, mid, last, temp); //merge two sorted halves - } - } - - /// - /// Merge sort helper method. Calls the recursive Merge sort method - /// - /// The original unsorted array - public static void DoMergeSort(int[] a) - { - if (a == null || a.Length <= 1) - return; - DoMergeSort(a, 0, a.Length, new int[a.Length]); - } - - public static void Main() - { - int[] a = new int[] {2, 4, 9, 6, 7, 8}; - Console.WriteLine("Before Merge Sort:"); - Console.WriteLine("[{0}]", string.Join(", ", a)); - DoMergeSort(a); - Console.WriteLine("After Merge Sort:"); - Console.WriteLine("[{0}]", string.Join(", ", a)); - } -} diff --git a/misc/algos-master/merge_sort/MergeSort.java b/misc/algos-master/merge_sort/MergeSort.java deleted file mode 100644 index 1cc6255..0000000 --- a/misc/algos-master/merge_sort/MergeSort.java +++ /dev/null @@ -1,56 +0,0 @@ -public class MergeSort { - - private static void merge(int[] a, int first, int mid, int last) { - int l = mid - first + 1; - int r = last - mid; - int[] left = new int[l]; - int[] right = new int[r]; - - for (int i = 0; i < l; i++) { //copy left - left[i] = a[first + i]; - } - for (int j = 0; j < r; j++) { //copy right - right[j] = a[mid + j + 1]; - } - int i = 0; - int j = 0; - int k = first; - while (i < l && j < r) { //merging - if (left[i] <= right[j]) { - a[k] = left[i]; - i++; - } else { - a[k] = right[j]; - j++; - } - k++; - } - while (i < l) { //remainig left element - a[k] = left[i]; - i++; - k++; - } - while (j < r) { //remainig right element - a[k] = right[j]; - j++; - k++; - } - } - - private static void mergeSort(int[] a, int first, int last) { - if (first < last) { - int mid = (first + last) / 2; //find the middle - mergeSort(a, first, mid); //sort left half - mergeSort(a, mid + 1, last); //sort right half - merge(a, first, mid, last); //merge above two sorted halves - } - } - - public static void main(String[] args) { - int[] arr = new int[] {2, 4, 9, 6, 7, 8}; - mergeSort(arr, 0, arr.length - 1); - for (int element : arr) { - System.out.println(element); - } - } -} diff --git a/misc/algos-master/merge_sort/mergeSort.js b/misc/algos-master/merge_sort/mergeSort.js deleted file mode 100644 index aca01b0..0000000 --- a/misc/algos-master/merge_sort/mergeSort.js +++ /dev/null @@ -1,49 +0,0 @@ -/* -* Implementation of merge sort algorithm -* Time complexity: O(size*log(size)) -* Space complexity: O(size) -*/ -function merge (left, right) { - let i = 0; - let j = 0; - let size = left.length + right.length; - let arr = []; - for (let k = 0; k < size; k++) { - if (i > left.length - 1 && j < right.length) { - arr[k] = right[j]; - j++; - } else if (j > right.length - 1 && i < left.length) { - arr[k] = left[i]; - i++; - } else if (left[i] < right[j]) { - arr[k] = left[i]; - i++; - } else { - arr[k] = right[j]; - j++; - } - } - return arr; -} - -/* -* :param arr: array to be sorted -*/ -function mergeSort (arr) { - if (arr.length < 2) { - return arr; - } - let middle = parseInt(arr.length / 2); - let left = arr.slice(0, middle); - let right = arr.slice(middle, arr.length); - return merge(mergeSort(left), mergeSort(right)); -} - -function main () { - let arr = [2, 1, 6, 444, 8, 99, 10]; - console.log('Sorted data is :'); - arr = mergeSort(arr); - console.log(arr); -} - -main(); diff --git a/misc/algos-master/merge_sort/merge_sort.go b/misc/algos-master/merge_sort/merge_sort.go deleted file mode 100644 index 293e00e..0000000 --- a/misc/algos-master/merge_sort/merge_sort.go +++ /dev/null @@ -1,47 +0,0 @@ -package main - -import "fmt" - -// MergeSort divides the slice into two parts, sorts both the part of slice and then merge it -// Time complexity : O(size(log(size))) -// Space complexity : O(size) -func MergeSort(slice []int) []int { - if len(slice) < 2 { - return slice - } - mid := (len(slice)) / 2 - return merge(MergeSort(slice[:mid]), MergeSort(slice[mid:])) -} - -// merge merges two sorted slice -// Time complexity : O(size) -// Space complexity : O(size) -func merge(left []int, right []int) []int { - i := 0 - j := 0 - size := len(left) + len(right) - slice := make([]int, size, size) // make built-in function allocates and initializes an object of type slice - for k := 0; k < size; k++ { - if i > len(left)-1 && j < len(right) { - slice[k] = right[j] - j++ - } else if j > len(right)-1 && i < len(left) { - slice[k] = left[i] - i++ - } else if left[i] < right[j] { - slice[k] = left[i] - i++ - } else { - slice[k] = right[j] - j++ - } - } - return slice -} - -func main() { - slice := []int{8, 2, 4, 9, 1, 699, 0, 9999} - fmt.Println("Sorted data is:") - slice = MergeSort(slice) - fmt.Println(slice) -} diff --git a/misc/algos-master/modular_exponential/ModularExponential.java b/misc/algos-master/modular_exponential/ModularExponential.java deleted file mode 100644 index 28a49c6..0000000 --- a/misc/algos-master/modular_exponential/ModularExponential.java +++ /dev/null @@ -1,24 +0,0 @@ -import java.math.BigInteger; - -public class ModularExponential { - public static BigInteger modularExponential(long base, long power, long mod) { - BigInteger result = BigInteger.ONE; - base = base % mod; - while(power > 0) { - if(power % 2 == 1) { - result = result.multiply(BigInteger.valueOf(base)); - result = result.mod(BigInteger.valueOf(mod)); - } - power = power / 2; - base = (base * base) % mod; - } - return result; - } - - public static void main(String[] args) { - long base = 78; - long pow = 20; - long mod = 65; - System.out.println(modularExponential(base, pow, mod)); - } -} diff --git a/misc/algos-master/modular_exponential/modularExponential.js b/misc/algos-master/modular_exponential/modularExponential.js deleted file mode 100644 index bbd8db0..0000000 --- a/misc/algos-master/modular_exponential/modularExponential.js +++ /dev/null @@ -1,30 +0,0 @@ -function modularExponential (base, power, mod) { - /* - Performs Modular Exponential. - Time Complexity : O(log (power)) - :param base: Number that is going to be raised. - :param power: Power to which the number is raised. - :param mod: Number by which modulo has to be performed. - :return: Returns (base ^ power) % mod - */ - let answer = 1; - base = base % mod; - while (power) { - if (power & 1) { - answer = (answer * base) % mod; - } - power = power >> 1; - base = (base * base) % mod; - } - return answer; -} - -function main () { - let base = 3; - let power = 5; - let mod = 61; - let res = modularExponential(base, power, mod); - console.log('%d\n', res); -} - -main(); diff --git a/misc/algos-master/modular_exponential/modular_exponential.go b/misc/algos-master/modular_exponential/modular_exponential.go deleted file mode 100644 index 6fc8171..0000000 --- a/misc/algos-master/modular_exponential/modular_exponential.go +++ /dev/null @@ -1,23 +0,0 @@ -package main - -import "fmt" - -// ModularExponential computes x^y -// Time Complexity : O(log(power)) -func ModularExponential(base int64, power int, mod int64) int64 { - result := int64(1) - base = base % mod - for power > 0 { - if power%2 == 1 { - result = (result * base) % mod - } - power = power >> 1 - base = (base * base) % mod - } - return result -} - -func main() { - base, power, mod := int64(2), 20, int64(100000) - fmt.Println(ModularExponential(base, power, mod)) -} diff --git a/misc/algos-master/n_queen_problem/NQueenProblem.java b/misc/algos-master/n_queen_problem/NQueenProblem.java deleted file mode 100644 index acd1f7d..0000000 --- a/misc/algos-master/n_queen_problem/NQueenProblem.java +++ /dev/null @@ -1,171 +0,0 @@ -import java.util.ArrayDeque; -import java.util.ArrayList; -import java.util.Deque; -import java.util.Iterator; -import java.util.List; - - -/** - *

This class solves the N Queens Problem.

- * - *

Once you create an object with the desired board size, you can get an iterator that lazily will create each - * possible solution is there's any. The code will create all solutions, not jut unique ones

- * - *

This way you have flexibility on how to use solutions, you can get only one or all.

- * - * @see N Queens Problem - */ -public class NQueenProblem implements Iterable { - - private final int size; - - /** - * Creates an NQueens object to solve the N Quees Problems on board of size n - * - * @param n - */ - public NQueenProblem(final int n) { - this.size = n; - } - - /** - * Returns an Iterator over the solutions for this N Queens Problem. - */ - @Override - public Iterator iterator() { - return new NQueenIterator(); - } - - /** - *

This class represents a Solution for the N Queen problem.

- * - *

Internally a solution is encoded as a list of integers. If in the index i there's integer j - * it means that one of the queens should be placed on the square (i, j)

- * - */ - public static class Solution { - - private final List board; - private static char QUEEN = 'Q'; - private static char EMPTY_SQUARE = '.'; - private static String NEW_LINE = String.format("%n"); // platform independent new line character. - - public Solution(final List board) { - this.board = board; - } - - /** - *

Returns an String that looks like a board where '.' represents an empty square and 'Q' represents an square with a queen

- */ - @Override - public String toString() { - StringBuilder builder = new StringBuilder(); - for (int i = 0; i < board.size(); ++i) { - for (int j = 0; j < board.size(); ++j) { - if (board.get(i) == j) { - builder.append(QUEEN); - } else { - builder.append(EMPTY_SQUARE); - } - } - builder.append(NEW_LINE); - } - return builder.toString(); - } - } - - private class NQueenIterator implements Iterator { - - /** - * Queue to store the intermediate boards necessary to build all solutions. - */ - private final Deque> queue; - /** - * Next solution to be returned. - */ - private Solution next; - - /** - * Initializes the queue and adds an empty board to it. - */ - private NQueenIterator() { - this.queue = new ArrayDeque<>(); - queue.add(new ArrayList<>(size)); - } - - /** - *

Returns true is there's one more solution.

- * - *

It uses a backtracking algorithm to check for a possible solution. It removes the last board enqueued - * and for the next empty column it tries to place a queen in every square. If that queen doesn't attack any of the already - * placed queens, it queues a board with that queen. Once it removes a board with 8 queens, it stops and returns true

- */ - @Override - public boolean hasNext() { - while (!queue.isEmpty()) { - List current = queue.removeLast(); - if (current.size() == size) { - this.next = new Solution(current); - return true; - } - int column = current.size(); - for (int row = 0; row < size; ++row) { - if (isValid(current, column, row)) { - List next = new ArrayList<>(current); - next.add(row); - queue.addLast(next); - } - } - } - return false; - } - - @Override - public Solution next() { - return next; - } - - /** - *

Returns true if is isValid to place a queen on the square (column, row)

- * - *

A queen can be placed if it doesn't attack any of the already placed queens: there can't be a queen - * already in the same row, and the queen can't be collinear with any other.

- * - * @param board a representation of the current board as explained in {@link Solution} - * @param column the column we want to test to see if a queen can be placed without attacking any existing one - * @param row the row we want to test to see if a queen can be placed without attacking any existing one - * @return true if a queen can be placed on (column, row) without attacking any queens already in board - */ - private boolean isValid(List board, int column, int row) { - for (int j = 0; j < column; ++j) { - if (board.get(j) == row) { - return false; - } - if (areCollinear(column, j, board.get(j), row)) { - return false; - } - } - return true; - } - - /** - * Verifies that the square (x, y) is not collinear with square (x1, y1) - * - * @param x - * @param y - * @param x1 - * @param y1 - * @return - */ - private boolean areCollinear(int x, int y, int x1, int y1) { - return Math.abs(y - x) == Math.abs(x1 - y1); - } - } - - public static void main(String[] args) { - NQueenProblem queens = new NQueenProblem(5); - for (Solution s : queens) { - System.out.println(s); - } - } -} diff --git a/misc/algos-master/n_queen_problem/n_queen_problem.go b/misc/algos-master/n_queen_problem/n_queen_problem.go deleted file mode 100644 index 6020165..0000000 --- a/misc/algos-master/n_queen_problem/n_queen_problem.go +++ /dev/null @@ -1,68 +0,0 @@ -// Given a chess board having N×N cells -// place N queens on the board in such a way that no queen attacks any other queen. - -// There can be a number of possible solutions for a given length of board. -// This implementation prints only one valid solution, it can be extended to print all possible valid solutions. - -package main - -import "fmt" - -func main() { - boardSize := 8 // size of chess board (8 x 8) - - // make board - board := make([][]int, boardSize) - for i := range board { - board[i] = make([]int, boardSize) - } - - if PlaceQueen(&board, boardSize) { - for i := 0; i < boardSize; i++ { - for j := 0; j < boardSize; j++ { - fmt.Printf("%d ", board[i][j]) - } - fmt.Print("\n") - } - } else { - fmt.Println("Not possible") - } -} - -func isAttacked(board *[][]int, x, y, boardSize int) bool { - for i := 0; i < boardSize; i++ { - if (*board)[x][i] == 1 { - return true - } - if (*board)[i][y] == 1 { - return true - } - for j := 0; j < boardSize; j++ { - if (i-j == x-y) || (i+j == x+y) { - if (*board)[i][j] == 1 { - return true - } - } - } - } - return false -} - -// PlaceQueen place queens on the board and will return true if it is possible to place all the queens else false -func PlaceQueen(board *[][]int, boardSize int) bool { - if boardSize == 0 { - return true - } - for i := 0; i < len(*board); i++ { - for j := 0; j < len(*board); j++ { - if !(isAttacked(board, i, j, len(*board))) { - (*board)[i][j] = 1 - if PlaceQueen(board, boardSize-1) { - return true - } - (*board)[i][j] = 0 - } - } - } - return false -} diff --git a/misc/algos-master/npm-requirements.txt b/misc/algos-master/npm-requirements.txt deleted file mode 100644 index 6681e30..0000000 --- a/misc/algos-master/npm-requirements.txt +++ /dev/null @@ -1,2 +0,0 @@ -happiness -eclint@2.2.0 diff --git a/misc/algos-master/pip2-requirements.txt b/misc/algos-master/pip2-requirements.txt deleted file mode 100644 index 3dc5e33..0000000 --- a/misc/algos-master/pip2-requirements.txt +++ /dev/null @@ -1,3 +0,0 @@ -numpy -requests -matplotlib diff --git a/misc/algos-master/pip3-requirements.txt b/misc/algos-master/pip3-requirements.txt deleted file mode 100644 index 84510ad..0000000 --- a/misc/algos-master/pip3-requirements.txt +++ /dev/null @@ -1,4 +0,0 @@ -coala-bears -requests -numpy -matplotlib diff --git a/misc/algos-master/prime_factor/PrimeFactor.java b/misc/algos-master/prime_factor/PrimeFactor.java deleted file mode 100644 index de87a38..0000000 --- a/misc/algos-master/prime_factor/PrimeFactor.java +++ /dev/null @@ -1,25 +0,0 @@ -import java.util.ArrayList; - -public class PrimeFactor { - - public static ArrayList primeFactor(int n) { - ArrayList primeNo = new ArrayList(); - for (int i = 2; i <= n; i++) { - if (n % i == 0) { - primeNo.add(i); - while (n % i == 0) { - n = n / i; - } - } - } - return primeNo; - } - - public static void main(String[] args) { - int n = 8; - System.out.println("Prime Factors are:"); - for (Integer i : primeFactor(n)) { - System.out.println(i); - } - } -} diff --git a/misc/algos-master/prime_factor/primeFactor.js b/misc/algos-master/prime_factor/primeFactor.js deleted file mode 100644 index e74fde1..0000000 --- a/misc/algos-master/prime_factor/primeFactor.js +++ /dev/null @@ -1,31 +0,0 @@ -function primeFactor (n) { - /* - Finding all the prime factors of a given number - :param n: Number whose prime factors are going to be found - :returns: Array with prime numbers - */ - let primes = []; - for (let i = 2; i <= Math.sqrt(n); i++) { - if (n % i === 0) { - primes.push(i); - while (n % i === 0) { - n = n / i; - } - } - } - if (n !== 1) { - primes.push(n); - } - return primes; -} - -function main () { - let n = 582; - console.log('Prime factors are:'); - let primes = primeFactor(n); - for (let i = 0; i < primes.length; i++) { - console.log(primes[i]); - } -} - -main(); diff --git a/misc/algos-master/prime_factor/prime_factor.go b/misc/algos-master/prime_factor/prime_factor.go deleted file mode 100644 index 670478c..0000000 --- a/misc/algos-master/prime_factor/prime_factor.go +++ /dev/null @@ -1,30 +0,0 @@ -package main - -import ( - "fmt" - "math" -) - -// PrimeFactor finds all the prime factor of given number -func PrimeFactor(n int) []int { - var primes []int - sqrt := int(math.Sqrt(float64(n))) - for i := 2; i <= sqrt; i++ { - if n%i == 0 { - primes = append(primes, i) - for n%i == 0 { - n = n / i - } - } - } - if n != 1 { - primes = append(primes, n) - } - return primes -} - -func main() { - n := 8 - fmt.Println("Prime Factors are :") - fmt.Println(PrimeFactor(n)) -} diff --git a/misc/algos-master/prims/Prims.java b/misc/algos-master/prims/Prims.java deleted file mode 100644 index c1048c9..0000000 --- a/misc/algos-master/prims/Prims.java +++ /dev/null @@ -1,74 +0,0 @@ -public class Prims { - private static int[] generate(int[][] ar) { - int length = ar.length; - // Stores the parent of each vertex - int parent[] = new int[length]; - // key value of each vertex - int key[] = new int[length]; - // Flag for included in the MST - boolean mstSet[] = new boolean[length]; - // Initialization of arguments - for (int i = 0; i < length; i++) { - mstSet[i] = false; - key[i] = Integer.MAX_VALUE; - } - - // Starting from the first vertex - // As the first vertex is the root - // So it doesn't have any parent - key[0] = 0; - parent[0] = -1; - - for (int i = 0; i < length - 1; i++) { - // minimum key from given vertices - int u = minKey(key, mstSet); - mstSet[u] = true; - - // Updating the neighbours key - for (int j = 0; j < length; j++) { - if (ar[u][j] != 0 && !mstSet[j] && ar[u][j] < key[j]) { - parent[j] = u; - key[j] = ar[u][j]; - } - } - - } - - return parent; - } - - private static int minKey(int[] key, boolean[] visited) { - int min = Integer.MAX_VALUE; - int minIdx = -1; - int length = key.length; - for (int i = 0; i < length; i++) { - if (!visited[i] && key[i] < min) { - min = key[i]; - minIdx = i; - } - } - return minIdx; - } - - public static void main(String[] args) { - // Given graph - int nodes[][] = new int[][] { - {0, 2, 0, 6, 0}, - {2, 0, 3, 8, 5}, - {0, 3, 0, 0, 7}, - {6, 8, 0, 0, 9}, - {0, 5, 7, 9, 0}, - }; - // parent of all the vertices - int parent[] = generate(nodes); - int length = nodes.length; - - // printing the MST (Prism Algorithm) - System.out.println("Edge : Weight"); - for (int i = 1; i < length; i++) { - System.out.println(parent[i] + " - " + i + " : " + nodes[i][parent[i]]); - } - } - -} - diff --git a/misc/algos-master/prims/prims.go b/misc/algos-master/prims/prims.go deleted file mode 100644 index 7f3e138..0000000 --- a/misc/algos-master/prims/prims.go +++ /dev/null @@ -1,71 +0,0 @@ -package main - -import ( - "fmt" - "math" -) - -// Prims finds a minimum spanning tree of given graph, starting at [0] and -// using Prim's algorithm. -func Prims(graph [][]int) []int { - length := len(graph) - // Stores the parent of each vertex - parents := make([]int, length) - // Stores key value of each vertex - keys := make([]int, length) - // true if already included in MST. Otherwise, false. - visited := make([]bool, length) - for i := 0; i < length; i++ { - keys[i] = math.MaxInt32 - } - - // Make the first node the root one (no parent) - keys[0] = 0 - parents[0] = -1 - - for i := 1; i < length; i++ { - // Find the minimum key - u := minKey(keys, visited) - visited[u] = true - - // Update the neighbours - for j := 0; j < length; j++ { - if graph[u][j] != 0 && !visited[j] && graph[u][j] < keys[j] { - parents[j] = u - keys[j] = graph[u][j] - } - } - } - return parents -} - -func minKey(keys []int, visited []bool) int { - min := math.MaxInt32 - minID := -1 - length := len(keys) - for i := 0; i < length; i++ { - if !visited[i] && keys[i] < min { - min = keys[i] - minID = i - } - } - return minID -} - -func main() { - graph := [][]int{ - {0, 2, 0, 6, 0}, - {2, 0, 3, 8, 5}, - {0, 3, 0, 0, 7}, - {6, 8, 0, 0, 9}, - {0, 5, 7, 9, 0}, - } - // Get parents of all the nodes - parents := Prims(graph) - - // Print the Minimum Spanning Tree - fmt.Println("Edge\tWeight") - for i := 1; i < len(graph); i++ { - fmt.Printf("%d - %d\t%d\n", parents[i], i, graph[i][parents[i]]) - } -} diff --git a/misc/algos-master/prims/prims.js b/misc/algos-master/prims/prims.js deleted file mode 100644 index 728b88f..0000000 --- a/misc/algos-master/prims/prims.js +++ /dev/null @@ -1,80 +0,0 @@ -function minKey (key, visited) { - let min = Number.MAX_VALUE; - let minIdx = -1; - let length = key.length; - - for (let i = 0; i < length; i++) { - if (!visited[i] && key[i] < min) { - min = key[i]; - minIdx = i; - } - } - - return minIdx; -} - -function generate (graph) { - /* - * Get the parent nodes in the MST - * :param graph: array which represents the graph - * :return: returns array of parent nodes - */ - let length = graph.length; - - // stores the parent of each vertex - let parent = []; - // key value of each vertex - let key = []; - // flag for included in the MST - let mstSet = []; - - // initialize arguments - for (let i = 0; i < length; i++) { - mstSet[i] = false; - key[i] = Number.MAX_VALUE; - } - - // starting from the first vertex - // the first vertex is the root, so it doesn't have any parent - key[0] = 0; - parent[0] = -1; - - for (let i = 0; i < length - 1; i++) { - // minimum key from given vertices - let u = minKey(key, mstSet); - mstSet[u] = true; - - // updating the neighbours key - for (let j = 0; j < length; j++) { - if (graph[u][j] !== 0 && !mstSet[j] && graph[u][j] < key[j]) { - parent[j] = u; - key[j] = graph[u][j]; - } - } - } - - return parent; -} - -function main () { - // given graph - let graph = [ - [0, 2, 0, 6, 0], - [2, 0, 3, 8, 5], - [0, 3, 0, 0, 7], - [6, 8, 0, 0, 9], - [0, 5, 7, 9, 0] - ]; - - // get the parent nodes of all the vertices - let parent = generate(graph); - let length = graph.length; - - // print the MST - console.log('Edge : Weight'); - for (let i = 1; i < length; i++) { - console.log(parent[i] + ' - ' + i + ' : ' + graph[i][parent[i]]); - } -} - -main(); diff --git a/misc/algos-master/queue/Queue.java b/misc/algos-master/queue/Queue.java deleted file mode 100644 index 5d700cd..0000000 --- a/misc/algos-master/queue/Queue.java +++ /dev/null @@ -1,143 +0,0 @@ -import java.util.NoSuchElementException; - -/** - * Implements https://docs.oracle.com/javase/8/docs/api/java/util/Queue.html - */ -public class Queue { - - private int total; - // Linked Lists used to store the data - private Node first, last; - - private class Node { - - private T data; - private Node next; - - public Node(T data) { - this.data = data; - } - } - - /** - * Inserts the specified element into this queue if it is possible to do so immediately without - * violating capacity restrictions, returning true upon success and throwing an - * IllegalStateException if no space is currently available. - * - * @param element the element to add - * @return true upon success, throwing an IllegalStateException if no space is currently - * available. - */ - public boolean add(T element) { - Node newNode = new Node(element); - - Node current = last; - last = newNode; - - if (total == 0) { - first = last; - } else { - current.next = last; - } - total++; - - return true; - } - - /** - * Inserts the specified element into this queue if it is possible to do so immediately without - * violating capacity restrictions. - * - * @param element the element to add - * @return true if the element was added to this queue, else false - */ - public boolean offer(T element) { - try { - return add(element); - } catch (Exception ex) { - //failed to add, return false - return false; - } - } - - /** - * Retrieves and removes the head of this queue. - * This method differs from poll only in that it throws an exception if this queue is empty. - * - * @return the head of this queue. - * @throws NoSuchElementException if this queue is empty - */ - public T remove() throws NoSuchElementException { - if (total == 0) { - throw new NoSuchElementException(); - } - T element = first.data; - first = first.next; - total--; - if (total == 0) { - last = null; - } - return element; - } - - /** - * Retrieves and removes the head of this queue, or returns null if this queue is empty. - * This method differs from peek only in that it throws an exception if this queue is empty. - * - * @return the head of this queue, or returns null if this queue is empty. - */ - public T poll() { - try { - return remove(); - } catch (Exception ex) { - //failed to remove, return null - return null; - } - } - - /** - * Retrieves, but does not remove, the head of this queue. - * - * @return the head of this queue - * @throws NoSuchElementException if this queue is empty - */ - public T element() throws NoSuchElementException { - if (total == 0) { - throw new NoSuchElementException(); - } - return first.data; - } - - /** - * Retrieves, but does not remove, the head of this queue, or returns null if this queue is empty. - * - * @return the head of this queue, or returns null if this queue is empty. - */ - public T peek() { - return total == 0 ? null : first.data; - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - Node tmp = first; - while (tmp != null) { - sb.append(tmp.data).append(", "); - tmp = tmp.next; - } - return sb.toString(); - } - - public static void main(String[] args) { - Queue queue = new Queue<>(); - for (int i = 1; i <= 10; i++) { // Creates a dummy queue which contains integers from 1-10 - queue.add(i); - } - - System.out.println("Queue :"); - - while (queue.peek() != null) { - System.out.println(queue.poll()); - } - } -} diff --git a/misc/algos-master/quick_select/QuickSelect.java b/misc/algos-master/quick_select/QuickSelect.java deleted file mode 100644 index 3b1f1e3..0000000 --- a/misc/algos-master/quick_select/QuickSelect.java +++ /dev/null @@ -1,64 +0,0 @@ -public class QuickSelect { - /* - * partition function - * array : array on which partitioning has to be done - * left : left index of the partitioning subarray - * right : right index of the partitioning subarray - * pivotIndex : pivot index from which partition has to done - * return : the index of the last element of the left subarray - */ - private static int partition(int[] array, int left, int right, int pivotIndex) { - int pivotValue = array[pivotIndex]; - int temp = array[right]; - array[right] = array[pivotIndex]; - array[pivotIndex] = temp; - int storeIndex = left; - while (left < right) { - if (array[left] < pivotValue) { - temp = array[storeIndex]; - array[storeIndex] = array[left]; - array[left] = temp; - storeIndex++; - } - left++; - } - temp = array[right]; - array[right] = array[storeIndex]; - array[storeIndex] = temp; - return storeIndex; - } - - /* - * Quick Select function - * left : left index of the subarray - * right : right index of the subarray - * pos : position to find the element using quick sort - * return : the value of element at pos place in the sorted array - */ - public static int quickSelect(int[] array, int left, int right, int pos) { - int pivotIndex; - if(pos < 0 || pos >= array.length) { - throw new IndexOutOfBoundsException("index: " + pos); - } - if (left == right) { - return array[left]; - } - pivotIndex = right - 1; - pivotIndex = partition(array, left, right, pivotIndex); - if (pos == pivotIndex) { - return array[pivotIndex]; - } - else if (pos < pivotIndex) { - return quickSelect(array, left, pivotIndex - 1, pos); - } - else { - return quickSelect(array, pivotIndex + 1, right, pos); - } - } - - public static void main(String[] args) { - int[] array = {10, 5, 1, 6, 7, 3, 2, 4, 8, 9}; - System.out.println(quickSelect(array, 0, array.length - 1, 3)); - } - -} diff --git a/misc/algos-master/quick_sort/QuickSort.cs b/misc/algos-master/quick_sort/QuickSort.cs deleted file mode 100644 index d24b6a5..0000000 --- a/misc/algos-master/quick_sort/QuickSort.cs +++ /dev/null @@ -1,110 +0,0 @@ -/* -Time Complexity: Best: O(n log(n)), Average: O(n log(n)), Worst: O(n^2) -Space Complexity: O(log(n)) -*/ - -using System; - -public class QuickSort -{ - - /// - /// Chooses a pivot based on the median of three values in the array (start, mid, end - 1). - /// Pivot is placed at the beginning of the array. - /// - /// The array - /// The start pivoting position in the array - /// The end pivoting position in the array - public static void ChoosePivot(int[] a, int start, int end) - { - int mid = start + (end - start) / 2; - int median = Math.Max(Math.Min(a[start], a[mid]), Math.Min(Math.Max(a[start], a[mid]), a[end - 1])); - int pivotPos = Array.IndexOf(a, median); - Swap(a, pivotPos, start); - } - - /// - /// Partitions an array into two parts based on a pivot. - /// All values smaller than the pivot will be placed before the pivot in the array. - /// All values grater than the pivot will be placed after the pivot in the array - /// - /// The array - /// The start pivoting position in the array - /// The end pivoting position in the array - /// The new position of the pivot in the array - public static int Partition(int[] a, int start, int end) - { - int pivotPos = start; //pivot position (index in the array) - int pivotVal = a[pivotPos]; //the value of the pivot - int bigStart = start + 1; //start index of all values greater than the pivot - - for (int curr = start + 1; curr < end; curr++) - { - if (a[curr] < pivotVal) - { - Swap(a, curr, bigStart); - bigStart++; - } - } - - Swap(a, pivotPos, bigStart - 1); - pivotPos = bigStart - 1; - return pivotPos; - } - - /// - /// Sorts an array using the Quick Sort algorithm - /// - /// The array to sort - /// The start sorting position in the array - /// The end sorting position in the array - public static void DoQuickSort(int[] a, int start, int end) - { - if(end - start == 2) - { - if(a[start] > a[end - 1]) - Swap(a, start, end - 1); - } - else if(end - start > 1) - { - ChoosePivot(a, start, end); - int pivotPos = Partition(a, start, end); - DoQuickSort(a, start, pivotPos); - DoQuickSort(a, pivotPos + 1, end); - } - } - - /// - /// Quick Sort helper method - /// - /// The array to sort - public static void DoQuickSort(int[] a) - { - if (a != null && a.Length > 1) - DoQuickSort(a, 0, a.Length); - } - - /// - /// Swap two index positions in an array - /// - /// The array - /// The first index - /// The second index - public static void Swap(int[] a, int x, int y) - { - int temp = a[x]; - a[x] = a[y]; - a[y] = temp; - } - - public static void Main() - { - int[] arr = new int[] {2, 4, 2, 6, 7, -1}; - DoQuickSort(arr); - foreach(int element in arr) - { - Console.Write(element + " "); - } - Console.WriteLine(""); - } -} diff --git a/misc/algos-master/quick_sort/QuickSort.java b/misc/algos-master/quick_sort/QuickSort.java deleted file mode 100644 index 8b24add..0000000 --- a/misc/algos-master/quick_sort/QuickSort.java +++ /dev/null @@ -1,66 +0,0 @@ -public class QuickSort { - - private static int compare(int[] arr, int i, int j) { - if (arr[i] > arr[j]) { - return i; - } else { - return j; - } - } - - /* - This method returns the index of median of array at i, j, k. - @param arr: Input array to be sorted. - @param i: Left end index of array. - @param j: Right end index of array. - @param k: Middle index of array. - @return: Index of median of array at i, j, k. - */ - private static int median(int[] arr, int i, int j, int k) { - if (arr[i] > arr[j] && arr[i] > arr[k]) { - return compare(arr, k, j); - } else if (arr[j] > arr[i] && arr[j] > arr[k]) { - return compare(arr, k, i); - } else { - return compare(arr, i, j); - } - } - - private static int partition(int[] arr, int start, int end) { - int l = median(arr, start, end, (start + end) / 2); - int p_idx = start - 1; - int tmp = arr[l]; - arr[l] = arr[end]; - arr[end] = tmp; - int pivot = arr[end]; - for (int i = start; i < end; ++i) { - if (arr[i] <= pivot) { - p_idx++; - tmp = arr[i]; - arr[i] = arr[p_idx]; - arr[p_idx] = tmp; - } - } - p_idx++; - tmp = arr[p_idx]; - arr[p_idx] = arr[end]; - arr[end] = tmp; - return p_idx; - } - - public static void quickSort(int[] a, int left, int right) { - if (left < right) { - int pi = partition(a, left, right); //pi index of pivot - quickSort(a, left, pi - 1); //sort left of pivot - quickSort(a, pi + 1, right); //sort right of pivot - } - } - - public static void main(String[] args) { - int[] arr = new int[] {2, 4, 2, 6, 7, -1}; - quickSort(arr, 0, arr.length - 1); - for (int element : arr) { - System.out.println(element); - } - } -} diff --git a/misc/algos-master/quick_sort/quickSort.js b/misc/algos-master/quick_sort/quickSort.js deleted file mode 100644 index 01a98c7..0000000 --- a/misc/algos-master/quick_sort/quickSort.js +++ /dev/null @@ -1,83 +0,0 @@ -/* -* Implementation of quicksort algorithm -* Time complexity: O(nlogn) -* Space complexity: O(n) -* n is the size of array -*/ -function median (arr, i, j, k) { - /* - :param arr: array of elements - :param i: index of first element - :param j: index of last element - :param k: index of middle element - :return: return median of values at indices i, j and k - */ - if (arr[i] > arr[j] && arr[i] > arr[k]) { - if (arr[k] > arr[j]) { - return k; - } else { - return j; - } - } else if (arr[j] > arr[i] && arr[j] > arr[k]) { - if (arr[k] > arr[i]) { - return k; - } else { - return i; - } - } else { - if (arr[i] > arr[j]) { - return i; - } else { - return j; - } - } -} - -function partition (arr, start, end) { - /* - :param arr: array of elements - :param start: index of first element - :param end: index of last element - :return: return value for function, used in partitioning of array - */ - let j = start - 1; - let tmp; - let pi = median(arr, start, end, parseInt((start + end) / 2)); - tmp = arr[pi]; - arr[pi] = arr[end]; - arr[end] = tmp; - let pivot = arr[end]; - for (let i = start; i < end; i++) { - if (arr[i] <= pivot) { - j++; - tmp = arr[i]; - arr[i] = arr[j]; - arr[j] = tmp; - } - } - tmp = arr[j + 1]; - arr[j + 1] = arr[end]; - arr[end] = tmp; - return j + 1; -} - -function quickSort (arr, left = 0, right = arr.length - 1) { - /* - :param arr: array to be sorted - :param left: index of first element - :param right: index of last element - */ - if (left < right) { - let p = partition(arr, left, right); - quickSort(arr, left, p - 1); - quickSort(arr, p + 1, right); - } -} - -function main () { - let arr = [2, 1, 6, 44, 8, 9, 10]; - quickSort(arr); - console.log('Sorted data is', arr); -} - -main(); diff --git a/misc/algos-master/quick_sort/quick_sort.go b/misc/algos-master/quick_sort/quick_sort.go deleted file mode 100644 index 5367773..0000000 --- a/misc/algos-master/quick_sort/quick_sort.go +++ /dev/null @@ -1,50 +0,0 @@ -package main - -import "fmt" - -// partitionArray finds the pivot index -func partitionArray(data []int, left int, right int) int { - pivotIndex := left - for true { - for data[pivotIndex] <= data[right] && pivotIndex != right { - right-- - } - if pivotIndex == right { - break - } else if data[pivotIndex] > data[right] { - data[right], data[pivotIndex] = data[pivotIndex], data[right] - pivotIndex = right - } - for data[pivotIndex] >= data[left] && pivotIndex != left { - left++ - } - if pivotIndex == left { - break - } else if data[pivotIndex] < data[left] { - data[left], data[pivotIndex] = data[pivotIndex], data[left] - pivotIndex = left - } - } - return pivotIndex -} - -func quickSort(data []int, begin int, end int) { - if begin < end { - pivotIndex := partitionArray(data, begin, end) - quickSort(data, begin, pivotIndex-1) - quickSort(data, pivotIndex+1, end) - } -} - -// QuickSort sorts data by quicksort algorithm -// Time complexity : O(n log n) -// Space Complexity : O(n) -func QuickSort(data []int) { - quickSort(data, 0, len(data)-1) -} - -func main() { - data := []int{1, 1122002, 2, 88171, 6754, 79901, 119856, -312, 1, -2} - QuickSort(data) - fmt.Println(data) -} diff --git a/misc/algos-master/trie/Trie.java b/misc/algos-master/trie/Trie.java deleted file mode 100644 index d4f425c..0000000 --- a/misc/algos-master/trie/Trie.java +++ /dev/null @@ -1,108 +0,0 @@ -import java.util.HashMap; -import java.util.Map; - -/** - * Implement a trie with insert, search, and starts with methods using hash map. - */ -class TrieNode { - public char character ; - // has map store trie node - public HashMap children = new HashMap(); - public boolean isLeaf; - - public TrieNode() { - } - - public TrieNode(char character) { - this.character = character; - } -} - -public class Trie { - private TrieNode root; - // constructor - public Trie() { - root = new TrieNode(); - } - - /* Insert into the Trie - * args : - * key : String to insert into Trie - * Time Complexity: O(len(word)) - */ - public void insert(String word) { - HashMap children = root.children; - // insert word char by char - for (int i = 0; i < word.length(); i++) { - char character = word.charAt(i); - TrieNode root; - /* Check status of that child node - * If it is empty, them fill it - * If it is present, them use this as the next root - */ - if (children.containsKey(character)) { - root = children.get(character); - } else { - root = new TrieNode(character); - children.put(character, root); - } - children = root.children; - //set leaf node - if (i == word.length() - 1) - root.isLeaf = true; - } - } - - /* Searches into the Trie - * args: - * key : string to search into Trie - * Time complexity : O(len(word)) - */ - public boolean search(String word) { - TrieNode root = searchNode(word); - // if valid words return true - return root != null && root.isLeaf; - } - - /** Returns if there is any word in the trie - * that start with the given prefix. - */ - public boolean startsWith(String prefix) { - // words not start with prefix then return false - return searchNode(prefix) == null; - } - - public TrieNode searchNode(String str) { - Map children = root.children; - TrieNode root = null; - // validate the words - for (int i = 0; i < str.length(); i++) { - char character = str.charAt(i); - if (children.containsKey(character)) { - root = children.get(character); - children = root.children; - } else { - return null; - } - } - return root; - } - - public static void main(String[] args) { - Trie node = new Trie(); - // Input keys words - node.insert("the"); - node.insert("a"); - node.insert("there"); - node.insert("answer"); - node.insert("any"); - node.insert("by"); - node.insert("bye"); - node.insert("their"); - // Search for different keys words - System.out.println(node.search("the")); - System.out.println(node.search("these")); - System.out.println(node.search("thaw")); - System.out.println(node.search("their")); - } -} diff --git a/misc/algos-master/avl_tree/avl_tree.c b/misc/avl_tree/avl_tree.c similarity index 100% rename from misc/algos-master/avl_tree/avl_tree.c rename to misc/avl_tree/avl_tree.c diff --git a/misc/algos-master/bin_sort/bin_sort.c b/misc/bin_sort/bin_sort.c similarity index 100% rename from misc/algos-master/bin_sort/bin_sort.c rename to misc/bin_sort/bin_sort.c diff --git a/misc/algos-master/bin_sort/bin_sort.py b/misc/bin_sort/bin_sort.py similarity index 100% rename from misc/algos-master/bin_sort/bin_sort.py rename to misc/bin_sort/bin_sort.py diff --git a/misc/algos-master/binary_search/binary_search.c b/misc/binary_search/binary_search.c similarity index 100% rename from misc/algos-master/binary_search/binary_search.c rename to misc/binary_search/binary_search.c diff --git a/misc/algos-master/binary_search/binary_search.py b/misc/binary_search/binary_search.py similarity index 100% rename from misc/algos-master/binary_search/binary_search.py rename to misc/binary_search/binary_search.py diff --git a/misc/algos-master/binary_search_tree/BinarySearchTree.py b/misc/binary_search_tree/BinarySearchTree.py similarity index 100% rename from misc/algos-master/binary_search_tree/BinarySearchTree.py rename to misc/binary_search_tree/BinarySearchTree.py diff --git a/misc/algos-master/breadth_first_search/breadth_first_search.py b/misc/breadth_first_search/breadth_first_search.py similarity index 100% rename from misc/algos-master/breadth_first_search/breadth_first_search.py rename to misc/breadth_first_search/breadth_first_search.py diff --git a/misc/algos-master/breadth_first_traversal/breadth_first_traversal.py b/misc/breadth_first_traversal/breadth_first_traversal.py similarity index 100% rename from misc/algos-master/breadth_first_traversal/breadth_first_traversal.py rename to misc/breadth_first_traversal/breadth_first_traversal.py diff --git a/misc/algos-master/coin_change_problem/coin_change_problem.c b/misc/coin_change_problem/coin_change_problem.c similarity index 100% rename from misc/algos-master/coin_change_problem/coin_change_problem.c rename to misc/coin_change_problem/coin_change_problem.c diff --git a/misc/algos-master/coin_change_problem/coin_change_problem.py b/misc/coin_change_problem/coin_change_problem.py similarity index 100% rename from misc/algos-master/coin_change_problem/coin_change_problem.py rename to misc/coin_change_problem/coin_change_problem.py diff --git a/misc/algos-master/counting_sort/counting_sort.c b/misc/counting_sort/counting_sort.c similarity index 100% rename from misc/algos-master/counting_sort/counting_sort.c rename to misc/counting_sort/counting_sort.c diff --git a/misc/algos-master/counting_sort/counting_sort.py b/misc/counting_sort/counting_sort.py similarity index 100% rename from misc/algos-master/counting_sort/counting_sort.py rename to misc/counting_sort/counting_sort.py diff --git a/misc/algos-master/depth_first_traversal/DepthFirstTraversal.py b/misc/depth_first_traversal/DepthFirstTraversal.py similarity index 100% rename from misc/algos-master/depth_first_traversal/DepthFirstTraversal.py rename to misc/depth_first_traversal/DepthFirstTraversal.py diff --git a/misc/algos-master/dijkstra/dijkstra.c b/misc/dijkstra/dijkstra.c similarity index 100% rename from misc/algos-master/dijkstra/dijkstra.c rename to misc/dijkstra/dijkstra.c diff --git a/misc/algos-master/dijkstra/dijkstra.py b/misc/dijkstra/dijkstra.py similarity index 100% rename from misc/algos-master/dijkstra/dijkstra.py rename to misc/dijkstra/dijkstra.py diff --git a/misc/algos-master/euclidean_gcd/euclidean_gcd.c b/misc/euclidean_gcd/euclidean_gcd.c similarity index 100% rename from misc/algos-master/euclidean_gcd/euclidean_gcd.c rename to misc/euclidean_gcd/euclidean_gcd.c diff --git a/misc/algos-master/euclidean_gcd/euclidean_gcd.py b/misc/euclidean_gcd/euclidean_gcd.py similarity index 100% rename from misc/algos-master/euclidean_gcd/euclidean_gcd.py rename to misc/euclidean_gcd/euclidean_gcd.py diff --git a/misc/algos-master/exponentiation_by_squaring/exponentiation_by_squaring.c b/misc/exponentiation_by_squaring/exponentiation_by_squaring.c similarity index 100% rename from misc/algos-master/exponentiation_by_squaring/exponentiation_by_squaring.c rename to misc/exponentiation_by_squaring/exponentiation_by_squaring.c diff --git a/misc/algos-master/exponentiation_by_squaring/exponentiation_by_squaring.py b/misc/exponentiation_by_squaring/exponentiation_by_squaring.py similarity index 100% rename from misc/algos-master/exponentiation_by_squaring/exponentiation_by_squaring.py rename to misc/exponentiation_by_squaring/exponentiation_by_squaring.py diff --git a/misc/algos-master/heap_sort/heap_sort.c b/misc/heap_sort/heap_sort.c similarity index 100% rename from misc/algos-master/heap_sort/heap_sort.c rename to misc/heap_sort/heap_sort.c diff --git a/misc/algos-master/heap_sort/heap_sort.py b/misc/heap_sort/heap_sort.py similarity index 100% rename from misc/algos-master/heap_sort/heap_sort.py rename to misc/heap_sort/heap_sort.py diff --git a/misc/algos-master/insertion_sort/insertion_sort.c b/misc/insertion_sort/insertion_sort.c similarity index 100% rename from misc/algos-master/insertion_sort/insertion_sort.c rename to misc/insertion_sort/insertion_sort.c diff --git a/misc/algos-master/insertion_sort/insertion_sort.py b/misc/insertion_sort/insertion_sort.py similarity index 100% rename from misc/algos-master/insertion_sort/insertion_sort.py rename to misc/insertion_sort/insertion_sort.py diff --git a/misc/algos-master/k_nn/k_nn.py b/misc/k_nn/k_nn.py similarity index 100% rename from misc/algos-master/k_nn/k_nn.py rename to misc/k_nn/k_nn.py diff --git a/misc/algos-master/largest_sum_contiguous_subarray/largestSumContiguousSubarray.c b/misc/largest_sum_contiguous_subarray/largestSumContiguousSubarray.c similarity index 100% rename from misc/algos-master/largest_sum_contiguous_subarray/largestSumContiguousSubarray.c rename to misc/largest_sum_contiguous_subarray/largestSumContiguousSubarray.c diff --git a/misc/algos-master/largest_sum_contiguous_subarray/largest_sum_contiguous_subarray.py b/misc/largest_sum_contiguous_subarray/largest_sum_contiguous_subarray.py similarity index 100% rename from misc/algos-master/largest_sum_contiguous_subarray/largest_sum_contiguous_subarray.py rename to misc/largest_sum_contiguous_subarray/largest_sum_contiguous_subarray.py diff --git a/misc/algos-master/linear_regression/linear_regression.py b/misc/linear_regression/linear_regression.py similarity index 100% rename from misc/algos-master/linear_regression/linear_regression.py rename to misc/linear_regression/linear_regression.py diff --git a/misc/algos-master/linear_search/linear_search.c b/misc/linear_search/linear_search.c similarity index 100% rename from misc/algos-master/linear_search/linear_search.c rename to misc/linear_search/linear_search.c diff --git a/misc/algos-master/linear_search/linear_search.py b/misc/linear_search/linear_search.py similarity index 100% rename from misc/algos-master/linear_search/linear_search.py rename to misc/linear_search/linear_search.py diff --git a/misc/algos-master/linked_list/linkedList.c b/misc/linked_list/linkedList.c similarity index 100% rename from misc/algos-master/linked_list/linkedList.c rename to misc/linked_list/linkedList.c diff --git a/misc/algos-master/linked_list/linked_list.py b/misc/linked_list/linked_list.py similarity index 100% rename from misc/algos-master/linked_list/linked_list.py rename to misc/linked_list/linked_list.py diff --git a/misc/algos-master/longest_common_subsequence/longestCommonSubsequence.c b/misc/longest_common_subsequence/longestCommonSubsequence.c similarity index 100% rename from misc/algos-master/longest_common_subsequence/longestCommonSubsequence.c rename to misc/longest_common_subsequence/longestCommonSubsequence.c diff --git a/misc/algos-master/longest_common_subsequence/longest_common_subsequence.py b/misc/longest_common_subsequence/longest_common_subsequence.py similarity index 100% rename from misc/algos-master/longest_common_subsequence/longest_common_subsequence.py rename to misc/longest_common_subsequence/longest_common_subsequence.py diff --git a/misc/algos-master/longest_palindromic_substring/longest_palindromic_substring.cpp b/misc/longest_palindromic_substring/longest_palindromic_substring.cpp similarity index 100% rename from misc/algos-master/longest_palindromic_substring/longest_palindromic_substring.cpp rename to misc/longest_palindromic_substring/longest_palindromic_substring.cpp diff --git a/misc/algos-master/longest_palindromic_substring/longest_palindromic_substring.py b/misc/longest_palindromic_substring/longest_palindromic_substring.py similarity index 100% rename from misc/algos-master/longest_palindromic_substring/longest_palindromic_substring.py rename to misc/longest_palindromic_substring/longest_palindromic_substring.py diff --git a/misc/algos-master/merge_sort/merge_sort.c b/misc/merge_sort/merge_sort.c similarity index 100% rename from misc/algos-master/merge_sort/merge_sort.c rename to misc/merge_sort/merge_sort.c diff --git a/misc/algos-master/merge_sort/merge_sort.py b/misc/merge_sort/merge_sort.py similarity index 100% rename from misc/algos-master/merge_sort/merge_sort.py rename to misc/merge_sort/merge_sort.py diff --git a/misc/algos-master/modular_exponential/modular_exponential.c b/misc/modular_exponential/modular_exponential.c similarity index 100% rename from misc/algos-master/modular_exponential/modular_exponential.c rename to misc/modular_exponential/modular_exponential.c diff --git a/misc/algos-master/modular_exponential/modular_exponential.py b/misc/modular_exponential/modular_exponential.py similarity index 100% rename from misc/algos-master/modular_exponential/modular_exponential.py rename to misc/modular_exponential/modular_exponential.py diff --git a/misc/algos-master/n_queen_problem/NQueenProblem.cpp b/misc/n_queen_problem/NQueenProblem.cpp similarity index 100% rename from misc/algos-master/n_queen_problem/NQueenProblem.cpp rename to misc/n_queen_problem/NQueenProblem.cpp diff --git a/misc/algos-master/n_queen_problem/n_queen_problem.py b/misc/n_queen_problem/n_queen_problem.py similarity index 100% rename from misc/algos-master/n_queen_problem/n_queen_problem.py rename to misc/n_queen_problem/n_queen_problem.py diff --git a/misc/algos-master/prime_factor/prime_factor.c b/misc/prime_factor/prime_factor.c similarity index 100% rename from misc/algos-master/prime_factor/prime_factor.c rename to misc/prime_factor/prime_factor.c diff --git a/misc/algos-master/prime_factor/prime_factor.py b/misc/prime_factor/prime_factor.py similarity index 100% rename from misc/algos-master/prime_factor/prime_factor.py rename to misc/prime_factor/prime_factor.py diff --git a/misc/algos-master/prims/prims.c b/misc/prims/prims.c similarity index 100% rename from misc/algos-master/prims/prims.c rename to misc/prims/prims.c diff --git a/misc/algos-master/queue/queue.py b/misc/queue/queue.py similarity index 100% rename from misc/algos-master/queue/queue.py rename to misc/queue/queue.py diff --git a/misc/algos-master/quick_select/quick_select.c b/misc/quick_select/quick_select.c similarity index 100% rename from misc/algos-master/quick_select/quick_select.c rename to misc/quick_select/quick_select.c diff --git a/misc/algos-master/quick_select/quick_select.py b/misc/quick_select/quick_select.py similarity index 100% rename from misc/algos-master/quick_select/quick_select.py rename to misc/quick_select/quick_select.py diff --git a/misc/algos-master/quick_sort/quick_sort.py b/misc/quick_sort/quick_sort.py similarity index 100% rename from misc/algos-master/quick_sort/quick_sort.py rename to misc/quick_sort/quick_sort.py diff --git a/misc/algos-master/quick_sort/quicksort.c b/misc/quick_sort/quicksort.c similarity index 100% rename from misc/algos-master/quick_sort/quicksort.c rename to misc/quick_sort/quicksort.c diff --git a/misc/algos-master/radix_sort/radix_sort.c b/misc/radix_sort/radix_sort.c similarity index 100% rename from misc/algos-master/radix_sort/radix_sort.c rename to misc/radix_sort/radix_sort.c diff --git a/misc/algos-master/radix_sort/radix_sort.py b/misc/radix_sort/radix_sort.py similarity index 100% rename from misc/algos-master/radix_sort/radix_sort.py rename to misc/radix_sort/radix_sort.py diff --git a/misc/algos-master/rod_cutting_problem/rod_cutting.c b/misc/rod_cutting_problem/rod_cutting.c similarity index 100% rename from misc/algos-master/rod_cutting_problem/rod_cutting.c rename to misc/rod_cutting_problem/rod_cutting.c diff --git a/misc/algos-master/rod_cutting_problem/rod_cutting.py b/misc/rod_cutting_problem/rod_cutting.py similarity index 100% rename from misc/algos-master/rod_cutting_problem/rod_cutting.py rename to misc/rod_cutting_problem/rod_cutting.py diff --git a/misc/algos-master/shell_sort/ShellSort.cpp b/misc/shell_sort/ShellSort.cpp similarity index 100% rename from misc/algos-master/shell_sort/ShellSort.cpp rename to misc/shell_sort/ShellSort.cpp diff --git a/misc/algos-master/shell_sort/shell_sort.py b/misc/shell_sort/shell_sort.py similarity index 100% rename from misc/algos-master/shell_sort/shell_sort.py rename to misc/shell_sort/shell_sort.py diff --git a/misc/algos-master/sieve_of_eratosthenes/sieveOfEratosthenes.c b/misc/sieve_of_eratosthenes/sieveOfEratosthenes.c similarity index 100% rename from misc/algos-master/sieve_of_eratosthenes/sieveOfEratosthenes.c rename to misc/sieve_of_eratosthenes/sieveOfEratosthenes.c diff --git a/misc/algos-master/sieve_of_eratosthenes/sieve_of_eratosthenes.py b/misc/sieve_of_eratosthenes/sieve_of_eratosthenes.py similarity index 100% rename from misc/algos-master/sieve_of_eratosthenes/sieve_of_eratosthenes.py rename to misc/sieve_of_eratosthenes/sieve_of_eratosthenes.py diff --git a/misc/algos-master/sleep_sort/sleep_sort.cpp b/misc/sleep_sort/sleep_sort.cpp similarity index 100% rename from misc/algos-master/sleep_sort/sleep_sort.cpp rename to misc/sleep_sort/sleep_sort.cpp diff --git a/misc/algos-master/sleep_sort/sleep_sort.py b/misc/sleep_sort/sleep_sort.py similarity index 100% rename from misc/algos-master/sleep_sort/sleep_sort.py rename to misc/sleep_sort/sleep_sort.py diff --git a/misc/algos-master/stack/stack.c b/misc/stack/stack.c similarity index 100% rename from misc/algos-master/stack/stack.c rename to misc/stack/stack.c diff --git a/misc/algos-master/stack/stack.py b/misc/stack/stack.py similarity index 100% rename from misc/algos-master/stack/stack.py rename to misc/stack/stack.py diff --git a/misc/algos-master/trie/trie.cpp b/misc/trie/trie.cpp similarity index 100% rename from misc/algos-master/trie/trie.cpp rename to misc/trie/trie.cpp