[
  {
    "path": ".github/ISSUE_TEMPLATE/Documentation.yml",
    "content": "name: Documentation\ndescription: Select this to document the repo\ntitle: \"Directory You Purpose to Document\"\nlabels: [\"Hacktoberfest2021\", \"Hacktoberfest\", \"new submssion\", \"first timer\", \"good first issue\", \n\"documentation\"]\nassignees:\n  - octocat\nbody:\n  - type: markdown\n    attributes:\n      value: |\n        Before starting please take a look at [this](https://github.com/ahampriyanshu/algo_ds_101/tree/main/DOCUMENTATION.md), [this](https://dsa.ahampriyanshu.com/DOCUMENTATION) and [this](https://dsa.ahampriyanshu.com/Data-Structures/Queue/).\n  - type: input\n    id: directory\n    attributes:\n      label: Directory\n      description: Path to the readme file\n      placeholder: Algorithm => Sorting => Merge-Sort => README.md\n    validations:\n      required: true\n  - type: checkboxes\n    id: language\n    attributes:\n      label: Things To Remember\n      description: Please check the following\n      options:\n        - label: The content added isn't directly copied from any sources like gfg, tutorialpoint, etc. For theory, use open-source alternatives like WikiPedia.\n        - label: I have used github flavoured md syntax only.\n        - label: All the relative links are working.\n        - label: All the absolute links are working.\n        - label: I have synced-up my forked repo.\n        - label: Ain't pushing from the main branch.\n"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/New-Submission.yml",
    "content": "name: New Submission\ndescription: Select this to submit new Algorithm/Data-Structure/STL/...\ntitle: \"Title of the Submission\"\nlabels: [\"Hacktoberfest\", \"new submission\", \"first timer\", \"good first issue\"]\nassignees:\n  - octocat\nbody:\n  - type: markdown\n    attributes:\n      value: |\n        I have verified that this issue doesn't already exist.\n  - type: dropdown\n    id: type\n    attributes:\n      label: Type\n      description: Type of the submission\n      options:\n        - Algorithm\n        - Data-Structure\n        - Maths\n        - STL\n        - Collection\n    validations:\n      required: true\n  - type: input\n    id: directory\n    attributes:\n      label: Directory\n      description: Location of the new file\n      placeholder: Algorithm => Sorting => Merge-Sort => Merge-Sort.ext\n    validations:\n      required: true\n  - type: textarea\n    id: description\n    attributes:\n      label: Description\n      description: Describe the submission\n      placeholder: A linked list is a linear collection of data elements whose ...\n    validations:\n      required: true\n  - type: checkboxes\n    id: language\n    attributes:\n      label: Programming Language\n      description: programming language\n      options:\n        - label: c++\n        - label: c\n        - label: python\n        - label: java\n        - label: kotlin\n        - label: javascript\n        - label: typescript\n        - label: c#\n        - label: swift\n        - label: ruby\n        - label: scala\n        - label: go\n        - label: php\n        - label: haskell\n        - label: bash\n"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/config.yml",
    "content": "blank_issues_enabled: false"
  },
  {
    "path": ".github/pull_request_template.md",
    "content": "## Assigned Issue Number ?\n#Issue_Number\n\n## Location of the file(s) ?\nFolder => Sub-Folder => ... => File.extension\n\n### Checklist\n\n- [ ] **I've followed the [contributing guidelines](https://github.com/ahampriyanshu/algo_ds_101/blob/main/CONTRIBUTING.md)**\n- [ ] The content added isn't directly copied from any sources like gfg, tutorialpoint, etc.\n- [ ] Input has been taken dynamically.\n- [ ] I've referred the correct issue number.\n- [ ] Comments have been added\n- [ ] I've  synced-up my forked repo.\n- [ ] Ain't pushing from the main branch.\n"
  },
  {
    "path": ".github/workflows/contributors.yml",
    "content": "name: Add contributors\non:\n  schedule:\n    - cron: '0 0 * * *'\n\njobs:\n  add-contributors:\n    runs-on: ubuntu-latest\n    steps:\n    - uses: actions/checkout@v2\n    - uses: BobAnkh/add-contributors@master\n      with:\n        REPO_NAME: 'ahampriyanshu/algo_ds_101'\n        CONTRIBUTOR: '### Contributors'\n        COLUMN_PER_ROW: '6'\n        ACCESS_TOKEN: ${{secrets.GITHUB_TOKEN}}\n        IMG_WIDTH: '100'\n        FONT_SIZE: '14'\n        PATH: '/CONTRIBUTORS.md'\n        COMMIT_MESSAGE: 'Updating Contributors'\n        AVATAR_SHAPE: 'square'\n"
  },
  {
    "path": ".github/workflows/welcome.yml",
    "content": "name: Welcome\non:\n  pull_request:\n    types: [opened, closed]\n  issues:\n    types: [opened]\njobs:\n  run:\n    runs-on: ubuntu-latest\n    steps:\n      - uses: bubkoo/welcome-action@v1\n        with:\n          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}\n          FIRST_ISSUE: |\n            👋 @{{ author }}\n             Thanks for opening your first issue here! Be sure to follow the issue template!\n             Regards @ahampriyanshu :v:\n\n          FIRST_PR: |\n            👋 @{{ author }}\n            Thanks for opening this pull request! Please check out our contributing guidelines.\n            Regards @ahampriyanshu :v:\n\n          FIRST_PR_MERGED: |\n            🎉 @{{ author }}\n            Congrats on merging your first pull request! Happy contributing!\n            Regards @ahampriyanshu :v:\n"
  },
  {
    "path": "404.md",
    "content": "---\ntitle: 404!\npermalink: /404.html\n---\n<center>\n<img src='https://user-images.githubusercontent.com/54521023/105541932-8f544a00-5d1e-11eb-82cb-8de5071998bc.png' alt='404'/>\n</center>"
  },
  {
    "path": "Algorithms/Array/Arr4 right shift.c",
    "content": "\r\n\r\n#include<stdio.h>\r\n\r\n#define MAX 5 \r\n\r\nvoid AcceptArray(int *Arr1 , int n)\r\n{\r\n\tint cnt ;\r\n\tint x ;\r\n\tint *ptr = Arr1 ;\r\n\tprintf(\"Accept an array\");\r\n\tfor(cnt=0;cnt<n ; cnt++)\r\n\t{\r\n\t\tprintf(\"enter the %d element \\n \",cnt);\r\n\t\tscanf(\"%d\",&x);\r\n\t\tprintf(\"ptr is at %x \\n\",ptr);\r\n\t\t*ptr=x;\r\n\t\tptr++;\t\r\n\t}\r\n\t*ptr=-1;\r\n\t\r\n}\r\nvoid DisplayArray(int *Arr1[],int n )\r\n{\r\n\tint cnt ;int x;\r\n\tint *ptr=Arr1;\r\n\t\r\n\tfor(cnt=n-1; cnt>0 ; cnt--)\r\n\t{\r\n\t\tprintf(\"cnt=%d ptr =%x ptr -1 %x \\n \",cnt ,ptr ,(ptr-1));\r\n\t\tx=*(ptr-1);\r\n\t\t*ptr=x;\r\n\t//\tprintf(\"%d\",*ptr);\r\n\t\tptr--;\t\t\r\n\t}\r\n\t*ptr=-1;\r\n\r\n\t\r\n}\r\nvoid main(void)\r\n{\r\n\tint Arr[MAX];\r\n\tint cnt ;\r\n\tint x ;\r\n\t\r\n\tprintf(\"in main %x \",&Arr[0]);\r\n\tprintf(\"\\n enter your array \\n\");\r\n\tAcceptArray(Arr,MAX);\r\n\tprintf(\"\\n you have entered \\n \");\r\n\tDisplayArray(Arr,MAX );\r\n\t\r\n\t\r\n\t\r\n}\r\n\r\n"
  },
  {
    "path": "Algorithms/Array/InsertArray.c",
    "content": "#include <stdio.h>\n#define max 10\n\nint main()\n{\n    int array[max], pos, i, n, value;\n    printf(\"Enter number of elements in array: \");\n    scanf(\"%d\", &n);\n    if (n <= max)\n    {\n        printf(\"Enter %d elements:\\n\", n);\n\n        for (i = 0; i < n; i++)\n        {\n            scanf(\"%d\\n\", &array[i]);\n        }\n        printf(\"Enter the location where you want to insert an element: \");\n        scanf(\"%d\", &pos);\n\n        printf(\"Enter the value to insert: \");\n        scanf(\"%d\", &value);\n\n        for (i = n - 1; i >= pos - 1; i--)\n            array[i + 1] = array[i];\n\n        array[pos - 1] = value;\n\n        printf(\"Resultant array:\\n\");\n\n        for (i = 0; i <= n; i++)\n            printf(\"%d\\n\", array[i]);\n    }\n    else\n    {\n        printf(\"Array out of bound.\");\n    }\n\n    return 0;\n}\n"
  },
  {
    "path": "Algorithms/Array/LinearSearch.java",
    "content": "\npublic class Main {\n{\n   public static void main(String[] args)\n   {\n      // Validate command line arguments count.\n\n      if (args.length != 2)\n      {\n         System.err.println(\"usage: java LinearSearch integers integer\");\n         return;\n      }\n\n      // Read integers from first command-line argument. Return if integers \n      // could not be read.\n\n      int[] ints = readIntegers(args[0]);\n      if (ints == null)\n         return;\n\n      // Read search integer; NumberFormatException is thrown if the integer\n      // isn't valid.\n\n      int srchint = Integer.parseInt(args[1]);\n\n      // Perform the search and output the result.\n\n      System.out.println(srchint + (search(ints, srchint) ? \" found\"\n                                                          : \" not found\"));\n   }\n\n   private static int[] readIntegers(String s)\n   {\n      String[] tokens = s.split(\",\");\n      int[] integers = new int[tokens.length];\n      for (int i = 0; i < tokens.length; i++)\n         integers[i] = Integer.parseInt(tokens[i]);\n      return integers;\n   }\n\n   private static boolean search(int[] x, int srchint)\n   {\n      for (int i = 0; i < x.length; i++)\n         if (srchint == x[i])\n            return true;\n\n      return false;\n   }\n}\n}\n"
  },
  {
    "path": "Algorithms/Array/Merge-Sorted-Array.c",
    "content": "#include<stdio.h>\n#include<stdlib.h>\nint cmpfunc (const void * a, const void * b) {\n   return ( *(int*)a - *(int*)b );\n}\n\nint main()\n{\n \tint aSize, bSize, cSize, mSize, i, j;\n\tint a[10], b[10], c[10], Merged[20];\n  \n \tprintf(\"\\n Please Enter the First Array Size  :  \");\n \tscanf(\"%d\", &aSize);\n \n \tprintf(\"\\nPlease Enter the First Array Elements :  \");\n \tfor(i = 0; i < aSize; i++)\n  \t{\n      \tscanf(\"%d\", &a[i]);\n  \t}\n  \tprintf(\"\\n Please Enter the Second Array Size  :  \");\n \tscanf(\"%d\", &bSize);\n   \n \tprintf(\"\\nPlease Enter the Second Array Elements  :  \");\n \tfor(i = 0; i < bSize; i++)\n  \t{\n      \tscanf(\"%d\", &b[i]);\n  \t}\n  \tprintf(\"\\n Please Enter the Third Array Size  :  \");\n \tscanf(\"%d\", &cSize);\n \tprintf(\"\\nPlease Enter the Third Array Elements  :  \");\n    for(i = 0; i < cSize; i++)\n  \t{\n      \tscanf(\"%d\", &c[i]);\n  \t}\n  \tfor(i = 0; i < aSize; i++)\n  \t{\n      \tMerged[i] = a[i];\n  \t}\n\tmSize = aSize + bSize;\n \n \tfor(i = 0, j = aSize; j < mSize && i < bSize; i++, j++)\n  \t{\n  \t\tMerged[j] = b[i];\n  \t}\n  \tmSize = aSize + bSize + cSize;\n  \tfor(i = 0, j = aSize + bSize; j < mSize && i < cSize; i++, j++)\n  \t{\n  \t\tMerged[j] = c[i];\n  \t}\n    qsort(Merged,mSize,sizeof(int),cmpfunc);\n \tprintf(\"\\n a[%d] Array Elements After Merging \\n\", mSize); \n \tfor(i = 0; i < mSize; i++)\n  \t{\n    \tprintf(\" %d \\t \",Merged[i]);\n  \t}\n \n  \treturn 0;\n}"
  },
  {
    "path": "Algorithms/Array/Merge-Sorted-Array.cpp",
    "content": "#include<bits/stdc++.h> \r\nusing namespace std; \r\n#define n 4 \r\n\r\n\r\nvoid printArray(int arr[], int size) \r\n{ \r\nfor (int i=0; i < size; i++) \r\n\tcout << arr[i] << \" \"; \r\n} \r\n\r\nvoid mergeKArrays(int arr[][n], int a, int output[]) \r\n{ \r\n\tint c=0; \r\n\t\r\n\tfor(int i=0; i<a; i++) \r\n\t{ \r\n\t\tfor(int j=0; j<n ;j++) \r\n\t\t\toutput[c++]=arr[i][j]; \r\n\t} \r\n\t\r\n\tsort(output,output + n*a); \r\n\t\r\n} \r\n\r\n\r\nint main() \r\n{\r\n\tint arr[][n] = {{2, 6, 12, 34}, \r\n\t\t\t\t\t{1, 9, 20, 1000}, \r\n\t\t\t\t\t{23, 34, 90, 2000}}; \r\n\tint k = sizeof(arr)/sizeof(arr[0]); \r\n\t\r\n\tint output[n*k]; \r\n\t\r\n\tmergeKArrays(arr, 3, output); \r\n\r\n\tcout << \"Merged array is \" << endl; \r\n\tprintArray(output, n*k); \r\n\r\n\treturn 0; \r\n} \r\n"
  },
  {
    "path": "Algorithms/Array/Merge-Sorted-Array.js",
    "content": "// Merge_sorted_array\n\nfunction mergeSorted(a, b) {\n    var answer = new Array(a.length + b.length), i = 0, j = 0, k = 0;\n    while (i < a.length && j < b.length) {\n      if (a[i] < b[j]) {\n          answer[k] = a[i];\n          i++;\n      }else {\n          answer[k] = b[j];\n          j++;\n      }\n      k++;\n    }\n    while (i < a.length) {\n      answer[k] = a[i];\n      i++;\n      k++;\n    }\n    while (j < b.length) {\n      answer[k] = b[j];\n      j++;\n      k++;\n    }\n    return answer;\n  }\n\n\n  // Merge All array that we pass.\n  var mergeAll = function(){\n      return Array.prototype.slice.call(arguments).reduce(mergeSorted);\n  };\n  \n\n  //Number of Sorted_Array to be merge\n  var a = [2, 4, 7,9];\n  var b = [3, 6, 11, 12];\n  var c = [5, 8, 10, 13];\n  \n  console.log(mergeAll(a,b,c).map(function(x){return x;}));\n\n\n  /* input arrays :\n   * a = [2, 4, 7,9];\n   * b = [3, 6, 11, 12];\n   * c = [5, 8, 10, 13];\n   * output single_array :\n   * 2 3 4 5 6 7 8 9 10 11 12 13\n   * /"
  },
  {
    "path": "Algorithms/Array/Merge-Sorted-Array.py",
    "content": "\nfrom heapq import merge \ndef mergeK(arr, k):     \n    l = arr[0] \n    for i in range(k-1): \n        l = list(merge(l, arr[i + 1])) \n    return l \n  \ndef printArray(arr): \n    print(*arr) \n  \n\narr =[[3, 4, 16 ],  \n    [ 5, 9 ],  \n    [22, 54, 94, 200 ]] \nk = 3\n\nout = mergeK(arr, k) \nprintArray(out) \n"
  },
  {
    "path": "Algorithms/Array/Merge_Sorted_Arrays.rb",
    "content": "def merge_sorted_arrays(arrays)\n    return [] if arrays.length == 0\n    return arrays[0] if arrays.length == 1\n  \n    # 1. Using built-in methods\n    # arrays.flatten.sort!\n\n    # 2. Not using built-in methods\n    full_array = arrays.inject([], :+)\n    sort(full_array)\nend\n\ndef sort(num_arr)\n    return num_arr if num_arr.size <= 1\n\n    mid = num_arr.length / 2\n    left = num_arr[0...mid]\n    right = num_arr[mid...num_arr.size]\n\n    merge(sort(left), sort(right))\nend\n  \ndef merge(left, right)\n    sorted = []\n    until left.empty? || right.empty?\n        if left.first <= right.first\n            sorted << left.shift\n        else\n            sorted << right.shift\n        end\n    end\n    sorted.concat(left).concat(right)\nend\n\n# Test example\narrays = [\n    [1, 4, 5],\n    [1, 3, 220],\n    [2, 6, 15, 1000],\n    [4, 10, 33]\n]\n\np merge_sorted_arrays(arrays)\n"
  },
  {
    "path": "Algorithms/Array/Rearrange-High-Low.js",
    "content": "function swap(arr, i, j)\n{\n    var temp = arr[i];\n    arr[i] = arr[j];\n    arr[j] = temp;\n}\n \n// Function to rearrange the array such that every second element\n// of the array is greater than its left and right elements\nfunction rearrangeArray(arr, n)\n{\n\n    for (let i = 1; i < n; i += 2)\n    {\n        // if the previous element is greater than the current element,\n        // swap the elements\n        if (arr[i - 1] > arr[i]) {\n            swap(arr, i - 1, i);\n        }\n \n        // if the next element is greater than the current element,\n        // swap the elements\n        if (i + 1 < n && arr[i + 1] > arr[i]) {\n            swap(arr, i + 1, i);\n        }\n    }\n}\n\nconst arr = [ 1, 2, 3, 4, 5, 6, 7 ];\nconst n = arr.length;\n\nrearrangeArray(arr, n);\n\n// print output array\nfor (let i = 0; i < n; i++) {\n    console.log(arr[i]);\n}\n\n/* \n    Output:\n\n            1\n            3\n            2\n            5\n            4\n            7\n            6\n\n*/\n"
  },
  {
    "path": "Algorithms/Array/Rearrange-High-Low.kt",
    "content": "// main function\nfun main(args: Array<String>) {\n  \n  // pre defined array\n    val arr=arrayOf(3, 6, 5, 10, 7, 20)\n    \n    // size of array\n    val n=arr.size\n  \n  // sort the array\n    arr.sort()\n    \n    // swap the alternate positions and increment in steps of 2\n    for (i in 0 until n step 2)\n    {\n        arr[i]=arr[i]+arr[i+1];\n        arr[i+1]=arr[i]-arr[i+1];\n        arr[i]=arr[i]-arr[i+1];\n    }\n    \n    // output the array\n    for(i in 0 until n)\n    println(arr[i])\n    \n}\n/* \n    Output:\n            5\n            3\n            7\n            6\n            20\n            10\n*/\n"
  },
  {
    "path": "Algorithms/Array/Remove-Dublicate.js",
    "content": "// RemoveDuplicateItem\n\nfunction RemoveDuplicateItem(arr) {\n    let newAr = [];\n\n\n    arr.forEach((item) => {\n        if (!newAr.includes(item)) {\n            newAr.push(item)\n        }\n    })\n    return newAr\n}\n\n"
  },
  {
    "path": "Algorithms/Array/Remove-Duplicates-from-Sorted-Array.c",
    "content": "\n/*\nGiven a sorted array nums, remove the duplicates in-place such that each element appears only once and returns the new length.\nDo not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.\n*/\n\n#include <iostream>\n#include<stdio.h> \n#include <bits/stdc++.h> \n#include <cmath>\n#include <vector>\n#include <map>\n#include <string>\n#include <algorithm>\n#include <iomanip>\n#include<utility>\nusing namespace std;\n#define ll long long\n#define len length()\n#define vi vector<int>\n#define vl vector<ll>\n\n#define fr(i,n) for(ll i=0;i<n;i++)\nll max(ll i,ll j){\n    return i>j?i:j;\n}\n\n\nint removeDuplicates(vector<int>& nums) {\n        int ind=1;\n        int n=nums.size();\n        if (n<=1) return n;\n        for(int i=0;i<n-1;i++){\n\n            if(nums[i+1]!=nums[i]){\n                nums[ind]=nums[i+1];\n                if(ind<n)\n                ind++;\n            }\n\n\n        }\n        nums.resize(ind);\n        return ind;\n}\n\nint main(){\n    int n;\n    cin>>n;\n vector<int> v(n,0);\n  fr(i,n){\n      int x; cin>>x;\n      v[i]=x;\n  }\n\n sort(v.begin(),v.end());\n removeDuplicates(v);\nfor(int u =0;u<h;u++){\n    cout<<v[u];\n }\n return 0;\n\n}\n"
  },
  {
    "path": "Algorithms/Array/Remove-Duplicates-from-Sorted-Array.cpp",
    "content": "/*\nGiven a sorted array nums, remove the duplicates in-place such that each element appears only once and returns the new length.\nDo not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.\n*/\n#include<iostream> \n\nusing namespace std; \n\nint removeDuplicates(int arr[], int n) \n\n{ \n\n    if (n==0 || n==1) \n\n        return n; \n\n    int j = 0; \n\n    for (int i=0; i < n-1; i++) \n\n        if (arr[i] != arr[i+1]) \n\n            arr[j++] = arr[i]; \n\n    arr[j++] = arr[n-1]; \n\n    return j; \n\n}  \n\nint main() \n\n{ \n    int n;\n    cin>>n;\n    int arr[n];\n\n    for(int i=0;i<n;i++){\n        cin>>a[i];\n        }\n\n    n = removeDuplicates(arr, n); \n\n    for (int i=0; i<n; i++) \n\n        cout << arr[i] << \" \"; \n\n    return 0; \n\n} \n\n\n\n\n\n"
  },
  {
    "path": "Algorithms/Array/Shuffle.c",
    "content": "/*\nYou are given an array consisting of n integers a1, a2, ..., an. Initially ax=1, all other elements are equal to 0.\nYou have to perform m operations. During the i-th operation, you choose two indices c and d such that li≤c,d≤ri, and swap ac and ad.\nCalculate the number of indices k such that it is possible to choose the operations so that ak=1 in the end.\n*/\n\n#include <iostream>\n#include<stdio.h> \n#include <bits/stdc++.h> \n#include <cmath>\n#include <vector>\n#include <map>\n#include <string>\n#include <algorithm>\n#include <iomanip>\n#include<utility>\nusing namespace std;\n#define ll long long\n#define len length()\n#define vi vector<int>\n#define vl vector<ll>\n\n#define fr(i,n) for(ll i=0;i<n;i++)\nll max(ll i,ll j){\n    return i>j?i:j;\n}\n \n \nint main(){\n    \nint t; \n//t=1;\ncin>>t;    \nwhile(t--){\n\nll n,x,m; cin>>n>>x>>m; \nll mx=x, mn=x;\n\nwhile(m--){\n    ll l,r;\n    cin>>l>>r;\n    \n    if(mn>=l&&mn<=r || mx>=l&&mx<=r){\n        \n        mn=min(mn,l); mx=max(mx,r);\n        \n    }\n    \n    \n}\nll ans=(mx-mn)+1;\ncout<<ans<<endl;\n  \n}\n \n}\n"
  },
  {
    "path": "Algorithms/Array/Two-Arrays-And-Swaps.c",
    "content": "/*\nYou are given two arrays a and b both consisting of n positive (greater than zero) integers. You are also given an integer k.\nIn one move, you can choose two indices i and j (1≤i,j≤n) and swap ai and bj (i.e. ai becomes bj and vice versa). Note that i and j can be equal or different (in particular, swap a2 with b2 or swap a3 and b9 both are acceptable moves).\nYour task is to find the maximum possible sum you can obtain in the array a if you can do no more than (i.e. at most) k such moves (swaps).\nYou have to answer t independent test cases.\n*/\n\n#include <iostream>\n#include<stdio.h> \n#include <bits/stdc++.h> \n#include <cmath>\n#include <vector>\n#include <map>\n#include <string>\n#include <algorithm>\n#include <iomanip>\n#include<utility>\nusing namespace std;\n#define ll long long\n#define len length()\n#define vi vector<int>\n#define vl vector<ll>\n\n#define fr(i,n) for(ll i=0;i<n;i++)\n\nint main(){\n    \nint t; cin>>t;\n    \nwhile(t--){\nll n,k; cin>>n>>k;\n \nvl a(n,0),b(n,0);\nfr(i,n){\n    cin>>a[i];\n}\n \nfr(i,n){\n    cin>>b[i];\n}\n \nsort(a.begin(),a.end());\nsort(b.begin(),b.end(),greater<int>());\nll s=0,ans=0;\nll j=0;\nfr(i,n){\n    if(s<k){\n       ll mx=max(a[i],b[j]);\n       ans+=mx;\n       if(mx==b[j]){\n           j++;\n           s++;\n       }\n    }\n    else{\n        ans+=a[i];\n    }\n}\n \ncout<<ans<<endl;\n}\n \n}\n"
  },
  {
    "path": "Algorithms/Array/check_two_equal_array.cpp",
    "content": "#include <bits/stdc++.h>\nusing namespace std;\n#define  LL long long\n#define F first\n#define S second\n#define fast_io ios::sync_with_stdio(false);cin.tie(NULL)\nint main()\n{\n\tint t;\n\tcin >> t;\n\twhile(t--)\n\t{\n\t\tint n,ans=1;\n\t\tcin >> n;\n\t\tint a[n+5],b[n+5];\n\t\tint h1[10005]={0},h2[10005]={0};\n\t\tfor(int i=0;i<n;i++)\n\t\t{\n\t\t\tcin >> a[i];\n\t\t\th1[a[i]]++;\n\t\t}\n\t\tfor(int i=0;i<n;i++)\n\t\t{\n\t\t\tcin >> b[i];\n\t\t\th2[b[i]]++;\n\t\t}\n\t\tfor(int i=0;i<=10000;i++)\n\t\t{\n\t\t\tif(h1[i] != h2[i])\n\t\t\t{\n\t\t\t\tans = 0;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tcout << ans << endl;\n\n\t}\n}"
  },
  {
    "path": "Algorithms/Array/copyarray.c",
    "content": "#include<stdio.h>\r\nint main()\r\n{\r\n    int arr1[40],n,i,arr2[40];\r\n\r\n    printf(\"How many number :\");\r\n    scanf(\"%d\",&n);\r\n\r\n    // scan  array_1 Elements;\r\n    for (i=0;i<n;i++)\r\n        {\r\n            scanf(\"%d\",&arr1[i]);\r\n        }\r\n\r\n    // Print Array_1\r\n    printf(\"Array_1 : \");\r\n    for(i=0;i<n;i++)\r\n\r\n    {\r\n        printf(\"%d \",arr1[i]);\r\n    }\r\n    printf(\"\\n\");\r\n\r\n// copy all Elements\r\n    for (i=0;i<n;i++)\r\n    {\r\n        arr2[i]=arr1[i];\r\n    }\r\n\r\n\r\n    // Print Array_2\r\n    printf(\"Array_2 : \");\r\n    for (i=0;i<n;i++)\r\n    {\r\n     printf(\"%d \",arr2[i]);\r\n    }\r\n\r\n\r\n getchar();\r\n}\r\n"
  },
  {
    "path": "Algorithms/Array/counting_frequency_of_char_in_string.c",
    "content": "#include <stdio.h>\nint main() {\n    char str[1000], ch;\n    int i,count = 0;\n    printf(\"Enter a string: \");\n    fgets(str, sizeof(str), stdin);\n\n    printf(\"Enter a character to find its frequency: \");\n    scanf(\"%c\", &ch);\n\n    for ( i = 0; str[i] != '\\0'; ++i) \n\t{\n        if (ch == str[i])\n            ++count;\n    }\n    printf(\"Frequency of %c = %d\", ch, count);\n    return 0;\n}\n"
  },
  {
    "path": "Algorithms/Array/findpos.py",
    "content": "def findposition(arr, x) :\n    flag = True\n    for i in range(0, len(arr)) :\n        if (x != arr[i]) :\n            continue\n        if (flag==True) :\n            first = i\n        last = i\n        flag = False\n     \n    if (flag==False) :\n        print( \"First Occurrence in array = \", first , \"\\n\" + \" Last Occurrence in array = \", last)\n    else :\n        print(\"Element Not Found\")\n         \narr = [1, 2, 2, 2, 2, 3, 4, 7, 8, 8 ]\nx=int(input(\"Enter the Element : \"))\nfindposition(arr, x)"
  },
  {
    "path": "Algorithms/Array/high-low-rearrangement.c",
    "content": "#include <stdio.h>\n//swap of elements\nvoid swap(int arr[], int i, int j)\n{\n    int temp = arr[i];\n    arr[i] = arr[j];\n    arr[j] = temp;\n}\n//arrange the array in high low order\nvoid rearrange(int arr[], int n)\n{\n    for (int i = 1; i < n; i += 2)\n    {\n        if (arr[i - 1] > arr[i]) {\n            swap(arr, i - 1, i);\n        }\n        if (i + 1 < n && arr[i + 1] > arr[i]) {\n            swap(arr, i + 1, i);\n        }\n    }\n}\n \nint main(void)\n{\n    //take input from user\n    int n;\n    printf(\"Enter array length : \\n\");\n    scanf(\"%d\",&n);\n    \n    int arr[n];\n    \n     printf(\"Enter array elements:\\n\");\n     for(int i = 0; i < n;  i++){\n        scanf(\"%d\", &arr[i]);\n     }\n \n    rearrange(arr, n);\n    for (int i = 0; i < n; i++) {\n        printf(\"%d \", arr[i]);\n    }\n \n    return 0;\n}\n"
  },
  {
    "path": "Algorithms/Array/high-low-rearrangement.c++",
    "content": "#include <bits/stdc++.h>\nusing namespace std;\n//swap of elements\nvoid swap(int arr[], int i, int j)\n{\n    int temp = arr[i];\n    arr[i] = arr[j];\n    arr[j] = temp;\n}\n//rearrange elements high and low\nvoid rearrange(int arr[], int n)\n{\n    for (int i = 1; i < n; i += 2)\n    {\n        if (arr[i - 1] > arr[i]) {\n            swap(arr, i - 1, i);\n        }\n        if (i + 1 < n && arr[i + 1] > arr[i]) {\n            swap(arr, i + 1, i);\n        }\n    }\n}\n \nint main()\n{\n    //enter array by user\n    int n;\n    cout<<\"Enter the number of elements:\"<<endl;\n    cin>>n;\n    \n    int arr[n];\n    \n     cout<<\"Enter array elements:\"<<endl;\n     for(int i = 0; i < n;  i++){\n        cin>>arr[i];\n     }\n \n    rearrange(arr, n);\n    for (int i = 0; i < n; i++) {\n        cout<<arr[i]<<endl;\n    }\n \n    return 0;\n}\n"
  },
  {
    "path": "Algorithms/Array/high-low-rearrangement.py",
    "content": "# Swap functions\ndef swap(A, i, j):\n    temp = A[i]\n    A[i] = A[j]\n    A[j] = temp \n# reaggrange array\ndef rearrangeArray(A):\n    for i in range(1, len(A), 2):\n        if A[i - 1] > A[i]:\n            swap(A, i - 1, i)\n        if i + 1 < len(A) and A[i + 1] > A[i]:\n            swap(A, i + 1, i)\nif __name__ == '__main__': \n    A = []\n    n = int(input(\"Enter number of elements : \")) \n    A = list(map(int,input(\"\\nEnter the numbers:\").strip().split()))[:n] \n    rearrangeArray(A)\nprint(A)\n"
  },
  {
    "path": "Algorithms/Array/largest-smallest-number-and-sum-of-all-elements-in-array.java",
    "content": "import java.io.*;\nclass t17question7\n{\n    public static void main(String args[])throws IOException\n    {\n        InputStreamReader in = new InputStreamReader(System.in);\n        BufferedReader y = new BufferedReader(in);\n        int i,ln=0,sn=0,s=0;\n        int n[]=new int[20];\n        System.out.println(\"Input 20 integers\");\n        for(i=0;i<20;i++)\n        {\n            n[i]=Integer.parseInt(y.readLine());\n        }\n        ln=n[0];\n        for(i=1;i<20;i++)\n        {\n        if(n[i]>ln)\n        ln=n[i];\n    }\n    System.out.println(\" The largest number is \"+ln);\n    sn=n[0];\n    for(i=1;i<20;i++)\n    {\n        if(n[i]<sn)\n        sn=n[i];\n    }\n    System.out.println(\" The smallest number is \"+sn);\n    for(i=0;i<20;i++)\n    {\n        s=s+n[i];\n    }\n    System.out.println(\" Sum of all the elements of the array is \"+s);\n}\n}\n\n\n\n"
  },
  {
    "path": "Algorithms/Array/merge-sorted-arrays-algo-only.py",
    "content": "# O(nk) time | O(n+k) space - where n is the total number of array elements and k is the nunber of arrays\n\ndef mergeSortedArrays(arrays):\n    sortedList = []\n    elementIdxs = [0 for array in arrays]\n    while True:\n        smallestItems = []\n        for arrayIdx in range(len(arrays)):\n            relevantArray = arrays[arrayIdx]\n            elementIdx = elementIdxs[arrayIdx]\n            if elementIdx == len(relevantArray):\n                continue\n            smallestItems.append(\n                {\"arrayIdx\": arrayIdx, \"num\": relevantArray[elementIdx]})\n        if len(smallestItems) == 0:\n            break\n        nextItem = getMinValue(smallestItems)\n        sortedList.append(nextItem[\"num\"])\n        elementIdxs[nextItem[\"arrayIdx\"]] += 1\n    return sortedList\n\n\ndef getMinValue(items):\n    minValueIdx = 0\n    for i in range(1, len(items)):\n        if items[i][\"num\"] < items[minValueIdx][\"num\"]:\n            minValueIdx = i\n    return items[minValueIdx]\n"
  },
  {
    "path": "Algorithms/Array/merge_without_extraspace.cpp",
    "content": "#include <bits/stdc++.h>\nusing namespace std;\n\n/*\n    Author : codewithmini\n*/\n\n/* Problem Statement\nWe are given two sorted arrays. We need to merge these two arrays such that the initial numbers (after complete sorting) are in the first array and the remaining numbers are in the second array. Extra space allowed in O(1).\n*/\n\nint main()\n{\n    int m,n;\n\n    // input as length of array 1\n    cout<<\"Enter the length of array 1 : \";\n    cin>>m;\n\n    // input as length of array 2\n    cout<<\"\\nEnter the length of array 2 : \";\n    cin>>n;\n\n    int arr1[m],arr2[n];\n\n    // array 1\n    cout<<\"\\nEnter the values of array 1 \\n\";\n    for(int i=0;i<m;i++)\n    {\n        cin>>arr1[i];\n    }\n    // array 2\n    cout<<\"\\nEnter the values of array 2 \\n\";\n    for(int i=0;i<n;i++)\n    {\n        cin>>arr2[i];\n    }\n\n    int i = 0, j = 0, k = m - 1;\n\n    // Till when i less than equal to k or j is less tha m\n    // while traversing the two sorted arrays parallelly, if we encounter the jth second array element is smaller than ith first array element, then jth element is to be included and replace some kth element in the first array\n    while (i <= k && j < n) \n    {\n        if (arr1[i] < arr2[j])\n        {    \n            i++;\n        }\n        else \n        {\n            swap(arr2[j++], arr1[k--]);\n        }\n    }\n\n    // sort both arr1 and arr2 \n    sort(arr1, arr1 + m);\n    sort(arr2, arr2 + n);\n\n    cout << \"After Merging \\nFirst Array: \";\n    for (int i = 0; i < m; i++)\n        cout << arr1[i] << \" \";\n    cout << \"\\nSecond Array: \";\n    for (int i = 0; i < n; i++)\n        cout << arr2[i] << \" \";\n    return 0;\n}\n\n\n/* \nOUTPUT :\nEnter the length of array 1 : 6\nEnter the length of array 2 : 4\nEnter the values of array 1 \n1\n5\n9\n10\n15\n20\nEnter the values of array 2 \n2\n3\n8\n13\nAfter Merging \nFirst Array: 1 2 3 5 8 9 \nSecond Array: 10 13 15 20\n*/  \n"
  },
  {
    "path": "Algorithms/Array/merging_2_arrays.c",
    "content": "#include<stdio.h>\nint main()\n{\n \tint n1, n2, n3, i, j;\n \tprintf(\"\\n Enter the number of elements for  First Array  :  \");\n \tscanf(\"%d\", &n1);     //Array Size Declaration\n    int a[n1];      //Array Declaration\n \tprintf(\"\\nEnter the elements for First Array :  \");\n \tfor(i = 0; i < n1; i++)\n  \t{\n      \tscanf(\"%d\", &a[i]);\n  \t}\n  \tprintf(\"\\n Enter the number of elements for  Second Array  :  \");\n \tscanf(\"%d\", &n2);    //Array Size Declaration\n    int b[n2];       //Array Declaration\n \tprintf(\"\\nEnter the elements for Second Array  :  \");\n \tfor(i = 0; i < n2; i++)\n  \t{\n      \tscanf(\"%d\", &b[i]);\n  \t}\n\tn3 = n1 + n2;     //Array Size Declaration\n    int c[n3];       //Array Declaration\n  \tfor(i = 0; i < n1; i++)\n  \t{\n      \tc[i] = a[i];\n  \t}\n \tfor(i = 0, j = n1; j < n3 && i < n2; i++, j++)\n  \t{\n  \t\tc[j] = b[i];\n  \t}\n \tprintf(\"\\n a[%d] Array Elements After Merging \\n\", n3); \n \tfor(i = 0; i < n3; i++)\n  \t{\n    \tprintf(\" %d \\t \",c[i]);\n  \t}\n  \treturn 0;\n}\n\n\n"
  },
  {
    "path": "Algorithms/Array/rearrange-high-low.java",
    "content": "import java.util.Scanner;\nclass Main\n{\n    // swap\n    private static void swap(int[] A, int i, int j)\n    {\n        int temp = A[i];\n        A[i] = A[j];\n        A[j] = temp;\n    }\n \n    // rearrange\n    public static void rearrangeArray(int[] A)\n    {\n        for (int i = 1; i < A.length; i += 2)\n        {\n            if (A[i - 1] > A[i]) {\n                swap(A, i - 1, i);\n            }\n            if (i + 1 < A.length && A[i + 1] > A[i]) {\n                swap(A, i + 1, i);\n            }\n        }\n    }\n    public static void main (String[] args)\n    {\n        int n;\n        Scanner sc = new Scanner(System.in);\n        System.out.println(\"Enter no. of elements in array:\");\n        n = sc.nextInt();\n        int A[] = new int[n];\n        System.out.println(\"Enter all the elements:\");\n        for(int i = 0; i < n; i++)\n        {\n            A[i] = sc.nextInt();\n        }\n \n        rearrangeArray(A);\n        System.out.println(Arrays.toString(A));\n    }\n}\n"
  },
  {
    "path": "Algorithms/Array/revering_array.c",
    "content": "#include<stdio.h>\n#include<stdlib.h>\nstruct Array\n{\nint A[10];\nint size;\nint length;\n};\nvoid Display(struct Array arr)\n{\nint i;\nprintf(\"\\nElements are\\n\");\nfor(i=0;i<arr.length;i++)\nprintf(\"%d \",arr.A[i]);\n}\nvoid swap(int *x,int *y)\n{\nint temp=*x;\n*x=*y;\n*y=temp;\n}\nvoid Reverse(struct Array *arr)\n{\nint *B;\nint i,j;\nB=(int *)malloc(arr->length*sizeof(int));\nfor(i=arr->length-1,j=0;i>=0;i--,j++)\nB[j]=arr->A[i];\nfor(i=0;i<arr->length;i++)\narr->A[i]=B[i];\n}\nvoid Reverse2(struct Array *arr)\n{\nint i,j;\nfor(i=0,j=arr->length-1;i<j;i++,j--)\n{\nswap(&arr->A[i],&arr->A[j]);\n}\n}\nint main()\n{\n\tstruct Array arr1={{2,3,9,16,18,21,28,32,35},10,9};\nReverse(&arr1);\nDisplay(arr1);\nreturn 0;\n}\n"
  },
  {
    "path": "Algorithms/Array/rotate_matrix_90degree.cpp",
    "content": "#include <bits/stdc++.h>\nusing namespace std;\n\n/*\n    Author : codewithrathi\n*/\n\n/*\nProblem Statement :\nRotate a matrix by 90 degree in clockwise or anticlockwise direction without using any extra space\n*/\n\nint main()\n{\n    int n;\n\n    // Dimension of square matrix\n    cout<<\"\\nEnter the dimension of Matrix : \";\n    cin>>n;\n\n    int arr[n][n],ch;\n\n    // matrix\n    cout<<\"\\nEnter the values of Matrix \\n\";\n    for(int i=0;i<n;i++)\n    {\n        for(int j=0;j<n;j++)\n        {\n            cin>>arr[i][j];\n        }\n    }\n\n    cout<<\"Enter your choice (1 or 2) : \\n\";\n    cout<<\"[1] anti-clockwise rotation \\n\";\n    cout<<\"[2] clockwise rotation \\n\";\n\n    cin>>ch;\n\n    cout<<\"Matrix before rotation :\\n\\n\";\n    for(int i=0;i<n;i++)\n    {\n        for(int j=0;j<n;j++)\n        {\n            cout<<arr[i][j]<<\" \";\n        }\n        cout<<endl;\n    }\n\n    if(ch==1)\n    {\n        for (int i = 0; i < n / 2; i++) \n        { \n            // Consider elements in group of 4 in \n            // current square \n            for (int j = i; j < n-i-1; j++) \n            { \n                // store current cell in temp variable \n                int temp = arr[i][j]; \n\n                // move values from right to top \n                arr[i][j] = arr[j][n-1-i]; \n\n                // move values from bottom to right \n                arr[j][n-1-i] = arr[n-1-i][n-1-j]; \n\n                // move values from left to bottom \n                arr[n-1-i][n-1-j] = arr[n-1-j][i]; \n\n                // assign temp to left \n                arr[n-1-j][i] = temp; \n            } \n        }\n    }\n    else if(ch==2)\n    {\n        for (int i = 0; i < n / 2; i++) \n        { \n            // Consider elements in group of 4 in \n            // current square \n            for (int j = i; j < n-i-1; j++) \n            { \n                // store current cell in temp variable \n                int temp = arr[i][j]; \n\n                // move values from right to top \n                arr[i][j] = arr[n-1-j][i]; \n\n                // move values from bottom to right \n                arr[n-1-j][i] = arr[n-1-i][n-1-j]; \n\n                // move values from left to bottom \n                arr[n-1-i][n-1-j] = arr[j][n-1-i]; \n\n                // assign temp to left \n                arr[j][n-1-i] = temp; \n            } \n        }\n    }\n    else\n    {\n        cout<<\"Invalid input\";\n    }\n    if(ch==1 || ch==2)\n    {\n        cout<<\"Matrix after rotation :\\n\\n\";\n        for(int i=0;i<n;i++)\n        {\n            for(int j=0;j<n;j++)\n            {\n                cout<<arr[i][j]<<\" \";\n            }\n            cout<<endl;\n        }\n\n    }\n\n    return 0;\n}\n\n\n/* \nOUTPUT :\nEnter the dimension of Matrix : 4\nEnter the values of Matrix \n1\n2\n3\n4\n5\n6\n7\n8\n9\n10\n11\n12\n13\n14\n15\n16\nEnter your choice (1 or 2) : \n[1] anti-clockwise rotation \n[2] clockwise rotation \n2\nMatrix before rotation :\n1 2 3 4 \n5 6 7 8 \n9 10 11 12 \n13 14 15 16 \nMatrix after rotation :\n13 9 5 1 \n14 10 6 2 \n15 11 7 3 \n16 12 8 4 \n...Program finished with exit code 0\nPress ENTER to exit console.\n*/ \n"
  },
  {
    "path": "Algorithms/Array/rotated_sorted_array_search.cpp",
    "content": "#include<bits/stdc++.h> \nusing namespace std;\n\nint rotatedSearch(vector<int> &A, int B) {\n\n    //low and high are the indices between which we search-\n    int low=0; \n    int high=A.size()-1;\n    \n    //finding the pivot of rotation-\n    for(int i=0; i<A.size()-1; i++){\n        if(A[i]>A[i+1]){                \n            \n            if(B>=A[0])\n                high=i;                //search only in the left of pivot\n            \n            else if(B<=A[A.size()-1])\n                low=i+1;              //search only in the right of pivot\n            \n            break;    \n        }\n    }\n    \n    //implementing Binary Search-\n    while(high>=low){                  \n        int mid=low+(high-low)/2;\n        if(A[mid]==B) return mid;     //B is found\n        else if(A[mid]>B) high=mid-1;\n        else if(A[mid]<B) low=mid+1;\n    }\n    return -1;                       //B is not found\n}\n"
  },
  {
    "path": "Algorithms/Array/twoSum.cpp",
    "content": "#include<bits/stdc++.h>\nusing namespace std;\n\n/*Naive Approach: Check for all pairs if they adds up to the target or not\nTC: O(n*n) SC: O(1)\n*/\npair<int, int> findTwoSumNaive(vector<int> nums, int target){\n    int n = nums.size();\n    for(int i = 0; i < n; i++){\n        for(int j = i + 1; j < n; j++){\n            if(nums[i] + nums[j] == target)\n                return {nums[i], nums[j]};\n        }\n    }\n    return {-1, -1};\n}\n/*Better Approach: Sort the given array\n->create two pointers one of which points to the first element and another one to the last element.\n->check if both the values pointed to by these pointers adds up to the target or not.\n->if yes, return the result.\n->otherwise, if the sum is lesser than the target increment left pointer\n->           otherwise decrement the right pointer.\n->The above intuition works because the array is sorted.\nTC: O(nlogn) SC: O(n)\n*/\npair<int, int> findTwoSumBetter(vector<int> nums, int target){\n    sort(nums.begin(), nums.end());\n    int lo = 0;\n    int hi = nums.size() - 1;\n    while(lo < hi){\n        if(nums[lo] + nums[hi] == target)\n            return {nums[lo],nums[hi]};\n        nums[lo] + nums[hi] < target ? lo++ : hi--;\n    }\n    return {-1, -1};\n}\n\n/*Optimal Approach: \n->Use a hashmap to store the numbers as you traverse.\n->At any point if you had added a value equal to the target - current_number in the hashmap.\n->Then we have our ans as {current_number, target - current_number} which adds up to the target value.\n->otherwise return {-1, -1} as the result.\nTC: O(n) SC: O(n)\nconsidering the hashmap works in O(1) on an average.\n*/\npair<int, int> findTwoSumOptimal(vector<int> nums, int target){\n    unordered_map<int, int>mp;\n    for(auto &a : nums){\n        if(mp[target - a])\n            return {target - a, a};\n        mp[a]++;\n    }\n    return {-1, -1};\n}\nint main(){\n    \n    //get the input array as a line of string\n    string s;\n    getline(cin, s);\n    \n    //get the target value \n    int target;\n    cin >> target;\n    \n    stringstream ss(s);\n    \n    vector<int> nums;\n    int value;\n    \n    //string values to integer values and add it the nums array\n    while(ss >> value)nums.push_back(value);\n    \n    //a pair of values to store the result\n    pair<int, int> values = findTwoSumOptimal(nums, target);\n    \n    //if both the values of the result are -1\n    //it means no such pair exists that adds up to the target value\n    //otherwise, print a valid pair of values\n    if(values.first == -1 and values.second == -1){\n        cout << \"No such pair exists\" << endl;\n    } else{\n        cout << values.first <<\" and \" << values.second\n            <<\" adds up to \" << target << endl;\n    }\n      \n    \n}"
  },
  {
    "path": "Algorithms/Array/twoSum.kt",
    "content": "import java.util.*\n\n/*Naive Approach: Check for all pairs if they adds up to the target or not\nTC: O(n*n) SC: O(1)\n*/\nfun findTwoSumNaive(nums: List<Int>, target: Int): IntArray{\n    val n = nums.size\n    for(i in 0 until n){\n        for(j in (i+1) until n){\n            if(nums[i] + nums[j] == target)\n                return intArrayOf(nums[i], nums[j])\n        }\n    }\n    return intArrayOf(-1, -1)\n}\n\n/*Better Approach: Sort the given array\n->create two pointers one of which points to the first element and another one to the last element.\n->check if both the values pointed to by these pointers adds up to the target or not.\n->if yes, return the result.\n->otherwise, if the sum is lesser than the target increment left pointer\n->           otherwise decrement the right pointer.\n->The above intuition works because the array is sorted.\nTC: O(nlogn) SC: O(n)\n*/\nfun findTwoSumBetter(nums: List<Int>, target: Int): IntArray{\n    Collections.sort(nums)\n    var (lo, hi) = Pair(0, nums.size - 1)\n    while(lo < hi){\n        val sum = nums[lo] + nums[hi]\n        if(sum == target){\n            return intArrayOf(nums[lo], nums[hi]);\n        }\n        if(sum < target) lo++ else hi--\n    }\n    return intArrayOf(-1, -1)\n}\n\n/*Optimal Approach: \n->Use a hashmap to store the numbers as you traverse.\n->At any point if you had added a value equal to the target - current_number in the hashmap.\n->Then we have our ans as {current_number, target - current_number} which adds up to the target value.\n->otherwise return {-1, -1} as the result.\nTC: O(n) SC: O(n)\nconsidering the hashmap works in O(1) on an average.\n*/\nfun findTwoSumOptimal(nums: List<Int>, target: Int): IntArray{\n    val map = mutableMapOf<Int, Boolean>()\n    for(num in nums){\n        if(map.containsKey(target - num))\n            return intArrayOf(target - num, num)\n        map[num] = true\n    }\n    return intArrayOf(-1, -1)\n}\n\n//main function\nfun main(){\n    //get the input array\n    val nums = readLine()!!.split(' ').map{it.toInt()}\n\n    //get the target value\n    val target = readLine()!!.toInt()\n\n    //a pair of values to store the result\n    val values = findTwoSumOptimal(nums, target)\n\n    //if both the values of the result are -1\n    //it means no such pair exists that adds up to the target value\n    //otherwise, print a valid pair of values\n    if(values[0] == -1 && values[1] == -1)\n        println(\"No such pair exists\")\n    else \n        println(\"${values[0]} and ${values[1]} adds up to $target\")\n}"
  },
  {
    "path": "Algorithms/Array/wave_form_array",
    "content": "//Print a 2d array in wave form i.e. \\/\\/\\/\\/\n#include <iostream>\nusing namespace std;\nint main()\n{\n    int a[1000][1000];\n    int m,n;\n    cin>>m>>n;\n    for(int i=0;i<m;i++){\n        for(int j=0;j<n;j++){\n            cin>>a[i][j];\n        }\n    }\n    cout<<\"The 2-D Array is:\"<<endl;\n    for(int i=0;i<m;i++){\n        for(int j=0;j<n;j++){\n            cout<<a[i][j]<<\" \";\n        }\n    cout<<endl;\n    }\n    cout<<\"The wave form of 2-D array is :\"<<endl;\n    //coloumn is constant row is changing\n    //row will be the inner loop because its changing\n    for(int j=0;j<n;j++){\n        if(j%2==0){\n            //topdown in even col\n            for(int i=0;i<m;i++){\n                cout<<a[i][j]<<\" \";\n            }\n        }\n        else{\n            //bottom down in odd col\n            for(int i=m-1;i>=0;i--){\n                cout<<a[i][j]<<\" \";\n            }\n        }\n    }\n}\n\n"
  },
  {
    "path": "Algorithms/Backtracking/Crossword/Crossword.cpp",
    "content": "/*\n  Problem description:\n  A 10 x 10 Crossword grid is provided,along with \n  a set of words (or names of places) which need \n  to be filled into the grid.The cells in the grid \n  are initially,either + signs or – signs.\n  Cells marked with a ‘+’ have to be left as they are.\n  Cells marked with a ‘-‘ need to be filled up with an \n  appropriate character.\n*/\n\n#include <bits/stdc++.h>\nusing namespace std;\n#define N 10\n\n//Return index of word which is not filled in crossword\nbool findString(vector<bool> &visited, int &index)\n{\n  int n = visited.size();\n  for (int i = 0; i < n; i++)\n    if (visited[i] == 0)\n    {\n      index = i;\n      return false;\n    }\n  return true;\n}\n\n//check if word can be filled in a column\nbool isPossible_col(vector<vector<char>> &grid, int row, int col, string word)\n{\n  int len = word.size();\n  for (int i = 0; i < len; i++)\n  {\n    if ((col + i) >= 10)\n      return false;\n    if (grid[row][col + i] != '-' && grid[row][col + i] != word[i])\n      return false;\n  }\n  return true;\n}\n\n//check if word can be filled in a row.\nbool isPossible_row(vector<vector<char>> &grid, int row, int col, string word)\n{\n  int len = word.size();\n  for (int i = 0; i < len; i++)\n  {\n    if ((row + i) >= 10)\n      return false;\n    if (grid[row + i][col] != '-' && grid[row + i][col] != word[i])\n      return false;\n  }\n  return true;\n}\n\n// Fill all words in crossword & return true if all words can be filled in the grid.\nbool crossword(vector<vector<char>> &grid, vector<bool> &visited, vector<string> &words)\n{\n  int index;\n  if (findString(visited, index))\n    return true;\n  for (int i = 0; i < 10; i++)\n  {\n    for (int j = 0; j < 10; j++)\n    {\n      if (grid[i][j] == '-' || grid[i][j] == words[index][0])\n      {\n        if (isPossible_col(grid, i, j, words[index]))\n        {\n          string prev_state = \"\";\n          for (int k = 0; k < words[index].size(); k++)\n            prev_state += grid[i][j + k], grid[i][j + k] = words[index][k];\n          visited[index] = 1;\n          bool flag = crossword(grid, visited, words);\n          if (flag)\n            return true;\n          visited[index] = 0;\n          for (int k = 0; k < words[index].size(); k++)\n            grid[i][j + k] = prev_state[k];\n        }\n        if (isPossible_row(grid, i, j, words[index]))\n        {\n          string prev_state = \"\";\n          for (int k = 0; k < words[index].size(); k++)\n            prev_state += grid[i + k][j], grid[i + k][j] = words[index][k];\n          visited[index] = 1;\n          bool flag = crossword(grid, visited, words);\n          if (flag)\n            return true;\n          visited[index] = 0;\n          for (int k = 0; k < words[index].size(); k++)\n            grid[i + k][j] = prev_state[k];\n        }\n      }\n    }\n  }\n  return false;\n}\nint main()\n{ //1. given crossword grid\n  vector<vector<char>> grid(N, vector<char>(N));\n  for (int i = 0; i < N; i++)\n    for (int j = 0; j < N; j++)\n      cin >> grid[i][j];\n  \n  //2. given words to be filled in Crossword\n  int num_of_words;\n  vector<string> words;\n  string word;\n  cin>>num_of_words;\n  for(int i=0;i<num_of_words;i++)\n  {\n  \tcin>>word;\n  \twords.push_back(word);\n  }\n\n  //3. calling function crossword to fill the grid\n  vector<bool> visited(num_of_words, 0);\n  if (crossword(grid, visited, words))\n  {\n    for (int i = 0; i < N; i++)\n    {\n      for (int j = 0; j < N; j++)\n        cout << grid[i][j];\n      cout << endl;\n    }\n  }\n  else\n  {\n    cout << \"We Cannot fill all the words in the grid\" << endl;\n  }\n}"
  },
  {
    "path": "Algorithms/Backtracking/Nqueen/N_Queen.java",
    "content": "import java.util.*;\r\npublic class N_Queen {\r\n\tfinal int N=4;\r\n\tpublic boolean solveNQUtil(int board[][],int col) {\r\n\t\tif(col>=N)\r\n\t\t\treturn  true;\r\n\t\tfor(int i=0;i<N;i++) {\r\n\t\t\tif(isSafe(board,i,col)) {\r\n\t\t\t\tboard[i][col]=1;\r\n\t\t\tif(solveNQUtil(board,col+1)) \r\n\t\t\t\treturn true;\r\n\t\t\tboard[i][col]=0;\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn false;\r\n\t\t\r\n\t}\r\nboolean isSafe(int board[][],int row,int col) {\r\n\tint i,j;\r\n\tfor(i=0;i<col;i++) \r\n\t\tif(board[row][i]==1)\r\n\t\t\treturn false;\r\n\t\tfor(i=row,j=col;i>=0&&j>=0;i--,j--)\r\n\t\t\tif(board[i][j]==1)\r\n\t\t\t\treturn false;\r\n\t\treturn true;\r\n\t\r\n}\r\n\r\n\r\nboolean solveNQ() {\r\n\tint board[][]= {{0,0,0,0},{0,0,0,0},{0,0,0,0},{0,0,0,0}\r\n\t\t\t\r\n\t};\r\n\r\n\tif(solveNQUtil(board,0)==false) {\r\n\t\tSystem.out.println(\"solution does nor exist\");\r\n\t\treturn false;\r\n\t}\r\n\t\r\n\tprintsolution(board);\r\n\treturn true;\r\n\t\r\n}\r\n\r\n\r\nvoid printsolution(int board[][]) {\r\n\tfor(int i=0;i<N;i++) {\r\n\t\tfor(int j=0;j<N;j++) \r\n\t\t\tSystem.out.print(\" \"+board[i][j]+\"  \");\r\n\t\tSystem.out.println();\r\n }\r\n}\r\n\tpublic static void main(String[] args) {\r\n\t\t// TODO Auto-generated method stub\r\n\t\t\r\n\t\tN_Queen Queen= new N_Queen();\r\n\t\tQueen.solveNQ();\r\n\t}\r\n\r\n}\r\n"
  },
  {
    "path": "Algorithms/Backtracking/Nqueen/Nqueens.c",
    "content": "#include<stdio.h>\n#include<math.h>\n \nchar a[10][10];\nint n;\n \nvoid printmatrix() {\n   int i, j;\n   printf(\"\\n\");\n \n   for (i = 0; i < n; i++) {\n      for (j = 0; j < n; j++)\n         printf(\"%c\\t\", a[i][j]);\n      printf(\"\\n\\n\");\n   }\n}\n \nint getmarkedcol(int row) {\n   int i;\n   for (i = 0; i < n; i++)\n      if (a[row][i] == 'Q') {\n         return (i);\n         break;\n      }\n}\n \nint feasible(int row, int col) {\n   int i, tcol;\n   for (i = 0; i < n; i++) {\n      tcol = getmarkedcol(i);\n      if (col == tcol || abs(row - i) == abs(col - tcol))\n         return 0;\n   }\n   return 1;\n}\n \nvoid nqueen(int row) {\n   int i, j;\n   if (row < n) {\n      for (i = 0; i < n; i++) {\n         if (feasible(row, i)) {\n            a[row][i] = 'Q';\n            nqueen(row + 1);\n            a[row][i] = '.';\n         }\n      }\n   } else {\n      printf(\"\\nThe solution is:- \");\n      printmatrix();\n   }\n}\n \nint main() {\n   int i, j;\n \n   printf(\"\\nEnter the no. of queens:- \");\n   scanf(\"%d\", &n);\n \n   for (i = 0; i < n; i++)\n      for (j = 0; j < n; j++)\n         a[i][j] = '.';\n \n   nqueen(0);\n   return (0);\n}\n"
  },
  {
    "path": "Algorithms/Backtracking/Nqueen/Nqueens.cpp",
    "content": "#include<bits/stdc++.h>\n#define ll long long\n#define mod 1000000007;\nusing namespace std;\nbool isvalid(int board[][10],int i,int j,int n)\n{\n    for(int k=0;k<i;k++)\n    {\n        if(board[k][j]==1)\n        {\n            return false;\n        }\n    }\n    int x=i;\n    int y=j;\n    while(x>=0&&y>=0)\n    {\n        if(board[x][y]==1)\n        {\n            return false;\n        }\n        x--;\n        y--;\n    }\n     x=i;\n     y=j;\n    while(x>=0&&y<n)\n    {\n        if(board[x][y]==1)\n        {\n            return false;\n        }\n        x--;\n        y++;\n    }\n    return true;\n}\nbool showNqueen(int board[][10],int i,int n)\n{\n    if(i==n)\n    {\n       for(int a=0;a<n;a++)\n       {\n           for(int b=0;b<n;b++)\n           {\n               if(board[a][b]==1)\n               {\n                   cout<<\"1 \";\n               }else\n               {\n                   cout<<\"0 \";\n               }\n           }\n           cout<<endl;\n       }\n\n\n        return true;\n    }\n    for(int j=0;j<n;j++)\n    {\n        if(isvalid(board,i,j,n))\n        {\n            board[i][j]=1;\n            if(showNqueen(board,i+1,n))\n            {\n                return true;\n            }\n            board[i][j]=0;\n        }\n    }\n    return false;\n}\nint main()\n{\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n    cout.tie(NULL);\n    int board[10][10]={0};\n    int n;\n    cin>>n;\n    bool f=showNqueen(board,0,n);\n    return 0;\n}\n"
  },
  {
    "path": "Algorithms/Backtracking/Nqueen/Nqueens_optimized.cpp",
    "content": "#include<bits/stdc++.h>\n#define ll long long\n#define mod 1000000007;\nusing namespace std;\nint c=0;\nint column[100]={0},d1[100]={0},d2[100]={0};\n\nvoid solve(int i,int n)\n{\n    if(i==n)\n    {\n        c++;\n        return ;\n    }\n    for(int j=0;j<n;j++)\n    {\n        if(column[j]==0&&d1[i-j+n-1]==0&&d2[i+j]==0)\n        {\n            column[j]=1;\n            d1[i-j+n-1]=1;\n            d2[i+j]=1;\n            solve(i+1,n);\n            column[j]=0;\n            d1[i-j+n-1]=0;\n            d2[i+j]=0;\n        }\n    }\n}\nint main()\n{\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n    cout.tie(NULL);\n    int n;\n    cin>>n;\n    solve(0,n);\n    cout<<c<<endl;\n    return 0;\n}\n"
  },
  {
    "path": "Algorithms/Backtracking/Nqueen/nqueen.cpp",
    "content": "//N-queen program using Backtracking in C++ by Apurva\n#include<iostream>\nusing namespace std;\nint grid[10][10];\n//print the solution\nvoid print(int n) {\n    for (int i = 0;i <= n-1; i++) {\n        for (int j = 0;j <= n-1; j++) {\n            \n                cout <<grid[i][j]<< \" \";\n            \n        }\n        cout<<endl;\n    }\n    cout<<endl;\n    cout<<endl;\n}\nbool isSafe(int col, int row, int n) {\n  //check for same column\n    for (int i = 0; i < row; i++) {\n        if (grid[i][col]) {\n            return false;\n        }\n    }\n    for (int i = row,j = col;i >= 0 && j >= 0; i--,j--) {\n        if (grid[i][j]) {\n            return false;\n        }\n    }\n    for (int i = row, j = col; i >= 0 && j < n; j++, i--) {\n        if (grid[i][j]) {\n            return false;\n        }\n    }\n    return true;\n}\nbool solve (int n, int row) {\n    if (n == row) {\n        print(n);\n        return true;\n    }\n    bool res = false;\n    for (int i = 0;i <=n-1;i++) {\n        if (isSafe(i, row, n)) {\n            grid[row][i] = 1;\n            res = solve(n, row+1) || res;//if res ==false then backtracking will occur \n            grid[row][i] = 0;\n        }\n    }\n    return res;\n}\nint main()\n{\n  ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n        int n;\n        cout<<\"Enter the number of queen\"<<endl;\n        cin >> n;\n        for (int i = 0;i < n;i++) {\n            for (int j = 0;j < n;j++) {\n                grid[i][j] = 0;\n            }\n        }\n        bool res = solve(n, 0);\n        if(res == false) {\n            cout << -1 << endl;\n        } else {\n            cout << endl;\n        }\n  return 0;\n}\n"
  },
  {
    "path": "Algorithms/Backtracking/Nqueen/nqueens.py",
    "content": "global N \nN = 4\n\ndef printSolution(board): \n\tfor i in range(N): \n\t\tfor j in range(N): \n\t\t\tprint(board[i][j],end=\",\")\n\t\tprint(\" \")\n  \ndef isSafe(board, row, col): \n\n\t# Check this row on left side \n\tfor i in range(col): \n\t\tif board[row][i] == 1: \n\t\t\treturn False\n\n\t# Check upper diagonal on left side \n\tfor i, j in zip(range(row, -1, -1), range(col, -1, -1)): \n\t\tif board[i][j] == 1: \n\t\t\treturn False\n\n\t# Check lower diagonal on left side \n\tfor i, j in zip(range(row, N, 1), range(col, -1, -1)): \n\t\tif board[i][j] == 1: \n\t\t\treturn False\n\n\treturn True\n\ndef solveNQUtil(board, col): \n\tif col >= N: \n\t\treturn True\n\tfor i in range(N): \n\n\t\tif isSafe(board, i, col): \n\t\t\t# Place this queen in board[i][col] \n\t\t\tboard[i][col] = 1\n\n\t\t\t# recur to place rest of the queens \n\t\t\tif solveNQUtil(board, col + 1) == True: \n\t\t\t\treturn True\n\t\t\tboard[i][col] = 0\n\n\treturn False\ndef solveNQ(): \n\tboard = [ [0, 0, 0, 0], \n\t\t\t[0, 0, 0, 0], \n\t\t\t[0, 0, 0, 0], \n\t\t\t[0, 0, 0, 0] \n\t\t\t] \n\n\tif solveNQUtil(board, 0) == False: \n\t\tprint(\"Solution does not exist\")\n\t\treturn False\n\n\tprintSolution(board) \n\treturn True\n\n# driver program to test above function \nsolveNQ() \n\n\n"
  },
  {
    "path": "Algorithms/Backtracking/Permutation/Permutations.c",
    "content": "#include<stdio.h>\r\n#include<stdlib.h>\r\n#include<conio.h>\r\n\r\nvoid swap(int *ar, int i, int j)\r\n{\r\n  int temp = ar[i];\r\n  ar[i] = ar[j];\r\n  ar[j] = temp;\r\n}\r\n\r\nvoid printar(int *ar, int n)\r\n{\r\n  for (int i = 0; i < n; i++)\r\n    printf(\"%d \", ar[i]);\r\n\r\n  printf(\"\\n\");\r\n}\r\n\r\nvoid permute(int *ar, int i, int n)\r\n{\r\n  if (n == i) {\r\n\r\n    printar(ar, n);\r\n    return;\r\n  }\r\n\r\n  int j = i;\r\n  for (j = i; j < n; j++)\r\n  {\r\n    swap(ar, i, j);\r\n    permute(ar , i + 1, n);\r\n    swap(ar, i, j);\r\n  }\r\n\r\n  return;\r\n}\r\n\r\nint main()\r\n{\r\n  int n;\r\n  scanf(\"%d\", &n);\r\n\r\n  int ar[n];\r\n\r\n  for (int i = 0; i < n; i++)\r\n    scanf(\"%d\", &ar[i]);\r\n\r\n  permute(ar, 0, n);\r\n\r\n}"
  },
  {
    "path": "Algorithms/Backtracking/Permutation/permutation.py",
    "content": "def permutation(arr):\n    if(len(arr) == 1):\n        return [arr]\n    \n    result = []\n\n    for i in arr:\n        #Array excluding i element\n        sub_arr = [j for j in arr if j != i]\n        p = permutation(sub_arr)\n\n        for k in p:\n            temp = [i]+k\n            result.append(temp)\n\n    return result\n"
  },
  {
    "path": "Algorithms/Backtracking/Permutation/permutations.cpp",
    "content": "#include<iostream>\nusing namespace std;\nvoid solve(vector<int>& nums, vector<int>& curr, vector<vector<int>> &res, int i){\n   if(curr.size()==nums.size())\n        //one possible permutation obtained-\n        res.push_back(curr);\n   else {\n        //backtracking algorithm implementation-\n        for(int j=i; j<nums.size(); j++){\n           curr.push_back(nums[j]);\n           swap(nums[j], nums[i]);\n           solve(nums, curr, res, i+1);\n           swap(nums[j], nums[i]);\n           curr.pop_back();\n        }\n   }\n   return;\n}\nvector<vector<int>> permute(vector<int>& nums) {\n   vector<vector<int>>res;\n   vector<int>curr;\n   solve(nums, curr, res, 0);\n   return res;\n}\nint main() {\n   int n;\n   cin >> n;\n   vector<int>arr(n);\n   for(int i=0; i<n; i++)\n       cin >> arr[i];\n   vector<vector<int>> answer = permute(arr);\n   //printing all the possible permutation arrays -\n   for(int i=0; i<answer.size(); i++){\n       cout << \"[ \" ;\n       for(int j=0; j<n; j++){\n           cout << answer[i][j] << \" \" ;\n       }\n       cout << \"]\" << \"\\n\";\n   }\n   return 0;\n}\n"
  },
  {
    "path": "Algorithms/Backtracking/Permutation/permutations.js",
    "content": "//Heap's Algorithm\n\n//Print Function\nfunction print(list,length){\n  empty_list = []\n  for(var i=0;i<length;i++){\n    empty_list.push(list[i])\n  }\n  console.log(empty_list)\n}\n\nfunction permutation(list,size,length){\n  // if size 1, print self\n  if(size==1) print(list,length)\n\n  for(var j=0;j<size;j++){\n\n    //recursive function\n    permutation(list,size-1,length)\n\n    //if size is odd, swap first and last element\n    if(size % 2 == 1){\n      var temp = list[0]\n      list[0] = list[size-1]\n      list[size-1] = temp\n    }\n\n    //else swap ith and last element\n    else{\n      var temp = list[j]\n      list[j] = list[size-1]\n      list[size-1] = temp\n    }\n      \n  }\n\n}\n\n//Test\nvar list = [4,5,6]\nsize = list.length\npermutation(list,size,size)\n"
  },
  {
    "path": "Algorithms/Backtracking/README.md",
    "content": "# This folder is empty.\n"
  },
  {
    "path": "Algorithms/Backtracking/Rat-In-A-Maze/Rat-In-A-Maze.cpp",
    "content": "//https://practice.geeksforgeeks.org/problems/rat-in-a-maze-problem/1 - Link to problem statement\r\n\r\n#include <bits/stdc++.h>\r\nusing namespace std;\r\n\r\n//function that returns the list of paths in lexicographically increasing order\r\nvoid rat_in_a_maze(int i, int j, int n, vector<vector<int>> &grid, vector<string> &paths, string &path)\r\n{\r\n    //base case\r\n    if (i == n - 1 && j == n - 1) {\r\n        paths.push_back(path);\r\n        return;\r\n    }\r\n\r\n    //if grid[0][0] is -1, no recursion takes place...\r\n    if (grid[i][j] == 0) {\r\n        return;\r\n    }\r\n\r\n    //moving down('D')\r\n    if ((i + 1) < n && grid[i + 1][j] == 1)\r\n    {\r\n        int x = grid[i][j];\r\n        path.push_back('D');\r\n        grid[i][j] = -1; //indicates this to be visited\r\n        rat_in_a_maze(i + 1, j, n, grid, paths, path);\r\n        path.pop_back(); //undoing change\r\n        grid[i][j] = x; //restoring the grid\r\n    }\r\n\r\n    //moving down('L')\r\n    if ((j - 1) >= n && grid[i][j - 1] == 1)\r\n    {\r\n        int x = grid[i][j];\r\n        path.push_back('L');\r\n        grid[i][j] = -1; //indicates this to be visited\r\n        rat_in_a_maze(i, j - 1, n, grid, paths, path);\r\n        path.pop_back(); //undoing change\r\n        grid[i][j] = x; //restoring the grid\r\n    }\r\n\r\n    //moving down('R')\r\n    if ((j + 1) < n && grid[i][j + 1] == 1)\r\n    {\r\n        int x = grid[i][j];\r\n        path.push_back('R');\r\n        grid[i][j] = -1; //indicates this to be visited\r\n        rat_in_a_maze(i, j + 1, n, grid, paths, path);\r\n        path.pop_back(); //undoing change\r\n        grid[i][j] = x; //restoring the grid\r\n    }\r\n\r\n    //moving down('U')\r\n    if ((i - 1) >= 0 && grid[i - 1][j] == 1)\r\n    {\r\n        int x = grid[i][j];\r\n        path.push_back('U');\r\n        grid[i][j] = -1; //indicates this to be visited\r\n        rat_in_a_maze(i - 1, j, n, grid, paths, path);\r\n        path.pop_back(); //undoing change\r\n        grid[i][j] = x; //restoring the grid\r\n    }\r\n}\r\n\r\nint main()\r\n{\r\n    int n;//size of the grid (n * n)\r\n    cin >> n;\r\n\r\n    vector<vector<int>> grid(n, vector<int> (n, 0));\r\n    for (int i = 0; i < n; ++i)\r\n    {\r\n        for (int j = 0; j < n; ++j)\r\n        {\r\n            cin >> grid[i][j];\r\n        }\r\n    }\r\n\r\n    vector<string> paths;\r\n    string path;\r\n\r\n    rat_in_a_maze(0, 0, n, grid, paths, path);\r\n\r\n    cout<<\"The Paths from the Top Right to Bottom Left are : \\n\";\r\n\r\n    for (string s : paths) {\r\n        cout << s << \" \";\r\n    }\r\n    cout << endl;\r\n}"
  },
  {
    "path": "Algorithms/Cryptography/AES_Cipher/AES_Cipher.py",
    "content": "import sys, base64, json, math\ntry:\n   from Crypto.Cipher import AES\nexcept ImportError:\n   print (\"Error!! Module AES is required. Run either or following commands\")\n   print(\"pip install pycrypto\")\n   print(\"---------OR--------\")\n   print(\"pip3 install pycrypto\")\n   sys.exit()\n\nKEY=\"\"\nPADDING_CHARACTER=\"S\"\nVECTOR_FOR_AES=\"SUDESH1611GITHUB\"\n\ndef GetKey():\n    global KEY\n    tempKey = input(\"Enter password(min length: 8, max length: 32)\")\n    while(len(tempKey.strip())<8 or len(tempKey.strip())>32 or ' ' in tempKey):\n        if(' ' in tempKey):\n            print(\"White spaces are not allowed!\")\n        else:\n            print(\"Password must be at least 8 characters long and at max 32 characters long. Try Again!\")\n    while(len(tempKey)%8!=0):\n        tempKey+=PADDING_CHARACTER\n    KEY=tempKey\n\ndef AES_Encryption(cleartext):\n    if(len(KEY)<8 or len(KEY)%8!=0):\n        print(\"Password is corrupted. Exiting!\")\n        sys.exit()\n        return\n    AES_Encryptor = AES.new(KEY,AES.MODE_CBC,VECTOR_FOR_AES)\n    cleartext_length = len(cleartext)\n    nearest_multiple_of_16 = 16 * math.ceil(cleartext_length/16)\n    padded_cleartext = cleartext.rjust(nearest_multiple_of_16)\n    raw_ciphertext = AES_Encryptor.encrypt(padded_cleartext)\n    return base64.b64encode(raw_ciphertext).decode('utf-8')\n\ndef AES_Decryption(ciphertext):\n    if(len(KEY)<8 or len(KEY)%8!=0):\n        print(\"Password is corrupted. Exiting!\")\n        sys.exit()\n        return\n    AES_Decryptor = AES.new(KEY,AES.MODE_CBC,VECTOR_FOR_AES)\n    raw_ciphertext = base64.b64decode(ciphertext)\n    decrypted_message_with_padding = AES_Decryptor.decrypt(raw_ciphertext)\n    return decrypted_message_with_padding.decode('utf-8').strip()\n\nif __name__ == \"__main__\":\n    type=\"S\"\n    while(type not in \"ed\"):\n        type = input(\"Encrypt or Decrypt the text(e/d): \")\n        type = type.strip().lower()\n        if(len(type)!=1):\n            type=\"S\"\n    GetKey()\n    if(type==\"e\"):\n        print(\"NOTE: If you forget this password, you will not be able to decrypt text correctly. So, DO NOT FORGET PASSWORD!!\")\n        message = input(\"Enter message in single line: \")\n        ciphertext = AES_Encryption(message)\n        print(\"Encrypted Message: %s\" % ciphertext)\n    else:\n        encText = input(\"Enter encrypted message: \")\n        message = AES_Decryption(encText)\n        print(\"Original Message: %s\" % message)\n"
  },
  {
    "path": "Algorithms/Cryptography/AES_Cipher/README.md",
    "content": "## AES\nThe Advanced Encryption Standard (AES), also known by its original name Rijndael is a specification for the encryption of electronic data with different key and block sizes.\n"
  },
  {
    "path": "Algorithms/Cryptography/Affine_Cipher/Affine_Cipher.cpp",
    "content": "// In the affine cipher the letters of an alphabet of size m are first mapped to the integers in the range 0 … m − 1. \n// It then uses modular arithmetic to transform the integer that each plaintext letter corresponds to into another \n// integer that correspond to a ciphertext letter.\n\n// ENCYPTION \n// E(x) = (a*x + b) % 26\n// DECRYPTION\n// D(x) = a^-1(x - b) % 26\n// where a^-1 is modular multiplicative inverse of a\n\n\n\n\n#include<bits/stdc++.h> \nusing namespace std; \n  \nint a = 5; \nint b = 8; \nint inv_a;\n\n\n// encryptMessage: encrypt the given text using affine ciper\n\n// param text: the text which need to pe encrypted\n// type test: string\n// param func: custom func can be passed by the user which will be used in affine cipher\n// type func: function (int) ->int\n// default func: x: a*x + b\n  \nstring encryptMessage(string text, int (*func)(int)=NULL) \n{ \n\n    string encrypted_text = \"\";\n    if(func==NULL){\n        func = [](int x){   return a*x + b; };\n    }\n\n    int mod = 26;\n    for(const char character : text)\n    {\n\n        //to check the case and convert the character in that specific case\n        //else if characte is not a alphabet don't change it\n        int ascii_val, new_ascii_val;\n        if (isupper(character))\n        {\n            ascii_val = int(character) - int('A');\n            new_ascii_val = func(ascii_val) % mod;\n            new_ascii_val += int('A');\n        }\n\n        else if (islower(character))\n        {   \n            ascii_val = int(character) - int('a');\n            new_ascii_val = func(ascii_val) % mod;\n            new_ascii_val += int('a');\n        }\n\n        else \n        {\n            ascii_val = int(character);\n            new_ascii_val = ascii_val;\n        }\n\n        encrypted_text = encrypted_text + char(new_ascii_val);\n    }\n    \n    return encrypted_text;\n\n} \n\n\n  \n// decryptMessage: decrypt the given text using affine ciper\n\n//  param text: the encrypted text which need to pe decrypted\n//  type test: str\n//  param func: custom func can be passed by the user which will be used in affine cipher\n//  type func: function \n//  default func: x: inv_a*(x - b)\n  \nstring decryptMessage(string text, int (*func)(int)=NULL) \n{ \n    \n// finding modular multiplicative inverse of a\n    for(int i = 0; i < 26; i++)\n    {\n        if((i*a)%26 == 1){   inv_a = i; break;   }\n    }\n\n    string decyrpted_text = \"\";\n    if(func==NULL){\n        func = [](int x){   \n            return inv_a*(x - b); \n        };\n    }\n\n    int mod = 26;\n    for(const char character : text)\n    {\n\n        //to check the case and convert the character in that specific case\n        //else if characte is not a alphabet don't change it\n        int ascii_val, new_ascii_val;\n        if (isupper(character))\n        {\n            ascii_val = int(character) - int('A');\n            new_ascii_val = func(ascii_val) % mod;\n            new_ascii_val = new_ascii_val<0 ? mod + new_ascii_val : new_ascii_val;\n            new_ascii_val += int('A');\n        }\n\n        else if (islower(character))\n        {   \n            ascii_val = int(character) - int('a');\n            new_ascii_val = func(ascii_val) % mod;\n            new_ascii_val = new_ascii_val<0 ? mod + new_ascii_val : new_ascii_val;\n            new_ascii_val += int('a');\n        }\n\n        else \n        {\n            ascii_val = int(character);\n            new_ascii_val = ascii_val;\n        }\n\n        decyrpted_text = decyrpted_text + char(new_ascii_val);\n    }\n    \n    return decyrpted_text;\n\n} \n  \n\nint main(void) \n{ \n    string msg;\n    getline(cin,msg); \n\n    // custom function can also be used   \n    string cipherText = encryptMessage(msg); \n    cout << \"Encrypted Message is : \" << cipherText<<endl; \n    cout << \"Decrypted Message is: \" << decryptMessage(cipherText); \n  \n    return 0; \n} \n"
  },
  {
    "path": "Algorithms/Cryptography/Affine_Cipher/Affine_Cipher.py",
    "content": "'''\nIn the affine cipher the letters of an alphabet of size m are first mapped to the integers in the range 0 … m − 1. \nIt then uses modular arithmetic to transform the integer that each plaintext letter corresponds to into another \ninteger that correspond to a ciphertext letter.\n\nENCYPTION \nE(x) = (a*x + b) % 26\nDECRYPTION\nD(x) = a^-1(x - b) % 26\nwhere a^-1 is modular multiplicative inverse of a\n'''\n\n# custom constants \n''' these are the custom constants which can be edited'''\na = 5\nb = 10\n\n\n\n'''\n    encryptMessage: encrypt the given text using affine ciper\n\n    param text: the text which need to pe encrypted\n    type test: str\n    param func: custom func can be passed by the user which will be used in affine cipher\n    type func: function \n    default func: x: a*x + b\n'''\ndef encryptMessage(text, func = lambda x: a*x + b):\n\n    encrypted_text = \"\"\n    mod = 26\n    for character in text:\n\n\n        # to check the case and convert the character in that specific case\n        # else if characte is not a alphabet don't change it\n        if character.isupper():\n            ascii_val = ord(character) - ord('A')\n            new_ascii_val = func(ascii_val) % mod\n            new_ascii_val += ord('A')\n\n        elif character.islower():\n            ascii_val = ord(character) - ord('a')\n            new_ascii_val = func(ascii_val) % mod\n            new_ascii_val += ord('a')\n        else:\n            ascii_val = ord(character)\n            new_ascii_val = ascii_val\n\n        encrypted_text = encrypted_text + chr(new_ascii_val)\n\n    \n    return encrypted_text\n\n\n# finding modular multiplicative inverse of a\ninv_a = a\nfor i in range(26):\n    if i*a%26 == 1: inv_a = i; break\n\n\n\n'''\n   decryptMessage: decrypt the given text using affine ciper\n\n    param text: the encrypted text which need to pe decrypted\n    type test: str\n    param func: custom func can be passed by the user which will be used in affine cipher\n    type func: function \n    default func: x: inv_a*(x - b)\n'''\ndef decryptMessage(text, func = lambda x: inv_a*(x - b)):\n\n    decrypted_text = \"\"\n    mod = 26\n    for character in text:\n\n\n        # to check the case and convert the character in that specific case\n        # else if characte is not a alphabet don't change it\n        if character.isupper():\n            ascii_val = ord(character) - ord('A')\n            new_ascii_val = func(ascii_val) % mod\n            new_ascii_val += ord('A')\n\n        elif character.islower():\n            ascii_val = ord(character) - ord('a')\n            new_ascii_val = func(ascii_val) % mod\n            new_ascii_val += ord('a')\n        else:\n            ascii_val = ord(character)\n            new_ascii_val = ascii_val\n\n        decrypted_text = decrypted_text + chr(new_ascii_val)\n\n    \n    return decrypted_text\n\n\n#--------------------------------------------------------------------\n\ndef  main():\n    \n    text = input(\"enter your text: \")\n\n    # custom function can also be used \n    # eg. encryptMessage(text, func = lambda x: 7*x + 11 ) \n    cipher = encryptMessage(text)\n    print(\"encrypted text : \" + cipher)\n    print(\"decypted text : \" + decryptMessage(cipher))\n\n    \nmain()"
  },
  {
    "path": "Algorithms/Cryptography/Affine_Cipher/README.md",
    "content": "## This folder is empty.\n"
  },
  {
    "path": "Algorithms/Cryptography/Affine_Cipher/affine_cipher.c",
    "content": "#include<stdio.h>\r\n#include<stdlib.h>\r\n#include<string.h>\r\n#include<ctype.h>\r\n#include<stdlib.h>\r\n#define MAX 100000\r\n\r\nint CalcGCD(int);\r\n\r\nint CalcGCD(int alpha)\r\n{\r\n\tint x;\r\n\tint temp1 = alpha;\r\n\tint temp2 = 26;\r\n\r\n\twhile (temp2 != 0)\r\n\t{\r\n\t\tx = temp2;\r\n\t\ttemp2 = temp1 % temp2;\r\n\t\ttemp1 = x;\r\n\t}\r\n\treturn (temp1);\r\n}\r\n\r\nint main()\r\n{\r\n\tint i, j, k, gcd, alpha, beta, numstr[100], numcipher[100];\r\n\r\n\tchar str[100], cipher[100];\r\n\r\n\tprintf(\"Enter a string\\n\");\r\n\r\n\tfgets(str, MAX, stdin);\r\n\r\n\tfor (i = 0, j = 0; i < strlen(str); i++)\r\n\t{\r\n\t\tif (str[i] != ' ')\r\n\t\t{\r\n\t\t\tstr[j] = toupper(str[i]);\r\n\t\t\tj++;\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tstr[j] = ' ';\r\n\t\t\tj++;\r\n\t\t}\r\n\t}\r\n\r\n\tstr[j] = '\\0';\r\n\r\n\tprintf(\"Enter Alpha value and must be between 1 and 25 both included\\n\");\r\n\tscanf(\"%d\", &alpha);\r\n\r\n\tif (alpha < 1 || alpha > 25)\r\n\t{\r\n\t\tprintf(\"Alpha should lie in between 1 and 25\\nSorry Try again !\\n\");\r\n\t\texit(0);\r\n\t}\r\n\r\n\tgcd = CalcGCD(alpha);\r\n\r\n\tif (gcd != 1)\r\n\t{\r\n\t\tprintf(\"gcd(alpha,26)=1 but \\n gcd(%d,26)=%d\\nSorry Try again !\\n\", alpha, gcd);\r\n\t\texit(0);\r\n\t}\r\n\r\n\tprintf(\"Enter Beta value and must be between 0 and 25 both included\\n\");\r\n\tscanf(\"%d\", &beta);\r\n\r\n\tif (beta < 0 || beta > 25)\r\n\t{\r\n\t\tprintf(\"Beta value should lie between 0 and 25\\nSorry Try again !\\n\");\r\n\t\texit(0);\r\n\t}\r\n\r\n\tfor (i = 0; i < strlen(str); i++)\r\n\t{\r\n\t\tif (str[i] != ' ')\r\n\t\t\tnumstr[i] = str[i] - 'A';\r\n\t\telse\r\n\t\t\tnumstr[i] = -20;\r\n\t}\r\n\r\n\tprintf(\"Affine Cipher text is: \");\r\n\r\n\tfor (i = 0; i < strlen(str); i++)\r\n\t{\r\n\t\tif (numstr[i] != -20)\r\n\t\t{\r\n\t\t\tnumcipher[i] = ((alpha * numstr[i]) + beta) % 26;\r\n\t\t\tprintf(\"%c\", (numcipher[i] + 'A'));\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tprintf(\" \");\r\n\t\t}\r\n\t}\r\n\r\n\tprintf(\"\\n\");\r\n\r\n}\r\n"
  },
  {
    "path": "Algorithms/Cryptography/Bifid_Cipher/Bifid_Cipher.py",
    "content": " \n\"\"\"\n@author: Abhinav Tiwari\n\n@github: abhinav-idle\n\"\"\"\n\n\"\"\"\nBifid Cipher was invented in 1901 by Felix Delastelle.\n\nBifid cipher is a cipher in which we combine polybius \nsquare with transposition and fractionation i.e \nwe use regular system to shift the letters of input-text\nso that the cipher-text constitutes\nof permutaion of different plaintext(transposition) as in \nhere we replace each letter of input text with respect to \nit co-ordinates in polybius square (fractionation).\nthe co-ordinates are stored in row by column arrays \nrespectively.\nAfter performing these steps for every letter in input text\nwe have two arrays of equal length constituting of rows and \ncolumns of each letter, we then concatinate both the arrays\nmaking one array, then we make couples of two and get the \ncharacter according to the polybius square and concatinate \neach character to the encrypted text.\nVoila, we have done bifid encryption, to cross verify you can \ndecrypt the encrypted message to get back the originat text, by \nreverting each step and using the same polybius square.\n\n\nIn this cipher I'll use a custom 8x8 polybis square to \ncover complex encryption/decryption that includes any \nalpha-numeric combination of the following characters i.e \n        A-Z, a-z, 0-9, ?, @\nOne can use their own customized polybius square to \nencrypt even more complex input text.\n\"\"\"\n\ndef find_pos(polybius_square, character):\n    #returns the co-ordinates of character according to polybius square created as a \n    #tuple of co-ordinates, indexing is done from 1 and not from 0.\n    \n    for i in range(8):\n        \n        #to avoid error we've used try exceplt block, as index function raises ValueError \n        #when elemnt is not found in list.\n        \n        try:\n            j = polybius_square[i].index(character)\n            return i + 1, j + 1\n        \n        except ValueError:\n            pass\n\ndef get_word(a, b, polybius_square):\n    \n    #returns the character present at (a - 1, b - 1) co-ordinate\n    #indexing is from 1 so, we're substracting 1 to get actual co-ordinates.\n    \n    return polybius_square[a-1][b-1]   \n     \ndef create_polybius_square():\n    \n    #create and return polybius square as a list\n    \n    arr = []\n    num = 48    #for numeric characters 0-9.\n    upper_case = 63    #for uppercase alphabets A-Z and ?,@.\n    lower_case = 97    #for lowercase alphabets a-z. \n    \n    for i in range(8):\n        \n        sub_arr = []\n        cnt = 0\n        \n        while(cnt<8):\n        \n            if num<=57 and cnt<8:\n                sub_arr.append(chr(num))\n                num += 1 \n                cnt += 1\n            \n            if upper_case<=90 and cnt<8:\n                sub_arr.append(chr(upper_case))\n                upper_case += 1\n                cnt+=1\n                \n            if lower_case<=122 and cnt<8:\n                sub_arr.append(chr(lower_case))\n                lower_case += 1\n                cnt+=1\n            \n        arr.append(sub_arr)\n    \n    return arr\n\ndef bifid_encryption(polybius_square, text):\n    #implementing bifid-encryption\n    \n    #to store co-ordinates\n    row = []\n    column = []\n\n    for letter in text:\n        i,j = find_pos(polybius_square, letter)\n        row.append(i)\n        column.append(j)\n\n    array = []    \n    array.extend(row)\n    array.extend(column)\n\n    encrypted_text = \"\"\n    \n    for i in range(0,len(array),2):\n        character = get_word(array[i], array[i+1], polybius_square)\n        encrypted_text += character\n\n    return encrypted_text   \n \ndef decryption(polybius_square, encrypted_text):    \n    #decrypt message\n    \n    array = []\n    for text in encrypted_text:\n        array.extend(list(find_pos(polybius_square,text)))\n\n    row  = array[:len(array)//2]\n    column  = array[len(array)//2:]\n\n    original_text = \"\"\n    \n    for i in range(len(row)):\n        original_text += get_word(row[i],column[i],polybius_square)\n    \n    return original_text    \n\n\ndef main():\n    \n    #Enter text to encrypt\n\n    text = input()\n\n    #created polybius square\n    polybius_square = create_polybius_square()\n\n    print(\"Encrypted text : \",bifid_encryption(polybius_square, text))\n    print(\"Original text : \",decryption(polybius_square, bifid_encryption(polybius_square, text)))\n\nmain()\n"
  },
  {
    "path": "Algorithms/Cryptography/Bifid_Cipher/README.md",
    "content": "## This folder is empty.\n"
  },
  {
    "path": "Algorithms/Cryptography/CIA_Triad_Ciper/README.md",
    "content": "## This folder is empty.\n"
  },
  {
    "path": "Algorithms/Cryptography/Caesar_Cipher/Caesar Cypher.cpp",
    "content": "#include<iostream>\n#include<string.h>\nusing namespace std;\nint main() {\n   cout<<\"Enter the message:\\n\";\n   char msg[100];\n   cin.getline(msg,100); //take the message as input\n   int i, j, length,choice,key;\n   cout << \"Enter key: \";\n   cin >> key; //take the key as input\n   length = strlen(msg);\n   cout<<\"Enter your choice \\n1. Encryption \\n2. Decryption \\n\";\n   cin>>choice;\n   if (choice==1) //for encryption{\n      char ch;\n      for(int i = 0; msg[i] != '\\0'; ++i) {\n         ch = msg[i];\n         //encrypt for lowercase letter\n         If (ch >= 'a' && ch <= 'z'){\n            ch = ch + key;\n            if (ch > 'z') {\n               ch = ch - 'z' + 'a' - 1;\n            }  \n            msg[i] = ch;\n         }\n         //encrypt for uppercase letter\n         else if (ch >= 'A' && ch <= 'Z'){\n            ch = ch + key;\n            if (ch > 'Z'){\n               ch = ch - 'Z' + 'A' - 1;\n            }\n            msg[i] = ch;\n         }\n      }\n      printf(\"Encrypted message: %s\", msg);\n   }\n   else if (choice == 2) { //for decryption\n      char ch;\n      for(int i = 0; msg[i] != '\\0'; ++i) {\n         ch = msg[i];\n         //decrypt for lowercase letter\n         if(ch >= 'a' && ch <= 'z') {\n            ch = ch - key;\n            if(ch < 'a'){\n               ch = ch + 'z' - 'a' + 1;\n            }\n            msg[i] = ch;\n         }\n         //decrypt for uppercase letter\n         else if(ch >= 'A' && ch <= 'Z') {\n            ch = ch - key;\n            if(ch < 'A') {\n               ch = ch + 'Z' - 'A' + 1;\n            }\n            msg[i] = ch;\n         }\n      }\n      cout << \"Decrypted message: \" << msg;\n   }\n}"
  },
  {
    "path": "Algorithms/Cryptography/Caesar_Cipher/Caesar Cypher.py",
    "content": "def encrypt(text,s):\nresult = \"\"\n   # transverse the plain text\n   for i in range(len(text)):\n      char = text[i]\n      # Encrypt uppercase characters in plain text\n      \n      if (char.isupper()):\n         result += chr((ord(char) + s-65) % 26 + 65)\n      # Encrypt lowercase characters in plain text\n      else:\n         result += chr((ord(char) + s - 97) % 26 + 97)\n      return result\n#check the above function\ntext = input()\ns = input()\n\nprint \"Plain Text : \" + text\nprint \"Shift pattern : \" + str(s)\nprint \"Cipher: \" + encrypt(text,s)"
  },
  {
    "path": "Algorithms/Cryptography/Caesar_Cipher/CaesarCipher.java",
    "content": "import java.util.Scanner;\n\npublic class CaesarCipher {\n    public static final int SHIFT_MAX = 26;\n\n    public static int shiftChar(int c, int shift) {\n        shift = (shift+SHIFT_MAX)%SHIFT_MAX;\n\n        if ('a' <= c && c <= 'z') {\n            return ((c - 'a' + shift)%SHIFT_MAX + 'a');\n        } else if ('A' <= c && c <= 'Z') {\n            return ((c - 'A' + shift)%SHIFT_MAX + 'A');\n        } else {\n            return c;\n        }\n    }\n\n    public static String cipher(String str, int shift) {\n        return str.chars().map(c->shiftChar(c, shift)).collect(\n                StringBuilder::new,\n                StringBuilder::appendCodePoint,\n                StringBuilder::append).toString();\n    }\n\n    public static String cipher(String str) {\n        return cipher(str, 13);\n    }\n\n    public static String decipher(String str, int shift) {\n        return cipher(str, SHIFT_MAX - shift);\n    }\n\n    public static String decipher(String str) {\n        return decipher(str, 13);\n    }\n\n    public static void main(String [] args) {\n        Scanner scanner = new Scanner(System.in);\n        System.out.print(\"Enter shift (Caesar's = 13): \");\n        int shift = scanner.nextInt();\n        System.out.println(\"Enter text to be encrypted:\");\n        System.out.print(\"> \");\n\n        String text = scanner.nextLine(); // We read empty newline\n        text = scanner.nextLine();\n\n        String crypt = cipher(text, shift);\n        System.out.println(crypt);\n        System.out.println(decipher(crypt, shift));\n    }\n}\n"
  },
  {
    "path": "Algorithms/Cryptography/Caesar_Cipher/Caesar_Cipher.c",
    "content": "#include<stdio.h>\n\nint main() {\n    char message[100], ch;\n    int i, key;\n\n    printf(\"Message to encrypt: \");\n    gets(message);\n    do {\n        printf(\"Key: \");\n        scanf(\"%d\", & key);\n    } while (key < 0 || key > 26);\n\n    for (i = 0; message[i] != '\\0'; ++i) {\n        ch = message[i];\n\n        if (ch >= 'a' && ch <= 'z') {\n            ch = ch + key;\n\n            if (ch > 'z') {\n                ch = ch - 'z' + 'a' - 1;\n            }\n\n            message[i] = ch;\n        } else if (ch >= 'A' && ch <= 'Z') {\n            ch = ch + key;\n\n            if (ch > 'Z') {\n                ch = ch - 'Z' + 'A' - 1;\n            }\n\n            message[i] = ch;\n        }\n    }\n\n    printf(\"Encrypted message: %s\\n\", message);\n\n    return 0;\n}\n"
  },
  {
    "path": "Algorithms/Cryptography/Caesar_Cipher/Caesar_Cipher.cs",
    "content": "using System;\n\nclass Program\n{\n    /// <summary>\n    /// Shifts every character of a given string by a specified amount\n    /// and returns the shifted string.\n    /// </summary>\n    private static string CaesarCipher(string text, int shiftAmount)\n    {\n        char[] characters = text.ToCharArray();\n\n        for (int i = 0; i < characters.Length; i++)\n        {\n            char character = characters[i];\n\n            if (char.IsLetter(character) == false) { continue; }\n\n            int offsetCharacter = (char.IsLower(character) ? 'a' : 'A');\n\n            characters[i] = (char)((((character + shiftAmount) - offsetCharacter) % 26) + offsetCharacter);\n        }\n\n        return string.Join(string.Empty, characters);\n    }\n\n    /// <summary>\n    /// Encrypts the given text using the Caesar cipher.\n    /// </summary>\n    private static string Encrypt(string text, int shiftAmount)\n    {\n        return Program.CaesarCipher(text, shiftAmount);\n    }\n\n    /// <summary>\n    /// Decrypts the given text using the Caesar cipher.\n    /// </summary>\n    private static string Decrypt(string text, int shiftAmount)\n    {\n        return Program.CaesarCipher(text, (26 - shiftAmount));\n    }\n\n    /// <summary>\n    /// Main application function.\n    /// </summary>\n    static void Main()\n    {\n        bool shouldEncrpyt;\n        int shiftAmount;\n        string textToProcess, userInput;\n        \n        Console.WriteLine(\"Do you want to [E]ncrypt or [D]ecrypt? (Enter \\\"E\\\" or \\\"D\\\"):\");\n        userInput = Console.ReadLine().ToLower();\n        \n        if ((userInput != \"e\") && (userInput != \"d\")) { Program.ExitAfterInvalidInput(); }\n        \n        shouldEncrpyt = (userInput == \"e\");\n\n        Console.WriteLine(string.Format(\"Enter the text to {0}:\", (shouldEncrpyt ? \"encrypt\" : \"decrypt\")));\n        userInput = Console.ReadLine();\n        \n        if (string.IsNullOrWhiteSpace(userInput)) { Program.ExitAfterInvalidInput(); }\n        \n        textToProcess = userInput;\n\n        Console.WriteLine(\"Enter an integer for the shift amount (key):\");\n        userInput = Console.ReadLine();\n        \n        if (int.TryParse(userInput, out shiftAmount) == false) { Program.ExitAfterInvalidInput(); }\n\n        string result = (shouldEncrpyt ? Program.Encrypt(textToProcess, shiftAmount) : Program.Decrypt(textToProcess, shiftAmount));\n        \n        Console.WriteLine();\n        Console.WriteLine(string.Format(\"Result: {0}\", result));\n    }\n    \n    /// <summary>\n    /// Informs the user that an invalid value has been entered and exits the program.\n    /// </summary>\n    private static void ExitAfterInvalidInput()\n    {\n        Console.WriteLine(\"You've entered an invalid value. Exiting...\");\n        Environment.Exit(1);\n    }\n}\n"
  },
  {
    "path": "Algorithms/Cryptography/Caesar_Cipher/Caesar_Cipher.js",
    "content": "var caesarEncypt = function(str, key) {\n\n    if (key < 0) {\n        return caesarEncypt(str, key + 26);\n    }\n\n    var encrypted = \"\";\n\n    for (var i = 0; i < str.length; i++) {\n\n        var c = str[i];\n\n        if (c.match(/[a-z]/i)) {\n\n            var code = str.charCodeAt(i);\n\n            if (code >= 65 && code <= 90) {\n                c = String.fromCharCode(((code - 65 + key) % 26) + 65);\n            } else if (code >= 97 && code <= 122) {\n                c = String.fromCharCode(((code - 97 + key) % 26) + 97);\n            }\n        }\n\n        encrypted += c;\n    }\n\n    return encrypted;\n};\n"
  },
  {
    "path": "Algorithms/Cryptography/Caesar_Cipher/Caesar_Cipher.php",
    "content": "<?php\nfunction cipher(string $str, int $key)\n{   \n    $k = $key % 26;\n\n    $input = array_map(function($char){\n        return ord($char);\n    }, str_split($str));\n    \n    $res = array_map(function($char) use($k){\n        //capital letters\n        if($char > 64 && $char < 91)\n        {\n            return chr(65 + ($char + $k) % 65 % 26);\n        }\n        else if($char > 96 && $char < 123)\n        {\n            return chr(97 + ($char + $k) % 97 % 26);\n        }\n        else\n        {\n            return chr($char);\n        }\n    }, $input);\n\n    return implode($res);\n}\n\n?>\n"
  },
  {
    "path": "Algorithms/Cryptography/Caesar_Cipher/Caesar_Cypher.rb",
    "content": "class CaesarCipher\n  ORDER_ALPHABET = (\"a\"..\"z\").to_a # Array of valid letter rotation (Only english alphabet letters)\n  class << self\n    def encrypt(sentence, times = 3)\n      # Converts to_s allowing to map through each char of it\n      sentence.to_s.chars.map.with_index {|char, index|\n        # If char is not included in the array, return the char without rotate\n        ORDER_ALPHABET.include?(char.downcase) ? rotate(times, char, index) : char\n      }.join(\"\")\n    end\n  \n    private\n    # Rotates the n times assigned by the user\n    def rotate(times,current_char, index)\n      ORDER_ALPHABET.rotate(times)[ORDER_ALPHABET.index(current_char.downcase)]\n    end\n  end\nend\n\nputs CaesarCipher.encrypt(\"Hello World\", 13) # uryyb jbeyq\nputs CaesarCipher.encrypt(\"Uryyb jbeyq\", -13) # hello world\nputs CaesarCipher.encrypt(\"Th1s 1s @ compl3x w0rd\", 5) # ym1x 1x @ htruq3c b0wi\nputs CaesarCipher.encrypt([\"Also\", \"Works\", \"for\", \"complex\", \"structures\"], 7) # [\"hszv\", \"dvyrz\", \"mvy\", \"jvtwsle\", \"zaybjabylz\"]\nputs CaesarCipher.encrypt(nil)\nputs CaesarCipher.encrypt(\"Nothing change\", 0) # nothing change"
  },
  {
    "path": "Algorithms/Cryptography/Caesar_Cipher/README.md",
    "content": "## This folder is empty.\n"
  },
  {
    "path": "Algorithms/Cryptography/README.md",
    "content": "# This folder is empty.\n"
  },
  {
    "path": "Algorithms/Cryptography/RSA_Cipher/README.md",
    "content": "## This folder is empty.\n"
  },
  {
    "path": "Algorithms/Cryptography/RSA_Cipher/RSA_Cipher.py",
    "content": "# -*- coding: utf-8 -*-\nimport random\nfrom math import gcd\n\nplaintext = (input('Enter the value of text = '))\n\npt = \"\"\nif (plaintext.isnumeric()) :\n    pt = plaintext\nelse :\n    for i in range(0,len(plaintext)):\n      pt += str(ord(plaintext[i]))\n    print(pt)    \n\ndef modInverse(e, phin) : \n    e = e % phin; \n    for d in range(1, phin) : \n        if ((e * d) % phin == 1) : \n            return d\n    return 1\n\nimport sympy\np=sympy.randprime(1000, 2000) \nq=sympy.randprime(1000, 2000) \n\nn=p*q\n\nphin=(p-1)*(q-1)\nlist=[]\n\nfor i in range(2,phin):\n  if gcd(phin,i)==1:\n    list.append(i)\n\ne = random.choice(list) \n\nd = modInverse(e,phin)\n\nciphertext = pow(int(pt),e)%n\ndecrypttext = pow(ciphertext,d)%n\n\nprint('n = '+str(n)+' e = '+str(e)+' phi(n) = '+str(phin)+' d = '+str(d)+' cipher text = '+str(ciphertext)+' decrypted text = '+str(decrypttext))\n"
  },
  {
    "path": "Algorithms/Cryptography/RSA_Cipher/RSA_cipher.cpp",
    "content": "#include <iostream>\n#include <ctime>\n#include <cstdlib>\n#include <cstring>\n#include <cstdio>\n#include <iomanip>\nusing namespace std;\n\n#define LIMIT 10000\n\nint log_power(int n, int p, int mod)\n{\n    int result = 1;\n    for (; p; p >>= 1)\n    {\n        if (p & 1)\n            result = (1LL * result * n) % mod;\n        n = (1LL * n * n) % mod;\n    }\n    return result;\n}\n\nbool new_func(int n)\n{\n    bool ok = true;\n\n    for (int i = 1; i <= 5 && ok; i++) {\n        int a = rand() + 1;\n        int result = log_power(a, n - 1, n);\n        ok &= (result == 1);\n    }\n\n    return ok;\n}\n\nint generate_prime()\n{\n    int generated = rand() % LIMIT;\n    while (!new_func(generated))\n        generated = rand() % LIMIT;\n    return generated;\n}\n\nint gcd(int a, int b)\n{\n    while (b)\n    {\n        int r = a % b;\n        a = b;\n        b = r;\n    }\n    return a;\n}\n\nint generate_coprime(int n)\n{\n    int generated = rand() % LIMIT;\n    while (gcd(n, generated) != 1)\n        generated = rand() % LIMIT;\n    return generated;\n}\n\npair<int, int> euclid_extended(int a, int b) {\n    if(!b) {\n        return {1, 0};\n    }\n\n    auto result = euclid_extended(b, a % b);\n    return { result.second, result.first - (a / b) * result.second };\n}\n\nint modular_inverse(int n, int mod)\n{\n    int inverse = euclid_extended(n, mod).first;\n    while(inverse < 0)\n        inverse += mod;\n    return inverse;\n}\n\ntypedef pair<int, int> PublicKey;\ntypedef pair<int, int> PrivateKey;\n\nstruct Keys\n{\n    PublicKey public_key;\n    PrivateKey private_key;\n};\n\nKeys generate_keys()\n{\n    Keys result;\n\n    int p, q;\n\n    p = generate_prime();\n    q = generate_prime();\n\n    int n = p * q;\n    int phi = (p -1) * (q - 1);\n    int e = generate_coprime(phi);\n\n    result.public_key =  make_pair(n, e);\n\n    int d = modular_inverse(e, phi);\n\n    result.private_key = make_pair(n, d);\n\n    return result;\n}\n\nint encrypt(PublicKey key, int value)\n{\n    return log_power(value, key.second, key.first);\n}\n\nint decrypt(PrivateKey key, int value)\n{\n    return log_power(value, key.second, key.first);\n}\n\nint main()\n{\n    string s;\n    srand(time(NULL));\n\n    Keys keys = generate_keys();\n\n    cout << \"Public key: \" << keys.public_key.first << \" \" << keys.public_key.second << \"\\n\";\n    cout << \"Private key: \" << keys.private_key.first << \" \" << keys.private_key.second << \"\\n\";\n    cout << \"Enter your message\\n\";\n    cin >> s;\n    int len = s.size();\n\n    cout << \"Initial string: \" << s << \"\\n\";\n    int enc[100] = {0};\n    int dec[100] = {0};\n\n    for (int i = 0; i < len; i++)\n        enc[i] = encrypt(keys.public_key, s[i]);\n\n    for (int i = 0; i < len; i++)\n        dec[i] = decrypt(keys.private_key, enc[i]);\n    cout << \"Encrypted string\\n\";\n    for(int i = 0; i < len; i++)\n        cout << (int)enc[i];\n    cout << \"\\n\";\n    cout << \"Decrypted string: \\n\";\n    for (int i = 0; i < len; i++)\n        cout << (char)dec[i];\n    cout << \"\\n\";\n\n    return 0;\n}\n"
  },
  {
    "path": "Algorithms/Cryptography/RSA_Cipher/RSA_cipher.java",
    "content": "/*\r\n * RSA algorithm is asymmetric cryptography algorithm. \r\n * Asymmetric actually means that it works on two different keys i.e. Public Key and Private Key. \r\n * As the name describes that the Public Key is given to everyone and Private key is kept private. \r\n */\r\n\r\nimport java.io.DataInputStream;\r\nimport java.io.IOException;\r\nimport java.math.BigInteger;\r\nimport java.util.Random;\r\n class Algorithm\r\n{\r\n    private BigInteger P;\r\n    private BigInteger Q;\r\n    public BigInteger N;\r\n    private BigInteger PHI;\r\n    public BigInteger e;\r\n    private BigInteger d;\r\n    private int maxLength = 1024;\r\n    private Random R;\r\n \r\n    public Algorithm()\r\n    {\r\n        R = new Random();\r\n        \r\n        //prime numbers \r\n        P = BigInteger.probablePrime(maxLength, R);\r\n        Q = BigInteger.probablePrime(maxLength, R);\r\n        \r\n        //N = P*Q\r\n        N = P.multiply(Q);\r\n        \r\n        //(|)(N) = (P-1)*(Q-1)\r\n        PHI = P.subtract(BigInteger.ONE).multiply(  Q.subtract(BigInteger.ONE));\r\n        \r\n        \r\n        e = BigInteger.probablePrime(maxLength / 2, R);\r\n        \r\n        while (PHI.gcd(e).compareTo(BigInteger.ONE) > 0 && e.compareTo(PHI) < 0)\r\n        {\r\n            e.add(BigInteger.ONE);\r\n        } //e relatively prime to PHI\r\n        \r\n        d = e.modInverse(PHI);\r\n        \r\n    }\r\n \r\n    public Algorithm(BigInteger e, BigInteger d, BigInteger N)\r\n    {\r\n        this.e = e;\r\n        this.d = d;\r\n        this.N = N;\r\n    }\r\n \r\n   \r\n\r\n \r\n    // Encrypting the data\r\n    public byte[] encryptMessage(byte[] data)\r\n    {\t\r\n    \t// returns (data^e)%N\r\n        return (new BigInteger(data)).modPow(e, N).toByteArray();\r\n    }\r\n \r\n    // Decrypting the data\r\n    public byte[] decryptMessage(byte[] data)\r\n    {\t\r\n    \t//returns (data^d)%N\r\n    \t//remember d is our private key, we never share that \r\n    \t//otherwise our security will be compromised.\r\n    \t\r\n        return (new BigInteger(data)).modPow(d, N).toByteArray();\r\n    }\r\n}\r\n\r\npublic class RSA_cipher {\r\n\t//return all the bytes concatenated in a string\r\n    private static String byte2String(byte[] cipher)\r\n    {\r\n        String temp = \"\";\r\n        for (byte b : cipher)\r\n        {\r\n            temp += Byte.toString(b);\r\n        }\r\n        return temp;\r\n    }\r\n\t\r\n\t public static void main (String [] arguments) throws IOException\r\n\t    {\r\n\t        Algorithm algorithm = new Algorithm();\r\n\t        DataInputStream input = new DataInputStream(System.in);\r\n\t        String inputString;\r\n\t        System.out.println(\"Enter data to send.\");\r\n\t        inputString = input.readLine();\r\n\t        System.out.println(\"Encrypting the data: \" + inputString);\r\n\t        System.out.println(\"The data in bytes is:: \"\r\n\t                + byte2String(inputString.getBytes()));\r\n\t        System.out.printf(\"Shared public key:\\nN: %d \\ne: %d \\n\\n\",algorithm.N, algorithm.e);\r\n\t        \r\n\t        // encryption\r\n\t        byte[] cipher = algorithm.encryptMessage(inputString.getBytes());\r\n\t        \r\n\t        // decryption\r\n\t        byte[] plain = algorithm.decryptMessage(cipher);\r\n\t        \r\n\t        System.out.println(\"Decrypting Bytes: \" + byte2String(plain));\r\n\t        System.out.println(\"Original data is: \" + new String(plain));\r\n\t    }\r\n\t \r\n}"
  },
  {
    "path": "Algorithms/Cryptography/Shamir_Cipher/Shamir_Cipher.c",
    "content": "#include <stdlib.h>\n#include <stdio.h>\n#include <time.h>\n#include <string.h>\n#include <math.h>\n#include <unistd.h>\n\nconst int N = 4;\nconst int K = 2;\nconst int prime = 256;\nsize_t size = 1024;\n\nint mod_expo(int base, int exp, int mod)\n{\n\tif (exp == 0)\n\t{\n\t\treturn 1;\n\t}\n\telse if (exp % 2 == 0)\n\t{\n\t\tint mysqrt = mod_expo(base, exp / 2, mod);\n\t\treturn (mysqrt * mysqrt) % mod;\n\t}\n\telse\n\t{\n\t\treturn (base * mod_expo(base, exp - 1, mod)) % mod;\n\t}\n}\n\nvoid free_heap_mem(char **shares, int n)\n{\n\tint i;\n\n\tfor (i = 0; i < n; ++i)\n\t{\n\t\tfree(shares[i]);\n\t}\n\tfree(shares);\n}\n\n\nint *gcdD(int a, int b)\n{\n\tint *xyz = malloc(sizeof(int) * 3);\n\n\tif (b == 0)\n\t{\n\t\txyz[0] = a;\n\t\txyz[1] = 1;\n\t\txyz[2] = 0;\n\t}\n\telse\n\t{\n\t\tint n = floor(a / b);\n\t\tint c = a % b;\n\t\tint *r = gcdD(b, c);\n\n\t\txyz[0] = r[0];\n\t\txyz[1] = r[2];\n\t\txyz[2] = r[1] - r[2] * n;\n\n\t\tfree(r);\n\t}\n\n\treturn xyz;\n}\n\nint modInverse(int k)\n{\n\tk = k % prime;\n\n\tint r;\n\tint *xyz;\n\n\tif (k < 0)\n\t{\n\t\txyz = gcdD(prime, -k);\n\t\tr = -xyz[2];\n\t}\n\telse\n\t{\n\t\txyz = gcdD(prime, k);\n\t\tr = xyz[2];\n\t}\n\n\tfree(xyz);\n\n\treturn (prime + r) % prime;\n}\n\nint *split_number(int number, int n, int t)\n{\n\tint *shares = malloc(sizeof(int) * n);\n\tint *coef = malloc(sizeof(int) * t);\n\tint x;\n\tint i;\n\n\tcoef[0] = number;\n\n\tfor (i = 1; i < t; ++i)\n\t{\n\n#ifdef HAVE_ARC4RANDOM\n\t\tcoef[i] = arc4random_uniform(prime);\n#else\n\t\tcoef[i] = rand() % (prime);\n#endif\n\t}\n\n\tfor (x = 0; x < n; ++x)\n\t{\n\t\tint y = coef[0];\n\n\t\tfor (i = 1; i < t; ++i)\n\t\t{\n\t\t\tint temp = mod_expo(x + 1, i, prime);\n\n\t\t\ty = (y + (coef[i] * temp % prime)) % prime;\n\t\t}\n\t\ty = (y + prime) % prime;\n\n\t\tshares[x] = y;\n\t}\n\n\tfree(coef);\n\n\treturn shares;\n}\n\nchar **split_string(char *secret, int n, int t)\n{\n\tint len = strlen(secret);\n\n\tchar **shares = malloc(sizeof(char *) * n);\n\tint i;\n\n\tfor (i = 0; i < n; ++i)\n\t{\n\n\t\tshares[i] = (char *)malloc(2 * len + 6 + 1);\n\n\t\tsprintf(shares[i], \"%02X%02XAA\", (i + 1), t);\n\t}\n\n\tfor (i = 0; i < len; ++i)\n\t{\n\t\tint letter = secret[i];\n\n\t\tif (letter < 0)\n\t\t{\n\t\t\tletter = prime + letter;\n\t\t}\n\n\t\tint *chunks = split_number(letter, n, t);\n\t\tint j;\n\n\t\tfor (j = 0; j < n; ++j)\n\t\t{\n\t\t\tif (chunks[j] == prime)\n\t\t\t{\n\t\t\t\tsprintf(shares[j] + 6 + i * 2, \"G0\");\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tsprintf(shares[j] + 6 + i * 2, \"%02X\", chunks[j]);\n\t\t\t}\n\t\t}\n\n\t\tfree(chunks);\n\t}\n\n\treturn shares;\n}\n\nint join_shares(int *xy_pairs, int n)\n{\n\tint secret = 0;\n\tlong numerator;\n\tlong denominator;\n\tlong startposition;\n\tlong nextposition;\n\tlong value;\n\tint i;\n\tint j;\n\n\tfor (i = 0; i < n; ++i)\n\t{\n\t\tnumerator = 1;\n\t\tdenominator = 1;\n\n\t\tfor (j = 0; j < n; ++j)\n\t\t{\n\t\t\tif (i != j)\n\t\t\t{\n\t\t\t\tstartposition = xy_pairs[i * 2];\n\t\t\t\tnextposition = xy_pairs[j * 2];\n\t\t\t\tnumerator = (numerator * -nextposition) % prime;\n\t\t\t\tdenominator = (denominator * (startposition - nextposition)) % prime;\n\t\t\t}\n\t\t}\n\n\t\tvalue = xy_pairs[i * 2 + 1];\n\n\t\tsecret = (secret + (value * numerator * modInverse(denominator))) % prime;\n\t}\n\n\tsecret = (secret + prime) % prime;\n\n\treturn secret;\n}\n\nchar *decode(char **shares, int n)\n{\n\n\tif ((n == 0) || (shares == NULL) || (shares[0] == NULL))\n\t{\n\t\treturn NULL;\n\t}\n\tint len = (strlen(shares[0]) - 6) / 2;\n\n\tchar *result = malloc(len + 1);\n\tchar codon[3];\n\tcodon[2] = '\\0';\n\n\tint x[n];\n\tint i;\n\tint j;\n\n\tfor (i = 0; i < n; ++i)\n\t{\n\t\tif (shares[i] == NULL)\n\t\t{\n\t\t\tfree(result);\n\t\t\treturn NULL;\n\t\t}\n\n\t\tcodon[0] = shares[i][0];\n\t\tcodon[1] = shares[i][1];\n\n\t\tx[i] = strtol(codon, NULL, 16);\n\t}\n\n\tfor (i = 0; i < len; ++i)\n\t{\n\t\tint *chunks = malloc(sizeof(int) * n * 2);\n\n\t\tfor (j = 0; j < n; ++j)\n\t\t{\n\t\t\tchunks[j * 2] = x[j];\n\n\t\t\tcodon[0] = shares[j][6 + i * 2];\n\t\t\tcodon[1] = shares[j][6 + i * 2 + 1];\n\n\t\t\tif (memcmp(codon, \"G0\", 2) == 0)\n\t\t\t{\n\t\t\t\tchunks[j * 2 + 1] = prime;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tchunks[j * 2 + 1] = strtol(codon, NULL, 16);\n\t\t\t}\n\t\t}\n\n\t\tchar letter = join_shares(chunks, n);\n\n\t\tfree(chunks);\n\n\t\tsprintf(result + i, \"%c\", letter);\n\t}\n\n\treturn result;\n}\n\nchar *encode(char *secret, int n, int t)\n{\n\tchar **result = split_string(secret, n, t);\n\n\tint len = strlen(secret);\n\tint key_len = 6 + 2 * len + 1;\n\tint i;\n\n\tchar *shares = malloc(key_len * n + 1);\n\n\tfor (i = 0; i < n; ++i)\n\t{\n\t\tsprintf(shares + i * key_len, \"%s\\n\", result[i]);\n\t}\n\n\tfree_heap_mem(result, n);\n\n\treturn shares;\n}\n\n// Driver Code\nint main(void)\n{\n\tsrand(time(NULL));\n\n\tint M;\n\tchar **codes = malloc(sizeof(char *) * prime);\n\tchar *code = malloc(sizeof(char) * prime);\n\tchar *str = malloc(sizeof(char) * size);\n\n\tgetline(&str, &size, stdin);\n\tchar *shares = encode(str, N, K);\n\tputs(shares);\n\n\tprintf(\"Enter the number of shares you want to enter to decode the orginal secret\\n\");\n\tscanf(\"%d\", &M);\n\tfor (int i = 0; i < M; i++)\n\t{\n\t\tprintf(\"Enter the %d share\\n\", i+1);\n\t\tscanf(\"%s\", code);\n\t\tcodes[i] = strdup(code);\n\t}\n\tchar *secret = decode(codes, M);\n\tprintf(\"The secret is : \");\n\tputs(secret);\n\tfree_heap_mem(codes, M);\n\tfree(shares);\n\tfree(secret);\n\tfree(code);\n\tfree(str);\n\treturn 0;\n}\n"
  },
  {
    "path": "Algorithms/Cryptography/Shamir_Cipher/Shamir_Cipher.cpp",
    "content": "#include <bits/stdc++.h>\nusing namespace std;\n\nint calculate_Y(int x, vector<int> &poly)\n{\n    int y = 0;\n    int temp = 1;\n    for (auto coeff : poly)\n    {\n        y = (y + (coeff * temp));\n        temp = (temp * x);\n    }\n    return y;\n}\n\nvoid secret_sharing(int S, vector<pair<int, int>> &points,\n                    int N, int K)\n{\n    vector<int> poly(K);\n    poly[0] = S;\n\n    for (int j = 1; j < K; ++j)\n    {\n        int p = 0;\n        while (p == 0)\n            p = (rand() % 997);\n        poly[j] = p;\n    }\n    for (int j = 1; j <= N; ++j)\n    {\n        int x = j;\n        int y = calculate_Y(x, poly);\n        points[j - 1] = {x, y};\n    }\n}\n\nstruct fraction\n{\n    int num, den;\n    fraction(int n, int d)\n    {\n        num = n, den = d;\n    }\n\n    void reduce_fraction(fraction &f)\n    {\n        int gcd = __gcd(f.num, f.den);\n        f.num /= gcd, f.den /= gcd;\n    }\n\n    fraction operator*(fraction f)\n    {\n        fraction temp(num * f.num, den * f.den);\n        reduce_fraction(temp);\n        return temp;\n    }\n\n    fraction operator+(fraction f)\n    {\n        fraction temp(num * f.den + den * f.num, den * f.den);\n        reduce_fraction(temp);\n        return temp;\n    }\n};\n\nint Generate_Secret(int x[], int y[], int M)\n{\n\n    fraction ans(0, 1);\n    for (int i = 0; i < M; ++i)\n    {\n        fraction l(y[i], 1);\n        for (int j = 0; j < M; ++j)\n        {\n            if (i != j)\n            {\n                fraction temp(-x[j], x[i] - x[j]);\n                l = l * temp;\n            }\n        }\n        ans = ans + l;\n    }\n    return ans.num;\n}\n\nvoid solve(int S, int N, int K)\n{\n    vector<pair<int, int>> points(N);\n    secret_sharing(S, points, N, K);\n    int M = 2;\n    if (M < K)\n    {\n        cout << \"Points are less than threshold \" << K << \" Points Required\" << endl;\n    }\n\n    int *x = new int[M];\n    int *y = new int[M];\n\n    for (int i = 0; i < M; ++i)\n    {\n        x[i] = points[i].first;\n        y[i] = points[i].second;\n    }\n\n    cout << \"Your Secret Code is \" << Generate_Secret(x, y, M) << endl;\n}\n\nint main()\n{\n    int S, N;\n    printf(\"Enter the Secret Code\\n\");\n    scanf(\"%d\", &S);\n    printf(\"Enter the number of Parts\\n\");\n    scanf(\"%d\", &N);\n    solve(S, N, 2);\n    return 0;\n}\n"
  },
  {
    "path": "Algorithms/Cryptography/Vernam_Cipher/README.md",
    "content": "## This folder is empty.\n"
  },
  {
    "path": "Algorithms/Cryptography/Vernam_Cipher/Vernam_Cipher.cpp",
    "content": "#include <cstring>\n#include <random>\n\n/**\n * Encrypts/decrypts data using vernam cipher\n * @param[in/out] data data to which Vernam cipher is applied\n * @param[in] key key, is expected to have the same size as data\n * @param[in] size memory size (in bytes) of data\n */\nvoid apply_vernam(void *data, void const * key, const size_t size)\n{\n\tstatic_assert(sizeof(char) == 1);\n\tconst unsigned sizeTypeSize = sizeof(size_t);\n\n\tconst size_t numberOfIterations = size / sizeTypeSize;\n\tsize_t *currentDataPosition = static_cast<size_t*>(data);\n\tsize_t const * currentKeyPosition = static_cast<size_t const *>(key);\n\n\tfor (size_t i = 0; i < numberOfIterations; ++i)\n\t{\n\t\t*currentDataPosition = *currentDataPosition ^ *currentKeyPosition; // XOR\n\t\t++currentDataPosition;\n\t\t++currentKeyPosition;\n\t}\n\n\tconst unsigned numberOfRemainingOperations = size % sizeTypeSize;\n\tchar *currentRemainingDataPosition = reinterpret_cast<char*>(currentDataPosition);\n\tchar const * currentRemainingKeyPosition = reinterpret_cast<char const *>(currentKeyPosition);\n\n\tfor (unsigned i = 0; i < numberOfRemainingOperations; ++i)\n\t{\n\t\t*currentRemainingDataPosition = *currentRemainingDataPosition ^ *currentRemainingKeyPosition; // XOR\n\t\t++currentRemainingDataPosition;\n\t\t++currentRemainingKeyPosition;\n\t}\n\n\treturn;\n}\n\n/** Generates a random uniformly distributed key. The key has to be allocated with at least size byte of memory.\n * @param[out] key generated key\n * @param[in] size size of key\n */\nvoid generate_key(void *key, const size_t size)\n{\n\tstd::random_device rd;\n\tstd::uniform_real_distribution<double> distribution(0.0, 0.1);\n\n\tconst unsigned doubleSize = sizeof(double);\n\n\tconst size_t numberOfIterations = size / doubleSize;\n\n\tdouble *currentKeyPosition = static_cast<double*>(key);\n\n\tfor (size_t i = 0; i < numberOfIterations; ++i)\n\t{\n\t\t*currentKeyPosition = distribution(rd);\n\t\t++currentKeyPosition;\n\t}\n\n\tconst unsigned numberOfRemainingOperations = size % doubleSize;\n\tchar * currentRemainingKeyPosition = reinterpret_cast<char*>(currentKeyPosition);\n\n\tfor (unsigned i = 0; i < numberOfRemainingOperations; ++i)\n\t{\n\t\tconst double randomNumber = distribution(rd);\n\t\tmemcpy(currentRemainingKeyPosition, &randomNumber, sizeof(char));\n\t\t++currentRemainingKeyPosition;\n\t}\n\n\treturn;\n}\n\n// Test section:\n\n#include <iostream>\n\nusing namespace std;\n\nint main()\n{\n\tstring data;\n\n\tcout << \"Enter plaintext:\" << endl;\n\tgetline(cin, data);\n\n\t// Generate random key:\n\tstring key(data);\n\tgenerate_key(&key[0], sizeof(char)*key.size());\n\n\tcout << \"Random key:\" << endl\n\t     << key << endl;\n\n\tapply_vernam(&data[0], &key[0], sizeof(char)*data.size());\n\n\tcout << endl << \"Ciphertext:\" << endl\n\t\t << data << endl;\n\n\tapply_vernam(&data[0], &key[0], sizeof(char)*data.size());\n\n\tcout << endl << \"Decrypted text:\" << endl\n\t\t << data << endl;\n\n\treturn 0;\n}\n"
  },
  {
    "path": "Algorithms/Cryptography/Vernam_Cipher/Vernam_Cipher.js",
    "content": "xin = \"Shubham\";\n\ntreshold = 150;\n\nc = {\n\t0: [], // input encoded\n\t1: [], // key encoded\n\t2: [], // cipher encoded\n\t3: []  // decoded encoded\n};\n\nfor (i=0;i<=xin.length;++i) c[0].push((xin[i]+\"\").charCodeAt(0));\nconsole.log(\"Encoded input: \" + c[0].join(\", \"));\n\n// c[0] is input\n\n// generate challenge key\n\nfor (i=0;i<=c[0].length;++i) c[1].push(Math.round(Math.random()*treshold));\nconsole.log(\"Generated Challenge Pad: \" + c[1].join(\", \"));\n\n// generate cipher\n\nfor (i=0;i<=c[0].length;++i) c[2].push(c[0][i] ^ c[1][i]);\nconsole.log(\"Resulting Cipher: \" + c[2].join(\", \"));\n\nfor (i=0;i<=c[0].length - 1;++i) c[3].push(c[2][i] ^ c[1][i]);\nconsole.log(\"Recalculated Pad: \" + c[3].join(\", \"));\n\nconsole.log(\"Has decoding been successful? \" + ( c[0].join() == c[3].join() ? \"Yes\" : \"No\" ));\n"
  },
  {
    "path": "Algorithms/Cryptography/Vernam_Cipher/Vernam_Cipher.py",
    "content": "#!/usr/bin/env python\nimport random\nimport string\nfrom operator import xor\ndef vernam_enc(msg):\n    #Generate Random Key\n    randomKey = ''.join([random.choice(string.ascii_letters) for i in range(len(msg))])\n    print(\"Random Key: \"+randomKey)\n    \n    #Convert string to decimal\n    convdecimal = []\n    for i in range(len(msg)):\n        convdecimal.append(str(ord(msg[i])))\n    decimal = ' '.join(convdecimal)\n\t\n\t#Convert decimal to biner\n    convbiner = []\n    for i in range(len(convdecimal)):\n        convbiner.append(str(bin(int(convdecimal[i]))[2:].zfill(8)))\n    biner = ''.join(convbiner)\n\n\n    #Convert key to decimal\n    convkeydecimal = []\n    for i in range(len(randomKey)):\n        convkeydecimal.append(str(ord(randomKey[i])))\n    keydecimal = ' '.join(convkeydecimal)\n    \n    #Convert key decimal to biner\n    convkeybiner = []\n    for i in range(len(convkeydecimal)):\n        convkeybiner.append(str(bin(int(convkeydecimal[i]))))\n    binerkey = ''.join(convkeybiner)\n\n\n    binermsg =biner.replace(\"b\",\"\")\n\n    binerkey =binerkey.replace(\"b\",\"\")\n\n    #XOR Function\n    ciphertext = []\n    for i in range(len(binermsg)):\n        ciphertext.append(xor(int(binermsg[i]),int(binerkey[i])))\n    cipherfix =''.join(map(str,ciphertext))\n    splits=[cipherfix[x:x+8] for x in range(0,len(cipherfix),8)]\n\n    #convert biner to decimal\n    hexa = []\n    for i in range(len(splits)):\n        hexa.append(hex(int(splits[i],2)))\n        \n    #convert hex to desimal\n    dec = []\n    for i in range(len(hexa)):\n        dec.append(int(hexa[i], 16))\n    print(\"Ciphertext-Num : \\n\"+str(dec))\n\n\t#final convert to text\n    teks = []\n    for i in range(len(dec)):\n        teks.append(chr(dec[i]))\n    print(\"Ciphertext : \\n\"+''.join(teks))\n    \n\ndef main():\n    print(\"Vernam Cipher\")\n    msg = input(\"Enter Text : \")\n    vernam_enc(msg)\nif __name__ == '__main__':\n    \tmain()\n"
  },
  {
    "path": "Algorithms/Cryptography/Vigenere_Cipher/README.md",
    "content": "## This folder is empty.\n"
  },
  {
    "path": "Algorithms/Cryptography/Vigenere_Cipher/Vigenere_Cipher.cpp",
    "content": "#include <algorithm>\n#include <cctype>\n#include <string>\n\n/**\n * Returns the mathematical (unsigned) modulus\n * @param x number\n * @param div divisor\n * @return the unsigned modulus x % div\n */\nunsigned positive_modulo(const int x, const int div)\n{\n\treturn (x % div + div) % div;\n}\n\n/**\n * Returns, wheter character is a letter of the alphabet\n * @param ch character\n * @return true if ch is a letter. false otherwise\n */\nbool is_letter(const unsigned char ch)\n{\n\tbool result = false;\n\tif (('A' <= ch && ch <= 'Z') || ('a' <= ch && ch <= 'z'))\n\t\tresult = true;\n\n\treturn result;\n}\n\n/**\n * Encrypts a string using Vigenere cipher\n * @input plaintext plaintext\n * @input keyword keyword\n * @return the encrypted plaintext\n */\nstd::string encrypt_vigenere(const std::string &plaintext, const std::string &keyword)\n{\n\tstd::string ciphertext(plaintext);\n\tstd::string cleanKeyword(keyword);\n\n\tciphertext.erase(std::remove_if(ciphertext.begin(), ciphertext.end(), [](const unsigned char ch){ return !is_letter(ch); }), ciphertext.end());\n\tcleanKeyword.erase(std::remove_if(cleanKeyword.begin(), cleanKeyword.end(), [](const unsigned char ch){ return !is_letter(ch); }), cleanKeyword.end());\n\n\tfor (size_t i = 0; i < ciphertext.size(); ++i)\n\t{\n\t\tciphertext[i] = toupper(ciphertext[i]);\n\t\tcleanKeyword[i] = toupper(cleanKeyword[i]);\n\n\t\t// shift by corresponding character of keyword\n\t\tciphertext[i] = positive_modulo((ciphertext[i] - 'A' + (cleanKeyword[i%keyword.size()] - 'A')), ('Z' - 'A' + 1)) + 'A';\n\t}\n\n\treturn ciphertext;\n}\n\n/**\n * Decrypts a string using Vigenere cipher\n * @input ciphertext ciphertext\n * @input keyword keyword\n * @return the decrypted ciphertext\n */\nstd::string decrypt_vigenere(const std::string &ciphertext, const std::string &keyword)\n{\n\tstd::string plaintext(ciphertext);\n\tstd::string cleanKeyword(keyword);\n\n\tplaintext.erase(std::remove_if(plaintext.begin(), plaintext.end(), [](const unsigned char ch){ return !is_letter(ch); }), plaintext.end());\n\tcleanKeyword.erase(std::remove_if(cleanKeyword.begin(), cleanKeyword.end(), [](const unsigned char ch){ return !is_letter(ch); }), cleanKeyword.end());\n\n\tfor (size_t i = 0; i < plaintext.size(); ++i)\n\t{\n\t\tplaintext[i] = toupper(plaintext[i]);\n\t\tcleanKeyword[i] = toupper(cleanKeyword[i]);\n\n\t\t// shift by corresponding character of keyword\n\t\tplaintext[i] = positive_modulo((plaintext[i] - 'A' - (cleanKeyword[i%keyword.size()] - 'A')), ('Z' - 'A' + 1)) + 'A';\n\t}\n\n\treturn plaintext;\n}\n\n\n// Test section:\n\n#include <iostream>\n\nusing namespace std;\n\nint main()\n{\n\tstring plaintext;\n\tstring keyword;\n\n\tcout << \"Enter plaintext:\" << endl;\n\tgetline(cin, plaintext);\n\n\tcout << endl << \"Enter keyword:\" << endl;\n\tgetline(cin, keyword);\n\n\tstring ciphertext = encrypt_vigenere(plaintext, keyword);\n\n\tcout << endl << \"Ciphertext:\" << endl\n\t\t << ciphertext << endl;\n\n\tstring decryptedtext = decrypt_vigenere(ciphertext, keyword);\n\n\tcout << endl << \"Decrypted text:\" << endl\n\t\t << decryptedtext << endl;\n\n\treturn 0;\n}\n"
  },
  {
    "path": "Algorithms/Cryptography/Vigenere_Cipher/Vigenere_Cipher.py",
    "content": "import sys\n\ndef create_key(msg, key):\n    key = list(key)\n    if len(msg) == len(key):\n        return key\n    elif len(key) < len(msg):\n        n = (len(msg) // len(key)) + 1\n        key = key * n\n        return ''.join(key[:len(msg)])\n\ndef encrypt(msg, key):\n    cipher_text = []\n    x = 0\n    key = create_key(msg, key)\n\n    for i in range(0, len(msg)):\n        x = (ord(msg[i]) + ord(key[i])) % 26\n        x += ord('A')\n        cipher_text.append(chr(x))\n    return cipher_text\n\ndef decrypt(msg, key):\n    key = create_key(msg, key)\n    plain_text = []\n\n    for i in range(0, len(msg)):\n        x = (ord(msg[i]) - ord(key[i]) + 26) % 26\n        x += ord('A')\n        plain_text.append(chr(x))\n    return plain_text\n\nif __name__ == '__main__':\n    print(\"\\t\\tVigenere Cipher Application\")\n    print(\"\\t\"+\"=\" * 41)\n    print(\"Please choose an option below:\\n\")\n    print(\"1. Encrypt\")\n    print(\"2. Decrypt\")\n    print(\"3. Exit\")\n    while True:\n        opt = input(\"Selection: \")\n        try:\n            opt = int(opt)\n            if opt == 1:\n                msg = input(\"Please provide your message to encrypt: \")\n                msg = msg.upper().replace(\" \", \"\")\n                key = input(\"Please provide your key: \")\n                key = key.upper().replace(\" \", \"\")\n                cipher_text = encrypt(msg, key)\n                print(\"Encrypted message:\", \"\".join(cipher_text))\n            elif opt == 2:\n                msg = input(\"Please provide your message to decrypt: \")\n                msg = msg.upper().replace(\" \", \"\")\n                key = input(\"Please provide your key: \")\n                key = key.upper().replace(\" \", \"\")\n                plain_text = decrypt(msg, key)\n                print(\"Encrypted message:\", \"\".join(plain_text))\n            elif opt == 3:\n                sys.exit()\n            else:\n                print(\"Incorrect option, try again\")\n                continue\n        except ValueError:\n            print(\"Incorrect option, try again\")\n            continue\n"
  },
  {
    "path": "Algorithms/Cryptography/Vigenere_Cipher/Vignere_Cipher.cs",
    "content": "using System;\nusing System.Linq;\nusing System.Collections.Generic;\n\npublic class Program\n{\n    static List<char> characters = \"abcdefghijklmnopqrstuvwxyz\".ToList();\n\n    // wrap value if it is above n or below zero\n    static int wrap(int k, int n)\n    {\n        int r = k % n;\n        return (r < 0) ? r + n : r;\n    }\n\n    static string VignereCipher(string plaintext, string key)\n    {\n        string ciphertext = \"\";\n        for (int i = 0; i < plaintext.Length; i++)\n        {\n            // get the current key character.\n            char keyCharacter = key[i % key.Length];\n            // shift value is the index of this character in 'characters'.\n            int shift = characters.IndexOf(keyCharacter);\n\n            // index of the plaintext character in the 'characters' array.\n            int plaincharNumber = characters.IndexOf(plaintext[i]);\n            // shift this index by the shift value, wrapping if it goes over 26.\n            int ciphercharNumber = wrap((plaincharNumber + shift), 26);\n            // and get the character from this index.\n            char cipherchar = characters[ciphercharNumber];\n\n            ciphertext += cipherchar;\n        }\n\n        return ciphertext;\n    }\n\n    static string VignereDecipher(string ciphertext, string key)\n    {\n        string plaintext = \"\";\n        for (int i = 0; i < ciphertext.Length; i++)\n        {\n            // get the current key character.\n            char keyCharacter = key[i % key.Length];\n            // shift value is the index of this character in 'characters'.\n            int shift = characters.IndexOf(keyCharacter);\n\n            // index of the ciphertext character in the 'characters' array.\n            int ciphercharNumber = characters.IndexOf(ciphertext[i]);\n            // shift this index by the shift value, but in the other direction,\n            // wrapping through 26 if it goes under 0.\n            int plaincharNumber = wrap((ciphercharNumber - shift), 26);\n            // and get the character from this index.\n            char plainchar = characters[plaincharNumber];\n\n            plaintext += plainchar;\n        }\n\n        return plaintext;\n    }\n\n    public static void Main(string[] args)\n    {\n        string ciphertext = VignereCipher(\"helloworld\", \"key\");\n        Console.WriteLine($\"Plaintext: helloworld -> Key: key ->  Ciphertext: {ciphertext}.\");\n\n        string plaintext = VignereDecipher(\"uogtprtso\", \"pass\");\n        Console.WriteLine($\"Ciphertext: uogtprtso <- Key: pass <- Plaintext: {plaintext}.\");\n    }\n}"
  },
  {
    "path": "Algorithms/Cryptography/Vigenere_Cipher/vigenereCipher.py",
    "content": "def vignereCipher(plain_text, key):\n    plain_text_length = len(plain_text)\n    key_length = len(key)\n    j = 0\n    cipher = ''\n    for i in range(plain_text_length):\n        if(j == key_length):\n            j = 0\n        cipher_text = (ord(plain_text[i])+ ord(key[j])) % 26\n        j+=1\n        cipher += chr(cipher_text+65)\n    return cipher\n\ndef decryptVignereCipher(cipher_text, key):\n    key_length = len(key)\n    decrpted_text = ''\n    j = 0\n    for i in range(len(cipher_text)): \n        if(j == key_length):\n            j = 0\n        decrpt = (ord(cipher_text[i]) - ord(key[j]) + 26) % 26\n        j+=1\n        decrpted_text += chr(decrpt+65)\n    return decrpted_text\n        \n    \nif __name__ == \"__main__\":\n    plain_text = \"PLAINTEXT\"\n    key = \"KEY\"\n    encrypted_text = vignereCipher(plain_text, key)\n    print(\"Cipher text \" + encrypted_text)\n    decrpted_text = decryptVignereCipher(encrypted_text, key)\n    print(\"Decrypt text \" + decrpted_text)"
  },
  {
    "path": "Algorithms/DP/0-1_Knapsack_Problem/0-1 Knapsack Problem.java",
    "content": "/*0-1 Knapsack problem */\r\nimport java.util.*;\r\npublic class Knapsack {\r\n\r\n    //function to return max. of two integers\r\n    static int max(int a, int b)\r\n    {\r\n        return (a > b) ? a : b;\r\n    }\r\n\r\n   //function to return proper max. value to fill knapsack of weight W\r\n    static int knapSack(int W, int wt[], int val[], int n)\r\n    {\r\n        int i, w;\r\n        int K[][] = new int[n + 1][W + 1];\r\n\r\n        // Build table K[][] in bottom up manner\r\n        for (i = 0; i <= n; i++) {\r\n            for (w = 0; w <= W; w++) {\r\n\r\n                if (i == 0 || w == 0)\r\n                    K[i][w] = 0;\r\n                else if (wt[i - 1] <= w)\r\n                    K[i][w] = max(\r\n                        val[i - 1] + K[i - 1][w - wt[i - 1]],\r\n                        K[i - 1][w]);\r\n                else\r\n                    K[i][w] = K[i - 1][w];\r\n            }\r\n        }\r\n\r\n        return K[n][W];\r\n    }\r\n    //Main function\r\n    public static void main(String args[])\r\n    {\r\n        Scanner input=new Scanner(System.in);\r\n        System.out.println(\"Enter the number of items in a Knapsack:\");\r\n        int n = input.nextInt();\r\n        int v[]=new int[n];\r\n        int w[]=new int[n];\r\n        for (int i=0; i<n; i++)\r\n        {\r\n            System.out.println(\"Enter value and weight for item \"+i+ \":\");\r\n            v[i] = input.nextInt();\r\n            w[i] = input.nextInt();\r\n        }\r\n        System.out.println(\"Enter the capacity of knapsack\");\r\n        int W = input.nextInt();\r\n        System.out.println(knapSack(W, w, v, n));\r\n    }\r\n}\r\n"
  },
  {
    "path": "Algorithms/DP/0-1_Knapsack_Problem/Branch_And_Bound/0-1_knapsack.cpp",
    "content": "// C++ program to solve knapsack problem using \n// branch and bound \n#include <bits/stdc++.h> \nusing namespace std; \n  \n// Structure for Item which store weight and corresponding \n// value of Item \nstruct Item \n{ \n    float weight; \n    int value; \n}; \n  \n// Node structure to store information of decision \n// tree \nstruct Node \n{ \n    // level  --> Level of node in decision tree (or index \n    //             in arr[] \n    // profit --> Profit of nodes on path from root to this \n    //            node (including this node) \n    // bound ---> Upper bound of maximum profit in subtree \n    //            of this node/ \n    int level, profit, bound; \n    float weight; \n}; \n  \n// Comparison function to sort Item according to \n// val/weight ratio \nbool cmp(Item a, Item b) \n{ \n    double r1 = (double)a.value / a.weight; \n    double r2 = (double)b.value / b.weight; \n    return r1 > r2; \n} \n  \n// Returns bound of profit in subtree rooted with u. \n// This function mainly uses Greedy solution to find \n// an upper bound on maximum profit. \nint bound(Node u, int n, int W, Item arr[]) \n{ \n    // if weight overcomes the knapsack capacity, return \n    // 0 as expected bound \n    if (u.weight >= W) \n        return 0; \n  \n    // initialize bound on profit by current profit \n    int profit_bound = u.profit; \n  \n    // start including items from index 1 more to current \n    // item index \n    int j = u.level + 1; \n    int totweight = u.weight; \n  \n    // checking index condition and knapsack capacity \n    // condition \n    while ((j < n) && (totweight + arr[j].weight <= W)) \n    { \n        totweight    += arr[j].weight; \n        profit_bound += arr[j].value; \n        j++; \n    } \n  \n    // If k is not n, include last item partially for \n    // upper bound on profit \n    if (j < n) \n        profit_bound += (W - totweight) * arr[j].value / \n                                         arr[j].weight; \n  \n    return profit_bound; \n} \n  \n// Returns maximum profit we can get with capacity W \nint knapsack(int W, Item arr[], int n) \n{ \n    // sorting Item on basis of value per unit \n    // weight. \n    sort(arr, arr + n, cmp); \n  \n    // make a queue for traversing the node \n    queue<Node> Q; \n    Node u, v; \n  \n    // dummy node at starting \n    u.level = -1; \n    u.profit = u.weight = 0; \n    Q.push(u); \n  \n    // One by one extract an item from decision tree \n    // compute profit of all children of extracted item \n    // and keep saving maxProfit \n    int maxProfit = 0; \n    while (!Q.empty()) \n    { \n        // Dequeue a node \n        u = Q.front(); \n        Q.pop(); \n  \n        // If it is starting node, assign level 0 \n        if (u.level == -1) \n            v.level = 0; \n  \n        // If there is nothing on next level \n        if (u.level == n-1) \n            continue; \n  \n        // Else if not last node, then increment level, \n        // and compute profit of children nodes. \n        v.level = u.level + 1; \n  \n        // Taking current level's item add current \n        // level's weight and value to node u's \n        // weight and value \n        v.weight = u.weight + arr[v.level].weight; \n        v.profit = u.profit + arr[v.level].value; \n  \n        // If cumulated weight is less than W and \n        // profit is greater than previous profit, \n        // update maxprofit \n        if (v.weight <= W && v.profit > maxProfit) \n            maxProfit = v.profit; \n  \n        // Get the upper bound on profit to decide \n        // whether to add v to Q or not. \n        v.bound = bound(v, n, W, arr); \n  \n        // If bound value is greater than profit, \n        // then only push into queue for further \n        // consideration \n        if (v.bound > maxProfit) \n            Q.push(v); \n  \n        // Do the same thing,  but Without taking \n        // the item in knapsack \n        v.weight = u.weight; \n        v.profit = u.profit; \n        v.bound = bound(v, n, W, arr); \n        if (v.bound > maxProfit) \n            Q.push(v); \n    } \n  \n    return maxProfit; \n} \n  \n// driver program to test above function \nint main() \n{ \n    int W = 10;   // Weight of knapsack \n    Item arr[] = {{2, 40}, {3.14, 50}, {1.98, 100}, \n                  {5, 95}, {3, 30}}; \n    int n = sizeof(arr) / sizeof(arr[0]); \n  \n    cout << \"Maximum possible profit = \"\n         << knapsack(W, arr, n); \n  \n    return 0; \n} \n"
  },
  {
    "path": "Algorithms/DP/0-1_Knapsack_Problem/knapsackProblem.java",
    "content": "/*0-1 Knapsack problem */\nimport java.util.*;\npublic class knapsackProblem {\n\n    //function to return max. of two integers\n    static int max(int a, int b)\n    {\n        return (a > b) ? a : b;\n    }\n\n   //function to return proper max. value to fill knapsack of weight W\n    static int knapSack(int W, int wt[], int val[], int n)\n    {\n        int i, w;\n        int K[][] = new int[n + 1][W + 1];\n\n        // Build table K[][] in bottom up manner\n        for (i = 0; i <= n; i++) {\n            for (w = 0; w <= W; w++) {\n\n                if (i == 0 || w == 0)\n                    K[i][w] = 0;\n                else if (wt[i - 1] <= w)\n                    K[i][w] = max(\n                        val[i - 1] + K[i - 1][w - wt[i - 1]],\n                        K[i - 1][w]);\n                else\n                    K[i][w] = K[i - 1][w];\n            }\n        }\n\n        return K[n][W];\n    }\n    //Main function\n    public static void main(String args[])\n    {\n        Scanner input=new Scanner(System.in);\n        System.out.println(\"Enter the number of items in a Knapsack:\");\n        int n = input.nextInt();\n        int v[]=new int[n];\n        int w[]=new int[n];\n        for (int i=0; i<n; i++)\n        {\n            System.out.println(\"Enter value and weight for item \"+i+ \":\");\n            v[i] = input.nextInt();\n            w[i] = input.nextInt();\n        }\n        System.out.println(\"Enter the capacity of knapsack\");\n        int W = input.nextInt();\n        System.out.println(knapSack(W, w, v, n));\n    }\n}\n"
  },
  {
    "path": "Algorithms/DP/0-1_Knapsack_Problem/knapsack_problem_0_1.cpp",
    "content": "#include <iostream>\nusing namespace std;\nint max(int x, int y)\n{\n    return (x > y) ? x : y;\n}\nint knapSack(int W, int w[], int v[], int n)\n{\n    int i, wt;\n    int K[n + 1][W + 1];\n    for (i = 0; i <= n; i++)\n    {\n        for (wt = 0; wt <= W; wt++)\n        {\n            if (i == 0 || wt == 0)\n                K[i][wt] = 0;\n            else if (w[i - 1] <= wt)\n                K[i][wt] = max(v[i - 1] + K[i - 1][wt - w[i - 1]], K[i - 1][wt]);\n            else\n                K[i][wt] = K[i - 1][wt];\n        }\n    }\n    return K[n][W];\n}\nint main()\n{\n    cout << \"Enter the number of items in a Knapsack:\";\n    int n, W;\n    cin >> n;\n    int v[n], w[n];\n    for (int i = 0; i < n; i++)\n    {\n        cout << \"Enter value and weight for item \" << i << \":\";\n        cin >> v[i];\n        cin >> w[i];\n    }\n    cout << \"Enter the capacity of knapsack\";\n    cin >> W;\n    cout << knapSack(W, w, v, n);\n    return 0;\n}"
  },
  {
    "path": "Algorithms/DP/0-1_Knapsack_Problem/knapsack_problem_0_1.py",
    "content": "#0/1 Knapsack problem\n\n\ndef knapsack(val, wt, N, C):\n    \n    table = [[ 0 for _ in range(0, C+1)] for _ in range(0, N+1)]\n    table[0][0] = 0\n    \n    for i in range(1, N+1):\n        for c in range(1, C+1):\n            \n            if c - wt[i-1] < 0:\n                table[i][c] = table[i-1][c]\n            else:\n                table[i][c] = max(table[i-1][c], table[i-1][c-wt[i-1]]+val[i-1])\n    return table[N][C]\n    \n\nN = int(input().strip())\nW = int(input().strip())  # capacity\nval = [ int(v) for v in input().strip().split(\" \")]\nwt =  [ int(w) for w in input().strip().split(\" \")]\nprint(knapsack(val, wt, N, W))"
  },
  {
    "path": "Algorithms/DP/AdjacentBitCounts.cpp",
    "content": "/*\nProblem description:\nFor a string of n bits x1,x2,x3,...,Xn the adjacent bit count of the string (AdjBC(x)) is given by\nX1*X2 + X2*X3 + X3*X4 + ... + Xn-1 * Xn\n\nwhich counts the number of times a 1 bit is adjacent to another 1 bit. For example:\nAdjBC(011101101) = 3\nAdjBC(111101101) = 4\nAdjBC(010101010) = 0\n\nWrite a program which takes as input integers n and k and returns the number of bit strings x of n bits \n(out of 2ⁿ) that satisfy AdjBC(x) = k.\n\nLink To Problem: https://www.spoj.com/problems/GNYR09F/\n*/\n\n#include <bits/stdc++.h>\nusing namespace std;\n//find Number of bit string with Adjacent Bit count k.\nint findAns(int n, int k, int firstBit, int ***dp)\n{\n    //Base cases\n    if (k < 0)\n        return 0;\n    if (dp[n][k][firstBit] != -1)\n        return dp[n][k][firstBit];\n\n    /*There are 2 cases\n      1. If First bit of binary string is assigned '1'\n      2. If first bit of binary string is assigned '0' \n    */\n    int option1, option2;\n    if (firstBit == 1)\n    {\n        option1 = findAns(n - 1, k - 1, 1, dp);\n        option2 = findAns(n - 1, k, 0, dp);\n    }\n    else\n    {\n        option1 = findAns(n - 1, k, 1, dp);\n        option2 = findAns(n - 1, k, 0, dp);\n    }\n    long long ans = (option1 + option2) % 1000000007;\n    dp[n][k][firstBit] = (int)ans;\n    return dp[n][k][firstBit];\n}\nint main()\n{           /*\n      [Problem Link : https://www.spoj.com/problems/GNYR09F/]\n      Input Format is taken from Problem Link\n    */\n    int ts; //testcases\n    cin >> ts;\n    while (ts--)\n    {\n        int index, num, k;\n        cin >> index >> num >> k;\n\n        /*creating a dp array for storing previous state answers.\n          Since dp array will depend on number of bits,k(Adjacent bit count) & firstbit(0 or 1)\n          therefore dp will be 3d array.*/\n        int ***dp = new int **[num + 1];\n        for (int i = 0; i <= num; i++)\n            dp[i] = new int *[k + 1];\n\n        for (int i = 0; i <= num; i++)\n        {\n            for (int j = 0; j <= k; j++)\n                dp[i][j] = new int[2];\n        }\n        //initialising dp\n        for (int i = 0; i <= num; i++)\n        {\n            for (int j = 0; j <= k; j++)\n                dp[i][j][0] = -1, dp[i][j][1] = -1;\n        }\n        dp[1][0][0] = dp[1][0][1] = 1;\n        for (int i = 1; i <= k; i++)\n            dp[1][i][0] = 0, dp[1][i][1] = 0;\n\n        //calling function to find ans.\n        int ans1 = findAns(num, k, 1, dp);\n        int ans2 = findAns(num, k, 0, dp);\n        long long int ans = (ans1 + ans2) % 1000000007;\n        cout << index << \" \" << ans << endl;\n\n        //deleting dp array\n        delete dp;\n    }\n    return 0;\n}\n"
  },
  {
    "path": "Algorithms/DP/AdjacentBitCounts.js",
    "content": "const readline = require('readline')\nconst reader = readline.createInterface(process.stdin, process.stdout)\n\nfunction countStrings(n, k) {\n    let dp = Array(n+1)\n    for(let i=0;i<n+1;++i) {\n        dp[i] = Array(k+1)\n        for(let j=0;j<k+1;++j)\n            dp[i][j] = Array(2).fill(0)\n    }\n    dp[1][0][0] = 1\n    dp[1][0][1] = 1\n    for (let i=2;i<=n;i++) {\n        for (let j=0;j<i&&j<k+1;j++) {\n            dp[i][j][0] = dp[i-1][j][0] + dp[i-1][j][1]\n            dp[i][j][1] = dp[i-1][j][0]\n            if (j-1>= 0) {\n                dp[i][j][1] += dp[i-1][j-1][1]\n            }\n        }\n    }\n    return dp[n][k][0] + dp[n][k][1]\n}\n\nreader.question(\"Enter 'N' and 'K' seperated by space: \", data => {\n    const arr = data.split(\" \")\n    console.log(\"Answer: \" + countStrings(parseInt(arr[0]), parseInt(arr[1])))\n    reader.close()\n})\n"
  },
  {
    "path": "Algorithms/DP/Bitmask DP/TravellingSalesman.cpp",
    "content": "#include <bits/stdc++.h>\n#define int long long int\nusing namespace std;\n\nint dis[21][21];\nint dp[21][(1 << 21)];\n\nint solve(int i, int mask, int n)\n{\n    if (mask == 0)\n    {\n        return dp[i][mask] = dis[i][0];\n    }\n    if (dp[i][mask] != -1)\n    {\n        return dp[i][mask];\n    }\n    int ans = INT_MAX;\n    for (int j = 0; j < n; j++)\n    {\n        if (mask & (1 << j))\n        {\n            ans = min(ans, dis[i][j] + solve(j, (mask ^ (1 << j)), n));\n        }\n    }\n    return ans;\n}\n\nsigned main()\n{\n    int n;\n    cin >> n;\n    memset(dp, -1, sizeof(dp));\n    for (int i = 0; i < n; i++)\n    {\n        for (int j = 0; j < n; j++)\n        {\n            cin >> dis[i][j];\n        }\n    }\n    cout << solve(0, (1 << n) - 1, n);\n}\n"
  },
  {
    "path": "Algorithms/DP/Branch_And_Bound/0_1_KnapSack.py",
    "content": "# a dynamic approach\n# Returns the maximum value that can be stored by the bag\ndef knapSack(W, wt, val, n):\n   K = [[0 for x in range(W + 1)] for x in range(n + 1)]\n   #Table in bottom up manner\n   for i in range(n + 1):\n      for w in range(W + 1):\n         if i == 0 or w == 0:\n            K[i][w] = 0\n         elif wt[i-1] <= w:\n            K[i][w] = max(val[i-1] + K[i-1][w-wt[i-1]], K[i-1][w])\n         else:\n            K[i][w] = K[i-1][w]\n   return K[n][W]\n#Main\nval = [50,100,150,200]\nwt = [8,16,32,40]\nW = 64\nn = len(val)\nprint(knapSack(W, wt, val, n))"
  },
  {
    "path": "Algorithms/DP/Branch_And_Bound/Knapsack_Branch_and_Bound.java",
    "content": "import java.io.*;\nimport java.util.*;\n\npublic class Knapsack_Branch_and_Bound {\n\t\n\tstatic boolean sol_found = false;\n\tstatic BufferedReader br = new BufferedReader(new InputStreamReader(System.in));\n\tstatic StringTokenizer st;\n\t\n\t//Node of Branch and Bound tree\n\tstatic class Node {\n\t\tint lvl, val;       //lvl indicates depth of current node\n\t\tdouble cap, bound;\n\t\tNode next;\n\n\t\tNode(int lvl, int val, double cap, double bound) {\n\t\t\tthis.lvl = lvl;\n\t\t\tthis.val = val;\n\t\t\tthis.cap = cap;\n\t\t\tthis.bound = bound;\n\t\t\tthis.next = null;\n\t\t}\n\t}\n\t\n\t//List to store node of Branch and Bound tree\n\tstatic class List {\n\t\tNode head;\n\t\n\t\t//add node in list in such a way that list always stay sorted in descending order by bound value of nodes\n\t\tvoid add(Node n)\n\t\t{\n\t\t\tif(this.head == null)\n\t\t\t\thead = n;\n\t\t\telse\n\t\t\t{\n\t\t\t\tNode temp = this.head;\n\t\t\t\tif(n.bound >= temp.bound) {\n\t\t\t\t\tn.next = temp;\n\t\t\t\t\tthis.head = n;\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\twhile(temp.next != null && n.bound < temp.next.bound)\n\t\t\t\t\t\ttemp = temp.next;\n\n\t\t\t\t\tif(temp.next != null)\n\t\t\t\t\t\tn.next = temp.next;\n\t\t\t\t\ttemp.next = n;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\t//returns the node with maximum upper bound i.e. the first node\n\t\t//in the list since list is always sorted in descending order\n\t\tNode get() {\n\t\t\tNode n = head;\n\t\t\thead = n.next;\n\t\t\tn.next = null;\n\t\t\treturn n;\n\t\t}\n\t}\n\t\n\t\n\tstatic class Item {\n\t\tdouble weight;\n\t\tint value;\n\t\t\n\t\tItem(double weight, int value) {\n\t\t\tthis.weight = weight;\n\t\t\tthis.value = value;\n\t\t}\n\t}\n\t\n\t//to sort the item array by value/weight in descending order\n\tstatic class Sort_Value_By_Weight implements Comparator<Item> {\n\t\tpublic int compare(Item a, Item b) {\n\t\t\tdouble x, y;\n\t\t\tx = a.value / a.weight;\n\t\t\ty = b.value / b.weight;\n\t\t\tif(x > y)\n\t\t\t\treturn -1;\n\t\t\telse if(x == y)\n\t\t\t\treturn 0;\n\t\t\treturn 1;\n\t\t}\n\t}\n\t\n\t//get upperbound for a node of depth k\n\tstatic double upperBound(Item item[], double cap, int k, int n) {\n\t\tint i;\n\t\tdouble tot_val = 0;\n\t\ti = k;\n\t\twhile(cap > 0 && i < n)\n\t\t{\n\t\t\tif(item[i].weight <= cap)\n\t\t\t\ttot_val += item[i].value;\n\t\t\telse\n\t\t\t\ttot_val += (1.0 * item[i].value / item[i].weight) * cap;\n\t\t\tcap -= item[i].weight;\n\t\t\ti++;\n\t\t}\n\t\treturn tot_val;\n\t}\n\t\n\t//Solves 0-1 knapsack by branch and bound technique\n\tstatic void knapsackBnB(Item[] item, int n, Node curr, List list)\n\t{\n\t\tif(curr.lvl == n && curr.cap >= 0) {\n\t\t\tSystem.out.println(\"Max Value: \" + curr.val);\n\t\t\tsol_found = true;\n\t\t}\n\n\t\telse if(curr.cap >= 0) {\n\t\t\tint k = curr.lvl;\n\t\t\tNode temp;\n\t\t\t\n\t\t\t//right child of current node\n\t\t\ttemp = new Node(k+1, curr.val, curr.cap, curr.val + upperBound(item, curr.cap, k+1, n));\n\t\t\tlist.add(temp);\n\t\t\t\n\t\t\t//left child of current node\n\t\t\tcurr = new Node(k+1, curr.val + item[k].value, curr.cap - item[k].weight, curr.bound);\n\n\t\t\t//function call itself for left child of current node\n\t\t\t//since it is the node with current max upperbound\n\t\t\tknapsackBnB(item, n, curr, list); \n\t\t\tif(!sol_found)\n\t\t\t\tknapsackBnB(item, n, list.get(), list);//call the function for max value of node in list\n\t\t}\n\t}\n\n\tpublic static void main(String[] args) throws IOException{\n\t\tint i, n;\n\t\tdouble cap;\n\t\t\n\t\tSystem.out.print(\"Enter no. of Items: \");\n\t\tn = Integer.parseInt(br.readLine());\n\n\t\tItem[] item = new Item[n];\n\n\t\tSystem.out.println(\"Enter weight-value pair :-\");\n\t\tfor(i=0; i<n; i++) {\n\t\t\tst = new StringTokenizer(br.readLine());\n\t\t\titem[i] = new Item(Double.parseDouble(st.nextToken()), Integer.parseInt(st.nextToken()));\n\t\t}\n\n\t\tSystem.out.print(\"Enter capacity of knapsack: \");\n\t\tcap = Double.parseDouble(br.readLine());\n\n\t\t//Sort the Item array by value/weight in descending order\n\t\tArrays.sort(item, new Sort_Value_By_Weight());\n\n\t\tList list = new List();\n\t\tlist.head = null;\n\t\t//root of the branch and bound tree\n\t\tNode curr = new Node(0, 0, cap, upperBound(item, cap, 0, n));\n\n\t\tknapsackBnB(item, n, curr, list);\n\t}\n}\n\n"
  },
  {
    "path": "Algorithms/DP/Count_Square_Matrices.cpp",
    "content": "#include <bits/stdc++.h>\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n\t//input n: rows and m: columns\r\n\tint n, m;\r\n\tcin >> n >> m;\r\n\r\n\t//create array of size n*m and take input from the user\r\n\tint ar[n][m];\r\n\tfor (int i = 0; i < n; i++)\r\n\t\tfor (int j = 0; j < m; j++)\r\n\t\t\tcin >> ar[i][j];\r\n\r\n\t//initialize count with 0 which keeps count of all submatrices having 1.\r\n\tint count = 0;\r\n\r\n\r\n\tfor (int i = 1; i < n; i++)\r\n\t{\r\n\t\tfor (int j = 1; j < m; j++)\r\n\t\t{\r\n\t\t\t//if ar[i][j] = 0, continue;\r\n\t\t\tif (ar[i][j] == 0)\r\n\t\t\t\tcontinue;\r\n\t\t\t//calculate submtrices that end with index (i , j);\r\n\t\t\t//basically we look at the previous row, column and diagonal and then add 1 to it's minimum.\r\n\t\t\telse\r\n\t\t\t\tar[i][j] = min({ar[i - 1][j], ar[i][j - 1], ar[i - 1][j - 1]}) + 1;\r\n\t\t}\r\n\t}\r\n\r\n\t//sum of the whole array to get final answer\r\n\tfor (int i = 0; i < n; i++)\r\n\t\tfor (int j = 0; j < m; j++)\r\n\t\t\tcount += ar[i][j];\r\n\r\n\r\n\t//print number of square submatrices containing all zeroes.\r\n\tcout << count << \"\\n\";\r\n\r\n\treturn 0;\r\n}\r\n"
  },
  {
    "path": "Algorithms/DP/Count_Square_Matrices.py",
    "content": "def countSquareMatrices(a, N, M):\n\n    count = 0\n\n    for i in range(1, N):\n        for j in range(1, M):\n            if (a[i][j] == 0):\n                continue\n\n            # Calculating  number of square submatrices ending at (i, j)\n            a[i][j] = min([a[i - 1][j], a[i][j - 1], a[i - 1][j - 1]])+1\n\n    # Calculate the sum of the array\n    for i in range(N):\n        for j in range(M):\n            count += a[i][j]\n\n    return count\n\nn = int(input())\nm = int(input())\n\nmatrix = []\nprint(\"Enter elements row-wise\")\nfor i in range(n):          # a for loop for row entries\n    a =[]\n    for j in range(m):      # a for loop for column entries\n         a.append(int(input()))\n    matrix.append(a)\n    \nprint(\"\\nNumber of square submatrices with all ones is\",countSquareMatrices(matrix, n, m))\n"
  },
  {
    "path": "Algorithms/DP/Edit_Distance/Edit_Distance.js",
    "content": "var string1 = prompt(\"Enter String 1 -> \");\r\nvar string2 = prompt(\"Enter String 2 -> \");\r\nvar length1 = string1.length,length2=string2.length;\r\nvar array1 = [];\r\nfor(var i=0;i<=length1;i++){\r\n    array1[i] = [];\r\n}\r\nfor(var i=0;i<=length1;i++){\r\n    array1[i][0] = i;\r\n}\r\nfor(var i=0;i<=length2;i++){\r\n    array1[0][i]=i;\r\n}\r\nfor(var i=1;i<=length1;i++){\r\n    for(var j=1;j<=length2;j++){\r\n        if(string1[i-1]==string2[j-1]){\r\n            array1[i][j]=array1[i-1][j-1];\r\n            [i][j]=array1[i-1][j-1];\r\n        }\r\n        else{\r\n            array1[i][j]=Math.min(Math.min(array1[i-1][j],array1[i][j-1]),array1[i-1][j-1])+1;\r\n        }\r\n    }\r\n}\r\nalert(\"Edit Distance is -> \" + array1[length1][length2]);"
  },
  {
    "path": "Algorithms/DP/Edit_Distance/Edit_distance.cpp",
    "content": "/*\nauthor-yogesh kansal\nproblem :- The edit distance between two strings is the minimum number of operations (insertions, deletions, and\nsubstitutions of symbols) to transform one string into another. It is a measure of similarity of two strings.\nEdit distance has applications, for example, in computational biology, natural language processing, and spell\nchecking. Your goal in this problem is to compute the edit distance between two strings\n\nOverall time complexity:- O(m*n)\n*/\n\n#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n\t\n\t\n\tstring s1,s2;\n\tcout<<\"enter string1:- \";\n\tcin>>s1;\n\tcout<<\"\\nenter string2:- \";\n\tcin>>s2;\n\t\n\tint n=s1.length()+1,m=s2.length()+1,i,j;\n\tint dp[n][m];\n\tfor(i=0;i<n;i++)\n\tdp[i][0]=i;\n\tfor(i=0;i<m;i++)\n\tdp[0][i]=i;\n\tfor(i=1;i<n;i++)\n\t{\n\t\tfor(j=1;j<m;j++)\n\t\t{\n\t\t\tif(s1[i-1]==s2[j-1])\n\t\t\t\tdp[i][j]=dp[i-1][j-1];\n\t\t\telse\n\t\t\tdp[i][j]=min(min(dp[i-1][j],dp[i][j-1]),dp[i-1][j-1])+1;\n\t\t}\n\t}\n\tcout<<\"\\nEditable distance is:- \";\n\tcout<<dp[n-1][m-1];\n\n\n\treturn 0;\n}\n"
  },
  {
    "path": "Algorithms/DP/Edit_Distance/README.md",
    "content": "## This folder is empty.\n"
  },
  {
    "path": "Algorithms/DP/Edit_Distance/edit_distance.py",
    "content": "\"\"\"\nauthor- Ose Oaiya (esoiya)\nproblem :- The edit distance between two strings is the minimum number of operations (insertions, deletions, and\nsubstitutions of symbols) to transform one string into another. It is a measure of similarity of two strings.\nEdit distance has applications, for example, in computational biology, natural language processing, and spell\nchecking. Your goal in this problem is to compute the edit distance between two strings\n\nOverall time complexity:- O(m*n)\n\"\"\"\n\ndef edit_distance(string1, string2):\n    \n    # for all i and j, d[i,j] will hold the Levenshtein distance between\n    # the first i characters of string1 and the first j characters of string2\n    # note that d has (m+1)*(n+1) values\n    m = len(string1) + 1\n    n = len(string2) + 1\n\n    d = [0] * (m * n)\n\n    # source prefixes can be transformed into empty string by\n    # dropping all characters\n    for i in range(m):\n        d[i] = i\n\n    # target prefixes can be reached from empty source prefix\n    # by inserting every character\n\n    for j in range(n):\n        d[j * m] = j\n\n    for j in range(1, n):\n        for i in range(1, m):\n            if string1[i-1] == string2[j-1]:\n                d[i + j * m] = d[i-1 + (j-1) * m]\n            else:\n                d[i + j * m] = min(\n                    d[i - 1 + j * m] + 1,  # deletion\n                    d[i + (j - 1) * m] + 1, # insertion\n                    d[i - 1 + (j - 1) * m] + 1 # subsitution\n                )\n\n    return d[-1]\n"
  },
  {
    "path": "Algorithms/DP/Egg_Drop/Egg_Drop.cpp",
    "content": "#include <bits/stdc++.h> \nusing namespace std;\n// Function for returning maximum of 2 numbers\nint max(int a, int b) \n{ \n    return (a > b) ? a : b; \n}\n\n// Function to obtain minimum number of trials required for finding the highest floor from which the egg can be dropped without breaking\nint EggDrop(int n, int k) \n{ \n\t// DP table to keep track of minimum number of trials for i eggs and j floors\n\tint eggFloor[n + 1][k + 1]; \n\tint res; \n\n\tfor (int i = 1; i <= n; i++) { \n        // If there are no floors, then 0 trials are required.\n        eggFloor[i][0] = 0; \n        // If there is only 1 floor, then 1 trial is required.\n\t\teggFloor[i][1] = 1;\n\t} \n\n\t// If there is only 1 egg, we have to drop it from each floor to check.\n    // Hence for j floors, j trials are required\n\tfor (int j = 1; j <= k; j++){\n        eggFloor[1][j] = j; \n    }\n\n\t// For the rest of the floors from 2nd to nth\n\tfor (int i = 2; i <= n; i++) { \n\t\tfor (int j = 2; j <= k; j++) { \n            // Consider the maximum possible trials initially\n\t\t\teggFloor[i][j] = INT_MAX; \n            // For jth floor, we consider all the trials from 1st floor to jth floor\n\t\t\tfor (int x = 1; x <= j; x++) { \n                // For each floor, we consider both cases:\n                // a) when the egg breaks: Number of eggs reduce by 1, and we know the critical floor is below xth floor -> eggFloor[i-1][x-1]\n                // b) when the egg doesn't break: Number of eggs remain same, and we know the critical is above xth floor -> eggFloor[i][j-x]\n                // For considering the worst case scenario, the maximum of both cases is taken\n\t\t\t\tres = 1 + max(eggFloor[i - 1][x - 1], eggFloor[i][j - x]); \n                // If the obtained result is better (smaller) than previous result for some other x, the previous result is replaced with the better result\n\t\t\t\tif (res < eggFloor[i][j]) \n\t\t\t\t\teggFloor[i][j] = res; \n\t\t\t} \n\t\t} \n\t} \n\n\t// The result is available is eggFloor[n][k] after all the possible cases have been considered\n\treturn eggFloor[n][k]; \n} \n\nint main() \n{ \n    // Initialise variables for number of eggs and number of floors\n    // n = number of eggs, k = number of floors\n\tint n, k;\n    cin >> n >> k;\n\tcout << \"Minimum number of trials required: \" << EggDrop(n,k) << endl;\n\treturn 0; \n} "
  },
  {
    "path": "Algorithms/DP/Egg_Drop/Egg_Drop.cs",
    "content": "﻿using System;\n\nnamespace ConsoleApp1\n{\n    static class Program\n    {\n        private static void Main(string[] args)\n        {\n            int n = int.Parse(Console.ReadLine());\n            int k = int.Parse(Console.ReadLine());\n            Console.WriteLine(\"Minimum number of trials \"\n                              + \"in worst case with \" + n + \" eggs and \"\n                              + k + \" floors is \" + eggDrop(n, k));\n        }\n        static int max(int a, int b)\n        {\n            return (a > b) ? a : b;\n        }\n\n        /* Function to get minimum number of  \n        trials needed in worst case with n \n        eggs and k floors */\n        static int eggDrop(int n, int k)\n        {\n\n            /* A 2D table where entery eggFloor[i][j] \n            will represent minimum number of trials \n            needed for i eggs and j floors. */\n            int[,] eggFloor = new int[n + 1, k + 1];\n            int res;\n            int i, j, x;\n\n            // We need one trial for one floor and0 \n            // trials for 0 floors \n            for (i = 1; i <= n; i++)\n            {\n                eggFloor[i, 1] = 1;\n                eggFloor[i, 0] = 0;\n            }\n\n            // We always need j trials for one egg \n            // and j floors. \n            for (j = 1; j <= k; j++)\n                eggFloor[1, j] = j;\n\n            // Fill rest of the entries in table \n            // using optimal substructure property \n            for (i = 2; i <= n; i++)\n            {\n                for (j = 2; j <= k; j++)\n                {\n                    eggFloor[i, j] = int.MaxValue;\n                    for (x = 1; x <= j; x++)\n                    {\n                        res = 1 + max(eggFloor[i - 1, x - 1],\n                                      eggFloor[i, j - x]);\n                        if (res < eggFloor[i, j])\n                            eggFloor[i, j] = res;\n                    }\n                }\n            }\n\n            // eggFloor[n][k] holds the result \n            return eggFloor[n, k];\n        }\n    }\n}\n// This code is contributed by Sam007 - GFG."
  },
  {
    "path": "Algorithms/DP/Egg_Drop/egg drop.java",
    "content": "public class EggDroppDP {\n\n    public int getDrops(int eggs, int floors){\n\n        int [][] eggDrops = new int [eggs+1][floors+1];\n        //base case 1:\n        //if floors = 0 then no drops are required // OR floors = 1 then 1 drop is required\n        for (int i = 1; i <=eggs ; i++) {\n            eggDrops[i][0] = 0;\n            eggDrops[i][1] = 1;\n        }\n        //base case 2:\n        //if only one egg is there then drops = floors\n        for (int i = 1; i <=floors ; i++) {\n            eggDrops[1][i] = i;\n        }\n\n        for (int i = 2; i <=eggs ; i++) {\n            for (int j = 2; j <=floors ; j++) {\n                eggDrops[i][j] = Integer.MAX_VALUE;\n                int tempResult;\n                for (int k = 1; k <=j ; k++) {\n                    tempResult = 1 + Math.max(eggDrops[i-1][k-1], eggDrops[i][j-k]);\n                    eggDrops[i][j] = Math.min(tempResult,eggDrops[i][j]);\n                }\n            }\n        }\n        // eggDrops[eggs][floors] will have the result : minimum number of drops required in worst case\n        return eggDrops[eggs][floors];\n    }\n\n    public static void main(String[] args) {\n        EggDroppDP eggDP = new EggDroppDP();\n        int eggs = 2;\n        int floors = 100;\n        System.out.printf(\"(DP) Minimum number of drops required in worst case with eggs:\n             %s and floors: %s is : %s\",eggs,floors,eggDP.getDrops(eggs,floors));\n    }\n}\n"
  },
  {
    "path": "Algorithms/DP/Egg_Drop/egg_drop.py",
    "content": "INT_MAX=32767\n\ndef egg_drop(n,k):\n    m=[[0 for x in range(k+1)]for x in range(n+1)]\n    for i in range(1,n+1):\n        m[i][0]=0\n        m[i][1]=1\n    \n    for j in range(1,k+1):\n        m[1][j]=j\n\n    for i in range(2,n+1):\n        for j in range(2,k+1):\n            m[i][j]=INT_MAX\n            for x in range(1,j+1):\n               res = 1 + max(m[i-1][x-1], m[i][j-x]) \n               if res < m[i][j]: \n                m[i][j] = res\n    print(m) \n    return m[n][k]\n\nn=2\nk=6\nprint(egg_drop(n,k))\n"
  },
  {
    "path": "Algorithms/DP/Egg_Drop/egg_drop.ts",
    "content": "const eggDrop = (n: number, k: number) => {\n  let eggFloor: number[][] = [];\n\n  // A 2d array where entry eggFloor[i][j] will represent\n  // the minimum number of trials needeed for i eggs and j floors\n  for (let i = 0; i < n + 1; i++) {\n    eggFloor.push(new Array(k + 1).fill(0));\n  }\n\n  // One trial for one floor and 0 trial for zero floor\n  for (let i = 1; i < n + 1; i++) {\n    eggFloor[i][1] = 1;\n    eggFloor[i][0] = 0;\n  }\n\n  // We always need j trials for one egg and j floors\n  for (let j = 1; j < k + 1; j++) {\n    eggFloor[1][j] = j;\n  }\n\n  // Fill the rest of the entries in table using optimal\n  // subtructure property\n  for (let i = 2; i < n + 1; i++) {\n    for (let j = 2; j < k + 1; j++) {\n      eggFloor[i][j] = Number.MAX_SAFE_INTEGER;\n      for (let x = 0; x < j + 1; x++) {\n        let res = 1 + Math.max(eggFloor[i - 1][x - 1], eggFloor[i][j - x]);\n        if (res < eggFloor[i][j]) {\n          eggFloor[i][j] = res;\n        }\n      }\n    }\n  }\n\n  // eggFloor[n][k] holds the result\n  return eggFloor[n][k];\n};\n\nconst n = 2;\nconst k = 36;\nconsole.log(\n  \"Minimum worst case of trials in worst case with \" +\n    n +\n    \" eggs \" +\n    k +\n    \" floors is \" +\n    eggDrop(n, k)\n);\n"
  },
  {
    "path": "Algorithms/DP/Fibonacci_Series/Fibonacci.c",
    "content": "#include<stdio.h>\nint main()\n{\nint first=0, second=1, i, n, sum=0;\nprintf(\"Enter the number of terms: \");\nscanf(\"%d\",&n);\n//accepting the terms\nprintf(\"Fibonacci Series:\");\nfor(i=0 ; i<n ; i++)\n{\nif(i <= 1)\n{\nsum=i;\n}\n//to print 0 and 1\nelse\n{\nsum=first + second;\nfirst=second;\nsecond=sum;\n//to calculate the remaining terms.\n//value of first and second changes as new term is printed.\n}\nprintf(\" %d\",sum)\n}\nreturn 0;\n}\n"
  },
  {
    "path": "Algorithms/DP/Fibonacci_Series/Fibonacci.php",
    "content": "<?php\n/**\n * Iterative solution for Fibonacci Numbers\n * Execute this file whith: php -f Fibonacci.php\n * @author juanmagutierrez89\n */\n\n/**\n * This function returns the nth fibonacci number\n * @param int $n \n * @return int the nth fibonacci number\n */\nfunction fibonacci(int $n) : int {\n    if ($n <= 1) {\n        return $n;\n    }\n    \n    $a = 0;\n    $b = 1;\n    \n    for ($i = 0; $i < $n; $i++) {\n        $a = $b - $a;\n        $b = $a + $b;\n    }\n    \n    return $a;\n}\n\n\necho \"First ten Fibonacci numbers: \\n\";\nfor ($i=0; $i < 10; $i++) {\n    echo \"fibonacci($i): \".fibonacci($i).\"\\n\";\n}\n\necho \"\\n\";\n\n?>"
  },
  {
    "path": "Algorithms/DP/Fibonacci_Series/fibonacci.go",
    "content": "package main\n\nimport \"fmt\"\n\nfunc Fibonacci(n uint) uint64 {\n  if n <= 1 {\n    return uint64(n)\n  }\n\n  var n2, n1 uint64 = 0, 1\n\n  for i := uint(2); i < n; i++ {\n    n2, n1 = n1, n1+n2\n  }\n\n  return n2 + n1\n}\n\nfunc main() {\n\tfor i := uint(0); i < 10; i++ {\n\t\tfmt.Println(Fibonacci(i))\n\t}\n}"
  },
  {
    "path": "Algorithms/DP/Fibonacci_Series/fibonacci.js",
    "content": "/*\nThis function returns the nth fibonacci number, given \n*/\nfunction fibonacci(n, memoizer) {\n    memoizer = memoizer || {};\n    if (memoizer[n]) {\n        return memoizer[n];\n    }\n    if (n <= 1) {\n        return 1;\n    }\n    return memoizer[n] = fibonacci(n - 1, memoizer) + fibonacci(n - 2, memoizer);\n}\n"
  },
  {
    "path": "Algorithms/DP/Fibonacci_Series/fibonacci.py",
    "content": "def fibonacci(n): \n\tFibArray = [0, 1] \n\t\n\twhile len(FibArray) < n + 1: \n\t\tFibArray.append(0) \n\t\n\tif n <= 1: \n\t\treturn n \n\telse: \n\t\tif FibArray[n - 1] == 0: \n\t\t\tFibArray[n - 1] = fibonacci(n - 1) \n\n\t\tif FibArray[n - 2] == 0: \n\t\t\tFibArray[n - 2] = fibonacci(n - 2) \n\t\t\t\n\tFibArray[n] = FibArray[n - 2] + FibArray[n - 1] \n\treturn FibArray[n] \n\t\nprint(fibonacci(5)) \n"
  },
  {
    "path": "Algorithms/DP/Gauss_Easter_Date/CalculateEasterDate.java",
    "content": "import java.util.HashMap;\nimport java.util.Map;\n\n/**\n * @author Alessandro Arosio - 04/10/2020 08:39\n */\n\npublic class CalculateEasterDate {\n    private static final String LOCATION_OF_YEAR = \"locationOfYear\";\n    private static final String LEAP_DAYS = \"leapDays\";\n    private static final String NON_LEAP_YEAR = \"nonLeapYear\";\n    private static final String YEARS_DIVIDED_100 = \"yearsDividedBy100\";\n    private static final String CENTURY = \"century\";\n    private static final String DIFFERENCE_LEAP_DAYS = \"differenceOfLeapDays\";\n    private static final String DAYS_TO_ADD = \"numberOfDaysToAdd\";\n    private static final String DAYS_TO_NEXT_SUNDAY = \"numberOfDaysToNextSunday\";\n    private static final String DAYS = \"days\";\n\n    public static void main(String[] args) {\n        int year = 2019;\n        gaussEaster(year);\n    }\n\n    static void gaussEaster(int year) {\n        Map<String, Double> gaussNumbers = getGaussNumbers(year);\n        Integer days = gaussNumbers.get(DAYS).intValue();\n\n        if (is29Days(gaussNumbers.get(DAYS_TO_ADD), gaussNumbers.get(DAYS_TO_NEXT_SUNDAY))) {\n            System.out.println(year + \"-04\" + \"-19\");\n        }\n        else if (is28Days(gaussNumbers.get(DAYS_TO_ADD),gaussNumbers.get(DAYS_TO_NEXT_SUNDAY))) {\n            System.out.println(year + \"-04\" + \"-18\");\n        } else {\n            if (gaussNumbers.get(DAYS) > 31) {\n                System.out.println(year + \"-04-\" + (days - 31));\n            }\n            else {\n                System.out.println(year + \"-03-\" + days);\n            }\n        }\n    }\n\n    private static boolean is29Days(Double days, Double daysToSunday) {\n        return days.intValue() == 29 && daysToSunday.intValue() == 6;\n    }\n\n    private static boolean is28Days(Double days, Double daysToSunday) {\n        return days.intValue() == 28 && daysToSunday.intValue() == 6;\n    }\n\n    private static Map<String, Double> getGaussNumbers(int year) {\n        Map<String, Double> gauss = new HashMap<>();\n        gauss.put(LOCATION_OF_YEAR, Double.valueOf(year % 19));\n        gauss.put(LEAP_DAYS, Double.valueOf(year % 4));\n        gauss.put(NON_LEAP_YEAR, Double.valueOf(year % 7));\n        gauss.put(YEARS_DIVIDED_100, Math.floor(year / 100));\n        gauss.put(CENTURY, calculateCentury(gauss.get(YEARS_DIVIDED_100)));\n        gauss.put(DIFFERENCE_LEAP_DAYS, (4 + gauss.get(YEARS_DIVIDED_100) - gauss.get(YEARS_DIVIDED_100) / 4) % 7);\n        gauss.put(DAYS_TO_ADD, (19 * gauss.get(LOCATION_OF_YEAR) + gauss.get(CENTURY)) % 30);\n        gauss.put(DAYS_TO_NEXT_SUNDAY, (2 * gauss.get(LEAP_DAYS) + 4 *\n                gauss.get(NON_LEAP_YEAR) + 6 *\n                gauss.get(DAYS_TO_ADD) +\n                gauss.get(DIFFERENCE_LEAP_DAYS)) % 7);\n        gauss.put(DAYS, 22 + gauss.get(DAYS_TO_ADD) + gauss.get(DAYS_TO_NEXT_SUNDAY));\n\n        return gauss;\n    }\n\n    private static Double calculateCentury(Double yearsDividedBy100) {\n        double floor = Math.floor((13 + 8 * yearsDividedBy100) / 25);\n        return (15 - floor + yearsDividedBy100 - yearsDividedBy100 / 4) % 30;\n    }\n}\n"
  },
  {
    "path": "Algorithms/DP/Gauss_Easter_Date/Gauss_Easter_Date.cpp",
    "content": "#include <iostream>\nusing namespace std;\n\nvoid gaussAlgorithm(int year, int *month, int *day);\n\nint main()\n{\n\tint year, easterMonth=3, easterDay=22;\n\tcout << \"Enter a year for which you wish to find out date of Easter for: \";\n\tcin >> year; //input year\n\tcout << endl;\n\tgaussAlgorithm(year, &easterMonth, &easterDay); //calculate month and day\n\tcout << \"Date of easter for year \" << year << \" is: \" << ((easterMonth == 3) ? \"March \" : \"April \") << easterDay << endl;\n\tchar ch;\n\tcin >> ch; //wait for user input\n\treturn 0;\n}\n\nvoid gaussAlgorithm(int year, int *month, int *day) //https://math.stackexchange.com/questions/896954/decoding-gauss-easter-algorithm\n{\n\tint a, b, c, k, p, q, M, N, d, e;\n\ta = year%19;\n\tb = year%4;\n\tc = year%7;\n\tk = year/100;\n\tp = (13+8*k)/25; q = k/4;\n\tM = (15-p+k-q)%30;\n\tN = (4+k-q)%7;\n\td = (19*a + M) %30;\n\te = (2*b + 4*c + 6*d + N)%7;\n\tif((22+d+e) < 32)\n\t{\n\t\t*day=22+d+e;\n\t}\n\telse\n\t{\n\t\t*day=d+e-9;\n\t\t*month=4;\n\t}\n\tif(d==29 && e==6 && *month==4 && *day==26)\n\t\t*day=19;\n\tif(d==28 && e==6 && *month==4 && *day==25 && (11*M+11)%30 < 19)\n\t\t*day=18;\n} //\"It is not possible to present here the entire analysis that led to the above formula\" -Gauss\n"
  },
  {
    "path": "Algorithms/DP/Gauss_Easter_Date/Gauss_Easter_Date.php",
    "content": "<?php\nfunction Gauss_Easter($year){\n\t$a = fmod($year,19);\n\t$b = fmod($year,4);\n\t$c = fmod($year,7);\n\t$p = floor($year/100);\n\t$q = floor((13+8*$p)/25);\n\t$m = fmod((15-$q+$p-($p/4)),30);\n\t$n = fmod(4+$p-($p/4),7);\n\t$d = fmod((19*$a+$m),30);\n\t$e = fmod($n+2*$b+4*$c+6*$d,7);\n\t$days = 22+$d+$e;\n\n\tif($d==29 && $e==6){\n\t\techo $year.\"April 19\";\n\t}\n\telseif($d==28 && $e==6){\n\t\techo $year.\"April 18\";\n\t}\n\telse{\n\t\tif($days>31){\n\t\t\techo $year.\"-April-\".($days-31);\n\t\t}\n\t\telse{\n\t\t\techo $year.\"-March-\".$days;\n\t\t}\n\t}\n}\n//Example Case\necho Gauss_Easter(2020);\n"
  },
  {
    "path": "Algorithms/DP/Gauss_Easter_Date/Gauss_Easter_Date.py",
    "content": "import math\n\ndef Easter(Year):\n    # Gauss Easter Algorithm\n    a = Year % 19\n    b = Year % 4\n    c = Year % 7\n    k = math.floor(Year / 100)\n    p = math.floor((13 + 8 * k) / 25)\n    q = k/4\n    m = (15 - p + k - q) % 30\n    n = (4 + k - q) % 7\n    d = (19 * a + m) % 30\n    e = (2 * b + 4 * c + 6 * d + n) % 7\n    days = (22 + d + e)\n  \n    # d is 29\n    if ((d == 29) and (e == 6)):\n        print(Year, \"- 04 -19\")\n        return\n    # d is 28\n    elif ((d == 28) and (e == 6)):\n        print(Year, \"- 04 -18\")\n        return\n    else:\n        # If days > 31, April\n        if (days > 31):\n            print(Year, \"- 04 -\", int(days - 31))\n            return\n        else:\n            # Otherwise, March\n            print(Year, \"- 03 -\", days)\n            return\n\n\n\n\nYear = 2012\nEaster(Year)\n\n\n\n\n\n"
  },
  {
    "path": "Algorithms/DP/Gauss_Easter_Date/Gauss_Easter_Date.rb",
    "content": "def gauss_easter(y)\r\n    a = y % 19\r\n    b = y % 4\r\n    c = y % 7\r\n    \r\n    p = (y / 100).floor\r\n    q = ((13 + 8 * p) / 25).floor\r\n    m = (15 - q + p - (p / 4)) % 30\r\n    \r\n    n = (4 + p - (p / 4)) % 7\r\n    \r\n    d = (19 * a + m) % 30\r\n    \r\n    e = (2 * b + 4 * c + 6 * d + n) % 7\r\n    \r\n    day = (22 + d + e)\r\n      \r\n    if (d == 29) && (e == 6)\r\n        puts(\"The Easter date for your entered year is: #{y}-04-19\")\r\n    elsif (d == 28) && (e == 6)\r\n        return puts(\"The Easter date for your entered year is: #{y}-04-18\")\r\n    else\r\n        if day > 31\r\n            return puts(\"The Easter date for your entered year is: #{y}-04-#{day-31}\")\r\n        else\r\n            return puts(\"The Easter date for your entered year is: #{y}-03-#{day}\")\r\n        end\r\n    end    \r\nend\r\n\r\nprint(\"Enter the year you want to calculate the Easter date: \")\r\ny = Integer(gets.chomp())\r\ngauss_easter(y)"
  },
  {
    "path": "Algorithms/DP/Gauss_Easter_Date/easterDate.cpp",
    "content": "#include <iostream>\n#include <string>\n\nusing namespace std;\n\nint main()\n{\n  unsigned short year, a, b;\n\n  cout << \"\\nFor which year do you want to know Easter date?\\n> \";\n  cin >> year;\n\n  a = (19 * (year % 19) + 15) % 30;\n  b = (2 * (year % 4) + 4 * (year % 7) + 6 * a + 6) % 7;\n\ncout << \"Easter date in \" << year << \" is \"\n  << ((a + b > 26) ?\n    (\"May \" + to_string(a + b - 26)) :\n    (\"April \" + to_string(4 + a + b)))\n  << endl;\n\nreturn 0;\n}\n"
  },
  {
    "path": "Algorithms/DP/Gauss_Easter_Date/easterDate.go",
    "content": "package main\n\nimport \"fmt\"\n\nfunc getEasterDate(_year int) {\n\ta := (19 * (_year % 19) + 15) % 30\n\tb := (2 * (_year % 4) + 4 * (_year % 7) + 6 * a + 6) % 7\n\n\tvar _date string\n\tif a + b > 26 {\n\t\t_date =  fmt.Sprintf(\"May %d\", (a + b - 26))\n\t} else {\n\t\t_date =  fmt.Sprintf(\"April %d\", (4 + a + b))\n\t}\n\n\tfmt.Println(_date, _year)\n}\n\nfunc main() {\n\tgetEasterDate(2020)\n}"
  },
  {
    "path": "Algorithms/DP/Gauss_Easter_Date/easterDate.java",
    "content": "import java.util.Date;\nimport java.util.Scanner;\n \n// Function calculates and prints\n// easter date for given year Y\n class Main {\n \n    static void gaussEaster(int Y)\n    {\n        float A, B, C, P, Q,\n            M, N, D, E;\n \n        // All calculations done\n        // on the basis of\n        // Gauss Easter Algorithm\n        A = Y % 19;\n        B = Y % 4;\n        C = Y % 7;\n        P = (float)Math.floor(Y / 100);\n        Q = (float)Math.floor(\n            (13 + 8 * P) / 25);\n        M = (15 - Q + P - P / 4) % 30;\n        N = (4 + P - P / 4) % 7;\n        D = (19 * A + M) % 30;\n        E = (2 * B + 4 * C + 6 * D + N) % 7;\n        int days = (int)(22 + D + E);\n \n        // A corner case,\n        // when D is 29\n        if ((D == 29) && (E == 6)) {\n            System.out.println(Y + \"-04\"\n                               + \"-19\");\n            return;\n        }\n        // Another corner case,\n        // when D is 28\n        else if ((D == 28) && (E == 6)) {\n            System.out.println(Y + \"-04\"\n                               + \"-18\");\n            return;\n        }\n        else {\n \n            // If days > 31, move to April\n            // April = 4th Month\n            if (days > 31) {\n                System.out.println(Y + \"-04-\"\n                                   + (days - 31));\n                return;\n            }\n            // Otherwise, stay on March\n            // March = 3rd Month\n            else {\n                System.out.println(Y + \"-03-\"\n                                   + days);\n                return;\n            }\n        }\n    }\n \n    // Driver code\n    public static void main(String[] args)\n    {\n        int Y = new java.util.Scanner(System.in).nextInt();\n        gaussEaster(Y);\n    }\n}\n"
  },
  {
    "path": "Algorithms/DP/Gauss_Easter_Date/easterDate.js",
    "content": "const readline = require('readline')\n\nconst rl = readline.createInterface({\n  input: process.stdin,\n  output: process.stdout\n});\n\nrl.question('\\nFor which year do you want to know Easter date?\\n> ', year => {\n  year = parseInt(year)\n\n  const a = (19 * (year % 19) + 15) % 30\n  const b = (2 * (year % 4) + 4 * (year % 7) + 6 * a + 6) % 7\n\n  console.log(`Easter date in ${year} is \\\n${a + b > 26 ? 'May ' + (a + b - 26) : 'April ' + (4 + a + b)}\\n`)\n\n  rl.close()\n})\n"
  },
  {
    "path": "Algorithms/DP/Generate_ATM_Codes.py",
    "content": "print('Welcome to Northen Frock Bank ATM')\n\nrestart=('Y')\n\nchances = 3\n\nbalance = 67.14\n\nwhile chances >= 0:\n\n    pin = int(input('Please Enter You 4 Digit Pin: '))\n\n    if pin == (1234):\n\n        print('You entered you pin Correctly\\n')\n\n        while restart not in ('n','NO','no','N'):\n\n            print('Please Press 1 For Your Balance\\n')\n\n            print('Please Press 2 To Make a Withdrawl\\n')\n\n            print('Please Press 3 To Pay in\\n')\n\n            print('Please Press 4 To Return Card\\n')\n\n            option = int(input('What Would you like to choose?'))\n\n            if option == 1:\n\n                print('Your Balance is Â£',balance,'\\n')\n\n                restart = input('Would You you like to go back? ')\n\n                if restart in ('n','NO','no','N'):\n\n                    print('Thank You')\n\n                    break\n\n            elif option == 2:\n\n                option2 = ('y')\n\n                withdrawl = float(input('How Much Would you like to      \n\nwithdraw? \\nÂ£10/Â£20/Â£40/Â£60/Â£80/Â£100 for other enter 1: '))\n\n                if withdrawl in [10, 20, 40, 60, 80, 100]:\n\n                    balance = balance - withdrawl\n\n                    print ('\\nYour Balance is now Â£',balance)\n\n                    restart = input('Would You you like to go back? ')\n\n                    if restart in ('n','NO','no','N'):\n\n                        print('Thank You')\n\n                        break\n\n                elif withdrawl != [10, 20, 40, 60, 80, 100]:\n\n                    print('Invalid Amount, Please Re-try\\n')\n\n                    restart = ('y')\n\n                elif withdrawl == 1:\n\n                    withdrawl = float(input('Please Enter Desired amount:'))    \n\n            elif option == 3:\n\n                Pay_in = float(input('How Much Would You Like To Pay In? '))\n\n                balance = balance + Pay_in\n\n                print ('\\nYour Balance is now Â£',balance)\n\n                restart = input('Would You you like to go back? ')\n\n                if restart in ('n','NO','no','N'):\n\n                    print('Thank You')\n\n                    break\n\n            elif option == 4:\n\n                print('Please wait whilst your card is Returned...\\n')\n\n                print('Thank you for you service')\n\n                break\n\n            else:\n"
  },
  {
    "path": "Algorithms/DP/Gold_Mine_Problem/goldmine.java",
    "content": "// Java program to solve Gold Mine problem \nimport java.util.Arrays; \n\nclass goldmine { \n\t\n\t\n\t\n\t// Returns maximum amount of gold that \n\t// can be collected when journey started \n\t// from first column and moves allowed \n\t// are right, right-up and right-down \n\tstatic int getMaxGold(int gold[][], int m, int n) \n\t{ \n\t\t\n\t\t// Create a table for storing \n\t\t// intermediate results and initialize \n\t\t// all cells to 0. The first row of \n\t\t// goldMineTable gives the maximum \n\t\t// gold that the miner can collect \n\t\t// when starts that row \n\t\tint goldTable[][] = new int[m][n]; \n\t\t\n\t\tfor(int[] rows:goldTable) \n\t\t\tArrays.fill(rows, 0); \n\t\n\t\tfor (int col = n-1; col >= 0; col--) \n\t\t{ \n\t\t\tfor (int row = 0; row < m; row++) \n\t\t\t{ \n\t\t\t\t\n\t\t\t\t// Gold collected on going to \n\t\t\t\t// the cell on the right(->) \n\t\t\t\tint right = (col == n-1) ? 0\n\t\t\t\t\t\t: goldTable[row][col+1]; \n\t\n\t\t\t\t// Gold collected on going to \n\t\t\t\t// the cell to right up (/) \n\t\t\t\tint right_up = (row == 0 || \n\t\t\t\t\t\t\tcol == n-1) ? 0 : \n\t\t\t\t\t\tgoldTable[row-1][col+1]; \n\t\n\t\t\t\t// Gold collected on going to \n\t\t\t\t// the cell to right down (\\) \n\t\t\t\tint right_down = (row == m-1\n\t\t\t\t\t\t\t|| col == n-1) ? 0 : \n\t\t\t\t\t\tgoldTable[row+1][col+1]; \n\t\n\t\t\t\t// Max gold collected from taking \n\t\t\t\t// either of the above 3 paths \n\t\t\t\tgoldTable[row][col] = gold[row][col] \n\t\t\t\t+ Math.max(right, Math.max(right_up, \n\t\t\t\t\t\t\t\t\tright_down)); \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t; \n\t\t\t} \n\t\t} \n\t\n\t\t// The max amount of gold collected will be \n\t\t// the max value in first column of all rows \n\t\tint res = goldTable[0][0]; \n\t\t\n\t\tfor (int i = 1; i < m; i++) \n\t\t\tres = Math.max(res, goldTable[i][0]); \n\t\t\t\n\t\treturn res; \n\t} \n\t\n\t//driver code \n\tpublic static void main(String arg[]) \n\t{ \n\t\tint gold[][]= { {1, 3, 1, 5}, \n\t\t\t\t\t\t{2, 2, 4, 1}, \n\t\t\t\t\t\t{5, 0, 2, 3}, \n\t\t\t\t\t\t{0, 6, 1, 2} }; \n\t\t\t\t\t\t\n\t\tint m = 4, n = 4; \n\t\t\n\t\tSystem.out.print(getMaxGold(gold, m, n)); \n\t} \n} \n\n\n"
  },
  {
    "path": "Algorithms/DP/Gold_Mine_Problem/goldmine.py",
    "content": "MAX = 100\n\n\ndef getMaxGold(gold, m, n):\n\n    goldTable = [[0 for i in range(n)]\n                 for j in range(m)]\n\n    for col in range(n-1, -1, -1):\n        for row in range(m):\n\n            if (col == n-1):\n                right = 0\n            else:\n                right = goldTable[row][col+1]\n\n            if (row == 0 or col == n-1):\n                right_up = 0\n            else:\n                right_up = goldTable[row-1][col+1]\n\n            if (row == m-1 or col == n-1):\n                right_down = 0\n            else:\n                right_down = goldTable[row+1][col+1]\n\n            goldTable[row][col] = gold[row][col] + \\\n                max(right, right_up, right_down)\n\n    res = goldTable[0][0]\n    for i in range(1, m):\n        res = max(res, goldTable[i][0])\n\n    return res\n\n\ngold = [[1, 3, 1, 8],\n        [2, 9, 8, 1],\n        [7, 0, 1, 3],\n        [0, 6, 1, 2]]\n\nm = 4\nn = 4\n\nprint(getMaxGold(gold, m, n))\n"
  },
  {
    "path": "Algorithms/DP/Golomb_Sequence/Golomb Sequence.cpp",
    "content": "#include <bits/stdc++.h> \nusing namespace std; \n  \nvoid printGolomb(int n) \n{ \n    int dp[n + 1]; \n    dp[1] = 1; \n    cout << dp[1] << \" \"; \n    for (int i = 2; i <= n; i++)  \n    { \n        dp[i] = 1 + dp[i - dp[dp[i - 1]]]; \n        cout << dp[i] << \" \"; \n    } \n} \nint main() \n{ \n    int n;\n    cin>>n;\n  \n    printGolomb(n); \n    return 0; \n} \n\nI/P: n=9\nO/P: 1 2 2 3 3 4 4 4 5\n"
  },
  {
    "path": "Algorithms/DP/Golomb_Sequence/Golomb.cpp",
    "content": "// C++ Program to find first \n// n terms of Golomb sequence. \n#include <bits/stdc++.h> \nusing namespace std; \n\n// Print the first n term \n// of Golomb Sequence \nvoid printGolomb(int n) \n{ \n\tint dp[100]; \n\n\t// base cases \n\tdp[1] = 1; \n\tcout << dp[1] << \" \"; \n\n\t// Finding and printing first \n\t// n terms of Golomb Sequence. \n\tfor (int i = 2; i <= n; i++) \n\t{ \n\t\tdp[i] = 1 + dp[i - dp[dp[i - 1]]]; \n\t\tcout << dp[i] << \" \"; \n\t} \n} \n// Driver Code \nint main() \n{ \n\tint n = 9; \n\n\tprintGolomb(n); \n\treturn 0; \n} \n"
  },
  {
    "path": "Algorithms/DP/Golomb_Sequence/Golomb.java",
    "content": "import java.util.*; \n  \nclass Golomb  \n{ \n      \n    public static void printGolomb(int n) \n    { \n        int dp[] = new int[n + 1];  \n        dp[1] = 1; \n        System.out.print(dp[1] + \" \"); \n        for (int i = 2; i <= n; i++)  \n        { \n            dp[i] = 1 + dp[i - dp[dp[i - 1]]]; \n              \n        System.out.print(dp[i] + \" \"); \n        } \n    } \n    public static void main (String[] args) \n    { \n        Scanner s = new Scanner(System.input());\n        int n = s.nextInt();\n        printGolomb(n); \n    } \n}"
  },
  {
    "path": "Algorithms/DP/Golomb_Sequence/golomb.py",
    "content": "# Golomb sequence \ndef findGolomb(n): \n\n\tif (n == 1): \n\t\treturn 1\n\n\treturn 1 + findGolomb(n - findGolomb(findGolomb(n - 1))) \n \ndef printGolomb(n): \n\n\tfor i in range(1, n + 1): \n\t\tprint(findGolomb(i), end=\" \") \n\nn = 19\nprintGolomb(n) \n"
  },
  {
    "path": "Algorithms/DP/Knight_Probability/Knight_Probability_in_a_ChessBoard.cpp",
    "content": "#include <bits/stdc++.h>\nusing namespace std;\n\ndouble knightProbability(int N, int K, int sr, int sc) \n    {\n        vector<vector<double> > dp(N, vector<double>(N));\n        int dr[8] = {2, 2, 1, 1, -1, -1, -2, -2};\n        int dc[8] = {1, -1, 2, -2, 2, -2, 1, -1};\n\n        dp[sr][sc] = 1;\n        for (; K > 0; K--) {\n            vector<vector<double> > dp2(N, vector<double>(N));\n            for (int r = 0; r < N; r++) {\n                for (int c = 0; c < N; c++) {\n                    for (int k = 0; k < 8; k++) {\n                        int cr = r + dr[k];\n                        int cc = c + dc[k];\n                        if (0 <= cr && cr < N && 0 <= cc && cc < N) {\n                            dp2[cr][cc] += dp[r][c] / 8.0;\n                        }\n                    }\n                }\n            }\n            dp = dp2;\n        }\n        double ans = 0.0;\n        for (auto row: dp) {\n            for (double x: row) ans += x;\n        }\n        return ans;\n    }\n    \nint main()\n{\n    int n, k, sr, sc;\n    cout << \"Please enter size of chessboard, number of moves, starting row and starting column\" << endl;\n    cin >> n >> k >> sr >> sc;\n    cout << \"The probability that the knight remains on the board after it has stopped moving is \" << knightProbability(n, k, sr, sc) << endl;\n    return 0;\n}\n"
  },
  {
    "path": "Algorithms/DP/Knight_Probability/Problem_Statement.md",
    "content": "On an NxN chessboard, a knight starts at the r-th row and c-th column and attempts to make exactly K moves. \nThe rows and columns are 0 indexed, so the top-left square is (0, 0), and the bottom-right square is (N-1, N-1).\n\nA chess knight has 8 possible moves it can make, as illustrated below. \nEach move is two squares in a cardinal direction, then one square in an orthogonal direction.\n\nEach time the knight is to move, it chooses one of eight possible moves uniformly at random (even if the piece would go off the chessboard) and moves there.\n\nThe knight continues moving until it has made exactly K moves or has moved off the chessboard. \nReturn the probability that the knight remains on the board after it has stopped moving.\n \n"
  },
  {
    "path": "Algorithms/DP/LCS/LCS_of_three_strings.py",
    "content": "def three_LCS(A,B,C):\n    m=len(A)\n    n=len(B)\n    o=len(C)\n    L=[[[0 for i in range(o+1)]for j in range(n+1)]for k in range(m+1)]\n    for i in range(m+1):\n        for j in range(n+1):\n            for k in range(o+1):\n                if (i==0 or j==0 or k==0):\n                    L[i][j][k]=0\n                elif (A[i-1]==B[j-1] and A[i-1]==C[k-1]):\n                     L[i][j][k]= 1+L[i-1][j-1][k-1]\n                else:\n                     L[i][j][k]=max(max(L[i-1][j][k],L[i][j-1][k]),L[i][j][k-1])\n    return L[m][n][o]\n\n\nX = 'ABCDAB'\nY = 'BDCABA'\nZ = '12XBA'\n\nprint('Length of LCS of three strings is', three_LCS(X, Y, Z))\n"
  },
  {
    "path": "Algorithms/DP/LCS/LongestCommonSubsequence.cpp",
    "content": "#include <bits/stdc++.h>\n\nusing namespace std;\nint LCS(string s1, string s2){//function to get the longest common subsequence\n    vector<vector<int>> dp(s1.length()+1, vector<int>(s2.length()+1, 0));//table of dp for finding length of longest subsequence\n    for(int i = 1; i<=s1.length(); i++){\n        for(int j = 1; j<= s2.length(); j++){\n            if(s1[i-1] == s2[j-1])//if letter match in both string the following line to be used\n                dp[i][j] = 1+ dp[i-1][j-1];\n            else\n                dp[i][j] = max(dp[i-1][j], dp[i][j-1]);\n        }\n    }\n    return dp[s1.length()][s2.length()];//length of longest common subsequence here\n}\nint main()\n{\n    string s1, s2;\n    cin>>s1;\n    cin>> s2;\n    int res = LCS(s1,s2);\n    cout<< res<<endl;\n    return 0;\n}\n"
  },
  {
    "path": "Algorithms/DP/LCS/LongestCommonSubsequenceLength.java",
    "content": "import java.util.Scanner;\nclass LongestCommonSubsequenceLength{\n  public static void main(String[]args){\n    //initialize scanner\n    Scanner kb=new Scanner(System.in);\n    //prompt user for input\n    System.out.println(\"Provide 2 Strings\");\n    //take in 2 strings\n    String s1=kb.nextLine();\n    String s2=kb.nextLine();\n    //make 2d array for strings (with space for zeroes to pad first row and column)\n    int[][]a=new int[s1.length()+1][s2.length()+1];\n\n    //pad firs column with 0s\n    for(int i=0; i<=s1.length(); i++)\n      a[i][0]=0;\n    //pad first column with 0s\n    for(int j=0; j<=s2.length(); j++)\n      a[0][j]=0;\n    /*now loop over the entire 2d matrix and use the following\n      recurrence relation: a[i][j]=max(a[i-1][j], a[i][j-1])\n      or if the current i,j position has a matching character include a[i-1][j-1] in that calculation.  \n\n      Why does this work?  We take either the longest common subsequence up to character j of string 2 or up to character i of string 1, whichever is better, because each occurrence must be in order, the greater of these two must be best up to index i in string 1 and index j in string 2.  \n\n      However, if the ith character of str1 matches the jth character of str2, then we must consider what happens if the optimal solution through character i-1 and j-1 was the same as i-1 and j or j-1 and i.  Clearly, in either of these cases, by taking the ith character of string 1, which matches the jth character of string 2, we are guaranteed to be better off taking i and j matching character next, because the alternative would be to wait for either i and j+1 or j and i+1 to match, both of which are at least no better than having the same count through i and j.  \n    */\n    for(int i=0; i<s1.length(); i++)\n      for(int j=0; j<s2.length(); j++)\n        if(s1.charAt(i)==s2.charAt(j))\n          a[i+1][j+1]=Math.max(Math.max(a[i][j]+1, a[i][j+1]),a[i+1][j]);\n        else\n          a[i+1][j+1]=Math.max(a[i][j+1], a[i+1][j]);\n\n    /*Then we just print out whatever is in the last position in our array since it's the longest common subsequence up through the final characters of each string*/\n    System.out.println(a[s1.length()][s2.length()]);\n    \n  }\n}\n"
  },
  {
    "path": "Algorithms/DP/LCS/Longest_Common_Subsequence_of_Three_String.java",
    "content": "import java.io.*;\nimport java.util.*;\nclass LCS3Strings { \n    public static int lcsOf3(String X, String Y, String Z, int m,int n, int o) \n    { \n        int[][][] L = new int[m+1][n+1][o+1]; \n  \n        for (int i=0; i<=m; i++) \n        { \n            for (int j=0; j<=n; j++) \n            { \n                for (int k=0; k<=o; k++) \n                { \n                    if (i == 0 || j == 0||k==0) \n\t\t    {\n                        L[i][j][k] = 0; \n\t\t    }       \n                    else if (X.charAt(i - 1) == Y.charAt(j - 1)  && X.charAt(i - 1)==Z.charAt(k - 1)) \n\t\t    {\n                        L[i][j][k] = L[i-1][j-1][k-1] + 1; \n\t\t    }       \n                    else\n\t\t    {\n                        L[i][j][k] = Math.max(Math.max(L[i-1][j][k],L[i][j-1][k]), L[i][j][k-1]); \n\t\t    }\n                } \n            } \n        } \n      \n        return L[m][n][o]; \n    } \n       \n    public static void main(String args[]) \n    { \n\tScanner sc = new Scanner(System.in);\n        String X = sc.nextLine();\n        String Y = sc.nextLine(); \n        String Z = sc.nextLine(); \n       \n        int m = X.length(); \n        int n = Y.length(); \n        int o = Z.length(); \n       \n        System.out.println(\"Length of LCS is \" + lcsOf3(X, Y,Z, m, n, o)); \n       \n    } \n} "
  },
  {
    "path": "Algorithms/DP/LCS/Longest_Common_Subsequence_of_Two_Sequences.c",
    "content": "/*\n\tAuthor-yogesh kansal\n\nproblem statement:\n\t\tGiven two sequences ?? = (a1, a2, . . . , am) and ?? = (b1, b2, . . . , bn),\n \t\tfind the length of their longest common subsequence'\n \ntime complexity :- O(m*n)\nspace complexity :- O(m*n)\n*/\n\n#include <stdio.h>\n#define M 1000000007LL\n#define mod 998244253LL\n#define ll long long int\n#define vi vector<int>\n\nint max(int a,int b) {\n\tif(a>b)\n\t\treturn a;\n\telse\n\t\treturn b;\n}\n\nint main() {\n\tint n,m,i,j;\n\t\n\tprintf(\"enter length of 1st subsequrnce:- \");\n\tscanf(\"%d\",&n);\n\tint a[n];\n\tprintf(\"\\nenter sequence:- \");\n\tfor(i=0;i<n;i++) scanf(\"%d\",&a[i]);\n\t\n\tprintf(\"\\nenter length of 2nd sequence:- \");\n\tscanf(\"%d\",&m);\n\tint b[m];\n\tprintf(\"\\nenter sequence:- \");\n\tfor(i=0;i<m;i++) scanf(\"%d\",&b[i]);\n\t\n\tint dp[n+1][m+1];\n\tfor(i=0;i<=n;i++)\n\tdp[i][0]=0;\n\tfor(i=0;i<=m;i++)\n\tdp[0][i]=0;\n\t\n\tfor(i=1;i<=n;i++)\n\t{\n\t\tfor(j=1;j<=m;j++)\n\t\t{\n\t\t\t\n\t\t\tdp[i][j]=max(max(dp[i-1][j],dp[i][j-1]),dp[i-1][j-1]);\n\t\t\tif(a[i-1]==b[j-1])\n\t\t\tdp[i][j]+=1;\n\t\t}\n\t}\n\tprintf(\"\\nlength of longest common subsequence is:- \");\n\tprintf(\"%d\",dp[n][m]);\n\treturn 0;\n}\n"
  },
  {
    "path": "Algorithms/DP/LCS/Longest_Common_Subsequence_of_Two_Sequences.cpp",
    "content": "/*\n\tAuthor-yogesh kansal\n\nproblem statement:\n\t\tGiven two sequences ?? = (a1, a2, . . . , am) and ?? = (b1, b2, . . . , bn),\n \t\tfind the length of their longest common subsequence'\n \ntime complexity :- O(m*n)\nspace complexity :- O(m*n)\n*/\n\n#include <stdio.h>\n#define M 1000000007LL\n#define mod 998244253LL\n#define ll long long int\n#define vi vector<int>\n\nint max(int a,int b) {\n\tif(a>b)\n\t\treturn a;\n\telse\n\t\treturn b;\n}\n\nint main() {\n\tint n,m,i,j;\n\t\n\tprintf(\"enter length of 1st subsequrnce:- \");\n\tscanf(\"%d\",&n);\n\tint a[n];\n\tprintf(\"\\nenter sequence:- \");\n\tfor(i=0;i<n;i++) scanf(\"%d\",&a[i]);\n\t\n\tprintf(\"\\nenter length of 2nd sequence:- \");\n\tscanf(\"%d\",&m);\n\tint b[m];\n\tprintf(\"\\nenter sequence:- \");\n\tfor(i=0;i<m;i++) scanf(\"%d\",&b[i]);\n\t\n\tint dp[n+1][m+1];\n\tfor(i=0;i<=n;i++)\n\tdp[i][0]=0;\n\tfor(i=0;i<=m;i++)\n\tdp[0][i]=0;\n\t\n\tfor(i=1;i<=n;i++)\n\t{\n\t\tfor(j=1;j<=m;j++)\n\t\t{\n\t\t\t\n\t\t\tdp[i][j]=max(max(dp[i-1][j],dp[i][j-1]),dp[i-1][j-1]);\n\t\t\tif(a[i-1]==b[j-1])\n\t\t\tdp[i][j]+=1;\n\t\t}\n\t}\n\tprintf(\"\\nlength of longest common subsequence is:- \");\n\tprintf(\"%d\",dp[n][m]);\n\treturn 0;\n}\n"
  },
  {
    "path": "Algorithms/DP/LCS/lcs.py",
    "content": "#Longest Common Subsequence\ntext1=input()\ntext2=input()\nm=len(text1)\nn=len(text2)\ndp=[[0 for j in range(n+1)]for i in range(m+1)]\nfor i in range(m+1):\n  for j in range(n+1):\n    if i==0 or j==0:\n      dp[i][j]=0\n    elif text1[i-1]==text2[j-1]:\n      dp[i][j]=1+dp[i-1][j-1]\n    else:\n      dp[i][j]=max(dp[i-1][j],dp[i][j-1])\nprint(dp[m][n])\n"
  },
  {
    "path": "Algorithms/DP/LCS/lcs_of_3_strings.cpp",
    "content": "#include<bits/stdc++.h> \nusing namespace std;\n \n#define ull unsigned long long\n#define int long long\n#define ld long double\n#define pb push_back\n#define pi  pair< int,int >\n#define ff first\n#define ss second\n#define mod 1000000007\n#define endl \"\\n\"\n \nsigned main()\n{\n \n    ios_base::sync_with_stdio(false); cin.tie(NULL);\n \n    // #ifndef ONLINE_JUDGE\n    // freopen(\"input.txt\", \"r\", stdin);\n    // freopen(\"output.txt\", \"w\", stdout);\n    // #endif\n \n    string s1,s2,s3;\n    cin>>s1>>s2>>s3;  // take input of three strings\n\n    // Find the length of the three strings\n    int n = s1.length(), m = s2.length(), l = s3.length();\n\n    // Finding the lcs length\n\n    int dp[n+1][m+1][l+1];\n\n    for(int i=0; i<=n; i++)\n    {\n        for(int j=0; j<=m; j++)\n        {\n            for(int k=0; k<=l; k++)\n            {\n                if(i==0 || j==0 || k==0)\n                    dp[i][j][k] = 0;\n                else if(s1[i-1] == s2[j-1] && s2[j-1] == s3[k-1])\n                    dp[i][j][k] = dp[i-1][j-1][k-1] + 1;\n                else\n                    dp[i][j][k] = max(dp[i-1][j][k], max(dp[i][j-1][k], dp[i][j][k-1]));\n            }\n        }\n    }\n\n    int length_of_lcs = dp[n][m][l];     // Length of LCS of the 3 strings\n\n    int i=n, j=m, k=l;\n\n    string ans=\"\";   // Initializing lcs string\n\n    while(i>0 && j>0 && k>0)\n    {\n        if(s1[i-1] == s2[j-1] && s2[j-1] == s3[k-1])   // If current character in s1, s2, and s3 are same, then current character is part of LCS \n        {\n            ans+=s1[i-1];\n            i--;\n            j--;\n            k--;\n        }\n        // If not same, then find the larger of the three and go in the direction of larger value \n        else if(dp[i-1][j][k] > dp[i][j-1][k] || dp[i-1][j][k] > dp[i][j][k-1])\n            i--;\n        else if(dp[i][j-1][k] > dp[i-1][j][k] || dp[i][j-1][k] > dp[i][j][k-1])\n            j--;\n        else\n            k--;\n    }\n\n    // We have to reverse the lcs string because we\n    // put characters in the lcs string from the last\n    reverse(ans.begin(), ans.end());\n\n    cout<<\"The longest common subsequence is: \";\n\n    cout<<ans<<endl;\n \n    return 0;\n   \n}"
  },
  {
    "path": "Algorithms/DP/LIS/LIS.c",
    "content": "/* Dynamic Programming C implementation of LIS problem */\n#include<stdio.h>  \n\t\n/* lis() returns the length of the longest increasing subsequence in arr[] of size n */\nint lis( int arr[], int n ) \n{ \n\tint lis[10000]; \n\tint i, j;\n\tlis[0] = 1; \n\n\t/* Compute optimized LIS values in bottom up manner */\n\tfor (i = 1; i < n; i++ ) \n\t{ \n\t\tlis[i] = 1; \n\t\tfor (j = 0; j < i; j++ ) \n\t\t\tif ( arr[i] > arr[j] && lis[i] < lis[j] + 1) \n\t\t\t\tlis[i] = lis[j] + 1; \n\t} \n\n\t// Return maximum value in lis[] \n\tint mmax=-99999;\n\tfor(i=0;i<n;i++)\n\t{\n\t\tif(mmax<lis[i])\n\t\t\tmmax = lis[i];\n\t}\n\treturn mmax; \n} \n\t\n/* Driver program to test above function */\nint main() \n{ \n\tint n;\n\tint arr[10000];\n\tscanf(\"%d\", &n);\n\tfor(int i=0;i<n;i++)\n\t\tscanf(\"%d\", &arr[i]);\n\tprintf(\"Length of lis is %d\\n\", lis( arr, n ) ); \n\n\treturn 0; \n}\n"
  },
  {
    "path": "Algorithms/DP/LIS/LIS.cpp",
    "content": "#include <bits/stdc++.h>\nusing namespace std;\n\n/*\nInput Format: length of the array and contents of the array\nOutput Format: length of LIS and contents of the LIS\nALgorithm: Bottom Up Dynamic programming\nTime Complexity: O(N^2), where N is the length of the array\nSpace Complexity: O(N^2)\n\nSample Input and Output\n\n**Sample Input 1:**\n\nEnter the number of elements of the array: 8\n\nEnter the elements of the array: 1 8 5 9 6 2 4 7\n\nThe length of LIS is: 4\n\nThe LIS is: 1 5 6 7\n\n**Sample Input 2:**\n\nEnter the number of elements of the array: 10\n\nEnter the elements of the array: 1 2 3 6 5 8 9 4 7 6\n\nThe length of LIS is: 6\n\nThe LIS is: 1 2 3 6 8 9\n\nGraph contains cycle!\n*/\n\nint main()\n{\n\n  int n; // number of elements of the array\n  cout << \"\\nEnter the number of elements of the array: \";\n  cin >> n;\n\n  vector<int> a(n);\n\n  vector<int> lis(n); // for storing the longest increasing subsequence size of each index\n\n  vector<vector<int>> seq(n); // storing the longest increasing subsequence for each index from 0 to n-1\n\n  cout << \"\\nEnter the elements of the array: \";\n  for (int i = 0; i < n; i++)\n  {\n    cin >> a[i];\n  }\n\n  // initialising the LIS for each index to 1\n  for (int i = 0; i < n; i++)\n  {\n    lis[i] = 1;\n  }\n\n  // counting the LIS in bottom up manner dynamic programming\n  for (int i = 1; i < n; i++)\n  {\n    vector<int> tmp;\n    for (int j = 0; j < i; j++)\n    {\n      // if the current LIS value is less that the value we just calculated we have got a new LIS for index i\n      if (a[i] > a[j] and lis[i] < lis[j] + 1)\n      {\n        lis[i] = lis[j] + 1;\n        tmp.push_back(a[j]);\n      }\n    }\n    tmp.push_back(a[i]);\n    seq[i] = tmp;\n  }\n\n  int answerIndex = 0;\n  int maxLength = *max_element(lis.begin(), lis.end());\n  for (int i = 0; i < n; i++)\n  {\n    if ((int)seq[i].size() == maxLength)\n    {\n      answerIndex = i;\n      break;\n    }\n  }\n  // printing the LIS and contents of the LIS\n  cout << \"\\nThe length of LIS is: \" << maxLength << '\\n';\n  cout << \"\\nThe LIS is: \";\n  for (auto u : seq[answerIndex])\n  {\n    cout << u << \" \";\n  }\n  cout << '\\n';\n}"
  },
  {
    "path": "Algorithms/DP/LIS/LIS.go",
    "content": "package main\n\nimport \"fmt\"\n\nfunc binarySearch(array []int, l int, r int, key int) int {\n\tfor r-l > 1 {\n\t\tcenter := l + (r-l)/2\n\t\tif array[center] >= key {\n\t\t\tr = center\n\t\t} else {\n\t\t\tl = center\n\t\t}\n\t}\n\n\treturn r\n}\n\n// LongestIncreasingSubsequence will returned a maximum increasing subsequence inside the input given\n// with complexity O(N log N)\nfunc LongestIncreasingSubsequence(input []int) int {\n\tif len(input) == 0 {\n\t\treturn 0\n\t}\n\n\tlength := 1\n\tarray := make([]int, len(input))\n\tarray[0] = input[0]\n\n\tfor i := 1; i < len(array); i++ {\n\t\tif input[i] < array[0] {\n\t\t\tarray[0] = input[i]\n\t\t} else if input[i] > array[length-1] {\n\t\t\tarray[length] = input[i]\n\t\t\tlength++\n\t\t} else {\n\t\t\tarray[binarySearch(array, -1, length-1, input[i])] = input[i]\n\t\t}\n\t}\n\n\treturn length\n}\n\nfunc main() {\n\tinput := []int{1, 4, 3, 8, 12, 1, 9, 10, 3, 11, 0, 3}\n\toutput := LongestIncreasingSubsequence(input)\n\n\tfmt.Println(output)\n}\n"
  },
  {
    "path": "Algorithms/DP/LIS/LIS.java",
    "content": "/*\nInput Format: length of the array and contents of the array\nOutput Format: length of LIS and contents of the LIS\nSample Input and Output\n**Sample Input 1:**\nEnter the number of elements of the array: 8\nEnter the elements of the array: 1 8 5 9 6 2 4 7\nThe length of LIS is: 4\nThe LIS is: 1 5 6 7\n**Sample Input 2:**\nEnter the number of elements of the array: 10\nEnter the elements of the array: 1 2 3 6 5 8 9 4 7 6\nThe length of LIS is: 6\nThe LIS is: 1 2 3 6 8 9\nGraph contains cycle!\n*/\n\n\nimport java.util.*; \n\nclass Main\n{\n\tpublic static void findLIS(int[] arr)\n\t{\n\t\t// LIS.get(i) stores the longest increasing subsequence of subarray\n\t\tList<List<Integer>> LIS = new ArrayList<>();\n\t\tfor (int i = 0; i < arr.length; i++) {\n\t\t\tLIS.add(new ArrayList<>());\n\t\t}\n\n\t\t// LIS[0] denotes longest increasing subsequence ending with arr[0]\n\t\tLIS.get(0).add(arr[0]);\n\n\t\n\t\tfor (int i = 1; i < arr.length; i++)\n\t\t{\n\n\t\t\tfor (int j = 0; j < i; j++)\n\t\t\t{\n\t\t\t\t// find longest increasing subsequence that ends with arr[j]\n\t\t\t\t// where arr[j] is less than the current element arr[i]\n\n\t\t\t\tif (arr[j] < arr[i] && LIS.get(j).size() > LIS.get(i).size()) {\n\t\t\t\t\tLIS.set(i, new ArrayList<>(LIS.get(j)));\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// include arr[i] in LIS.get(i)\n\t\t\tLIS.get(i).add(arr[i]);\n\t\t}\n\n\t\t\n\t\tint j = 0;\n\t\tfor (int i = 0; i < arr.length; i++) {\n\t\t\tif (LIS.get(j).size() < LIS.get(i).size()) {\n\t\t\t\tj = i;\n\t\t\t}\n\t\t}\n\t\t\n        System.out.print(\"The length of LIS is:\" + (LIS.get(j)).size());\n\t\tSystem.out.print(\"\\n\"+\"The LIS is:\" + LIS.get(j));\n\t}\n\n\tpublic static void main(String[] args)\n\t{\n\t\t\n\t\tScanner sc = new Scanner(System.in);\n\t\tSystem.out.print(\"Enter the number of elements of the array:\"+\"\\n\");\n\t\tint n = sc.nextInt();\n\tSystem.out.print(\"Enter the elements of the array:\"+\"\\n\");\n        int array[] = new int[n];\n        for (int i = 0; i < n; ++i)\n        {\n            array[i] = sc.nextInt();\n        }\n\n\t\tfindLIS(array);\n\t\t\n\t}\n}\n"
  },
  {
    "path": "Algorithms/DP/LIS/LongestIncreaseSubSequence.cpp",
    "content": "#include <iostream>\nusing namespace std;\n\nint lis(int* input, int n) {\n\tint* output = new int[n];\n\toutput[0] = 1;\n\tfor (int i = 1; i < n; i++) {\n\t\toutput[i] = 1;\n\t\tfor (int j = i - 1; j >= 0; j--) {\n\t\t\tif (input[j] > input[i]) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tint possibleAns = output[j] + 1;\n\t\t\tif (possibleAns > output[i]) {\n\t\t\t\toutput[i] = possibleAns;\n\t\t\t}\n\t\t}\n\t}\n\tint best = 0;\n\tfor (int i = 0; i < n; i++) {\n\t\tif (best < output[i]) {\n\t\t\tbest = output[i];\n\t\t}\n\t}\n\tdelete [] output;\n\treturn best;\n}\n\nint main() {\n\tint n;\n\tcin >> n;\n\tint * input = new int[n];\n\tfor (int i = 0; i < n; i++) {\n\t\tcin >> input[i];\n\t}\n\tint ans = lis(input, n);\n\tcout << ans << endl;\n\tdelete [] input;\n}"
  },
  {
    "path": "Algorithms/DP/LIS/README.md",
    "content": "## LIS (Longest Increasing Subsequence)\n\n- [LIS C++](LIS.cpp)\n- [LIS Java](LIS.java)\n- [LIS Python3](lis.py)\n- [LIS Go](LIS.go)\n\n---\n### [⬆](#toc) <a name='stat'>Problem Statement</a>\nGiven an array of integers, find the length of the longest (strictly) increasing subsequence \nfrom the given array along with that print the contents of the LIS\n\n- <h4>Input Format:</h4> length of the array and contents of the array</br>\n- <h4>Output Format:</h4> length of LIS and contents of the LIS\n\n---\n\n\n### [⬆](#toc) <a name='stat'>Sample Input Output</a>\n\n- <h4>Input:</h4> N = 16</br> A[] = 0 8 4 12 2 10 6 14 1 9 5 13 3 11 7 15\n- <h4>Output:</h4> The length of LIS is: 6 </br> The LIS is: 0 2 6 9 13 15\n\n---\n"
  },
  {
    "path": "Algorithms/DP/LIS/lis.py",
    "content": "def lis(arr): \n\tn = len(arr) \n\tlis = [1]*n\n\tfor i in range (1, n): \n\t\tfor j in range(0, i): \n\t\t\tif arr[i] > arr[j] and lis[i]< lis[j] + 1 : \n\t\t\t\tlis[i] = lis[j]+1\n\tmaximum = 0\n\tfor i in range(n): \n\t\tmaximum = max(maximum, lis[i]) \n\n\treturn maximum \n\n    \narr = [10, 22, 9, 33, 21, 50, 41, 60] \nprint(\"Length of lis is\"+\" \"+ str(lis(arr)))\n\n"
  },
  {
    "path": "Algorithms/DP/LSCS/LSCS.c",
    "content": "#include <stdio.h>\n#include <limits.h>\n\nint largest_subarray_sum(int *arr, int size)\n{\n\tif (size <= 0) {\n\t\tprintf(\"Size must be a positive integer\\n\");\n\t\treturn 1;\n\t}\n\n\tint start = 0, best_start = 0, best_end = 0;\n\tint sum = 0, best_sum = INT_MIN;\n\n\tfor (int end = 0; end < size; ++end) {\n\t\tif (sum <= 0) {\n\t\t\tstart = end;\n\t\t\tsum = arr[end];\n\t\t} else {\n\t\t\tsum += arr[end];\n\t\t}\n\n\t\tif (sum > best_sum) {\n\t\t\tbest_sum = sum;\n\t\t\tbest_start = start;\n\t\t\tbest_end = end;\n\t\t}\n\t}\n\tprintf(\"Best sum is %d\\nFirst index: %d\\nLast index: %d\\n\",\n\t\t\tbest_sum, best_start, best_end);\n\t\n\treturn 0;\n}\n"
  },
  {
    "path": "Algorithms/DP/LSCS/LSCS.cpp",
    "content": "using namespace std; \n#include<iostream> \n#include<climits> \n\nint maxSubArraySum(int a[], int size) \n{ \n    int max_so_far = INT_MIN, max_ending_here = 0, \n       start =0, end = 0, s=0; \n  \n    for (int i=0; i< size; i++ ) \n    { \n        max_ending_here += a[i]; \n  \n        if (max_so_far < max_ending_here) \n        { \n            max_so_far = max_ending_here; \n            start = s; \n            end = i; \n        } \n  \n        if (max_ending_here < 0) \n        { \n            max_ending_here = 0; \n            s = i + 1; \n        } \n    } \n    cout << \"Maximum contiguous sum is \"\n        << max_so_far << endl; \n    cout << \"Starting index \"<< start \n        << endl << \"Ending index \"<< end << endl; \n} \n"
  },
  {
    "path": "Algorithms/DP/LSCS/lscs.go",
    "content": "package main\n\nimport \"fmt\"\n\nfunc max(x, y int) int {\n\tif x < y {\n\t\treturn y\n\t}\n\treturn x\n}\n\nfunc sol(s1 string, s2 string, n int, m int) int {\n\tdp := make([][]int, n+1)\n\tfor i := 0; i <= n+1; i++ {\n\t\tdp[i] = make([]int, m+1)\n\t}\n\tfor i := 1; i <= n; i++ {\n\t\tfor j := 1; j <= m; j++ {\n\t\t\tif s1[i-1] == s2[j-1] {\n\t\t\t\tdp[i][j] = 1 + dp[i-1][j-1]\n\t\t\t} else {\n\t\t\t\tdp[i][j] = max(dp[i-1][j], dp[i][j-1])\n\t\t\t}\n\t\t}\n\t}\n\treturn dp[n][m]\n}\n\nfunc main() {\n\tvar t int\n\tfmt.Scanf(\"%d\", t)\n\tfor _ = 0; t >= 0; t-- {\n\t\tvar s1, s2 string\n\t\tfmt.Scanf(\"%s\", s1)\n\t\tfmt.Scanf(\"%s\", s2)\n\n\t\tn, m := len(s1), len(s2)\n\t\traw_res := sol(s1, s2, n, n)\n\t\tres := n + m - raw_res\n\t\tfmt.Printf(\"%d\\n\", res)\n\t}\n}\n"
  },
  {
    "path": "Algorithms/DP/LSCS/lscs.py",
    "content": "def find_max_subarray(alist, start, end):\n    max_ending_at_i = max_seen_so_far = alist[start]\n    max_left_at_i = max_left_so_far = start\n    max_right_so_far = start + 1\n    for i in range(start + 1, end):\n        if max_ending_at_i > 0:\n            max_ending_at_i += alist[i]\n        else:\n            max_ending_at_i = alist[i]\n            max_left_at_i = i\n        if max_ending_at_i > max_seen_so_far:\n            max_seen_so_far = max_ending_at_i\n            max_left_so_far = max_left_at_i\n            max_right_so_far = i + 1\n    return max_left_so_far, max_right_so_far, max_seen_so_far\n \n \n\nalist = [-13, -3, -25, -20, -3, -16, -23, -12, -5, -22, -15, -4, -7] \nstart, end, maximum = find_max_subarray(alist, 0, len(alist))\nprint('The maximum subarray starts at index {}, ends at index {}'\n      ' and has sum {}.'.format(start, end - 1, maximum))\n"
  },
  {
    "path": "Algorithms/DP/LSCS/shortest_common_supersequence.c",
    "content": "#include<stdio.h>\nint max(int a,int b)\n{\n    return a>b?a:b;\n}\nint sol(char* s1,char* s2,int n,int m)\n{\n    int dp[n+1][m+1];\n    for(int i=0;i<=n;i++)\n    {\n        for(int j=0;j<=m;j++)\n        dp[i][j]=0;\n    }\n    for(int i=1;i<=n;i++)\n    {\n        for(int j=1;j<=m;j++)\n        {\n            if(s1[i-1]==s2[j-1])\n            dp[i][j]=1+dp[i-1][j-1];\n            else\n            dp[i][j]=max(dp[i-1][j],dp[i][j-1]);\n        }\n    }\n    return dp[n][m];\n}\n\nint main() {\n    int t;\n    scanf(\"%d\",&t);\n    while(t--){\n\tchar s1[101],s2[101];\n\tscanf(\"%s\",&s1);\n\tscanf(\"%s\",&s2);\n\t\n//\tprintf(\"%s %s\\n\",s1,s2);\n\tint n=strlen(s1),m=strlen(s2);\n\tint ans=sol(s1,s2,n,m);\n\tprintf(\"%d\\n\",n+m-ans);\n    }\n\treturn 0;\n}\n"
  },
  {
    "path": "Algorithms/DP/Largest Divisible Subset.cpp",
    "content": "#include <bits/stdc++.h>\n\nusing namespace std;\n\n/* \nGiven an array of distinct posotive integers,find the largest subset such that every pair(a1,a2)\nof elements in this subset satisfies\na1 % a2 = 0 or a2 % a1 = 0\n\nNote - In case of multiple sych solutions return any subset.\n\nExample 1: \nInput : [1 , 2 , 3]\nOutput : [1 , 2] or [1 , 3]\n\nExample 2:\nInput : [1 , 2 , 4 , 8]\nOutput : [1 , 2 , 4 , 8]\n*/\n\nvector<int> largestDivisibleSubset(vector<int>& nums) \n{\n    int n = nums.size();\n    vector<int>ans;\n    int max = 1;\n    sort(nums.begin(),nums.end());\n    vector<int>dp(n+1,1);\n    for(int i=1;i<n;i++)\n    {\n        for(int j=0;j<i;j++)\n        {\n            if(nums[i]%nums[j]==0&&1+dp[j]>dp[i])\n            {\n                dp[i]=1+dp[j];\n                if(max<dp[i])\n                {\n                    max=dp[i];\n                }\n            }\n        }\n        int prev=-1;\n        for(int i=n-1;i>=0;i--)\n        {\n            if(dp[i]==max&&(prev%nums[i]==0||prev==-1)){\n                ans.push_back(nums[i]);\n                max-=1;\n                prev=nums[i];\n            }\n        }\n        return ans;\n    }\n}\n\nint main()\n{\n    int n;\n\tcout << \"array size : \";\n\tcin >> n;\n\tvector<int> arr(n);\n\tcout << \"array element :\\n\";\n    for(int i=0;i<n;i++)\n    {\n\t    cin>>arr[i];\n    }\n    cout << largestDivisibleSubset(arr) << endl;\n    return 0;\n}\n"
  },
  {
    "path": "Algorithms/DP/Largest divisible subset in array/file.py",
    "content": "# Python 3 program to find largest divisible subset in a given array \n  \n# Prints largest divisible subset \ndef findLargest(arr, n): \n      \n    # We first sort the array so that all divisors of a number are before it. \n    arr.sort(reverse = False) \n  \n    # To store count of divisors of all elements \n    divCount = [1 for i in range(n)] \n  \n    # To store previous divisor in result \n    prev = [-1 for i in range(n)] \n  \n    # To store index of largest element in maximum size subset \n    max_ind = 0\n  \n    # In i'th iteration, we find length of chain ending with arr[i] \n    for i in range(1,n): \n        # Consider every smaller element as previous element. \n        for j in range(i): \n            if (arr[i] % arr[j] == 0): \n                if (divCount[i] < divCount[j] + 1): \n                    divCount[i] = divCount[j]+1\n                    prev[i] = j \n  \n        # Update last index of largest subset if size of current subset is more. \n        if (divCount[max_ind] < divCount[i]): \n            max_ind = i \n  \n    # Print result \n    k = max_ind \n    while (k >= 0): \n        print(arr[k],end = \" \") \n        k = prev[k] \n  \n# Driven code \nif __name__ == '__main__': \n    arr = [1, 2, 17, 4] \n    n = len(arr) \n    findLargest(arr, n) \n"
  },
  {
    "path": "Algorithms/DP/Largest_Divisible_Subset.js",
    "content": "var largestDivisibleSubset = function(nums) {\n  if(nums.length < 2) return nums;\n  let n = nums.length;\n  nums.sort((a,b) => a - b)\n  let dp = Array(n).fill(1);\n  let parent = Array(n);\n\n  for(let i = 0; i < n; i++) parent[i] = i;\n\n  for(let i = 0; i < n; i++) {\n    for(let j = 0; j < i; j++) {\n      if(nums[i] % nums[j] === 0) {\n        if(dp[j] + 1 > dp[i]) {\n          dp[i] = dp[j] + 1;\n          parent[i] = j;\n        }\n      }\n    }\n  }\n\n  let max = Math.max(...dp)\n  let maxIndex = -1;\n\n  for(let i = 0; i < n; i++ ) {\n    if(dp[i] == max) {\n      maxIndex = i;\n      break;\n    }\n  }\n\n\n  let ans = [];\n  let member = maxIndex;\n  while(true) {\n    ans.push(member)\n\n    if(parent[member] == member) {\n      break;\n    }\n    member = parent[member];\n  }\n  return ans.reverse().map(i => nums[i])\n};\n"
  },
  {
    "path": "Algorithms/DP/Largest_Divisible_Subsets.java",
    "content": "import java.util.*; \n  \npublic class DivSubset { \n  \n    public static int[][] dp; \n  \n    static void findLargest(int[] arr) { \n  \n        int divCount[] = new int[arr.length]; \n        Arrays.fill(divCount, 1); \n        \n        int prev[] = new int[arr.length]; \n        Arrays.fill(prev, -1); \n        int max_ind = 0; \n  \n        for (int i = 1; i < arr.length; i++) { \n            for (int j = 0; j < i; j++) { \n\n                if (arr[i] % arr[j] == 0 &&  \n                    divCount[i] < divCount[j] + 1) { \n                    prev[i] = j; \n                    divCount[i] = divCount[j] + 1; \n                } \n            } \n\n            if (divCount[i] > divCount[max_ind]) \n                max_ind = i; \n        } \n  \n        int k = max_ind; \n        while (k >= 0) { \n            System.out.print(arr[k] + \" \"); \n            k = prev[k]; \n        } \n    } \n  \n    public static void main(String[] args) { \n  \n        int[] x = { 1, 2, 17, 4}; \n  \n        Scanner s = new Scanner(System.in);\n\n        System.out.println(\"Enter number of elements\");\n        int n = s.nextInt();\n\n        int arr[]=new int[n];\n\n        System.out.println(\"Enter elements\");\n        for(int i=0;i<n;i++){\n            arr[i]=s.nextInt();\n        }\n        \n        Arrays.sort(arr); \n  \n        findLargest(arr); \n      \n    } \n}\n"
  },
  {
    "path": "Algorithms/DP/Largest_Divisible_Subsets.py",
    "content": "def largestDivisibleSubset(nums):\n    S = {-1: set()}\n    for x in sorted(nums):\n        S[x] = max((S[d] for d in S if x % d == 0), key=len) | {x}\n    return list(max(S.values(), key=len))\n\nif __name__ == '__main__': \n\n    lst = [] \n    n = int(input(\"Enter number of elements : \")) \n    for i in range (n):\n        x=int(input(\"enter no. \\n\")) \n        lst.insert(i,x)\n        i+=1\n\n    print(largestDivisibleSubset(lst))\n"
  },
  {
    "path": "Algorithms/DP/Largest_Sum_Contiguous_Subarray/.vscode/c_cpp_properties.json",
    "content": "{\n    \"configurations\": [\n        {\n            \"name\": \"Win32\",\n            \"includePath\": [\n                \"${workspaceFolder}/**\"\n            ],\n            \"defines\": [\n                \"_DEBUG\",\n                \"UNICODE\",\n                \"_UNICODE\"\n            ],\n            \"intelliSenseMode\": \"msvc-x64\"\n        }\n    ],\n    \"version\": 4\n}"
  },
  {
    "path": "Algorithms/DP/Largest_Sum_Contiguous_Subarray/.vscode/launch.json",
    "content": "{\n    // Use IntelliSense to learn about possible attributes.\n    // Hover to view descriptions of existing attributes.\n    // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387\n    \"version\": \"0.2.0\",\n    \"configurations\": [\n        {\n            \"name\": \"Launch Chrome\",\n            \"request\": \"launch\",\n            \"type\": \"pwa-chrome\",\n            \"url\": \"http://localhost:8080\",\n            \"webRoot\": \"${workspaceFolder}\"\n        },\n        {\n            \"name\": \"(gdb) Bash on Windows Attach\",\n            \"type\": \"cppdbg\",\n            \"request\": \"attach\",\n            \"program\": \"enter program name, for example ${workspaceFolder}/a.exe\",\n            \"processId\": \"${command:pickRemoteProcess}\",\n            \"pipeTransport\": {\n                \"debuggerPath\": \"/usr/bin/gdb\",\n                \"pipeProgram\": \"${env:windir}\\\\system32\\\\bash.exe\",\n                \"pipeArgs\": [\"-c\"],\n                \"pipeCwd\": \"\"\n            },\n            \"setupCommands\": [\n                {\n                    \"description\": \"Enable pretty-printing for gdb\",\n                    \"text\": \"-enable-pretty-printing\",\n                    \"ignoreFailures\": true\n                }\n            ]\n        },\n\n\n        {\n            \"name\": \"(Windows) Launch\",\n            \"type\": \"cppvsdbg\",\n            \"request\": \"launch\",\n            \"program\": \"enter program name, for example ${workspaceFolder}/a.exe\",\n            \"args\": [],\n            \"stopAtEntry\": false,\n            \"cwd\": \"${workspaceFolder}\",\n            \"environment\": [],\n            \"externalConsole\": false\n        }\n    ]\n}"
  },
  {
    "path": "Algorithms/DP/Largest_Sum_Contiguous_Subarray/.vscode/tasks.json",
    "content": "{\n    // See https://go.microsoft.com/fwlink/?LinkId=733558\n    // for the documentation about the tasks.json format\n    \"version\": \"2.0.0\",\n    \"tasks\": [\n        {\n            \"label\": \"build\",\n            \"type\": \"shell\",\n            \"command\": \"msbuild\",\n            \"args\": [\n                \"/property:GenerateFullPaths=true\",\n                \"/t:build\",\n                \"/consoleloggerparameters:NoSummary\"\n            ],\n            \"group\": {\n                \"kind\": \"build\",\n                \"isDefault\": true\n            },\n            \"presentation\": {\n                \"reveal\": \"silent\"\n            },\n            \"problemMatcher\": \"$msCompile\"\n        }\n    ]\n}"
  },
  {
    "path": "Algorithms/DP/Largest_Sum_Contiguous_Subarray/C++_Implementation/makefile",
    "content": "all: Kadane.o\n\nKadane.o: obj/main.o obj/functions.o\n\tg++ obj/main.o obj/functions.o -o Kadane\n\nobj/main.o: src/main.cpp\n\tg++ -c src/main.cpp && mv main.o obj/main.o\n\nobj/functions.o: src/functions.cpp\n\tg++ -c src/functions.cpp && mv functions.o obj/functions.o\n"
  },
  {
    "path": "Algorithms/DP/Largest_Sum_Contiguous_Subarray/C++_Implementation/src/functions.cpp",
    "content": "#include<iostream>\n#include\"include/functions.h\"\n\nint Kadane(int arr[], int size)\n{\n  int max_so_far=0;\n  int max_ending_here=0;\n\n  for(int i=0; i<size; i++)\n  {\n    max_ending_here= max_ending_here + arr[i];\n    if(max_so_far<max_ending_here)\n      max_so_far= max_ending_here;\n    if(max_ending_here<0)\n      max_ending_here=0;\n  }\n\n  return max_so_far;\n}\n"
  },
  {
    "path": "Algorithms/DP/Largest_Sum_Contiguous_Subarray/C++_Implementation/src/include/functions.h",
    "content": "int Kadane(int arr[], int size); \n//return largest sum contigious array\n"
  },
  {
    "path": "Algorithms/DP/Largest_Sum_Contiguous_Subarray/C++_Implementation/src/main.cpp",
    "content": "#include<iostream>\n#include \"include/functions.h\"\nusing namespace std;\n\nint main()\n{\n  int size;\n  cout<<\"Enter the size of the array: \";\n  cin>>size;\n\n  int arr[size];\n\n  cout<<\"Enter array elements\"<<endl;\n  for(int i=0; i<size; i++)\n  {\n    cout<<\"enter \"<<i<<\"th element: \";\n    cin>>arr[i];\n  }\n\n  cout<<\"The largest contiguous subsequence sum for the given array is:\"<<Kadane(arr,size)<<endl;\n}\n\n"
  },
  {
    "path": "Algorithms/DP/Largest_Sum_Contiguous_Subarray/Kadane's Algorithm.cpp",
    "content": "#include<iostream>\n#include<vector>\n#include<bits/stdc++.h>\nusing namespace std;\n\nint main() {\n\t//code\n\tint T;\n\tcin>>T;\n\twhile(T--)\n\t{\n\t    int n;\n\t    cin>>n;\n\t    vector<int> v(n,0);\n\t    for(int i=0;i<n;i++)\n\t    {\n\t        cin>>v[i];\n\t    }\n\t    int sum=INT_MIN;\n\t    int maxSum=INT_MIN;\n\t    \n\t    for(int i=0;i<n;i++)\n\t    {\n\t        if(sum>0)\n\t        {\n\t            sum+=v[i];\n\t        }\n\t        else\n\t        {\n\t            sum=v[i];\n\t        }\n\t        maxSum=max(sum,maxSum);\n\t    }\n\t    cout<<maxSum<<endl;\n\t}\n\treturn 0;\n}"
  },
  {
    "path": "Algorithms/DP/Largest_Sum_Contiguous_Subarray/LSCS.cpp",
    "content": "#include<iostream>\n\nint Kadane(int arr[], int size)\n{\n  int max_so_far=0;\n  int max_ending_here=0;\n\n  for(int i=0; i<size; i++)\n  {\n    max_ending_here= max_ending_here + arr[i];\n    if(max_so_far<max_ending_here)\n      max_so_far= max_ending_here;\n    if(max_ending_here<0)\n      max_ending_here=0;\n  }\n\n  return max_so_far;\n}\n"
  },
  {
    "path": "Algorithms/DP/Largest_Sum_Contiguous_Subarray/LSCS.js",
    "content": "  let allPositives = arr => arr.every(n => n > 0)\n  let allNegatives = arr => arr.every(n => n < 0)\n  let sum = arr => arr.reduce((curr_max, max_so_far) => curr_max + max_so_far, 0)\n  \n  var maxSequence = function(arr){\n    if(arr.length === 0 || allNegatives(arr)) return 0;\n    if(allPositives(arr)) return sum(arr);\n  \n    var curr_max = 0, max_so_far = 0;\n  \n    for(var i = 0; i < arr.length; i++){  \n      curr_max = Math.max(0, curr_max + arr[i]);\n      max_so_far = Math.max(curr_max, max_so_far);\n    }\n    return max_so_far;\n  }"
  },
  {
    "path": "Algorithms/DP/Largest_Sum_Contiguous_Subarray/LSCS.swift",
    "content": "func maxSubArray(_ array: [Int]) -> Int {\n    var currentSum = 0\n    var result = Int.min\n    for i in 0 ..< array.count {\n        currentSum = max(array[i], array[i] + currentSum)\n        result = max(result, currentSum)\n    }\n    return result\n}\n\nvar array:[Int] = [-2, -3, 4, -1, -2, 1, 5, -3]\nlet max_sum = maxSubArray(array)\nprint(\"Maximum continous sum is \\(max_sum)\")\n"
  },
  {
    "path": "Algorithms/DP/Largest_Sum_Contiguous_Subarray/lscs.c",
    "content": "#include <stdio.h>\n\nint max(int a,int b)\n{\n    if(a>b)\n    {\n        return a;\n    }\n    return b;\n}\n\nint maxSubArray(int* nums, int numsSize){\n    int i,ans;\n    int maxSum[numsSize+1];\n    \n    for(i=0;i<numsSize;i++)\n    {\n        if(i==0)\n        {\n            maxSum[i]=nums[0];\n        }\n        else\n        {\n        maxSum[i] = max( nums[i], nums[i] + maxSum[i - 1] );\n        }\n    }\n    ans = maxSum[0];\n    for(i=0;i<numsSize;i++)\n    {\n        if(ans<maxSum[i])\n        {\n            ans = maxSum[i];\n        }\n    }\n    return ans;\n\n}\n\nint main() {\n    int numsSize,i;\n    scanf(\"%d\",&numsSize);\n    int nums[numsSize];\n    for(i=0;i<numsSize;i++)\n    {\n        scanf(\"%d\",&nums[i]);\n    }\n    printf(\"%d\",maxSubArray(nums,numsSize));\n    return 0;\n}\n"
  },
  {
    "path": "Algorithms/DP/MOS_Algorithm.cpp",
    "content": "#include <bits/stdc++.h>\nusing std::vector;\nusing std::tuple;\n\n/*\n * Take out adding\\removing logic into separate class.\n * It provides functions to add and remove numbers from\n * our structure, while maintaining cnt[] and current_answer.\n * \n */\nstruct Mo\n{\n    static constexpr int MAX_VALUE = 1005000;\n    vector<long long> cnt;\n    long long current_answer;\n\n    void process(int number, int delta)\n    {\n        current_answer -= cnt[number] * cnt[number] * number;\n        cnt[number] += delta;\n        current_answer += cnt[number] * cnt[number] * number;\n    }\npublic:\n    Mo()\n    {\n        cnt = vector<long long>(MAX_VALUE, 0);\n        current_answer = 0;\n    }\n\n    long long get_answer() const\n    {\n        return current_answer;\n    }\n\n    void add(int number)\n    {\n        process(number, 1);\n    }\n\n    void remove(int number)\n    {\n        process(number, -1);\n    }\n};\n\nint main()\n{\n    int N, Q, BLOCK_SIZE;\n    std::cin.sync_with_stdio(false);\n    std::cin >> N >> Q;\n    BLOCK_SIZE = static_cast<int>(sqrt(N));\n\n    // No global variables, everything inside.\n    vector<int> arr(N);\n    vector<long long> answers(Q);\n    vector< tuple<int, int, int> > queries;\n    queries.reserve(Q);\n\n    for(int i = 0; i < N; i++)\n        std::cin >> arr[i];\n\n    for(int i = 0; i < Q; i++) {\n        int le, rg;\n        std::cin >> le >> rg;\n        queries.emplace_back(le, rg, i);\n    }\n\n    // Comparator as a lambda-function, which catches BLOCK_SIZE\n    // from the above definition.\n    auto mo_cmp = [BLOCK_SIZE](const tuple<int, int, int> &x,\n            const tuple<int, int, int> &y) -> bool {\n        int block_x = std::get<0>(x) / BLOCK_SIZE;\n        int block_y = std::get<0>(y) / BLOCK_SIZE;\n        if(block_x != block_y)\n            return block_x < block_y;\n        return std::get<1>(x) < std::get<1>(y);\n    };\n\n    std::sort(queries.begin(), queries.end(), mo_cmp);\n\n    Mo solver;\n    int mo_left = 0, mo_right = -1;\n\n    // Usual Mo's algorithm stuff.\n    for(const auto &q: queries) {\n        int left, right, answer_idx;\n        std::tie(left, right, answer_idx) = q;\n\n        while(mo_right < right) {\n            mo_right++;\n            solver.add(arr[mo_right]);\n        }\n        while(mo_right > right) {\n            solver.remove(arr[mo_right]);\n            mo_right--;\n        }\n\n        while(mo_left < left) {\n            solver.remove(arr[mo_left]);\n            mo_left++;\n        }\n        while(mo_left > left) {\n            mo_left--;\n            solver.add(arr[mo_left]);\n        }\n\n        answers[answer_idx] = solver.get_answer();\n    }\n\n    for(int i = 0; i < Q; i++)\n        std::cout << answers[i] << \"\\n\";\n    return 0;\n}\n"
  },
  {
    "path": "Algorithms/DP/Max_Product_Subarray/max_product_subarray.py",
    "content": "def max_product(nums):\n    n = len(nums)\n\n    ans = nums[0]\n    maxy = mini = ans\n    for i in range(1, n):\n\n        if nums[i] < 0:\n            maxy, mini = mini, maxy\n\n        maxy = max(nums[i], maxy * nums[i])\n        mini = min(nums[i], mini * nums[i])\n\n        ans = max(ans, maxy)\n\n    return ans\n\nif __name__ == '__main__':\n    ans = max_product([2, 3, -2, 4])\n    assert ans == 6, \"Wrong answer\"\n    print(ans)\n\n"
  },
  {
    "path": "Algorithms/DP/Maximum_Achievable_Coins/Maximum_Achievable_Coins.php",
    "content": "<?php\nfunction maxAchieveable($num)\n{\n    $row = range(1, $num);\n    shuffle($row);\n    define(\"ROW\", $row);\n\n    $matrix = array_map(function() use($num){\n        return array_pad(array(), $num, 0);\n    }, range(1, $num));\n\n    foreach(range(0, $num-1) as $d)\n    {\n        foreach(range($d, $num) as $j)\n        {\n            $i = $j - $d;\n            list($a, $b, $c) = [0, 0, 0];\n\n            if(($i+2) <= $j) $a = $matrix[$i+2][$j];\n            if(($i+1) <= $j) $b = $matrix[$i+1][$j-1];\n            if($i <= $j) $c = $matrix[$i][$j-2];\n\n            $matrix[$i][$j] = max(ROW[$i] + min($a, $b) , ROW[$j] + min($b, $c));\n        }\n    }\n\n    return \"Row: \".json_encode(ROW).\" , Max Achieveable: \".$matrix[0][$num-1];\n}\n?>\n"
  },
  {
    "path": "Algorithms/DP/Maximum_Achievable_Coins/Maximum_Achievable_coins.c",
    "content": "#include <stdio.h>\n\nvoid swap(int *xp, int *yp) \n{ \n    int temp = *xp; \n    *xp = *yp; \n    *yp = temp; \n} \n  \n// A function to implement bubble sort \nvoid bubbleSort(int arr[], int n) \n{ \n   int i, j; \n   for (i = 0; i < n-1; i++)       \n  \n       // Last i elements are already in place    \n       for (j = 0; j < n-i-1; j++)  \n           if (arr[j] > arr[j+1]) \n              swap(&arr[j], &arr[j+1]); \n}\n\nint main(void) {\n\tint numb;\n\t//I am assuming even input for numb \n\tscanf(\"%d\",&numb);\n\tint coins[numb];\n\tfor(int i=0;i<numb;i++)\n\t    scanf(\"%d\",&coins[i]);\n\tbubbleSort(coins,numb);//function call above lol\n\tint sum=0;\n\tfor(int i=numb-1;i>(numb/2)-1;i--)//looks complicated but i dont wanna use many variable to depict all the calculation\n\t    sum += coins[i];\n\t\n\tprintf(\"%d\",sum);\n\treturn 0;\n}\n\n"
  },
  {
    "path": "Algorithms/DP/Maximum_Achievable_Coins/Maximum_Achievable_coins.java",
    "content": "\r\nclass MaximumAchievablecoins { \r\n\r\nstatic int Maximum_Achievable_coins( \r\n        int arr[], int n) \r\n    { \r\n      \r\n        int table[][] = new int[n][n]; \r\n        int gap, i, j, x, y, z; \r\n  \r\n        \r\n        for (gap = 0; gap < n; ++gap) { \r\n            for (i = 0, j = gap; j < n; ++i, ++j) { \r\n  \r\n                \r\n                x = ((i + 2) <= j) \r\n                        ? table[i + 2][j] \r\n                        : 0; \r\n                y = ((i + 1) <= (j - 1)) \r\n                        ? table[i + 1][j - 1] \r\n                        : 0; \r\n                z = (i <= (j - 2)) \r\n                        ? table[i][j - 2] \r\n                        : 0; \r\n  \r\n                table[i][j] = Math.max( \r\n                    arr[i] + Math.min(x, y), \r\n                    arr[j] + Math.min(y, z)); \r\n            } \r\n        } \r\n  \r\n        return table[0][n - 1]; \r\n    } \r\n  \r\n    \r\n    public static void main(String[] args) \r\n    { \r\n        int arr1[] = { 8, 15, 3, 7 }; \r\n        int n = arr1.length; \r\n        System.out.println( \r\n            \"\"\r\n            + Maximum_Achievable_coins(arr1, n)); \r\n  \r\n        int arr2[] = { 2, 2, 2, 2 }; \r\n        n = arr2.length; \r\n        System.out.println( \r\n            \"\"\r\n            + Maximum_Achievable_coins(arr2, n)); \r\n  \r\n        int arr3[] = { 20, 30, 2, 2, 2, 10 }; \r\n        n = arr3.length; \r\n        System.out.println( \r\n            \"\"\r\n            + Maximum_Achievable_coins(arr3, n)); \r\n    } \r\n}"
  },
  {
    "path": "Algorithms/DP/Maximum_Achievable_Coins/Maximum_Achievable_coins.py",
    "content": "def Maximum_Achievable_coins(arr, n):\n    matrix = [[0 for x in range(n)] for y in range(n)]\n\n    for diagonal in range(n):\n        for j in range(diagonal,n):\n            i = j - diagonal\n\n            x = 0\n            if( (i+2) <= j):\n                x =  matrix[i+2][j]\n            y = 0\n            if( (i+1) <= (j-1)):\n                y =  matrix[i+1][j-1]\n            z = 0\n            if( i <= (j-2)):\n                z =  matrix[i][j-2]\n\n            matrix[i][j] = max(arr[i]+min(x,y), arr[j]+min(y,z))\n    return print(\"The maximum possible amount of money that we can definitely win if we move first is: \"+str(matrix[0][n-1]))\n\nif __name__ == '__main__':\n    n = int(input('Coin numbers: '))\n    arr = []\n    [arr.append(int(input('Coin number '+str(x+1)+' : '))) for x in range(n)]\n    Maximum_Achievable_coins(arr, n)\n"
  },
  {
    "path": "Algorithms/DP/Maximum_Achievable_Coins/maximum_achievable_coins.cpp",
    "content": "\n#include <bits/stdc++.h> \nusing namespace std; \n\n\nint optimalStrategyOfGame( \n\tint* arr, int n) \n{ \n\t\n\tint table[n][n]; \n\n\t\n\tfor (int gap = 0; gap < n; ++gap) { \n\t\tfor (int i = 0, j = gap; j < n; ++i, ++j) { \n\t\t\t\n\t\t\tint x = ((i + 2) <= j) \n\t\t\t\t\t\t? table[i + 2][j] \n\t\t\t\t\t\t: 0; \n\t\t\tint y = ((i + 1) <= (j - 1)) \n\t\t\t\t\t\t? table[i + 1][j - 1] \n\t\t\t\t\t\t: 0; \n\t\t\tint z = (i <= (j - 2)) \n\t\t\t\t\t\t? table[i][j - 2] \n\t\t\t\t\t\t: 0; \n\n\t\t\ttable[i][j] = max( \n\t\t\t\tarr[i] + min(x, y), \n\t\t\t\tarr[j] + min(y, z)); \n\t\t} \n\t} \n\n\treturn table[0][n - 1]; \n} \n\n\nint main() \n{ \n\tint *arr; \n\tint n;\n    cin>>n;\n    arr = new int[n];\n    for(int i = 0; i < n; ++i) cin>>arr[i];\n\tprintf(\"%d\\n\", \n\t\toptimalStrategyOfGame(arr, n)); \n\n\treturn 0; \n} \n"
  },
  {
    "path": "Algorithms/DP/Minimum_Sum_Descent/min-sum.c",
    "content": "/*\n* Contributor: Jean Choi\n* Minimum-Sum Descent\n*\n* Some positive integers are arranged in an equilateral triangle\n* with n numbers in its base like the one shown in the figure below\n* for n = 4.\n*\n* This program finds the  the smallest sum in a descent \n* from the triangle apex to its base through a sequence \n* of adjacent numbers (shown in the figure by dashes).\n*\n*           -2-\n*       -5-      4\n*    -1-     4       7\n* 8     -6-      9      6\n*\n*/\n\n#include <stdlib.h>\n#include <stdio.h>\n\n/*\n* Finds the minimum between two integers\n*/\nint minimum(int a, int b){\n  return (a < b) ? a : b;\n}\n\n/*\n* Tabular Solution for created pyramid\n*/\nint tabular(int ** arr,  int n){\n  for(int r = n; r >= 0; r--){\n    for(int c = 0; c <= r; c++){\n      if(r == n)\n        arr[r][c] = arr[r][c];\n      else\n        arr[r][c] = arr[r][c] + minimum(arr[r+1][c], arr[r+1][c+1]);\n    }\n  }\n  return arr[0][0];\n}\n\nint main(){\n  //get number of levels in pyramid\n  int levels;\n  printf(\"Enter number of levels: \");\n  scanf(\"%d\", &levels);\n\n  //allocate pyramid[][]\n  int **pyramid;\n  pyramid = malloc(levels * sizeof *pyramid);\n  for (int i=0; i < levels; i++) {\n    pyramid[i] = malloc(levels * sizeof *pyramid[i]);\n  }\n\n  //get values for pyramid[][]\n  printf(\"Please only enter positive integers\\n\");\n  for(int r = 0; r <= levels-1; r++) {\n    printf(\"Enter %d items for level %d: \", r+1, r);\n    for(int c = 0; c <= r; c++) {\n      scanf(\"%d\", &pyramid[r][c]);\n    }\n  }\n\n  //print pyramid[][]\n  printf(\"Here's the pyramid: \\n\");\n  for (int r = 0; r < levels; r++){\n    for (int c = 0; c <= r; c++){\n      printf(\"%d \", pyramid[r][c]);\n    }\n    printf(\"\\n\");\n  }\n  printf(\"Minimum-Sum Descent for created pyramid (Tabular): %d\\n\", tabular(pyramid, levels-1));\n\n\n  // deallocate the array\n  for (int i=0; i<levels; i++) {\n    free(pyramid[i]);\n  }\n  free(pyramid);\n  return 0;\n}\n"
  },
  {
    "path": "Algorithms/DP/Minimum_Sum_Descent/minsum.cs",
    "content": "using System;\nusing System.Collections.Generic;\n\n// C# program of min sum path in a triangle\nnamespace Minimum_sum_descent_in_C\n{\n  class Program\n  {\n    static void Main(string[] args)\n    {\n      List<List<int>> A = new List<List<int>>();\n      A.Add(new List<int> { 2 });\n      A.Add(new List<int> { 3, 9 });\n      A.Add(new List<int> { 1, 6, 7 });\n      Console.WriteLine(Triangle.minSumPath(ref A));\n    }\n  }\n\n  class Triangle\n  {\n    // Function to find minimum sum for a path\n    public static int minSumPath(ref List<List<int>> A)\n    {\n      // Storing the result in a array and simultaneously updating the result\n      int[] memo = new int[A.Count];\n      int n = A.Count - 1;\n\n      // For the bottom row\n      for (int i = 0; i < A[n].Count; i++)\n        memo[i] = A[n][i];\n\n      // Calculation of the remaining rows\n      for (int i = A.Count - 2; i >= 0; i--)\n        for (int j = 0; j < A[i + 1].Count - 1; j++)\n          memo[j] = A[i][j] +\n                    (int)Math.Min(memo[j],\n                             memo[j + 1]);\n\n      // Return the top element\n      return memo[0];\n    }\n  }\n}\n"
  },
  {
    "path": "Algorithms/DP/Minimum_Sum_Descent/minsum.go",
    "content": "package main\n\nimport (\n\t\"fmt\"\n)\n\nfunc main() {\n\t//get number of levels in pyramid\n\tvar levels int\n\tfmt.Println(\"Enter number of levels: \")\n\tfmt.Scan(&levels)\n\n\t//allocate pyramid[][]\n\tpyramid := make([][]int, levels)\n\tfor i := range pyramid {\n\t\tpyramid[i] = make([]int, levels)\n\t}\n\n\t//get values for pyramid[][]\n\tfmt.Println(\"Please only enter positive integers\")\n\tfor r := 0; r <= levels-1; r++ {\n\t\tfmt.Printf(\"Enter %d items for level %d: \", r+1, r)\n\t\tfor c := 0; c <= r; c++ {\n\t\t\tfmt.Scan(&pyramid[r][c])\n\t\t}\n\t}\n\n\t//print pyramid[][]\n\tfmt.Println(\"Here's the pyramid: \")\n\tfor r := 0; r < levels; r++ {\n\t\tfor c := 0; c <= r; c++ {\n\t\t\tfmt.Printf(\"%d \", pyramid[r][c])\n\t\t}\n\t\tfmt.Println(\"\")\n\t}\n\n\tfmt.Printf(\"Minimum-Sum Descent for created pyramid (Tabular): %d\", tabular(pyramid, levels-1))\n\tfmt.Println(\"\")\n}\n\n/*\n* Finds the minimum between two integers\n */\nfunc minimum(a, b int) int {\n\tif a < b {\n\t\treturn a\n\t}\n\treturn b\n}\n\n/*\n* Tabular Solution for created pyramid\n */\nfunc tabular(arr [][]int, n int) int {\n\tfor r := n; r >= 0; r-- {\n\t\tfor c := 0; c <= r; c++ {\n\t\t\tif r != n {\n\t\t\t\tarr[r][c] = arr[r][c] + minimum(arr[r+1][c], arr[r+1][c+1])\n\t\t\t}\n\t\t}\n\t}\n\treturn arr[0][0]\n}\n"
  },
  {
    "path": "Algorithms/DP/Minimum_Sum_Descent/minsum.ts",
    "content": "/* Implementation of Dynamic programming\nof Minimum sum descent in TypeScript\n*/\n\nconst minSum = (triangle: number[][]) => {\n  let memo: number[] = [];\n  let n = triangle.length - 1;\n\n  // memo for bottom row\n  for (let i = 0; i < triangle[n].length; i++) {\n    memo[i] = triangle[n][i];\n  }\n\n  // Calculating the remaining rows in bottom-up manner\n  for (let i = triangle.length - 2; i >= 0; i--) {\n    for (let j = 0; j < triangle[i].length; j++) {\n      memo[j] = triangle[i][j] + Math.min(memo[j], memo[j + 1]);\n    }\n  }\n\n  return memo[0];\n};\n\nconst triangle = [[2], [3, 9], [1, 6, 7]];\nconsole.log(minSum(triangle));\n"
  },
  {
    "path": "Algorithms/DP/Partition_Sum/DP_PartitionSum.java",
    "content": "//Code contributed by Aditya Prakash(@PrakashAditya17)\nimport java.io.*;\nimport java.util.*;\npublic class DP_PartitionSum\n{\n    public static boolean checking(int arr[],int SUM)\n    {\n        int len=arr.length;\n        //arr2[i][j] ->true , when there's subset of arr[0..j-1] having sum=i.\n        boolean arr2[][]=new boolean[SUM+1][len+1];\n        \n        //Here sum->0, then its set true.\n        for(int i=0;i<=len;i++)\n            arr2[0][i]=true;\n        \n        //The 0th column is false because sum not equals 0(Except arr[0][0])\n        for (int i = 1; i<=SUM;i++) \n            arr2[i][0]=false;\n        \n        //Rest of the 2d matrix DP is filled up in bottom up manner    \n        for (int i=1;i<= SUM;i++) \n        { \n            for (int j=1;j<=len;j++) \n            { \n                arr2[i][j]=arr2[i][j-1]; \n                if (i>=arr[j - 1]) \n                    arr2[i][j]=arr2[i][j] || arr2[i-arr[j-1]][j-1]; \n            } \n        } \n        //The corner most element is where the answer is stored.\n        return(arr2[SUM][len]);\n        \n    }\n\tpublic static void main(String[] args) \n\t{\n\t    Scanner sc=new Scanner(System.in);\n\t    int n;\n\t\tSystem.out.println(\"Enter array size and the array\");\n\t\tn=sc.nextInt();\n\t\tint sum=0;\n\t    int a[]=new int[n];\n\t    for(int i=0;i<n;i++)\n\t    {\n\t        a[i]=sc.nextInt();   \n\t        sum+=a[i];\n\t    }\n\t    if(sum%2==1)                   // sum is odd so it can't be divided into 2 subsets.\n\t        System.out.println(\"FALSE : NOT POSSIBLE\");\n\t    else   // We check if the even sum can be divided into two subsets or not, using DP                        \n\t    {\n\t        System.out.println(checking(a,sum/2));\n\t    }\n\t}\n}\n"
  },
  {
    "path": "Algorithms/DP/Partition_Sum/partition_sum.c",
    "content": "// A Dynamic Programming based C program to partition problem \n#include <stdio.h> \n\n// Returns true if arr[] can be partitioned in two subsets of equal sum, otherwise false \nint findPartiion (int arr[], int n) \n{ \n\tint sum = 0; \n\tint i, j; \n\t\n\t// Calculate sum of all elements \n\tfor (i = 0; i < n; i++) \n\tsum += arr[i]; \n\t\n\tif (sum%2 != 0) \n\t\treturn 0; \n\t\n\tint part[sum/2+1][n+1]; \n\t\n\t// initialize top row as true \n\tfor (i = 0; i <= n; i++) \n\t\tpart[0][i] = 1; \n\t\t\n\t// initialize leftmost column, except part[0][0], as 0 \n\tfor (i = 1; i <= sum/2; i++) \n\t\tpart[i][0] = 0;\t \n\t\n\t// Fill the partition table in bottom up manner \n\tfor (i = 1; i <= sum/2; i++) \n\t{ \n\t\tfor (j = 1; j <= n; j++) \n\t\t{ \n\t\t\tpart[i][j] = part[i][j-1]; \n\t\t\tif (i >= arr[j-1]) \n\t\t\t\tpart[i][j] = part[i][j] || part[i - arr[j-1]][j-1]; \n\t\t}\t\t \n\t}\t \n\t\n\treturn part[sum/2][n]; \n}\t \n\n// Driver program to test above function \nint main() \n{ \n\tint n,i;\n\tint arr[10000];\n\tscanf(\"%d\", &n);\n\tfor(i=0;i<n;i++)\n\t\tscanf(\"%d\", &arr[i]); \n\tif (findPartiion(arr, n) == 1) \n\t\tprintf(\"Can be divided into two subsets of equal sum\"); \n\telse\n\t\tprintf(\"Can not be divided into two subsets of equal sum\"); \n\tgetchar(); \n\treturn 0; \n} \n"
  },
  {
    "path": "Algorithms/DP/Partition_Sum/partition_sum.cpp",
    "content": "// A Dynamic Programming based C++ program to partition problem \n#include <bits/stdc++.h> \nusing namespace std; \n\n// Returns true if arr[] can be partitioned in two subsets of equal sum, otherwise false \nbool findPartiion (int arr[], int n) \n{ \n\tint sum = 0; \n\tint i, j; \n\t\n\t// Calculate sum of all elements \n\tfor (i = 0; i < n; i++) \n\tsum += arr[i]; \n\t\n\tif (sum % 2 != 0) \n\t\treturn false; \n\t\n\tbool part[sum / 2 + 1][n + 1]; \n\t\n\t// initialize top row as true \n\tfor (i = 0; i <= n; i++) \n\t\tpart[0][i] = true; \n\t\t\n\t// initialize leftmost column, \n\t// except part[0][0], as 0 \n\tfor (i = 1; i <= sum / 2; i++) \n\t\tpart[i][0] = false; \n\t\n\t// Fill the partition table in bottom up manner \n\tfor (i = 1; i <= sum / 2; i++) \n\t{ \n\t\tfor (j = 1; j <= n; j++) \n\t\t{ \n\t\t\tpart[i][j] = part[i][j - 1]; \n\t\t\tif (i >= arr[j - 1]) \n\t\t\t\tpart[i][j] = part[i][j] || part[i - arr[j - 1]][j - 1]; \n\t\t}\t \n\t} \n\t\n\treturn part[sum / 2][n]; \n} \n\n// Driver Code \nint main() \n{ \n\tint n;\n\tcin>>n;\n\tint arr[n];\n\tfor(int i=0;i<n;i++)\n\t\tcin>>arr[i];\n\tif (findPartiion(arr, n) == true) \n\t\tcout << \"Can be divided into two subsets of equal sum\"; \n\telse\n\t\tcout << \"Can not be divided into\"\n\t\t\t<< \" two subsets of equal sum\"; \n\treturn 0; \n} \n"
  },
  {
    "path": "Algorithms/DP/Partition_Sum/partition_sum.cs",
    "content": "// A recursive C# solution for partition problem\nusing System;\n \nclass GFG {\n     \n    // A utility function that returns true if there is a\n    // subset of arr[] with sun equal to given sum\n    static bool isSubsetSum(int[] arr, int n, int sum)\n    {\n        // Base Cases\n        if (sum == 0)\n            return true;\n        if (n == 0 && sum != 0)\n            return false;\n \n        // If last element is greater than sum, then ignore\n        // it\n        if (arr[n - 1] > sum)\n            return isSubsetSum(arr, n - 1, sum);\n \n        /* else, check if sum can be obtained by any of\n        the following\n        (a) including the last element\n        (b) excluding the last element\n        */\n        return isSubsetSum(arr, n - 1, sum)\n            || isSubsetSum(arr, n - 1, sum - arr[n - 1]);\n    }\n \n    // Returns true if arr[] can be partitioned in two\n    // subsets of equal sum, otherwise false\n    static bool findPartition(int[] arr, int n)\n    {\n        // Calculate sum of the elements in array\n        int sum = 0;\n        for (int i = 0; i < n; i++)\n            sum += arr[i];\n \n        // If sum is odd, there cannot be two subsets\n        // with equal sum\n        if (sum % 2 != 0)\n            return false;\n \n        // Find if there is subset with sum equal to half\n        // of total sum\n        return isSubsetSum(arr, n, sum / 2);\n    }\n \n    // Driver code\n    public static void Main()\n    {\n \n        int[] arr = { 3, 1, 5, 9, 12 };\n        int n = arr.Length;\n       \n        // Function call\n        if (findPartition(arr, n) == true)\n            Console.Write(\"Can be divided into two \"\n                          + \"subsets of equal sum\");\n        else\n            Console.Write(\"Can not be divided into \"\n                          + \"two subsets of equal sum\");\n    }\n}\n"
  },
  {
    "path": "Algorithms/DP/Partition_Sum/partition_sum.php",
    "content": "<?php\ndeclare(strict_types=1);\n\nfunction partitionSum(array $input): array\n{\n    $total = array_sum($input);\n    if ($total % 2 !== 0) {\n        // There's no way we can split this equally\n        return [];\n    }\n\n    $target = $total / 2;\n\n    $temp = $input;\n    sort($temp);\n    $numElements = count($input);\n    $usedElements = array_fill(0, $numElements, false);\n\n    $usedElements[$numElements - 1] = true;\n    $sum = $temp[$numElements - 1];\n\n    if ($sum > $target) {\n        // The largest number is already larger than the target value, no point in trying to partition with equal sums.\n        return [];\n    }\n\n    for ($i = $numElements - 2; $i >= 0; $i--) {\n        for ($j = $i; $j >= 0; $j--) {\n            $n = $temp[$j];\n            if ($sum + $n <= $target) {\n                $usedElements[$j] = true;\n                $sum += $n;\n            }\n            if ($sum === $target) {\n                break 2;\n            }\n        }\n\n        // Remove everything we tried so far\n        for ($j = $i; $j >= 0; $j--) {\n            if ($usedElements[$j]) {\n                $usedElements[$j] = false;\n                $sum -= $temp[$j];\n            }\n        }\n    }\n\n    if ($sum !== $target) {\n        return [];\n    }\n\n    $firstPartition = [];\n    $secondPartition = [];\n\n    for ($i = 0; $i < count($usedElements); $i++) {\n        if ($usedElements[$i]) {\n            $firstPartition[] = $temp[$i];\n        } else {\n            $secondPartition[] = $temp[$i];\n        }\n    }\n\n    return [$firstPartition, $secondPartition];\n}\n\n$array = [2, 4, 5, 6, 7, 8, 10];\n\n$result = partitionSum($array);\nif (count($result) > 0) {\n    printf(\"[%s]\\n[%s]\", implode(', ', $result[0]), implode(', ', $result[1]));\n} else {\n    print 'Could not split array in two partitions with equals sums.';\n}\n"
  },
  {
    "path": "Algorithms/DP/README.md",
    "content": "# This folder is empty.\n"
  },
  {
    "path": "Algorithms/DP/Recaman's Sequence.c",
    "content": "#include<graphics.h>\n\nint main()\n{\n\tint i,j,a[101],gd,gm;\n\tfloat s=6.0;\n\tchar text[80];\n\tdetectgraph(&gd,&gm);\n\tinitgraph(&gd,&gm,NULL);\n\tsetbkcolor(15);\n\tcleardevice();\n\tsetcolor(0);\n\tsettextstyle(0,0,3);\n\tline(0,350,1400,350);\n\tdelay(2000);\n\ta[0]=0; \n\tfor(i=1;i<=100;i++)\n\t{\t\t\n\t\tj=i;\n\t\tif(a[i-1]-i>0)\n\t\t{\n\t\t\tfor(j=i;j>0;j--)\n\t\t\t{\n\t\t\t\tif(a[j]==a[i-1]-i)\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t}\t\t\n\t\tif(j==0)\n\t\t\ta[i]=a[i-1]-i;\n\t\telse\n\t\t\ta[i]=a[i-1]+i;\n\t\tsprintf(text,\"Recaman(%d) = %d   \",i,a[i]);\n\t\touttextxy(0,0,text);\n\t\tif(i%2==1)\n\t\t\tarc((a[i]+a[i-1])/2.0*s,350,0,180,abs(a[i]-a[i-1])/2.0*s);\n\t\telse\n\t\t\tarc((a[i]+a[i-1])/2.0*s,350,180,360,abs(a[i]-a[i-1])/2.0*s);\t\t\n\t\tSleep(500);\n\t}\n\tgetch();\n\tclosegraph();\n\treturn 0;\n}\n"
  },
  {
    "path": "Algorithms/DP/Scramble Strings/ScrambleString.cpp",
    "content": "\n#include<bits/stdc++.h>\nusing namespace std;\nunordered_map<string,int>mp;\n    bool scramble(string s1,string s2)\n    {\n      \n        if(s1==s2)\n            return true;\n        if(s1.length()<=1)\n            return false;\n        string key=s1+\" \"+s2;\n        if(mp.find(key)!=mp.end())\n            return mp[key];\n        int n=s1.length();\n      \n        bool flag=false;\n        for(int i=1;i<=n-1;i++)\n        {\n           \n          \n            if((scramble(s1.substr(0,i),s2.substr(n-i,i)) && \n              scramble(s1.substr(i,n-i),s2.substr(0,n-i)) )||\n               (scramble(s1.substr(0,i),s2.substr(0,i)) && \n              scramble(s1.substr(i,n-i),s2.substr(i,n-i)) )\n              )\n            { flag=true;\n                 break;\n            }\n        }\n        return mp[key]=flag;\n    }\n    bool isScramble(string s1, string s2) {\n        if(s1.length()!=s2.length())\n            return false;\n        if(s1.length()==0 && s2.length()==0)\n            return true;\n        mp.clear();\n        return scramble(s1,s2);\n        \n        \n    }\n    \n    \n    int main()\n    {\n        string s1,s2;\n        cin>>s1>>s2;\n        bool ans=isScramble(s1,s2);\n        cout<<ans<<endl;\n        return 0;\n    }\n"
  },
  {
    "path": "Algorithms/DP/Shortest_Common_Supersequence/shortest_common_sequence.java",
    "content": "class Solution {\n\n    public String shortestCommonSupersequence(String str1, String str2) {\n        int m = str1.length();\n        int n = str2.length();\n    \n        int[][] dp = new int[m+1][n+1];\n    \n        for(int i = 1 ; i <= m ; i++){\n            dp[i][0] = i;\n        }\n    \n        for(int j = 1 ; j <= n ; j++){\n            dp[0][j] = j;\n        }\n    \n        for(int i = 1 ; i <= m ; i++){\n            for(int j = 1 ; j <= n ; j++){\n                if(str1.charAt(i-1) == str2.charAt(j-1)){\n                    dp[i][j] = dp[i-1][j-1] + 1;\n                }\n                else{\n                    dp[i][j] = Math.min(dp[i-1][j],dp[i][j-1]) + 1;\n                }\n            }\n        }\n        StringBuilder sb = new StringBuilder();\n        int i = m;\n        int j = n;\n    \n        while(i > 0 && j > 0){\n            if(str1.charAt(i-1) == str2.charAt(j-1)){\n                sb.append(str1.charAt(i-1));\n                i--;\n                j--;\n            }\n            else{\n                if(dp[i-1][j]+1 == dp[i][j]){\n                    sb.append(str1.charAt(i-1));\n                    i--;\n                }\n                else{\n                    sb.append(str2.charAt(j-1));\n                    j--;\n                }\n            }\n        }\n        while(i > 0){\n            sb.append(str1.charAt(i-1));\n            i--;\n        }\n        while(j > 0){\n            sb.append(str2.charAt(j-1));\n            j--;\n        }\n    \n        return sb.reverse().toString();\n    }\n    }"
  },
  {
    "path": "Algorithms/DP/Shortest_Common_Supersequence/shortest_common_supersequence.cpp",
    "content": "#include<bits/stdc++.h> \nusing namespace std;\n\nint max(int a, int b) \n{ \n    return (a > b)? a : b; \n} \n\nint lcs(string X, string Y, int m, int n); \n\nint shortestSuperSequence(string X, string Y) \n{\n    int m = X.length();\n    int n = Y.length(); \n    int l = lcs(X, Y, m, n); \n\n    return (m + n - l); \n} \n\nint lcs(string X,string Y,int m,int n) \n{ \n    int dp[m+1][n+1]; \n    int i,j;\n\n    for(i=0;i<=m;i++) \n    {\n        for(j=0;j<=n;j++) \n        { \n            if(i == 0 || j == 0) \n                dp[i][j] = 0;\n            else if(X[i-1] == Y[j-1]) \n                dp[i][j] = dp[i-1][j-1] + 1; \n            else\n                dp[i][j] = max(dp[i-1][j],dp[i][j-1]); \n        }\n    } \n    return dp[m][n]; \n} \n\nint main() \n{ \n    string s1,s2; \n    cout<<\"Enter the first string :\"<<\"\\n\"; \n    cin>>s1; \n    cout<<\"\\nEnter the second string :\"<<\"\\n\";\n    cin>>s2;\n    cout<<\"\\nLength of the shortest common supersequence is \"<<shortestSuperSequence(s1,s2); \n          \n    return 0; \n} "
  },
  {
    "path": "Algorithms/DP/Shortest_Common_Supersequence/shortest_common_supersequence.cs",
    "content": "using System; \n\nclass SCS\n{ \n\n\n\tstatic String printShortestSuperSeq(String X, String Y) \n\t{ \n\t\tint m = X.Length; \n\t\tint n = Y.Length; \n\n\t\tint [,]dp = new int[m + 1, n + 1]; \n\t\tint i, j; \n\t\t\n\t \n\t\tfor (i = 0; i <= m; i++) \n\t\t{ \n\t\t\tfor (j = 0; j <= n; j++) \n\t\t\t{ \n\t\t\t\t\n\t\t\t\t \n\t\t\t\tif (i == 0) \n\t\t\t\t{ \n\t\t\t\t\tdp[i, j] = j; \n\t\t\t\t} \n\t\t\t\telse if (j == 0) \n\t\t\t\t{ \n\t\t\t\t\tdp[i, j] = i; \n\t\t\t\t} \n\t\t\t\telse if (X[i - 1] == Y[j - 1]) \n\t\t\t\t{ \n\t\t\t\t\tdp[i, j] = 1 + dp[i - 1, j - 1]; \n\t\t\t\t} \n\t\t\t\telse\n\t\t\t\t{ \n\t\t\t\t\tdp[i, j] = 1 + Math.Min(dp[i - 1, j], dp[i, j - 1]); \n\t\t\t\t} \n\t\t\t} \n\t\t} \n\n\t\tint index = dp[m, n]; \n\n\t\tString str = \"\"; \n\n\t\ti = m; j = n; \n\t\twhile (i > 0 && j > 0) \n\t\t{ \n\t\t\tif (X[i - 1] == Y[j - 1]) \n\t\t\t{ \n\t\t\t\tstr += (X[i - 1]); \n\t\t\t\ti--; \n\t\t\t\tj--; \n\t\t\t\tindex--; \n\t\t\t} \n\t\t\t\n\t\t\n\t\t\telse if (dp[i - 1, j] > dp[i, j - 1]) \n\t\t\t{\n\t\t\t\tstr += (Y[j - 1]); \n\t\t\t\tj--; \n\t\t\t\tindex--; \n\t\t\t} \n\t\t\telse\n\t\t\t{ \n\t\t\t\t\n\t\t\t\t\n\t\t\t\tstr += (X[i - 1]); \n\n\t\t\n\t\t\t\ti--; \n\t\t\t\tindex--; \n\t\t\t} \n\t\t} \n\n\t \n\t\twhile (i > 0) \n\t\t{ \n\t\t\tstr += (X[i - 1]); \n\t\t\ti--; \n\t\t\tindex--; \n\t\t} \n\n\t\t\n\t\twhile (j > 0) \n\t\t{ \n\t\t\tstr += (Y[j - 1]); \n\t\t\tj--; \n\t\t\tindex--; \n\t\t} \n\n\t\n\t\tstr = reverse(str); \n\t\treturn str; \n\t} \n\n\tstatic String reverse(String input) \n\t{ \n\t\tchar[] temparray = input.ToCharArray(); \n\t\tint left, right = 0; \n\t\tright = temparray.Length - 1; \n\n\t\tfor (left = 0; left < right; left++, right--) \n\t\t{ \n\t\t\tchar temp = temparray[left]; \n\t\t\ttemparray[left] = temparray[right]; \n\t\t\ttemparray[right] = temp; \n\t\t} \n\t\treturn String.Join(\"\",temparray); \n\t} \n\t\n\t// code \n\tpublic static void Main(String[] args) \n\t{ \n\t\tString X;\n\t\tString Y;\n\t\tX = Console.ReadLine();\n\t\tY = Console.ReadLine();\n\t\tConsole.WriteLine(printShortestSuperSeq(X, Y)); \n\t} \n} \n\n"
  },
  {
    "path": "Algorithms/DP/Shortest_Common_Supersequence/shortest_common_supersequence.js",
    "content": "const readline = require('readline')\nconst reader = readline.createInterface(process.stdin, process.stdout); \n\nfunction shortestCommonSuperstring(str1, str2) {\n    let m = str1.length, n = str2.length\n    let dp = Array(m+1)\n    for(let i=0;i<=m;++i) {\n        dp[i] = Array(n+1)\n        for(let j=0;j<=n;++j) {\n            if(i === 0)\n                dp[i][j] = j\n            else if(j === 0)\n                dp[i][j] = i\n            else if(str1.charAt(i-1) === str2.charAt(j-1))\n                dp[i][j] = 1 + dp[i - 1][j - 1]\n            else\n                dp[i][j] = 1 + Math.min(dp[i - 1][j], dp[i][j - 1])\n        }\n    }\n    return dp[m][n]\n}\n\nreader.question('Enter two string seperated by space: ', string => {\n    let string_arr = string.split(\" \")\n    console.log(\"Length of the shortest supersequence is \" + shortestCommonSuperstring(string_arr[0], string_arr[1]))\n    reader.close()\n})\n"
  },
  {
    "path": "Algorithms/DP/Shortest_Common_Supersequence/shortest_common_supersequence.py",
    "content": "# This algorithm finds the shortest common supersequence of 2 strings - \n# the shortest string that has both str1 and str2 as subsequences. \n# If 'm' is the length of the first string and 'n' is the length of \n# the second string, then this algo takes O(m * n) time and O(m * n) space.\n\n# Returns length of the shortest supersequence of X and Y \ndef superSeq(X, Y, m, n): \n\tdp = [[0] * (n + 2) for i in range(m + 2)] \n\n\t# Fill table in bottom up manner \n\tfor i in range(m + 1): \n\t\tfor j in range(n + 1): \n\t\t\t\n\t\t\t#Below steps follow above recurrence \n\t\t\tif (not i): dp[i][j] = j \n\t\t\telif (not j): dp[i][j] = i \n\t\t\t\n\t\t\telif (X[i - 1] == Y[j - 1]): \n\t\t\t\tdp[i][j] = 1 + dp[i - 1][j - 1] \n\t\t\t\t\n\t\t\telse: dp[i][j] = 1 + min(dp[i - 1][j], \n\t\t\t\t\t\t\t\t\tdp[i][j - 1]) \n\t\t\t\n\treturn dp[m][n] \n\n# Driver Code \nX = \"AGGTAB\"\nY = \"GXTXAYB\"\nprint(\"Length of the shortest supersequence is %d\"\n\t% superSeq(X, Y, len(X), len(Y))) \n\n# This code is contributed by Ansu Kumari \n"
  },
  {
    "path": "Algorithms/DP/Sudoku_Solver/README.md",
    "content": "## This folder is empty.\n"
  },
  {
    "path": "Algorithms/DP/Sudoku_Solver/SudokuSolver.java",
    "content": "import java.util.*;\nimport java.io.*;\nclass SudokuSolver {\n    static class FastReader{\n        BufferedReader br;\n        StringTokenizer st;\n        FastReader(){\n            br = new BufferedReader(new InputStreamReader(System.in));\n        }\n        String next(){\n            while(st==null || !st.hasMoreElements()){\n                try{\n                    st =new StringTokenizer(br.readLine());\n                }\n                catch(IOException e)    {\n                    e.printStackTrace();\n                }\n            }\n            return st.nextToken();\n        }\n        int nextInt(){\n            return Integer.parseInt(next());\n        }\n    }\n    public static void main(String[] args) {\n        FastReader fr = new FastReader();\n        int n = fr.nextInt();\n        int[][] board = new int[n][n];\n        for(int i=0;i<n;i++){\n            for(int j=0;j<n;j++){\n                board[i][j] = fr.nextInt();\n            }\n        }\n        solveSudoku(board, 0,0);\n    }\n    public static boolean isSafe(int[][] board,int row,int col,int index){\n        if(board[row][col]!=0){\n            return false;\n        }\n        for(int i=0;i<9;i++){\n            if(board[row][i]==index){\n                return false;\n            }\n        }\n        for(int i=0;i<9;i++){\n            if(board[i][col]==index){\n                return false;\n            }\n        }\n        row = row - row%3;\n        col = col - col%3;\n        for(int i=row;i<row+3;i++){\n            for(int j=col;j<col+3;j++){\n                if(board[i][j]==index){\n                    return false;\n                }\n            }\n        }\n        return true;\n    }\n    public static void solveSudoku(int[][] board, int row, int col){\n        if(row==9){\n            for(int i=0;i<9;i++){\n                for(int j=0;j<9;j++){\n                    System.out.print(board[i][j]+ \" \");\n                }\n                System.out.println();\n            }\n            return;\n        }\n        if(col==9){\n            solveSudoku(board, row+1,0);\n            return;\n        }\n        if(board[row][col]==0)\n        {\n            for(int i=1;i<=9;i++){\n                if(isSafe(board,row,col,i)){\n                    board[row][col] = i;\n                    solveSudoku(board, row,col+1);\n                    board[row][col]=0;\n                }\n            }\n        }else{\n            solveSudoku(board, row,col+1);\n        }\n    }\n}\n"
  },
  {
    "path": "Algorithms/DP/Sudoku_Solver/SudokuSolver.py",
    "content": "\ndef print_grid(arr): \n\tfor i in range(9): \n\t\tfor j in range(9): \n\t\t\tprint arr[i][j], \n\t\tprint ('n') \n\n\t\t\ndef find_empty_location(arr, l): \n\tfor row in range(9): \n\t\tfor col in range(9): \n\t\t\tif(arr[row][col]== 0): \n\t\t\t\tl[0]= row \n\t\t\t\tl[1]= col \n\t\t\t\treturn True\n\treturn False\n\ndef used_in_row(arr, row, num): \n\tfor i in range(9): \n\t\tif(arr[row][i] == num): \n\t\t\treturn True\n\treturn False\n\ndef used_in_col(arr, col, num): \n\tfor i in range(9): \n\t\tif(arr[i][col] == num): \n\t\t\treturn True\n\treturn False\n\ndef used_in_box(arr, row, col, num): \n\tfor i in range(3): \n\t\tfor j in range(3): \n\t\t\tif(arr[i + row][j + col] == num): \n\t\t\t\treturn True\n\treturn False\n\ndef check_location_is_safe(arr, row, col, num): \n\t\n\treturn not used_in_row(arr, row, num) and not used_in_col(arr, col, num) and not used_in_box(arr, row - row % 3, col - col % 3, num) \n\ndef solve_sudoku(arr): \n\t\n\tl =[0, 0] \n\t \n\tif(not find_empty_location(arr, l)): \n\t\treturn True\n\t\n\trow = l[0] \n\tcol = l[1] \n\t\n\tfor num in range(1, 10): \n\t\t\n\t\tif(check_location_is_safe(arr, row, col, num)): \n\t\t\t\n\t\t\tarr[row][col]= num \n\n\t\t\treturn True\n\n\t\t\tarr[row][col] = 0\n\t\t\t\n\treturn False\n\nif __name__==\"__main__\": \n\t\n\tgrid =[[0 for x in range(9)]for y in range(9)] \n\t\n\tgrid =[[3, 0, 6, 5, 0, 8, 4, 0, 0], \n\t\t[5, 2, 0, 0, 0, 0, 0, 0, 0], \n\t\t[0, 8, 7, 0, 0, 0, 0, 3, 1], \n\t\t[0, 0, 3, 0, 1, 0, 0, 8, 0], \n\t\t[9, 0, 0, 8, 6, 3, 0, 0, 5], \n\t\t[0, 5, 0, 0, 9, 0, 6, 0, 0], \n\t\t[1, 3, 0, 0, 0, 0, 2, 5, 0], \n\t\t[0, 0, 0, 0, 0, 0, 0, 7, 4], \n\t\t[0, 0, 5, 2, 0, 6, 3, 0, 0]] \n\t\n\tif(solve_sudoku(grid)): \n\t\tprint_grid(grid) \n\telse: \n\t\tprint \"No solution exists\"\n"
  },
  {
    "path": "Algorithms/DP/Sudoku_Solver/Sudoku_Solver.cpp",
    "content": "#include <bits/stdc++.h> \nusing namespace std; \n  \n#define UNASSIGNED 0 \n  \n\n#define N 9 \n  \n\nbool FindUnassignedLocation(int grid[N][N], \n                            int& row, int& col); \n  \n \nbool isSafe(int grid[N][N], int row, \n            int col, int num); \n  \n\nbool SolveSudoku(int grid[N][N]) \n{ \n    int row, col; \n  \n   \n    if (!FindUnassignedLocation(grid, row, col)) \n         \n        return true; \n  \n     \n    for (int num = 1; num <= 9; num++) { \n        \n        if (isSafe(grid, row, col, num)) { \n            \n            grid[row][col] = num; \n  \n            \n            if (SolveSudoku(grid)) \n                return true; \n  \n            \n            grid[row][col] = UNASSIGNED; \n        } \n    } \n     \n    return false; \n} \n  \n\nbool FindUnassignedLocation(int grid[N][N], \n                            int& row, int& col) \n{ \n    for (row = 0; row < N; row++) \n        for (col = 0; col < N; col++) \n            if (grid[row][col] == UNASSIGNED) \n                return true; \n    return false; \n} \n  \n\nbool UsedInRow(int grid[N][N], int row, int num) \n{ \n    for (int col = 0; col < N; col++) \n        if (grid[row][col] == num) \n            return true; \n    return false; \n} \n  \n\nbool UsedInCol(int grid[N][N], int col, int num) \n{ \n    for (int row = 0; row < N; row++) \n        if (grid[row][col] == num) \n            return true; \n    return false; \n} \n  \n\nbool UsedInBox(int grid[N][N], int boxStartRow, \n               int boxStartCol, int num) \n{ \n    for (int row = 0; row < 3; row++) \n        for (int col = 0; col < 3; col++) \n            if (grid[row + boxStartRow] \n                    [col + boxStartCol] \n                == num) \n                return true; \n    return false; \n} \n  \n\nbool isSafe(int grid[N][N], int row, \n            int col, int num) \n{ \n    \n    return !UsedInRow(grid, row, num) \n           && !UsedInCol(grid, col, num) \n           && !UsedInBox(grid, row - row % 3, \n                         col - col % 3, num) \n           && grid[row][col] == UNASSIGNED; \n} \n  \n\nvoid printGrid(int grid[N][N]) \n{ \n    for (int row = 0; row < N; row++) { \n        for (int col = 0; col < N; col++) \n            cout << grid[row][col] << \" \"; \n        cout << endl; \n    } \n} \n  \n\nint main() \n{ \n\n    int grid[N][N] = { { 3, 0, 6, 5, 0, 8, 4, 0, 0 }, \n                       { 5, 2, 0, 0, 0, 0, 0, 0, 0 }, \n                       { 0, 8, 7, 0, 0, 0, 0, 3, 1 }, \n                       { 0, 0, 3, 0, 1, 0, 0, 8, 0 }, \n                       { 9, 0, 0, 8, 6, 3, 0, 0, 5 }, \n                       { 0, 5, 0, 0, 9, 0, 6, 0, 0 }, \n                       { 1, 3, 0, 0, 0, 0, 2, 5, 0 }, \n                       { 0, 0, 0, 0, 0, 0, 0, 7, 4 }, \n                       { 0, 0, 5, 2, 0, 6, 3, 0, 0 } }; \n    if (SolveSudoku(grid) == true) \n        printGrid(grid); \n    else\n        cout << \"No solution exists\"; \n  \n    return 0; \n} "
  },
  {
    "path": "Algorithms/DP/Sudoku_Solver/Sudoku_Solver.cs",
    "content": "using System; \n\nclass GFG { \n\n\tpublic static bool isSafe(int[, ] board, \n\t\t\t\t\t\t\tint row, int col, \n\t\t\t\t\t\t\tint num) \n\t{ \n\t\t\n\t\tfor (int d = 0; d < board.GetLength(0); d++) { \n\t\t\tif (board[row, d] == num) { \n\t\t\t\treturn false; \n\t\t\t} \n\t\t} \n\t\tfor (int r = 0; r < board.GetLength(0); r++) { \n\t\t\t\n\t\t\tif (board[r, col] == num) { \n\t\t\t\treturn false; \n\t\t\t} \n\t\t} \n \n\t\tint sqrt = (int)Math.Sqrt(board.GetLength(0)); \n\t\tint boxRowStart = row - row % sqrt; \n\t\tint boxColStart = col - col % sqrt; \n\n\t\tfor (int r = boxRowStart; \n\t\t\tr < boxRowStart + sqrt; r++) { \n\t\t\tfor (int d = boxColStart; \n\t\t\t\td < boxColStart + sqrt; d++) { \n\t\t\t\tif (board[r, d] == num) { \n\t\t\t\t\treturn false; \n\t\t\t\t} \n\t\t\t} \n\t\t} \n\t\treturn true; \n\t} \n\n\tpublic static bool solveSudoku(int[, ] board, int n) \n\t{ \n\t\tint row = -1; \n\t\tint col = -1; \n\t\tbool isEmpty = true; \n\t\tfor (int i = 0; i < n; i++) { \n\t\t\tfor (int j = 0; j < n; j++) { \n\t\t\t\tif (board[i, j] == 0) { \n\t\t\t\t\trow = i; \n\t\t\t\t\tcol = j; \n\t\t\t\t\tisEmpty = false; \n\t\t\t\t\tbreak; \n\t\t\t\t} \n\t\t\t} \n\t\t\tif (!isEmpty) { \n\t\t\t\tbreak; \n\t\t\t} \n\t\t} \n\t\tif (isEmpty) { \n\t\t\treturn true; \n\t\t} \n\n\t\n\t\tfor (int num = 1; num <= n; num++) { \n\t\t\tif (isSafe(board, row, col, num)) { \n\t\t\t\tboard[row, col] = num; \n\t\t\t\tif (solveSudoku(board, n)) { \n\t\t\t\t\t// print(board, n); \n\t\t\t\t\treturn true; \n\t\t\t\t} \n\t\t\t\telse { \n\t\t\t\t\tboard[row, col] = 0; \n\t\t\t\t} \n\t\t\t} \n\t\t} \n\t\treturn false; \n\t} \n\n\tpublic static void print(int[, ] board, int N) \n\t{ \n\t\tfor (int r = 0; r < N; r++) { \n\t\t\tfor (int d = 0; d < N; d++) { \n\t\t\t\tConsole.Write(board[r, d]); \n\t\t\t\tConsole.Write(\" \"); \n\t\t\t} \n\t\t\tConsole.Write(\"\\n\"); \n\n\t\t\tif ((r + 1) % (int)Math.Sqrt(N) == 0) { \n\t\t\t\tConsole.Write(\"\"); \n\t\t\t} \n\t\t} \n\t} \n\tpublic static void Main(String[] args) \n\t{ \n\n\t\tint[, ] board = new int[, ] { \n\t\t\t{ 3, 0, 6, 5, 0, 8, 4, 0, 0 }, \n\t\t\t{ 5, 2, 0, 0, 0, 0, 0, 0, 0 }, \n\t\t\t{ 0, 8, 7, 0, 0, 0, 0, 3, 1 }, \n\t\t\t{ 0, 0, 3, 0, 1, 0, 0, 8, 0 }, \n\t\t\t{ 9, 0, 0, 8, 6, 3, 0, 0, 5 }, \n\t\t\t{ 0, 5, 0, 0, 9, 0, 6, 0, 0 }, \n\t\t\t{ 1, 3, 0, 0, 0, 0, 2, 5, 0 }, \n\t\t\t{ 0, 0, 0, 0, 0, 0, 0, 7, 4 }, \n\t\t\t{ 0, 0, 5, 2, 0, 6, 3, 0, 0 } \n\t\t}; \n\t\tint N = board.GetLength(0); \n\n\t\tif (solveSudoku(board, N)) { \n\t\t\tprint(board, N); // print solution \n\t\t} \n\t\telse { \n\t\t\tConsole.Write(\"No solution\"); \n\t\t} \n\t} \n} \n"
  },
  {
    "path": "Algorithms/DP/Sudoku_Solver/Sudoku_Solver.js",
    "content": " // I solved this question with backtracking algorithm:\n\n const _board = [\n    ['.', '9', '.', '.', '4', '2', '1', '3', '6'],\n    ['.', '.', '.', '9', '6', '.', '4', '8', '5'],\n    ['.', '.', '.', '5', '8', '1', '.', '.', '.'],\n    ['.', '.', '4', '.', '.', '.', '.', '.', '.'],\n    ['5', '1', '7', '2', '.', '.', '9', '.', '.'],\n    ['6', '.', '2', '.', '.', '.', '3', '7', '.'],\n    ['1', '.', '.', '8', '.', '4', '.', '2', '.'],\n    ['7', '.', '6', '.', '.', '.', '8', '1', '.'],\n    ['3', '.', '.', '.', '9', '.', '.', '.', '.'],\n];\nsodokuSolver(_board);\nconsole.log(_board);\n\nfunction isValid(board, row, col, k) {\n    for (let i = 0; i < 9; i++) {\n        const m = 3 * Math.floor(row / 3) + Math.floor(i / 3);\n        const n = 3 * Math.floor(col / 3) + i % 3;\n        if (board[row][i] == k || board[i][col] == k || board[m][n] == k) {\n          return false;\n        }\n    }\n    return true;\n}\n\n\nfunction sodokuSolver(data) {\n  for (let i = 0; i < 9; i++) {\n    for (let j = 0; j < 9; j++) {\n      if (data[i][j] == '.') {\n        for (let k = 1; k <= 9; k++) {\n          if (isValid(data, i, j, k)) {\n            data[i][j] = `${k}`;\n          if (sodokuSolver(data)) {\n           return true;\n          } else {\n           data[i][j] = '.';\n          }\n         }\n       }\n       return false;\n     }\n   }\n }\n return true;\n}"
  },
  {
    "path": "Algorithms/DP/Target_Sum/Target_Sum.c",
    "content": "#include <stdio.h>\n#include <stdlib.h> \n\nint CntSum(int arr[], int N, int required_sum) \n{ \n    int t[N+1][required_sum+1] , i ,j ;\n    for(i = 0 ; i < N+1;i++)\n        t[i][0] = 1;\n    for(i = 1 ; i < required_sum+1;i++)\n        t[0][i] = 0;\n    for(i = 1; i < N+1;i++)\n    {\n        for(j = 1 ; j < required_sum+1;j++)\n        {\n            if(arr[i-1] <= j)\n                t[i][j] = t[i-1][j-arr[i-1]]+t[i-1][j];\n            else\n                t[i][j] = t[i-1][j];\n        }\n    }\n    return t[N][required_sum]; \n} \nint main() \n{ \n    int N , i;\n    printf(\"Enter Size of Array :- \\n\");\n    scanf(\"%d\",&N);\n    int A[N];\n    printf(\"Enter Array Elements :- \\n\");\n    for(i = 0 ; i< N;i++)\n        scanf(\"%d\",&A[i]);\n    printf(\"Enter Target Sum :- \\n\");\n    int X;\n    scanf(\"%d\",&X);\n    long int ans = CntSum(A , N , X);\n    printf(\"Count = %ld\\n\", ans);\n  \n    return 0; \n} "
  },
  {
    "path": "Algorithms/DP/Target_Sum/Target_Sum.cpp",
    "content": "\n#include <iostream>\nusing namespace std;\n\nint SubsetSum(int arr[],int n, int sum)\n{\n    int t[n+1][sum+1];\n    for(int i=0;i<n+1;i++){\n        for(int j=0;j<sum+1;j++){\n             if(i==0)\n               t[i][j]=0;\n             if(j==0)\n               t[i][j]=1;\n        }\n    }\n    for(int i=1;i<n+1;i++){\n        for(int j=1;j<sum+1;j++){\n             if(arr[i-1]<=j)  \n                t[i][j]=t[i-1][j-arr[i-1]] + t[i-1][j];\n            else\n               t[i][j]=t[i-1][j]; \n        }\n    }\n return t[n][sum];\n}\n\nint main()\n{\n\t    int n;\n\t    cout<<\"array size : \";\n\t    cin>>n;\n\t    int arr[n];\n\t    cout<<\"array element :\\n\";\n\t    for(int i=0;i<n;i++)\n\t        cin>>arr[i];\n        int sum;\n        cout<<\"sum :\";\n        cin>>sum;\n      cout<<\"\\ncount : \"<<SubsetSum(arr,n,sum);\n\t /* if(EqualSumPartition(arr,n))\n\t     cout<<\"YES\"<<endl;\n\t   else\n\t     cout<<\"Not Possible\"<<endl;*/\n\treturn 0;\n}\n"
  },
  {
    "path": "Algorithms/DP/Target_Sum/Target_Sum.java",
    "content": "\nimport java.util.*; \n\npublic class Target_Sum\n{ \n\nstatic int Sum(int arr[], int n, int i, \n\t\t\t\t\tint sum, int count) \n{ \n\t\n\tif (i == n) \n\t{\n\t\tif (sum == 0) \n\t\t{ \n\t\t\tcount++; \n\t\t} \n\t\treturn count; \n\t} \n\n\tcount = Sum(arr, n, i + 1, sum - arr[i], count); \n\tcount = Sum(arr, n, i + 1, sum, count); \n\treturn count; \n} \n \npublic static void main(String[] args) \n{ \n    Scanner sc= new Scanner(System.in);\n    int n,sum;\n    System.out.println(\"Enter number of elements in array\");\n    n = sc.nextInt();\n    int [] arr = new int [n];\n    System.out.println(\"Enter array elements\");\n    for( int i =0 ; i<n ; ++i) arr[i]=sc.nextInt();\n    System.out.println(\"Enter sum\");\n    sum = sc.nextInt();\n\n\n\tSystem.out.print(Sum(arr, n, 0, sum, 0)); \n} \n} \n\n"
  },
  {
    "path": "Algorithms/DP/Target_Sum/Target_Sum.js",
    "content": "function targetSum(arr, target) {\n  return countSub(arr, arr.length, 0, target, 0)\n}\n\nfunction countSub(arr, n, i, sum, count) {\n  if(i === n) {\n    if(sum === 0) {\n      count += 1  \n    }\n    return count \n  }\n  count = countSub(arr, n, i+1, sum - arr[i], count)\n  count = countSub(arr, n, i+1, sum, count)\n\n  return count   \n}"
  },
  {
    "path": "Algorithms/DP/Target_Sum/Target_Sum.py",
    "content": "arr = list(map(int, input('Enter array: ').split()))\ntargetSum = int(input('Enter target sum: '))\n\ndp = [[0 for i in range(targetSum + 1)] for i in range(len(arr))]\nvisited = [[0 for i in range(targetSum + 1)] for i in range(len(arr))]\n\ndef findNumberOfSubsetsMemo(arr, i, targetSum, n) : \n    \n    print(i, targetSum)\n\n    # Base condition\n    if (i == n) : \n        if (targetSum == 0) : \n            return 1;  \n        else : \n            return 0;  \n\n    if(targetSum < 0):\n\n        return 0;\n   \n    #Retrieve if already solved\n    if (visited[i][targetSum] == 1) : \n        return dp[i][targetSum];  \n    \n    #Set as solved\n    visited[i][targetSum] = 1;  \n  \n    # Recursion call\n    dp[i][targetSum] = findNumberOfSubsetsMemo(arr, i + 1, targetSum, n) + findNumberOfSubsetsMemo(arr, i + 1, targetSum - arr[i], n);  \n      \n    return dp[i][targetSum];\n\ndef findNumberOfSubsetsRecur(arr, n, i,sum, count): \n      \n    if (i == n): \n  \n        if (sum == 0): \n            count += 1\n        return count \n  \n    count = findNumberOfSubsetsRecur(arr, n, i + 1, sum - arr[i], count) \n    count = findNumberOfSubsetsRecur(arr, n, i + 1, sum, count) \n    return count\n\nprint('By Memo:', findNumberOfSubsetsMemo(arr, 0, targetSum, len(arr)))"
  },
  {
    "path": "Algorithms/DP/Tower_Of_Hanoi/README.md",
    "content": "## This folder is empty.\n"
  },
  {
    "path": "Algorithms/DP/Tower_Of_Hanoi/TOH.java",
    "content": "package com.codenuclear;\r\n \r\nimport java.util.Scanner;\r\n \r\npublic class TowersOfHanoi {\r\n \r\n\tpublic void solveTowersOfHanoi(int n, String source, String aux, String dest)\r\n\t{\r\n\t\t// If only 1 disk, make the move and return.\r\n\t\tif(n==1)\r\n\t\t{\r\n\t\t\tSystem.out.println(source+\" --> \"+dest);\r\n\t\t\treturn;\r\n\t\t}\r\n\t\t\r\n\t\t// Move top n-1 disks from A to B using C as auxiliary.\r\n\t\tsolveTowersOfHanoi(n-1, source, dest, aux);\r\n\t\t\r\n\t\t//Move remaining disks from A to C\r\n\t\tSystem.out.println(source+\" --> \"+dest);\r\n\t\t\r\n\t\t// Move n-1 disks from B to C using A as auxiliary\r\n\t\tsolveTowersOfHanoi(n-1, aux, source, dest);\r\n\t\t\r\n\t}\r\n\t\r\n\tpublic static void main(String args[])\r\n\t{\r\n\t\tTowersOfHanoi obj = new TowersOfHanoi();\r\n\t\t\r\n\t\tSystem.out.println(\"Enter number of disks :- \");\r\n\t    \r\n\t\tScanner scanner = new Scanner(System.in);\r\n\t\tint n = scanner.nextInt();\r\n\t\tscanner.close();\r\n\t\t\r\n\t\tSystem.out.println(\"Move disks as below illustration.\");\r\n\t\tobj.solveTowersOfHanoi(n, \"A\", \"B\", \"C\");\r\n\t\t\r\n\t}\t\r\n}\r\n "
  },
  {
    "path": "Algorithms/DP/Tower_Of_Hanoi/Tower_Of_Hanoi.cs",
    "content": "﻿using System;\n\nnamespace Tower_Of_Hanoi\n{\n    class Tower_Of_Hanoi\n    {\n        static void Main(string[] args)\n        {\n            int numOfDisks;\n            char source = 'A', auxiliary = 'B', destination = 'C';\n            Console.WriteLine(\"The Tower of Hanoi consists of three rods and a number of disks of different sizes.\");\n            Console.Write(\"Enter the number of disks: \");\n            \n            numOfDisks = Convert.ToInt32(Console.ReadLine());\n\n            if(numOfDisks > 0)\n            {\n                TowerOfHanoi(numOfDisks, source, auxiliary, destination);\n            }\n            else\n            {\n                Console.WriteLine(\"The number should be greater than 0\");\n            }\n        }\n\n        public static void TowerOfHanoi(int numDisk, char source, char auxiliary, char destination)\n        {\n\n            if (numDisk > 1)\n            {\n                TowerOfHanoi(numDisk - 1, source, auxiliary, destination);\n                Console.WriteLine(\"Move disk \" + numDisk + \" from source \" + source + \" to destination \" + destination);\n                TowerOfHanoi(numDisk - 1, auxiliary, destination, source);\n            }\n            else\n            {\n                Console.WriteLine(\"Move disk 1 from cource \" + source + \" to destination \" + destination);\n            }\n\n        }\n    }\n}\n"
  },
  {
    "path": "Algorithms/DP/Tower_Of_Hanoi/Tower_Of_Hanoi.js",
    "content": "'use strict';\n\nfunction Tower_Of_Hanoi () {\n  const game = {\n      A : ['A'],\n      B : ['B'],\n      C : ['C'],\n\n    print() {\n      console.log(`${this.A}   ${this.B}   ${this.C}`)\n    },\n\n    moveDiscs(n, source, dest, spare) {\n      if (n === 1) { \n        dest.push(1), \n        source.pop()\n        this.print(); \n      }\n      else {\n        this.moveDiscs(n-1, source, spare, dest); \n        dest.push(n);\n        source.pop();\n        this.print();\n        this.moveDiscs(n-1, spare, dest, source);\n      }\n    },\n\n    play(n) {\n      for (let i = n; i > 0; i--) this.A.push(i);\n      this.print();\n      this.moveDiscs(n, this.A, this.B, this.C);\n    }\n  }\n  return game;\n}\n\nconst theGame = Tower_Of_Hanoi();\n\nconst readline = require(\"readline\");\nconst rl = readline.createInterface({\n    input: process.stdin,\n    output: process.stdout\n});\nrl.question(\"Please enter the number of discs ? \", function(n) {\n  theGame.play(n);\n  rl.close()\n});\n"
  },
  {
    "path": "Algorithms/DP/Tower_Of_Hanoi/Tower_of_hanoi.ts",
    "content": "function solveHanoi(\n    counting: number,\n    from: string,\n    to: string,\n    other: string,\n    move: (from: string, to: string) => void\n)\n{\n    if (counting > 0) {\n        solveHanoi(counting - 1, from, other, to, move)\n        move(from, to)\n        solveHanoi(counting - 1, other, to, from, move)\n    }\n}\n \n// Example: six discs\nvar moveCounting = 0\nsolveHanoi(6, \"Left\", \"Right\", \"Middle\", (from , to) => {\n    ++moveCounting\n    console.log(moveCounting + \": Move from \" + from + \" to \" + to + \".\")\n})\n"
  },
  {
    "path": "Algorithms/DP/Tower_Of_Hanoi/tower_of_hanoi.c",
    "content": "#include <stdio.h>\n\nvoid hanoi(char from, char helper, char to, int n) {\n\t//Base case - only one disk to move\n\tif (n == 1) {\n\t\tprintf(\"Move disk 1 from tower %c to tower %c\\n\", from, to);\n\t\treturn;\n\t}\n\n\t//When two or more disks must be moved we call the function again\n\thanoi(from, to, helper, n - 1);\n\tprintf(\"Move disk %d from tower %c to tower %c\\n\", n, from, to);\n\thanoi(helper, from, to, n - 1);\n}\n\nint main() {\n\tint n;\n\t\n\t//Prompt for user interaction\n\tprintf(\"Enter the number of disks to play: \");\n\tscanf_s(\"%d\", &n);\n\n\t//Calculate the game moves\n\thanoi('A', 'B', 'C', n);\n\n\treturn 0;\n}"
  },
  {
    "path": "Algorithms/DP/Tower_Of_Hanoi/tower_of_hanoi.cpp",
    "content": "#include <iostream>\n\nusing namespace std;\n\nvoid towerOfHanoi(char from,char to,char aux,int n){\n\tif(n == 1){\n\t\tcout<<\"Move disk 1 from rod \"<<from<<\" to rod \"<<to<<endl;\n\t\treturn;\n\t}\n\n\ttowerOfHanoi(from,aux,to,n-1);\n\tcout<<\"Move disk \"<<n<<\" from rod \"<<from<<\" to rod \"<<to<<endl;\n\ttowerOfHanoi(aux,to,from,n-1);\n}\n\nint main(){\n\tint n; cin>>n;\n\ttowerOfHanoi('A','C','B',n);\n\treturn 0;\n}\n"
  },
  {
    "path": "Algorithms/DP/Tower_Of_Hanoi/tower_of_hanoi.go",
    "content": "package main\n\nimport (\n\t\"fmt\"\n)\n\n//we will use a two-dimensional slice to hold our stacks\n//this representation of the stacks will use the first element of each\n//slice as the bottom (i.e. stacks[x][0]). the disc size will be\n//represented by the integer value, higher numbers meaning bigger discs\nvar stacks = [][]int{\n\t[]int{},\n\t[]int{},\n\t[]int{}}\n\nfunc main() {\n\t//get tower height from user input\n\tvar towerHeight int\n\tfor towerHeight <= 1 {\n\t\tfmt.Println(\"Enter tower height\")\n\t\tfmt.Scan(&towerHeight)\n\t}\n\n\t//initialize the first stack\n\tstacks[0] = make([]int, towerHeight)\n\tfor i := range stacks[0] {\n\t\tstacks[0][i] = towerHeight - i\n\t}\n\n\t//display initial stack configuration\n\tfmt.Println(\"This is the starting position\")\n\tprintStacks()\n\n\tmoveTower(towerHeight, 0, 2, 1)\n}\n\nfunc moveTower(height int, from int, to int, help int) {\n\tif height == 1 { //for one-disc-towers, there is nothing else to do but move the disc from start-stack to finish-stack\n\t\tmoveDisc(height, from, to)\n\t} else { //for towers with more than one disk, we use recursion to\n\t\tmoveTower(height-1, from, help, to) //move a smaller tower (all discs but the bottom) to the helper-stack\n\t\tmoveDisc(height, from, to)          //then move the bottom disc to the finish-stack\n\t\tmoveTower(height-1, help, to, from) //and finally move the smaller tower from the helper stack on top of the bottom disk that now sits on the finish-stack\n\t}\n}\n\nfunc moveDisc(index int, from int, to int) {\n\tdisc := stacks[from][len(stacks[from])-1]         //get last element of the origin array\n\tstacks[from] = stacks[from][:len(stacks[from])-1] //new origin array will contain everything except the last element\n\tstacks[to] = append(stacks[to], disc)             //append that element to the destination array\n\n\tfmt.Printf(\"Move disc %d from stack %d to stack %d\\n\", index, from+1, to+1)\n\tprintStacks()\n}\n\nfunc printStacks() {\n\t//for the sake of simplicity, the display will just print out the slices\n\tfor _, stack := range stacks {\n\t\tfmt.Println(stack)\n\t}\n\tfmt.Println()\n}\n"
  },
  {
    "path": "Algorithms/DP/Tower_Of_Hanoi/tower_of_hanoi.py",
    "content": "def TowerOfHanoi(n , source, destination, auxiliary): \n\tif n==1: \n\t\tprint \"Move disk 1 from source\",source,\"to destination\",destination \n\t\treturn\n\tTowerOfHanoi(n-1, source, auxiliary, destination) \n\tprint \"Move disk\",n,\"from source\",source,\"to destination\",destination \n\tTowerOfHanoi(n-1, auxiliary, destination, source) \n\t\t\n \nn = int(input().strip())\nTowerOfHanoi(n,'A','B','C') \n\n"
  },
  {
    "path": "Algorithms/DP/TrappingWater/TrappingWater.cpp",
    "content": "// Author - Nishit Bansal, Nishit278 @github \n// Solution using 2 pointer method  \n// Time Complexity - O(n)\n\n#include <bits/stdc++.h>\nusing namespace std;\n\nint trap(vector<int>& h) {\n        int n = h.size();\n        int left =  0;\n        int maxLeft = 0, maxRight = 0;\n        int right = n-1;\n        int ans = 0;\n        \n        while(left <= right){\n            if(h[left] <= h[right]){\n                if(maxLeft <= h[left]) maxLeft = h[left];\n                else ans+=maxLeft-h[left];\n                left++;\n            } else {\n                if(maxRight <= h[right]) maxRight = h[right];\n                else ans+=maxRight - h[right];\n                right--;\n            }\n        }\n        return ans;\n    }\n\n// Driver's code \nint main(){\n    int n;\n    cin >> n;\n    vector <int> v(n);\n    int x;\n    for(int i=0;i<n;i++){\n        cin>>x;\n        v[i] = x;\n    }\n    \n    cout << trap(v) << endl;\n}"
  },
  {
    "path": "Algorithms/DP/Water_Area/QUESTION.md",
    "content": "### Water Area\n\nYou're given an array of non-negative integers where each non-zero integer represents the height of a pillar of width 1 . Imagine water being poured over all of the pillars; write a function that returns the surface area of the water trapped between the pillars viewed from the front. Note that spilled water should be ignored.\n"
  },
  {
    "path": "Algorithms/DP/Water_Area/Water-area.py",
    "content": "#O(N) T | O(1) S\n\ndef waterArea(heights):\n\twater = 0\t\n\ttallestRight = [0 for x in heights]\n\tmaxHtRight = 0\t\n\ttallestLeft = [0 for x in heights]\n\tmaxHtLeft = 0\t\n\t\n\tfor i in reversed(range(len(tallestRight))):\n\t\ttallestRight[i] = maxHtRight\n\t\tmaxHtRight = max(maxHtRight, heights[i])\n\t\t\n\tfor i in range(len(tallestLeft)):\n\t\ttallestLeft[i] = max(maxHtLeft, heights[i])\n\t\tmaxHtLeft = max(maxHtLeft,heights[i])\n\t\t\n\tfor i in range(len(heights)):\t\t\t\n\t\tleftMax = tallestLeft[i]\n\t\trightMax = tallestRight[i]\t\t\n\t\tminHeight = min(leftMax, rightMax)\n\t\theight = heights[i]\n\t\tif height < minHeight:\n\t\t\twater += minHeight - height\n\t\telse:\t\n\t\t\twater += 0\n\treturn water\n\nheights = input('Enter a list of non-negative numbers separated by spaces without any enclosing braces\\n')\nheights_str = list(heights.split(' '))\nheights_int = [int(height) for height in heights_str]\nwater = waterArea(heights_int)\nprint(water)"
  },
  {
    "path": "Algorithms/DP/Water_Area/water_area.rb",
    "content": "#!/usr/bin/env ruby\n\ndef calculateWaterArea(pillarHeights)\n    waterArea = 0\n    maximumHeightRight = 0\n    maximumHeightLeft = 0\n    tallestFromRight = Array.new(pillarHeights.length())\n    tallestFromLeft = Array.new(pillarHeights.length())\n    \n    \n    (0...tallestFromLeft.length()).each do |i|\n        tallestFromLeft[i] = [maximumHeightLeft, pillarHeights[i]].max\n        maximumHeightLeft = [maximumHeightLeft, pillarHeights[i]].max\n    end\n\n    (0...tallestFromRight.length()).reverse_each do |i|\n        tallestFromRight[i] = maximumHeightRight\n        maximumHeightRight = [maximumHeightRight, pillarHeights[i]].max\n    end\n\n    (0...pillarHeights.length()).each do |i|\n        leftMax = tallestFromLeft[i]\n        rightMax = tallestFromRight[i]\n        minHeight = [leftMax, rightMax].min\n        height = pillarHeights[i]\n        if height < minHeight then\n            waterArea += minHeight - height\n        else\n            waterArea += 0\n        end\n    end\n\n    return waterArea\nend\n\nputs \"Enter a list of positive numbers:\"\nheights = gets.chomp(\" \")\n            .split(\" \")\n            .map(&:to_i)\n\nputs calculateWaterArea(heights)\n"
  },
  {
    "path": "Algorithms/DP/Z_Algorithm/README.md",
    "content": "## This folder is empty.\n"
  },
  {
    "path": "Algorithms/DP/Z_Algorithm/Z-Algorithm.c++",
    "content": "#include<bits/stdc++.h> \nusing namespace std; \n\nvoid getZarr(string str, int Z[]); \nvoid search(string text, string pattern) \n{ \n    \n    string concat = pattern + \"$\" + text; \n    int l = concat.length(); \n    int Z[l]; \n    getZarr(concat, Z); \n    for (int i = 0; i < l; ++i) \n    { \n        if (Z[i] == pattern.length()) \n            cout << \"Pattern found at index \"\n                << i - pattern.length() -1 << endl; \n    } \n} \n\nvoid getZarr(string str, int Z[]) \n{ \n    int n = str.length(); \n    int L, R, k; \n    L = R = 0; \n    for (int i = 1; i < n; ++i) \n    { \n        if (i > R) \n        { \n            L = R = i; \n            while (R<n && str[R-L] == str[R]) \n                R++; \n            Z[i] = R-L; \n            R--; \n        } \n        else\n        { \n            k = i-L; \n            if (Z[k] < R-i+1) \n                Z[i] = Z[k]; \n  \n            else\n            { \n                L = i; \n                while (R<n && str[R-L] == str[R]) \n                    R++; \n                Z[i] = R-L; \n                R--; \n            } \n        } \n    } \n} \n\nint main() \n{ \n    string text , pattern; \n    cout << \"Enter Text in which you want to search pattern :- \"<< \"\\n\";\n    getline(cin , text);\n    cout << \"Enter pattern you want to search  :- \"<< \"\\n\";\n    getline(cin , pattern);\n    search(text, pattern); \n    return 0; \n} "
  },
  {
    "path": "Algorithms/DP/Z_Algorithm/Z_Algo.py",
    "content": "'''\nZ algorithm for string searching.\n@ Author - Sandip Dutta\n'''\n\n# Z Algorithm for String Searching in Linear Time\n'''\nZ Algorithm is a very fast string comparing algorithm.\nIt creates an additional Z Array which stores the length\nof the longest substring from i'th position of the string \nwhich is also a prefix of string.\n\nIf Z[i] matches the length of the pattern, we have found\nthe pattern.\n'''\n\ndef get_Z_arr(pattern, text):\n    ''' Implements the Z-algorithm\n    @ Args:\n    > pattern - (str) String having the pattern\n    > text - (str) The text in which to search the data.\n    @ Return:\n    > Z - The Z array for the data\n    '''\n    # L, R - variables which store the maximum window length\n    L, R, k = 0, 0, 0\n\n    # tempString[L,..., R] is a substring which is a prefix\n\n    # $ is a special character for separating pattern from string\n    tempString = pattern + \"$\" + text \n    totalLength = len(tempString)\n\n    Z = [None] * totalLength # Z array\n\n    for i in range(1, totalLength):    # Fill each element of Z Array\n        # If i is beyond R\n        # use normal way to compute the Z[i]\n        if i > R:\n            # Start from current position\n            L = R = i\n            # while R is within bounds and tempString[0..R] == tempString[i..i+R]\n            while R < totalLength and tempString[R - L] == tempString[R]:\n                R += 1\n            # Z[i] is the largest prefix substring. R-L is the value\n            Z[i] = R - L\n            # [L, R] is the prefix substring, R exits loop with one more than length\n            # Hence adjust the value\n            R -= 1\n\n        # If within [L, R]\n        # Try to do with fewer computations as we already know [L, R]\n        #  is a prefix substring\n        else:\n            # Get k value\n            k = i -  L\n            # Check if i + Z[k] exceeds the string\n            # if does not, fill normally with previous\n            # computed values\n            if Z[k] < R - i + 1:\n                Z[i] = Z[k]\n\n            else:\n                # Recall that [L, R] is the largest substring\n                # If Z[i] where  L <= i <= R and i + Z[i] = t > R\n                # Then [L, t] the largest substring.\n                # Thus we further compute the values to get the proper R\n                L = i\n                while R < totalLength and tempString[R - L] == tempString[R]:\n                    R += 1\n                Z[i] = R - L\n                # Decrease R by 1 to maintain condition\n                R -= 1\n    # print(Z)\n    return Z\n\ndef ZSearch(text, pattern):\n    ''' Searches for pattern using Z Algorithm'''\n    lenPattern = len(pattern)\n    Z = get_Z_arr(pattern, text) # Get the Z array\n\n    patternPositions = [] # Positions where pattern is found\n\n    for element in range(len(Z)):\n        if Z[element] == lenPattern:\n            patternPositions.append(element - lenPattern - 1)\n\n    return patternPositions\n\ndef main():\n    '''Driver Code'''\n    pattern = input(\"Enter the pattern to be found > \")\n    text = input(\"Enter the text where we need to find the pattern > \")\n    positions = ZSearch(text, pattern)\n    if positions:\n        print(f\"Pattern found at indices {positions}\")\n    else:\n        print(\"! Pattern not found\")\n\nif __name__ == '__main__':\n    main()"
  },
  {
    "path": "Algorithms/DP/creating an string input function in C.c",
    "content": "#include <stdio.h>\n\nint input(char str[],int n)\n{\n    int ch;\n    int i=0;\n    while((ch=getchar())!='\\n')\n    {\n        if(i<n)\n        str[i++]=ch;\n    }\n    str[i]='\\0';\n    return i;\n}\n\nint main()\n{\n   char str[100];\n   printf(\"Enter your line \\n\");\n   int n = input(str,20);\n   printf(\"%d %s\",n,str);\n}\n"
  },
  {
    "path": "Algorithms/DP/partition_sum.py",
    "content": "def findPartition(arr, n): \n\tsum = 0\n\ti, j = 0, 0\n\t\n\t# calculate sum of all elements \n\tfor i in range(n): \n\t\tsum += arr[i] \n\t\n\tif sum % 2 != 0: \n\t\treturn false \n\t\n\tpart = [[ True for i in range(n + 1)] \n\t\t\t\tfor j in range(sum // 2 + 1)] \n\t\n\t# initialize top row as true \n\tfor i in range(0, n + 1): \n\t\tpart[0][i] = True\n\n\tfor i in range(1, sum // 2 + 1): \n\t\tpart[i][0] = False\n\tfor i in range(1, sum // 2 + 1): \n\t\tfor j in range(1, n + 1): \n\t\t\tpart[i][j] = part[i][j - 1] \n\t\t\tif i >= arr[j - 1]: \n\t\t\t\tpart[i][j] = (part[i][j] or\n\t\t\t\t\t\t\tpart[i - arr[j - 1]][j - 1]) \n\t\t\n\treturn part[sum // 2][n] \n\t\n# Driver Code \narr = [3, 1, 1, 2, 2, 1] \nn = len(arr) \nif findPartition(arr, n) == True: \n\tprint(\"Can be divided into two\", \n\t\t\t\"subsets of equal sum\") \nelse: \n\tprint(\"Can not be divided into \", \n\t\t\"two subsets of equal sum\") \n"
  },
  {
    "path": "Algorithms/DP/rod-cutting-problem.cpp",
    "content": "/*\nCode by Urjita Sharma\nGiven a rod of length n inches and an array of prices that contains prices of all pieces of size smaller than n. \nDetermine the maximum value obtainable by cutting up the rod and selling the pieces.\n*/\n\n#include <iostream>\n#include <bits/stdc++.h>\n#include <vector>\nusing namespace std;\n\n\nint rodCut(vector<int> price,int n){\n\n    vector<int>val(n+1,INT_MIN);  //max value of rod for each length.\n    val[0]=0; // value of rod of length zero is zero/\\.\n\n    for(int i=1;i<=n;i++){\n        for(int j=0;j<i;j++){\n            val[i]=max(val[i],price[j]+val[i-j-1]);\n        }\n    }\n\n    return val[n]; //max value of rod of length n.\n}\n\n\nint main() {\ncout<<\"Enter length of rod. \";\nint n; cin>>n;\ncout<<endl;\nvector<int> prices(n,0);\n\nfor(int i=0;i<n;i++){\n    cout<<\"Enter price of rod of length \"<<i+1;\n    int x;\n    cin>>x;\n    cout<<endl;\n    prices[i]=x;\n}\ncout<<\"Maximum value of the rod can be - \"<<rodCut(prices,n)<<endl;\n\n}\n"
  },
  {
    "path": "Algorithms/Graph/A_Star/A_star.cpp",
    "content": "#include<bits/stdc++.h> \nusing namespace std; \n#define ROW 9 \n#define COL 10  \ntypedef pair<int, int> Pair;  \ntypedef pair<double, pair<int, int>> pPair;  \nstruct cell \n{ \n\tint parent_i, parent_j;  \n\tdouble f, g, h; \n}; \nbool isValid(int row, int col) \n{ \n\treturn (row >= 0) && (row < ROW) && \n\t\t(col >= 0) && (col < COL); \n}  \nbool isUnBlocked(int grid[][COL], int row, int col) \n{ \n \n\tif (grid[row][col] == 1) \n\t\treturn (true); \n\telse\n\t\treturn (false); \n} \nbool isDestination(int row, int col, Pair dest) \n{ \n\tif (row == dest.first && col == dest.second) \n\t\treturn (true); \n\telse\n\t\treturn (false); \n} \n\ndouble calculateHValue(int row, int col, Pair dest) \n{ \n\treturn ((double)sqrt ((row-dest.first)*(row-dest.first) \n\t\t\t\t\t\t+ (col-dest.second)*(col-dest.second))); \n} \nvoid tracePath(cell cellDetails[][COL], Pair dest) \n{ \n\tprintf (\"\\nThe Path is \"); \n\tint row = dest.first; \n\tint col = dest.second; \n\n\tstack<Pair> Path; \n\n\twhile (!(cellDetails[row][col].parent_i == row \n\t\t\t&& cellDetails[row][col].parent_j == col )) \n\t{ \n\t\tPath.push (make_pair (row, col)); \n\t\tint temp_row = cellDetails[row][col].parent_i; \n\t\tint temp_col = cellDetails[row][col].parent_j; \n\t\trow = temp_row; \n\t\tcol = temp_col; \n\t} \n\n\tPath.push (make_pair (row, col)); \n\twhile (!Path.empty()) \n\t{ \n\t\tpair<int,int> p = Path.top(); \n\t\tPath.pop(); \n\t\tprintf(\"-> (%d,%d) \",p.first,p.second); \n\t} \n\n\treturn; \n} \nvoid aStarSearch(int grid[][COL], Pair src, Pair dest) \n{ \n\t// If the source is out of range \n\tif (isValid (src.first, src.second) == false) \n\t{ \n\t\tprintf (\"Source is invalid\\n\"); \n\t\treturn; \n\t} \n\n\t// If the destination is out of range \n\tif (isValid (dest.first, dest.second) == false) \n\t{ \n\t\tprintf (\"Destination is invalid\\n\"); \n\t\treturn; \n\t} \n\n\t// Either the source or the destination is blocked \n\tif (isUnBlocked(grid, src.first, src.second) == false || \n\t\t\tisUnBlocked(grid, dest.first, dest.second) == false) \n\t{ \n\t\tprintf (\"Source or the destination is blocked\\n\"); \n\t\treturn; \n\t} \n\tif (isDestination(src.first, src.second, dest) == true) \n\t{ \n\t\tprintf (\"We are already at the destination\\n\"); \n\t\treturn; \n\t} \n\n\t\n\tbool closedList[ROW][COL]; \n\tmemset(closedList, false, sizeof (closedList)); \n\n\t\n\tcell cellDetails[ROW][COL]; \n\n\tint i, j; \n\n\tfor (i=0; i<ROW; i++) \n\t{ \n\t\tfor (j=0; j<COL; j++) \n\t\t{ \n\t\t\tcellDetails[i][j].f = FLT_MAX; \n\t\t\tcellDetails[i][j].g = FLT_MAX; \n\t\t\tcellDetails[i][j].h = FLT_MAX; \n\t\t\tcellDetails[i][j].parent_i = -1; \n\t\t\tcellDetails[i][j].parent_j = -1; \n\t\t} \n\t} \n\ti = src.first, j = src.second; \n\tcellDetails[i][j].f = 0.0; \n\tcellDetails[i][j].g = 0.0; \n\tcellDetails[i][j].h = 0.0; \n\tcellDetails[i][j].parent_i = i; \n\tcellDetails[i][j].parent_j = j; \n\n\t\n\tset<pPair> openList; \n\n\t\n\topenList.insert(make_pair (0.0, make_pair (i, j))); \n\tbool foundDest = false; \n\n\twhile (!openList.empty()) \n\t{ \n\t\tpPair p = *openList.begin(); \n\t\topenList.erase(openList.begin()); \n\t\ti = p.second.first; \n\t\tj = p.second.second; \n\t\tclosedList[i][j] = true; \n\t\tdouble gNew, hNew, fNew; \n\t\tif (isValid(i-1, j) == true) \n\t\t{\n\t\t\tif (isDestination(i-1, j, dest) == true) \n\t\t\t{ \n\t\t\t\t// Set the Parent of the destination cell \n\t\t\t\tcellDetails[i-1][j].parent_i = i; \n\t\t\t\tcellDetails[i-1][j].parent_j = j; \n\t\t\t\tprintf (\"The destination cell is found\\n\"); \n\t\t\t\ttracePath (cellDetails, dest); \n\t\t\t\tfoundDest = true; \n\t\t\t\treturn; \n\t\t\t} \n\t\t\telse if (closedList[i-1][j] == false && \n\t\t\t\t\tisUnBlocked(grid, i-1, j) == true) \n\t\t\t{ \n\t\t\t\tgNew = cellDetails[i][j].g + 1.0; \n\t\t\t\thNew = calculateHValue (i-1, j, dest); \n\t\t\t\tfNew = gNew + hNew; \n\n\t\t\t\t\n\t\t\t\tif (cellDetails[i-1][j].f == FLT_MAX || \n\t\t\t\t\t\tcellDetails[i-1][j].f > fNew) \n\t\t\t\t{ \n\t\t\t\t\topenList.insert( make_pair(fNew, \n\t\t\t\t\t\t\t\t\t\t\tmake_pair(i-1, j))); \n\n\t\t\t\t\t// Update the details of this cell \n\t\t\t\t\tcellDetails[i-1][j].f = fNew; \n\t\t\t\t\tcellDetails[i-1][j].g = gNew; \n\t\t\t\t\tcellDetails[i-1][j].h = hNew; \n\t\t\t\t\tcellDetails[i-1][j].parent_i = i; \n\t\t\t\t\tcellDetails[i-1][j].parent_j = j; \n\t\t\t\t} \n\t\t\t} \n\t\t} \n\t\tif (isValid(i+1, j) == true) \n\t\t{\n\t\t\tif (isDestination(i+1, j, dest) == true) \n\t\t\t{ \n\t\t\t\t// Set the Parent of the destination cell \n\t\t\t\tcellDetails[i+1][j].parent_i = i; \n\t\t\t\tcellDetails[i+1][j].parent_j = j; \n\t\t\t\tprintf(\"The destination cell is found\\n\"); \n\t\t\t\ttracePath(cellDetails, dest); \n\t\t\t\tfoundDest = true; \n\t\t\t\treturn; \n\t\t\t} \n\t\t\telse if (closedList[i+1][j] == false && \n\t\t\t\t\tisUnBlocked(grid, i+1, j) == true) \n\t\t\t{ \n\t\t\t\tgNew = cellDetails[i][j].g + 1.0; \n\t\t\t\thNew = calculateHValue(i+1, j, dest); \n\t\t\t\tfNew = gNew + hNew; \n\t\t\t\tif (cellDetails[i+1][j].f == FLT_MAX || \n\t\t\t\t\t\tcellDetails[i+1][j].f > fNew) \n\t\t\t\t{ \n\t\t\t\t\topenList.insert( make_pair (fNew, make_pair (i+1, j))); \n\t\t\t\t\t// Update the details of this cell \n\t\t\t\t\tcellDetails[i+1][j].f = fNew; \n\t\t\t\t\tcellDetails[i+1][j].g = gNew; \n\t\t\t\t\tcellDetails[i+1][j].h = hNew; \n\t\t\t\t\tcellDetails[i+1][j].parent_i = i; \n\t\t\t\t\tcellDetails[i+1][j].parent_j = j; \n\t\t\t\t} \n\t\t\t} \n\t\t} \n\n\t\tif (isValid (i, j+1) == true) \n\t\t{ \n\t\t\t\n\t\t\tif (isDestination(i, j+1, dest) == true) \n\t\t\t{ \n\t\t\t\t// Set the Parent of the destination cell \n\t\t\t\tcellDetails[i][j+1].parent_i = i; \n\t\t\t\tcellDetails[i][j+1].parent_j = j; \n\t\t\t\tprintf(\"The destination cell is found\\n\"); \n\t\t\t\ttracePath(cellDetails, dest); \n\t\t\t\tfoundDest = true; \n\t\t\t\treturn; \n\t\t\t} \n\t\t\telse if (closedList[i][j+1] == false && \n\t\t\t\t\tisUnBlocked (grid, i, j+1) == true) \n\t\t\t{ \n\t\t\t\tgNew = cellDetails[i][j].g + 1.0; \n\t\t\t\thNew = calculateHValue (i, j+1, dest); \n\t\t\t\tfNew = gNew + hNew; \n\n\t\t\t\t\n\t\t\t\tif (cellDetails[i][j+1].f == FLT_MAX || \n\t\t\t\t\t\tcellDetails[i][j+1].f > fNew) \n\t\t\t\t{ \n\t\t\t\t\topenList.insert( make_pair(fNew, \n\t\t\t\t\t\t\t\t\t\tmake_pair (i, j+1))); \n\n\t\t\t\t\t// Update the details of this cell \n\t\t\t\t\tcellDetails[i][j+1].f = fNew; \n\t\t\t\t\tcellDetails[i][j+1].g = gNew; \n\t\t\t\t\tcellDetails[i][j+1].h = hNew; \n\t\t\t\t\tcellDetails[i][j+1].parent_i = i; \n\t\t\t\t\tcellDetails[i][j+1].parent_j = j; \n\t\t\t\t} \n\t\t\t} \n\t\t} \n\n\t\tif (isValid(i, j-1) == true) \n\t\t{ \n\t\t\t// If the destination cell is the same as the \n\t\t\t// current successor \n\t\t\tif (isDestination(i, j-1, dest) == true) \n\t\t\t{ \n\t\t\t\t// Set the Parent of the destination cell \n\t\t\t\tcellDetails[i][j-1].parent_i = i; \n\t\t\t\tcellDetails[i][j-1].parent_j = j; \n\t\t\t\tprintf(\"The destination cell is found\\n\"); \n\t\t\t\ttracePath(cellDetails, dest); \n\t\t\t\tfoundDest = true; \n\t\t\t\treturn; \n\t\t\t} \n\t\t\telse if (closedList[i][j-1] == false && \n\t\t\t\t\tisUnBlocked(grid, i, j-1) == true) \n\t\t\t{ \n\t\t\t\tgNew = cellDetails[i][j].g + 1.0; \n\t\t\t\thNew = calculateHValue(i, j-1, dest); \n\t\t\t\tfNew = gNew + hNew; \n\n\t\t\t\t\n\t\t\t\tif (cellDetails[i][j-1].f == FLT_MAX || \n\t\t\t\t\t\tcellDetails[i][j-1].f > fNew) \n\t\t\t\t{ \n\t\t\t\t\topenList.insert( make_pair (fNew, \n\t\t\t\t\t\t\t\t\t\tmake_pair (i, j-1))); \n\n\t\t\t\t\t// Update the details of this cell \n\t\t\t\t\tcellDetails[i][j-1].f = fNew; \n\t\t\t\t\tcellDetails[i][j-1].g = gNew; \n\t\t\t\t\tcellDetails[i][j-1].h = hNew; \n\t\t\t\t\tcellDetails[i][j-1].parent_i = i; \n\t\t\t\t\tcellDetails[i][j-1].parent_j = j; \n\t\t\t\t} \n\t\t\t} \n\t\t} \n\n\t\t//----------- 5th Successor (North-East) ------------ \n\n\t\t// Only process this cell if this is a valid one \n\t\tif (isValid(i-1, j+1) == true) \n\t\t{\n\t\t\tif (isDestination(i-1, j+1, dest) == true) \n\t\t\t{ \n\t\t\t\t// Set the Parent of the destination cell \n\t\t\t\tcellDetails[i-1][j+1].parent_i = i; \n\t\t\t\tcellDetails[i-1][j+1].parent_j = j; \n\t\t\t\tprintf (\"The destination cell is found\\n\"); \n\t\t\t\ttracePath (cellDetails, dest); \n\t\t\t\tfoundDest = true; \n\t\t\t\treturn; \n\t\t\t} \n\n\t\t\t\n\t\t\telse if (closedList[i-1][j+1] == false && \n\t\t\t\t\tisUnBlocked(grid, i-1, j+1) == true) \n\t\t\t{ \n\t\t\t\tgNew = cellDetails[i][j].g + 1.414; \n\t\t\t\thNew = calculateHValue(i-1, j+1, dest); \n\t\t\t\tfNew = gNew + hNew; \n\t\t\t\tif (cellDetails[i-1][j+1].f == FLT_MAX || \n\t\t\t\t\t\tcellDetails[i-1][j+1].f > fNew) \n\t\t\t\t{ \n\t\t\t\t\topenList.insert( make_pair (fNew, \n\t\t\t\t\t\t\t\t\tmake_pair(i-1, j+1))); \n\n\t\t\t\t\t// Update the details of this cell \n\t\t\t\t\tcellDetails[i-1][j+1].f = fNew; \n\t\t\t\t\tcellDetails[i-1][j+1].g = gNew; \n\t\t\t\t\tcellDetails[i-1][j+1].h = hNew; \n\t\t\t\t\tcellDetails[i-1][j+1].parent_i = i; \n\t\t\t\t\tcellDetails[i-1][j+1].parent_j = j; \n\t\t\t\t} \n\t\t\t} \n\t\t} \n\t\tif (isValid (i-1, j-1) == true) \n\t\t{ \n\t\t\tif (isDestination (i-1, j-1, dest) == true) \n\t\t\t{ \n\t\t\t\t// Set the Parent of the destination cell \n\t\t\t\tcellDetails[i-1][j-1].parent_i = i; \n\t\t\t\tcellDetails[i-1][j-1].parent_j = j; \n\t\t\t\tprintf (\"The destination cell is found\\n\"); \n\t\t\t\ttracePath (cellDetails, dest); \n\t\t\t\tfoundDest = true; \n\t\t\t\treturn; \n\t\t\t} \n\t\t\telse if (closedList[i-1][j-1] == false && \n\t\t\t\t\tisUnBlocked(grid, i-1, j-1) == true) \n\t\t\t{ \n\t\t\t\tgNew = cellDetails[i][j].g + 1.414; \n\t\t\t\thNew = calculateHValue(i-1, j-1, dest); \n\t\t\t\tfNew = gNew + hNew; \n\t\t\t\tif (cellDetails[i-1][j-1].f == FLT_MAX || \n\t\t\t\t\t\tcellDetails[i-1][j-1].f > fNew) \n\t\t\t\t{ \n\t\t\t\t\topenList.insert( make_pair (fNew, make_pair (i-1, j-1))); \n\t\t\t\t\t// Update the details of this cell \n\t\t\t\t\tcellDetails[i-1][j-1].f = fNew; \n\t\t\t\t\tcellDetails[i-1][j-1].g = gNew; \n\t\t\t\t\tcellDetails[i-1][j-1].h = hNew; \n\t\t\t\t\tcellDetails[i-1][j-1].parent_i = i; \n\t\t\t\t\tcellDetails[i-1][j-1].parent_j = j; \n\t\t\t\t} \n\t\t\t} \n\t\t} \n\n\t\t//----------- 7th Successor (South-East) ------------ \n\n\t\t// Only process this cell if this is a valid one \n\t\tif (isValid(i+1, j+1) == true) \n\t\t{ \n\t\t\t// If the destination cell is the same as the \n\t\t\t// current successor \n\t\t\tif (isDestination(i+1, j+1, dest) == true) \n\t\t\t{ \n\t\t\t\t// Set the Parent of the destination cell \n\t\t\t\tcellDetails[i+1][j+1].parent_i = i; \n\t\t\t\tcellDetails[i+1][j+1].parent_j = j; \n\t\t\t\tprintf (\"The destination cell is found\\n\"); \n\t\t\t\ttracePath (cellDetails, dest); \n\t\t\t\tfoundDest = true; \n\t\t\t\treturn; \n\t\t\t} \n\t\t\telse if (closedList[i+1][j+1] == false && \n\t\t\t\t\tisUnBlocked(grid, i+1, j+1) == true) \n\t\t\t{ \n\t\t\t\tgNew = cellDetails[i][j].g + 1.414; \n\t\t\t\thNew = calculateHValue(i+1, j+1, dest); \n\t\t\t\tfNew = gNew + hNew; \n\t\t\t\tif (cellDetails[i+1][j+1].f == FLT_MAX || \n\t\t\t\t\t\tcellDetails[i+1][j+1].f > fNew) \n\t\t\t\t{ \n\t\t\t\t\topenList.insert(make_pair(fNew, \n\t\t\t\t\t\t\t\t\t\tmake_pair (i+1, j+1))); \n\n\t\t\t\t\t// Update the details of this cell \n\t\t\t\t\tcellDetails[i+1][j+1].f = fNew; \n\t\t\t\t\tcellDetails[i+1][j+1].g = gNew; \n\t\t\t\t\tcellDetails[i+1][j+1].h = hNew; \n\t\t\t\t\tcellDetails[i+1][j+1].parent_i = i; \n\t\t\t\t\tcellDetails[i+1][j+1].parent_j = j; \n\t\t\t\t} \n\t\t\t} \n\t\t} \n\n\t\t//----------- 8th Successor (South-West) ------------ \n\n\t\t// Only process this cell if this is a valid one \n\t\tif (isValid (i+1, j-1) == true) \n\t\t{ \n\t\t\t// If the destination cell is the same as the \n\t\t\t// current successor \n\t\t\tif (isDestination(i+1, j-1, dest) == true) \n\t\t\t{ \n\t\t\t\t// Set the Parent of the destination cell \n\t\t\t\tcellDetails[i+1][j-1].parent_i = i; \n\t\t\t\tcellDetails[i+1][j-1].parent_j = j; \n\t\t\t\tprintf(\"The destination cell is found\\n\"); \n\t\t\t\ttracePath(cellDetails, dest); \n\t\t\t\tfoundDest = true; \n\t\t\t\treturn; \n\t\t\t} \n\n\t\t\t// If the successor is already on the closed \n\t\t\t// list or if it is blocked, then ignore it. \n\t\t\t// Else do the following \n\t\t\telse if (closedList[i+1][j-1] == false && \n\t\t\t\t\tisUnBlocked(grid, i+1, j-1) == true) \n\t\t\t{ \n\t\t\t\tgNew = cellDetails[i][j].g + 1.414; \n\t\t\t\thNew = calculateHValue(i+1, j-1, dest); \n\t\t\t\tfNew = gNew + hNew; \n\n\t\t\t\t\n\t\t\t\tif (cellDetails[i+1][j-1].f == FLT_MAX || \n\t\t\t\t\t\tcellDetails[i+1][j-1].f > fNew) \n\t\t\t\t{ \n\t\t\t\t\topenList.insert(make_pair(fNew, \n\t\t\t\t\t\t\t\t\t\tmake_pair(i+1, j-1))); \n\n\t\t\t\t\t// Update the details of this cell \n\t\t\t\t\tcellDetails[i+1][j-1].f = fNew; \n\t\t\t\t\tcellDetails[i+1][j-1].g = gNew; \n\t\t\t\t\tcellDetails[i+1][j-1].h = hNew; \n\t\t\t\t\tcellDetails[i+1][j-1].parent_i = i; \n\t\t\t\t\tcellDetails[i+1][j-1].parent_j = j; \n\t\t\t\t} \n\t\t\t} \n\t\t} \n\t} \n\tif (foundDest == false) \n\t\tprintf(\"Failed to find the Destination Cell\\n\"); \n\n\treturn; \n} \n\n\n// Driver program to test above function \nint main() \n{ \n\t/* Description of the Grid- \n\t1--> The cell is not blocked \n\t0--> The cell is blocked */\n\tint grid[ROW][COL] = \n\t{ \n\t\t{ 1, 0, 1, 1, 1, 1, 0, 1, 1, 1 }, \n\t\t{ 1, 1, 1, 0, 1, 1, 1, 0, 1, 1 }, \n\t\t{ 1, 1, 1, 0, 1, 1, 0, 1, 0, 1 }, \n\t\t{ 0, 0, 1, 0, 1, 0, 0, 0, 0, 1 }, \n\t\t{ 1, 1, 1, 0, 1, 1, 1, 0, 1, 0 }, \n\t\t{ 1, 0, 1, 1, 1, 1, 0, 1, 0, 0 }, \n\t\t{ 1, 0, 0, 0, 0, 1, 0, 0, 0, 1 }, \n\t\t{ 1, 0, 1, 1, 1, 1, 0, 1, 1, 1 }, \n\t\t{ 1, 1, 1, 0, 0, 0, 1, 0, 0, 1 } \n\t}; \n\n\t// Source is the left-most bottom-most corner \n\tPair src = make_pair(8, 0); \n\n\t// Destination is the left-most top-most corner \n\tPair dest = make_pair(0, 0); \n\n\taStarSearch(grid, src, dest); \n\n\treturn(0); \n}\n"
  },
  {
    "path": "Algorithms/Graph/A_Star/A_star.cs",
    "content": "using System;\nusing System.Collections.Generic;\nusing System.Drawing;\nusing System.Linq;\n\n//Please use Wikipedia to see, what A* is and how it works. I will try to point out as much as i can inside\n//my comments, but a complete explanation would blow up this file.\n\n//In this implementation, i do not support diagonal movement to reduce a little complexity and\n//eliminate the need for a rule about movement through diagonal walls\n\npublic class AStar\n{\n    private readonly IList<Node> _nodes;\n    private readonly Point _start;\n    private readonly Point _finish;\n\n    public AStar(IList<Node> nodes, Point start, Point finish)\n    {\n        _nodes = nodes;\n        _start = start;\n        _finish = finish;\n    }\n\n    public IEnumerable<Point> GetPath()\n    {\n        //select the starting node\n        var startNode = _nodes.Single(n => n.Position == _start);\n        \n        //calculate the path\n        if (PathExists(startNode))\n        {\n            //if a path between start and finish can be found, it can be read via the parentNode\n            //properties that now link from finish to start\n            //(for this example the order is irrelevant, but for other usecases, the result might\n            //have to be reverted to point from start to finish)\n            return ReadPath();\n        }\n\n        return Enumerable.Empty<Point>();\n    }\n\n    private bool PathExists(Node currentNode)\n    {\n        //uncomment following two lines to see A* in action\n        //Tools.PrintMaze(_nodes.ToList(), Enumerable.Empty<Point>().ToList(), _start, _finish,  currentNode.Position);\n        //Console.ReadKey();\n        \n        //set current node state to closed, so that we will not walk back here and create a loop\n        currentNode.State = NodeState.Closed;\n        \n        //get possible next nodes\n        var nextNodes =\n            GetSurroundingWalkableNodes(currentNode) //get a list of all nodes that should be considered for our next move\n                .Select(n => UpdateNodeParameters(n, currentNode)) //update each nodes properties\n                .OrderBy(n => n.EstimatedTotalDistance); //check most promising decisions first\n\n        foreach (var nextNode in nextNodes) //iterate through all possible next nodes\n        {\n            if (nextNode.Position == _finish) //if we reached the finishing point, we're done \n                return true;\n            if (PathExists(nextNode)) //otherwise we'll check our moves from this node on\n                return true; //if the next node reached the finishing point, we're done. otherwise we continue withe the next foreach iteration\n        }\n        //if we checked every possible way and did not reach the finishing point, there is no way\n        return false;\n    }\n\n    private IEnumerable<Node> GetSurroundingWalkableNodes(Node currentNode)\n    {\n        //first, get all four possibly surrounding points of current node\n        //don't worry about nodes that are outside the grid, we'll filter them out next\n        var surroundingPoints = GetSurroundingPoints(currentNode);\n\n        return _nodes\n            .Where(n => surroundingPoints\n                .Contains(n.Position)) //now we have all nodes that exist for surrounding points\n            .Where(n => n.IsWalkable) //filter out all that are not walkable\n            .Where(n => n.State != NodeState.Closed) //filter out all nodes, that already exist in the current path\n            .Where(n =>\n            {\n                switch (n.State)\n                {\n                    case NodeState.Untested: //previously untested nodes are always considered for next move\n                        return true;\n                    case NodeState.Open: //if a node has already been tested, we only consider it, if that new node cannot be reached on a shorter way\n                        if (currentNode.MovesFromStart + 1 < n.MovesFromStart)\n                            return true;\n                        return false;\n                    case NodeState.Closed:\n                        return false;\n                    default:\n                        throw new ArgumentOutOfRangeException();\n                }\n            });\n    }\n\n    private IEnumerable<Point> GetSurroundingPoints(Node currentNode)\n    {\n        yield return new Point(currentNode.Position.X + 1, currentNode.Position.Y);\n        yield return new Point(currentNode.Position.X - 1, currentNode.Position.Y);\n        yield return new Point(currentNode.Position.X, currentNode.Position.Y - 1);\n        yield return new Point(currentNode.Position.X, currentNode.Position.Y + 1);\n    }\n\n    private Node UpdateNodeParameters(Node nextNode, Node currentNode)\n    {\n        //set new parent\n        nextNode.Parent = currentNode;\n        \n        //on this path, this node is one hop further than the parent\n        nextNode.MovesFromStart = currentNode.MovesFromStart + 1; \n        \n        //calculate the straight line distance to finish point. this will stay the same value on each iteration, \n        //so it only needs to be done once\n        if (nextNode.State == NodeState.Untested)\n        {\n            nextNode.StraightLineDistanceToFinish = StraightLineDistance(nextNode.Position, _finish);\n            nextNode.State = NodeState.Open;\n        }\n\n        //return updatedNode\n        return nextNode;\n    }\n\n    private double StraightLineDistance(Point a, Point b)\n    {\n        //simple pythagorean triangle.\n        //no need to worry if b.X-a.X might become negative, because we square it anyway \n        return Math.Sqrt(Math.Pow(b.X - a.X, 2) + Math.Pow(b.Y - a.Y, 2));\n    }\n    \n    private IEnumerable<Point> ReadPath()\n    {\n        yield return _finish;\n        \n        var node = _nodes.First(n => n.Position == _finish);\n        \n        while (node.Parent != null)\n        {\n            yield return node.Parent.Position;\n            node = node.Parent;\n        }\n\n        yield return _start;\n    }\n}\n\npublic class Node \n{\n    public Point Position { get; set; }\n    public int MovesFromStart { get; set; }\n    public double StraightLineDistanceToFinish { get; set; }\n    public double EstimatedTotalDistance => MovesFromStart + StraightLineDistanceToFinish;\n    public NodeState State { get; set; }\n    public bool IsWalkable { get; set; }\n    public Node Parent { get; set; }\n\n    public Node(int x, int y, bool isWalkable)\n    {\n        Position = new Point(x, y);\n        IsWalkable = isWalkable;\n    }\n}\n\npublic enum NodeState\n{\n    Untested = 0,\n    Open = 1,\n    Closed = 2\n}\n\n\n//use dotnet-script to run this file without solution\nprivate const char ObstacleChar = 'x';\nprivate const char FreeFieldChar = '.';\nprivate const char StartingPointChar = 's';\nprivate const char FinishingPointChar = 'f';\nprivate const char PathChar = '*';\n\n\nConsole.WriteLine(\"Enter maze via command line\");\nConsole.WriteLine(\"S = Start\");\nConsole.WriteLine(\"F = Finish\");\nConsole.WriteLine(\"X = Obstacle\");\nConsole.WriteLine(\". = Free Field (actually any char but X, S or F will work)\");\nConsole.WriteLine(\"Empty line will finish maze creation\");\n\nvar maze = new List<Node>();\nPoint? start = null;\nPoint? finish = null;\n\nvar input = Console.ReadLine();\nvar yIndex = 0;\nwhile (!string.IsNullOrEmpty(input))\n{\n    var chars = input\n        .ToLower()\n        .ToCharArray();\n    var xIndex = 0;\n    foreach (var c in chars)\n    {\n        var walkable = c != ObstacleChar;\n        maze.Add(new Node(xIndex, yIndex, walkable));\n        if (c == StartingPointChar)\n            start = new Point(xIndex, yIndex);\n        if (c == FinishingPointChar)\n            finish = new Point(xIndex, yIndex);\n        xIndex++;\n    }\n\n    yIndex++;\n    input = Console.ReadLine();\n}\n\nif (start == null || finish == null) throw new ArgumentException(\"Start and Finish need to be set\");\n\nvar solution = new AStar(maze, start.Value, finish.Value).GetPath().ToList();\n\nTools.PrintMaze(maze, solution, start, finish);\nConsole.WriteLine(solution.Any() ? \"A* found a path\" : \"Could not find a path\");\n    \npublic static class Tools {\n    public static void PrintMaze(List<Node> maze, IList<Point> solution, Point? start, Point? finish, Point? current = null)\n    {\n        Console.Clear();\n\n        var lines = maze\n            .OrderBy(n => n.Position.X)\n            .GroupBy(n => n.Position.Y)\n            .OrderBy(l => l.Key);\n\n        foreach (var line in lines)\n        {\n            foreach (var node in line)\n            {\n                SetConsoleColor(solution, node, current);\n                var character = GetCharacter(solution, start, finish, current, node);\n                Console.Write(character);\n            }\n            Console.WriteLine();\n        }\n\n    }\n\n    private static char GetCharacter(IList<Point> solution, Point? start, Point? finish, Point? current, Node node)\n    {\n        var character = ObstacleChar;\n        if (node.IsWalkable) character = FreeFieldChar;\n        if (solution.Contains(node.Position)) character = PathChar;\n        if (node.Position == start) character = StartingPointChar;\n        if (node.Position == finish) character = FinishingPointChar;\n        if (node.Position == current) character = PathChar;\n        return character;\n    }\n\n    private static void SetConsoleColor(IList<Point> solution, Node node, Point? current)\n    {\n        Console.ForegroundColor = ConsoleColor.White;\n        if (solution.Contains(node.Position)) Console.ForegroundColor = ConsoleColor.Green;\n        if (node.Position == current) Console.ForegroundColor = ConsoleColor.Red;\n    }\n}"
  },
  {
    "path": "Algorithms/Graph/A_Star/A_star.py",
    "content": "class Node:\n    def __init__(self, position:(), parent:()):\n        self.position = position\n        self.parent = parent\n        self.g = 0 \n        self.h = 0 \n        self.f = 0 \n    def __eq__(self, other):\n        return self.position == other.position\n    def __lt__(self, other):\n         return self.f < other.f\n\n    def __repr__(self):\n        return ('({0},{1})'.format(self.position, self.f))\n\ndef draw_grid(map, width, height, spacing=2, **kwargs):\n    for y in range(height):\n        for x in range(width):\n            print('%%-%ds' % spacing % draw_tile(map, (x, y), kwargs), end='')\n        print()\n\ndef draw_tile(map, position, kwargs):\n    \n    value = map.get(position)\n   \n    if 'path' in kwargs and position in kwargs['path']: value = '+'\n    if 'start' in kwargs and position == kwargs['start']: value = '@'\n    if 'goal' in kwargs and position == kwargs['goal']: value = '$'\n   \n    return value \n\ndef astar_search(map, start, end):\n    \n    open = []\n    closed = []\n    \n    start_node = Node(start, None)\n    goal_node = Node(end, None)\n\n    open.append(start_node)\n  \n    while len(open) > 0:\n      \n        open.sort()\n\n        current_node = open.pop(0)\n     \n        closed.append(current_node)\n    \n        if current_node == goal_node:\n            path = []\n            while current_node != start_node:\n                path.append(current_node.position)\n                current_node = current_node.parent\n            return path[::-1]\n       \n        (x, y) = current_node.position\n\n        neighbors = [(x-1, y), (x+1, y), (x, y-1), (x, y+1)]\n\n        for next in neighbors:\n     \n            map_value = map.get(next)\n\n            if(map_value == '#'):\n                continue\n            neighbor = Node(next, current_node)\n            if(neighbor in closed):\n                continue\n      \n            neighbor.g = abs(neighbor.position[0] - start_node.position[0]) + abs(neighbor.position[1] - start_node.position[1])\n            neighbor.h = abs(neighbor.position[0] - goal_node.position[0]) + abs(neighbor.position[1] - goal_node.position[1])\n            neighbor.f = neighbor.g + neighbor.h\n        \n            if(add_to_open(open, neighbor) == True):\n    \n                open.append(neighbor)\n\n    return None\n\ndef add_to_open(open, neighbor):\n    for node in open:\n        if (neighbor == node and neighbor.f >= node.f):\n            return False\n    return True\ndef main():\n    map = {}\n    chars = ['c']\n    start = None\n    end = None\n    width = 0\n    height = 0\n    fp = open('data\\\\maze.in', 'r')\n    \n    while len(chars) > 0:\n        chars = [str(i) for i in fp.readline().strip()]\n        width = len(chars) if width == 0 else width\n        for x in range(len(chars)):\n            map[(x, height)] = chars[x]\n            if(chars[x] == '@'):\n                start = (x, height)\n            elif(chars[x] == '$'):\n                end = (x, height)\n\n        if(len(chars) > 0):\n            height += 1\n    fp.close()\n\n    path = astar_search(map, start, end)\n    print()\n    print(path)\n    print()\n    draw_grid(map, width, height, spacing=1, path=path, start=start, goal=end)\n    print()\n    print('Steps to goal: {0}'.format(len(path)))\n    print()\nif __name__ == \"__main__\": main()\n"
  },
  {
    "path": "Algorithms/Graph/A_Star/A_star.ts",
    "content": "/* GraphNode clas for A* Pathfinding \n parent is parent of the current Node\n position is current psition of the Node in the maze\n g is cost from start to current Node\n h is heuristic based estimated cost for current Node to end Node\n f is total cost of present node: i.e. : f = g + h\n*/\nclass GraphNode {\n    public g: number;\n    public h: number;\n    public f: number;\n    public position: Position;\n    public parent: GraphNode | undefined;\n    constructor(position: Position);\n    constructor(position: Position, parent: GraphNode);\n    constructor(position: Position, parent?: GraphNode) {\n        this.g = 0;\n        this.h = 0;\n        this.f = 0;\n        this.position = position;\n        this.parent = parent;\n    }\n\n    isEqual(other: Position): boolean {\n        return this.position.x == other.x && this.position.y == other.y;\n    }\n}\n\n// Check if node is within the graph\nconst isValid = (grid: number[][], row: number, col: number): boolean => {\n    return row >= 0 && row < grid.length && col >= 0 && col < grid[0].length;\n};\n\n// Check if node is not blocked node\nconst isUnBlocked = (grid: number[][], row: number, col: number) => {\n    return grid[row][col] == 1;\n};\n\nconst reachedDestination = (src: Position, dst: Position) => {\n    return src.x == dst.x && src.y == dst.y;\n};\n\nconst inList = (child: GraphNode, list: GraphNode[]): null | GraphNode => {\n    for (let node of list) {\n        if (node.isEqual(child.position)) {\n            return node;\n        }\n    }\n    return null;\n};\n\nconst aStarSearch = (grid: number[][], src: Position, dst: Position) => {\n    // If source is invalid\n    if (!isValid(grid, src.x, src.y)) {\n        console.log(\"Source is invalid\");\n        return;\n    }\n    // If destionation is invalid\n    if (!isValid(grid, dst.x, dst.y)) {\n        console.log(\"Destination is invalid\");\n    }\n\n    // Check if the source and destination node code is blocked\n    if (!isUnBlocked(grid, src.x, src.y) || !isUnBlocked(grid, dst.x, dst.y)) {\n        console.log(\"Source or the destination is blocked\");\n    }\n\n    //Check the destination node is the same as the source cell\n    if (reachedDestination(src, dst)) {\n        console.log(\"Destination is already reached \");\n    }\n\n    // Initialize startNode and endNode\n    let startNode = new GraphNode(src);\n    let endNode = new GraphNode(dst);\n\n    console.log(startNode);\n    console.log(endNode);\n\n    // Initialize both open and closed list\n    let openList: GraphNode[] = [];\n    let closedList: GraphNode[] = [];\n\n    // Add the start node to open list\n    openList.push(startNode);\n\n    while (openList.length > 0) {\n        // Get the current node\n        let currentNode = openList[0];\n        let currentIndex = 0;\n        for (let i = 0; i < openList.length; i++) {\n            if (openList[i].f < currentNode.f) {\n                currentNode = openList[i];\n                currentIndex = i;\n            }\n        }\n\n        // Pop current off open list, add to closed list\n        openList.splice(currentIndex, 1);\n        closedList.push(currentNode);\n\n        // if the destination node is reached\n        if (currentNode.isEqual(endNode.position)) {\n            let path = [];\n            let current: GraphNode | undefined = currentNode;\n            while (current != undefined) {\n                path.push(current.position);\n                current = current.parent;\n            }\n            return path.reverse();\n        }\n\n        // Generate children\n        let children = [];\n        let neighbours = [\n            new Position(0, -1),\n            new Position(0, 1),\n            new Position(-1, 0),\n            new Position(1, 0),\n            new Position(-1, -1),\n            new Position(-1, 1),\n            new Position(1, -1),\n            new Position(1, 1),\n        ];\n\n        for (let position of neighbours) {\n            // Get node postion\n            let nodePosition = new Position(\n                currentNode.position.x + position.x,\n                currentNode.position.y + position.y\n            );\n\n            // Make sure within the range\n            if (!isValid(grid, nodePosition.x, nodePosition.y)) {\n                continue;\n            }\n\n            if (!isUnBlocked(grid, nodePosition.x, nodePosition.y)) {\n                continue;\n            }\n\n            let newNode = new GraphNode(nodePosition, currentNode);\n            children.push(newNode);\n\n            // Loop through children\n            for (let child of children) {\n                if (inList(child, closedList)) {\n                    continue;\n                }\n\n                child.g = currentNode.g + 1;\n                child.h =\n                    (child.position.x - endNode.position.x) ** 2 +\n                    (child.position.y - endNode.position.y) ** 2;\n                child.f = child.g + child.h;\n\n                let openNode = inList(child, openList);\n                if (openNode && child.g > openNode.g) {\n                    continue;\n                }\n\n                // Add the child to the open list\n                openList.push(child);\n            }\n        }\n    }\n};\n\nclass Position {\n    constructor(public x: number, public y: number) {}\n}\n\n// 1--> The cell is not blocked\n// 0--> The cell is blocked\nlet grid: number[][] = [\n    [1, 0, 1, 1, 1, 1, 0, 1, 1, 1],\n    [1, 1, 1, 0, 1, 1, 1, 0, 1, 1],\n    [1, 1, 1, 0, 1, 1, 0, 1, 0, 1],\n    [0, 0, 1, 0, 1, 0, 0, 0, 0, 1],\n    [1, 1, 1, 0, 1, 1, 1, 0, 1, 0],\n    [1, 0, 1, 1, 1, 1, 0, 1, 0, 0],\n    [1, 0, 0, 0, 0, 1, 0, 0, 0, 1],\n    [1, 0, 1, 1, 1, 1, 0, 1, 1, 1],\n    [1, 1, 1, 0, 0, 0, 1, 0, 0, 1],\n];\n\nlet src = new Position(8, 0);\n\nlet dst = new Position(0, 0);\n\nlet path = aStarSearch(grid, src, dst);\nconsole.log(path);\n"
  },
  {
    "path": "Algorithms/Graph/A_Star/astar.py",
    "content": "class Node():\n    def __init__(self, parent=None, position=None):\n        self.parent = parent\n        self.position = position\n        self.g = 0\n        self.h = 0\n        self.f = 0\n    def __eq__(self, other):\n        return self.position == other.position\ndef astar(maze, start, end):\n    start_node = Node(None, start)\n    start_node.g = start_node.h = start_node.f = 0\n    end_node = Node(None, end)\n    end_node.g = end_node.h = end_node.f = 0\n    open_list = []\n    closed_list = []\n    open_list.append(start_node)\n    while len(open_list) > 0:\n        current_node = open_list[0]\n        current_index = 0\n        for index, item in enumerate(open_list):\n            if item.f < current_node.f:\n                current_node = item\n                current_index = index\n        open_list.pop(current_index)\n        closed_list.append(current_node)\n        if current_node == end_node:\n            path = []\n            current = current_node\n            while current is not None:\n                path.append(current.position)\n                current = current.parent\n            return path[::-1]\n        children = []\n        for new_position in [(0, -1), (0, 1), (-1, 0), (1, 0), (-1, -1), (-1, 1), (1, -1), (1, 1)]:\n            node_position = (current_node.position[0] + new_position[0], current_node.position[1] + new_position[1])\n            if node_position[0] > (len(maze) - 1) or node_position[0] < 0 or node_position[1] > (\n                    len(maze[len(maze) - 1]) - 1) or node_position[1] < 0:\n                continue\n            if maze[node_position[0]][node_position[1]] != 0:\n                continue\n            new_node = Node(current_node, node_position)\n            children.append(new_node)\n        for child in children:\n            for closed_child in closed_list:\n                if child == closed_child:\n                    continue\n            child.g = current_node.g + 1\n            child.h = ((child.position[0] - end_node.position[0]) ** 2) + (\n                    (child.position[1] - end_node.position[1]) ** 2)\n            child.f = child.g + child.h\n            for open_node in open_list:\n                if child == open_node and child.g > open_node.g:\n                    continue\n            open_list.append(child)\ndef main():\n    graph = [[0, 1, 0, 0, 0, 0],\n             [1, 0, 1, 0, 1, 0],\n             [0, 1, 0, 0, 0, 1],\n             [0, 0, 0, 0, 1, 0],\n             [0, 1, 0, 1, 0, 0],\n             [0, 0, 1, 0, 0, 0]\n             ]\n    start = (0, 0)\n    end = (5, 5)\n\n    path1 = astar(graph, start, end)\n    print(path1)\nif __name__ == '__main__':\n    main()\n"
  },
  {
    "path": "Algorithms/Graph/BFS/BFS.c",
    "content": "// BFS algorithm in C\n\n#include <stdio.h>\n#include <stdlib.h>\n#define SIZE 40\n\nstruct queue {\n  int items[SIZE];\n  int front;\n  int rear;\n};\n\nstruct queue* createQueue();\nvoid enqueue(struct queue* q, int);\nint dequeue(struct queue* q);\nvoid display(struct queue* q);\nint isEmpty(struct queue* q);\nvoid printQueue(struct queue* q);\n\nstruct node {\n  int vertex;\n  struct node* next;\n};\n\nstruct node* createNode(int);\n\nstruct Graph {\n  int numVertices;\n  struct node** adjLists;\n  int* visited;\n};\n\n// BFS algorithm\nvoid bfs(struct Graph* graph, int startVertex) {\n  struct queue* q = createQueue();\n\n  graph->visited[startVertex] = 1;\n  enqueue(q, startVertex);\n\n  while (!isEmpty(q)) {\n    printQueue(q);\n    int currentVertex = dequeue(q);\n    printf(\"Visited %d\\n\", currentVertex);\n\n    struct node* temp = graph->adjLists[currentVertex];\n\n    while (temp) {\n      int adjVertex = temp->vertex;\n\n      if (graph->visited[adjVertex] == 0) {\n        graph->visited[adjVertex] = 1;\n        enqueue(q, adjVertex);\n      }\n      temp = temp->next;\n    }\n  }\n}\n\n// Creating a node\nstruct node* createNode(int v) {\n  struct node* newNode = malloc(sizeof(struct node));\n  newNode->vertex = v;\n  newNode->next = NULL;\n  return newNode;\n}\n\n// Creating a graph\nstruct Graph* createGraph(int vertices) {\n  struct Graph* graph = malloc(sizeof(struct Graph));\n  graph->numVertices = vertices;\n\n  graph->adjLists = malloc(vertices * sizeof(struct node*));\n  graph->visited = malloc(vertices * sizeof(int));\n\n  int i;\n  for (i = 0; i < vertices; i++) {\n    graph->adjLists[i] = NULL;\n    graph->visited[i] = 0;\n  }\n\n  return graph;\n}\n\n// Add edge\nvoid addEdge(struct Graph* graph, int src, int dest) {\n  // Add edge from src to dest\n  struct node* newNode = createNode(dest);\n  newNode->next = graph->adjLists[src];\n  graph->adjLists[src] = newNode;\n\n  // Add edge from dest to src\n  newNode = createNode(src);\n  newNode->next = graph->adjLists[dest];\n  graph->adjLists[dest] = newNode;\n}\n\n// Create a queue\nstruct queue* createQueue() {\n  struct queue* q = malloc(sizeof(struct queue));\n  q->front = -1;\n  q->rear = -1;\n  return q;\n}\n\n// Check if the queue is empty\nint isEmpty(struct queue* q) {\n  if (q->rear == -1)\n    return 1;\n  else\n    return 0;\n}\n\n// Adding elements into queue\nvoid enqueue(struct queue* q, int value) {\n  if (q->rear == SIZE - 1)\n    printf(\"\\nQueue is Full!!\");\n  else {\n    if (q->front == -1)\n      q->front = 0;\n    q->rear++;\n    q->items[q->rear] = value;\n  }\n}\n\n// Removing elements from queue\nint dequeue(struct queue* q) {\n  int item;\n  if (isEmpty(q)) {\n    printf(\"Queue is empty\");\n    item = -1;\n  } else {\n    item = q->items[q->front];\n    q->front++;\n    if (q->front > q->rear) {\n      printf(\"Resetting queue \");\n      q->front = q->rear = -1;\n    }\n  }\n  return item;\n}\n\n// Print the queue\nvoid printQueue(struct queue* q) {\n  int i = q->front;\n\n  if (isEmpty(q)) {\n    printf(\"Queue is empty\");\n  } else {\n    printf(\"\\nQueue contains \\n\");\n    for (i = q->front; i < q->rear + 1; i++) {\n      printf(\"%d \", q->items[i]);\n    }\n  }\n}\n\nint main() {\n  struct Graph* graph = createGraph(6);\n  addEdge(graph, 0, 1);\n  addEdge(graph, 0, 2);\n  addEdge(graph, 1, 2);\n  addEdge(graph, 1, 4);\n  addEdge(graph, 1, 3);\n  addEdge(graph, 2, 4);\n  addEdge(graph, 3, 4);\n\n  bfs(graph, 0);\n\n  return 0;\n}\n"
  },
  {
    "path": "Algorithms/Graph/BFS/BFS.cpp",
    "content": "#include<iostream> \n#include <list> \n  \nusing namespace std; \n  \n// This class represents a directed graph using \n// adjacency list representation \nclass Graph \n{ \n    int V;    // No. of vertices \n  \n    // Pointer to an array containing adjacency \n    // lists \n    list<int> *adj;    \npublic: \n    Graph(int V);  // Constructor \n  \n    // function to add an edge to graph \n    void addEdge(int v, int w);  \n  \n    // prints BFS traversal from a given source s \n    void BFS(int s);   \n}; \n  \nGraph::Graph(int V) \n{ \n    this->V = V; \n    adj = new list<int>[V]; \n} \n  \nvoid Graph::addEdge(int v, int w) \n{ \n    adj[v].push_back(w); // Add w to v’s list. \n} \n  \nvoid Graph::BFS(int s) \n{ \n    // Mark all the vertices as not visited \n    bool *visited = new bool[V]; \n    for(int i = 0; i < V; i++) \n        visited[i] = false; \n  \n    // Create a queue for BFS \n    list<int> queue; \n  \n    // Mark the current node as visited and enqueue it \n    visited[s] = true; \n    queue.push_back(s); \n  \n    // 'i' will be used to get all adjacent \n    // vertices of a vertex \n    list<int>::iterator i; \n  \n    while(!queue.empty()) \n    { \n        // Dequeue a vertex from queue and print it \n        s = queue.front(); \n        cout << s << \" \"; \n        queue.pop_front(); \n  \n        // Get all adjacent vertices of the dequeued \n        // vertex s. If a adjacent has not been visited,  \n        // then mark it visited and enqueue it \n        for (i = adj[s].begin(); i != adj[s].end(); ++i) \n        { \n            if (!visited[*i]) \n            { \n                visited[*i] = true; \n                queue.push_back(*i); \n            } \n        } \n    } \n} \n  \n// Driver program to test methods of graph class \nint main() \n{ \n    // Create a graph given in the above diagram \n    Graph g(4); \n    g.addEdge(0, 1); \n    g.addEdge(0, 2); \n    g.addEdge(1, 2); \n    g.addEdge(2, 0); \n    g.addEdge(2, 3); \n    g.addEdge(3, 3); \n  \n    cout << \"Following is Breadth First Traversal \"\n         << \"(starting from vertex 2) \\n\"; \n    g.BFS(2); \n  \n    return 0; \n} \n"
  },
  {
    "path": "Algorithms/Graph/BFS/BFS.go",
    "content": "// Credits: Code inspiration from Milos Gajdos on Cybernetist\n\npackage main\n\nimport (\n    \"container/list\"\n    \"fmt\"\n)\n\n// node is a graph node\ntype node struct {\n    Id string\n    friends map[string]*node\n}\n\n// Nodes returns a list of all graph nodes\nfunc Nodes(n *node) []*node {\n    // track the visited nodes\n    visited := make(map[string]*node)\n    // queue of the nodes to visit\n    queue := list.New()\n    queue.PushBack(n)\n    // add the root node to the map of the visited nodes\n    visited[n.Id] = n\n    \n    for queue.Len() > 0 {\n        qnode := queue.Front()\n        // iterate through all of its friends\n        // mark the visited nodes; enqueue the non-visited\n        for id, node := range qnode.Value.(*node).friends {\n            if _, ok := visited[id]; !ok {\n                visited[id] = node\n                queue.PushBack(node)\n            }\n        }\n        queue.Remove(qnode)\n    }\n    \n    nodes := make([]*node, 0)\n    // collect all the nodes into slice\n    for _, node := range visited {\n        nodes = append(nodes, node)\n    }\n    \n    \n    return nodes\n}\n\nfunc main() {\n    node1 := &node{Id: \"node1\", friends: make(map[string]*node)}\n    node2 := &node{Id: \"node2\", friends: make(map[string]*node)}\n    node3 := &node{Id: \"node3\", friends: make(map[string]*node)}\n    \n    // node2 is directly connected to node1\n    node2.friends[node1.Id] = node1\n    // node3 is directly connected to node2\n    node3.friends[node2.Id] = node2\n    // node1 is direcyly connected to node3\n    node1.friends[node3.Id] = node3\n    \n    // root node; this graph is actually not atree so it does not have a root node\n    root := &node{Id: \"root\", friends: make(map[string]*node)}\n    n := make(map[string]*node)\n    n[root.Id] = root\n    n[root.Id] = friends[node1.Id] = node1\n    n[root.Id] = friends[node2.Id] = node2\n    n[root.Id] = friends[node3.Id] = node3\n    \n    nodes := Nodes(root)\n    for _, node := range nodes {\n        fmt.Printf(\"%+V\\n\", node.Id)\n    }\n    \n}\n    \n    \n\n}\n\n\n"
  },
  {
    "path": "Algorithms/Graph/BFS/BFS.java",
    "content": "import java.io.*; \nimport java.util.*; \n  \n// This class represents a directed graph using adjacency list \n// representation \nclass Graph \n{ \n    private int V;   // No. of vertices \n    private LinkedList<Integer> adj[]; //Adjacency Lists \n  \n    // Constructor \n    Graph(int v) \n    { \n        V = v; \n        adj = new LinkedList[v]; \n        for (int i=0; i<v; ++i) \n            adj[i] = new LinkedList(); \n    } \n  \n    // Function to add an edge into the graph \n    void addEdge(int v,int w) \n    { \n        adj[v].add(w); \n    } \n  \n    // prints BFS traversal from a given source s \n    void BFS(int s) \n    { \n        // Mark all the vertices as not visited(By default \n        // set as false) \n        boolean visited[] = new boolean[V]; \n  \n        // Create a queue for BFS \n        LinkedList<Integer> queue = new LinkedList<Integer>(); \n  \n        // Mark the current node as visited and enqueue it \n        visited[s]=true; \n        queue.add(s); \n  \n        while (queue.size() != 0) \n        { \n            // Dequeue a vertex from queue and print it \n            s = queue.poll(); \n            System.out.print(s+\" \"); \n  \n            // Get all adjacent vertices of the dequeued vertex s \n            // If a adjacent has not been visited, then mark it \n            // visited and enqueue it \n            Iterator<Integer> i = adj[s].listIterator(); \n            while (i.hasNext()) \n            { \n                int n = i.next(); \n                if (!visited[n]) \n                { \n                    visited[n] = true; \n                    queue.add(n); \n                } \n            } \n        } \n    } \n  \n    // Driver method to \n    public static void main(String args[]) \n    { \n        Graph g = new Graph(4); \n  \n        g.addEdge(0, 1); \n        g.addEdge(0, 2); \n        g.addEdge(1, 2); \n        g.addEdge(2, 0); \n        g.addEdge(2, 3); \n        g.addEdge(3, 3); \n  \n        System.out.println(\"Following is Breadth First Traversal \"+ \n                           \"(starting from vertex 2)\"); \n  \n        g.BFS(2); \n    } \n} \n"
  },
  {
    "path": "Algorithms/Graph/BFS/BFS.py",
    "content": "#Created by Timothy Chua\n#Implementation of Breadth First Search in Python\n#References:\n# - https://csacademy.com/app/graph_editor/\n# - https://www.tutorialspoint.com/data_structures_algorithms/graph_data_structure.htm\n\n\n\ndef BFS(graph, point, explored, to_explore):\n    if(len(graph) == len(explored)): #If we have explored every possible point\n      return explored\n\n    else:\n      #We use two lists to track what we've explored and what is there left to explore\n      explored.append(point)\n      for vertice in graph[point]:\n        if(vertice not in explored and vertice not in to_explore): #If the point we encounter isn't explored and not in our to_explore list, we add it.\n          to_explore.append(vertice)\n\n      while(len(to_explore) != 0):\n        vertice = to_explore.pop(0)\n        BFS(graph, vertice, explored, to_explore)\n\n\n      return explored\n\n\n\n\nif __name__ == \"__main__\":\n\n    #Let's construct the graph using a dictionary\n    #The keys of the dictionary are called vertices of the graph\n    #The values of the dictionary are called the edges of the the graph\n    graph = { \"a\" : [\"b\", \"c\"],\n              \"b\" : [\"a\", \"d\"],\n              \"c\" : [\"a\", \"d\"],\n              \"d\" : [\"e\"],\n              \"e\" : [\"d\"]\n            }\n\n    #Let us start with point a on the graph\n    print(BFS(graph, \"b\", [], []))\n"
  },
  {
    "path": "Algorithms/Graph/BFS/BFS.rb",
    "content": "def bfs(node)\n  return nil if node.nil? || root.nil? # nothing to do if there is no node or root to begin the search\n  queue = Queue.new\n  queue.enq(root)\n  result = nil\n  while !queue.empty?\n    value = queue.deq\n    if value.title == node.title && value.rating == node.rating\n      result = value\n      break\n    end\n\n    # keep moving the levels in tree by pushing left and right nodes of tree in queue\n    queue.enq(value.left) if value.left\n    queue.enq(value.right) if value.right\n  end\n\n  result # returns node found in BST else default value nil\nend\n"
  },
  {
    "path": "Algorithms/Graph/BFS/README.md",
    "content": "## This folder is empty.\n"
  },
  {
    "path": "Algorithms/Graph/BFS/bfs.js",
    "content": "function bfs(at) {\n  let queue = [at];\n  // mark the first node as visited\n  visited[at] = true;\n  // adding the first node to the result\n  result.push(at)\n\n  // find the node neighbours\n  let nodes = adjList.get(at);\n  while(queue.length > 0){\n    // take the next node to explore\n    let node = queue.shift();\n    // find the node neighbours\n    let nodes = adjList.get(node);\n    for(let neigh of nodes){\n      if(!visited[neigh]){\n        queue.push(neigh);\n        // mark the node as visited\n        visited[neigh] = true;\n        // adding the node to the explored nodes\n        result.push(neigh); // or you can do something with the node\n      }\n    }\n  }\n}\n\nfunction addNode(node) {\n    // adding the node, at first point to nothing\n    adjList.set(node, []);\n}\n\nfunction addEdge(origin, destination) {\n    // finding the node origin and set the edge to destination\n    adjList.get(origin).push(destination);\n    // finding the node destination and set the edge to origin\n    adjList.get(destination).push(origin);\n}\n\n// T E S T\nconst nodes = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];\nconst edges = [\n    [0, 4],\n    [0, 3],\n    [3, 2],\n    [3, 7],\n    [3, 8],\n    [5, 4],\n    [5, 1],\n    [5, 10],\n    [5, 6],\n    [10, 1],\n];\n\n// define a structure to support the graph\nlet adjList = new Map();\n\n// biulding the nodes of the graph\nnodes.forEach(addNode);\n\n// building the edges\nedges.forEach(edge => addEdge(...edge));\n\n// building an array for the flag of the visited nodes\nlet visited = new Array(nodes.length).fill(false);\n\n// traverse starting from node 0\nlet start_node = 0;\nlet result = [];\nbfs(start_node);\nconsole.log(`the result of traverse the graph from ${start_node} is`, result);"
  },
  {
    "path": "Algorithms/Graph/Bellman_Ford/BellMan_Ford.py",
    "content": "#Bellman-Ford Python Implementation\n#Complexity : O(|V|*|E|) where V = No. of vertices ; E = No. of edges\n\nclass Graph:\n\n\t#Initialise the data structure\n\tdef __init__(self, nodes):\n\t\tself.nodes = nodes\n\t\tself.weighted_edges = []\n\t\n\t#Add edges in the form \n\t#(u -> 1st vertex, v -> 2nd vertex, weight -> weight of u--v)\t\t\n\tdef createEdge(self, u, v, weight):\n\t\tif u>=self.nodes or v>=self.nodes:\n\t\t\t#Taking care of wrong Input\n\t\t\tprint(\"Please enter vertices from 0 to |V|-1\")\n\t\t\texit(0)\n\t\tself.weighted_edges.append((u,v,weight))\n\t\t\n\t\n\t\t\nclass Solution:\n\t\n\t#Print the shortest distances from src to all vertices\n\tdef printSoln(self, dist, src):\n\t\tprint(\"Dist from source : \",src,\" are as follows\")\n\t\tfor vertex,weight in enumerate(dist):\n\t\t\tprint(\"to vertex : \",vertex,\" shortest distance is : \",weight)\n\t\n\t\n\tdef bellmanFord(self, graph, src):\n\t\t#Initialise all distances with infinity and src distance with 0\n\t\tdist = [float(\"inf\")]*graph.nodes\n\t\tdist[src] = 0\n\t\t\n\t\t#Update each edge weight by any smaller weighted path possible\n\t\t#we do it for |V|-1 times to ensure all edge weights have least possible value\n\t\tfor i in range(graph.nodes-1):\n\t\t\t\n\t\t\t#Relax all the edges\n\t\t\tfor u,v,w in graph.weighted_edges:\n\t\t\t\tif dist[u] != float(\"inf\") and dist[v] > dist[u] + w:\n\t\t\t\t\tdist[v] = dist[u] + w\n\t\t\n\t\t#After |V|-1 relaxations if again a shorter edge\n\t\t#found means a negative cycle encountered\n\t\tfor u, v, w in graph.weighted_edges:\n\t\t\tif dist[u] != float(\"inf\") and dist[u] + w < dist[v]:  \n                        \tprint(\"Negative weight cycle detected\")\n                        \t#If negative cycle detected, no solution exists, so return \n                        \treturn\n                #To print the final solution\n\t\tself.printSoln(dist, src)\n                \nif __name__==\"__main__\":\n\t\n\t#Inputs from stdin\n\tV = int(input(\"Enter total vertices in graph : \"))\n\tE = int(input(\"Enter no. of edges : \"))\n\t\n\t#Create a Graph object with |V| vertices\n\tg = Graph(V)\n\t\n\t#Input and Add edges to the graph object g\n\tfor i in range(E):\n\t\tu,v,w = map(int,input(\"Enter u,v,w subjected to (0-|V|-1,0-|V|-1,Any Integer) values seperated by space : \").split())\n\t\tg.createEdge(u, v, w)\n\t\t\n\t#Input Source from which distance is to be calculated\n\tsrc = int(input(\"Select the source : \"))\n\tans = Solution()\n\tprint(\"==================================\")\n\t#Call the Bellman Ford algorithm\n\tans.bellmanFord(g, src)\n                \n                \n                \n                \n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\n\t\t\n"
  },
  {
    "path": "Algorithms/Graph/Bellman_Ford/README.md",
    "content": "Algorithm\n\nFollowing are the detailed steps.\n\nInput: Graph and a source vertex src\nOutput: Shortest distance to all vertices from src. If there is a negative weight cycle, then shortest distances are not calculated, negative weight cycle is reported.\n\n1) This step initializes distances from the source to all vertices as infinite and distance to the source itself as 0. Create an array dist[] of size |V| with all values as infinite except dist[src] where src is source vertex.\n\n2) This step calculates shortest distances. Do following |V|-1 times where |V| is the number of vertices in given graph.\n…..a) Do following for each edge u-v\n………………If dist[v] > dist[u] + weight of edge uv, then update dist[v]\n………………….dist[v] = dist[u] + weight of edge uv\n\n\n\n3) This step reports if there is a negative weight cycle in graph. Do following for each edge u-v\n……If dist[v] > dist[u] + weight of edge uv, then “Graph contains negative weight cycle”\nThe idea of step 3 is, step 2 guarantees the shortest distances if the graph doesn’t contain a negative weight cycle. If we iterate through all edges one more time and get a shorter path for any vertex, then there is a negative weight cycle\n\nHow does this work? \n\nLike other Dynamic Programming Problems, the algorithm calculates shortest paths in a bottom-up manner. It first calculates the shortest distances which have at-most one edge in the path. Then, it calculates the shortest paths with at-most 2 edges, and so on. After the i-th iteration of the outer loop, the shortest paths with at most i edges are calculated. There can be maximum |V| – 1 edges in any simple path, that is why the outer loop runs |v| – 1 times. The idea is, assuming that there is no negative weight cycle, if we have calculated shortest paths with at most i edges, then an iteration over all edges guarantees to give shortest path with at-most (i+1) edges\n"
  },
  {
    "path": "Algorithms/Graph/Bellman_Ford/bellmanFord.cpp",
    "content": "// A C++ program for Bellman-Ford's single source \n// shortest path algorithm. \n#include <bits/stdc++.h> \n\n// a structure to represent a weighted edge in graph \nstruct Edge { \n\tint src, dest, weight; \n}; \n\n// a structure to represent a connected, directed and \n// weighted graph \nstruct Graph { \n\t// V-> Number of vertices, E-> Number of edges \n\tint V, E; \n\n\t// graph is represented as an array of edges. \n\tstruct Edge* edge; \n}; \n\n// Creates a graph with V vertices and E edges \nstruct Graph* createGraph(int V, int E) \n{ \n\tstruct Graph* graph = new Graph; \n\tgraph->V = V; \n\tgraph->E = E; \n\tgraph->edge = new Edge[E]; \n\treturn graph; \n} \n\n// A utility function used to print the solution \nvoid printArr(int dist[], int n) \n{ \n\tprintf(\"Vertex Distance from Source\\n\"); \n\tfor (int i = 0; i < n; ++i) \n\t\tprintf(\"%d \\t\\t %d\\n\", i, dist[i]); \n} \n\n// The main function that finds shortest distances from src to \n// all other vertices using Bellman-Ford algorithm. The function \n// also detects negative weight cycle \nvoid BellmanFord(struct Graph* graph, int src) \n{ \n\tint V = graph->V; \n\tint E = graph->E; \n\tint dist[V]; \n\n\t// Step 1: Initialize distances from src to all other vertices \n\t// as INFINITE \n\tfor (int i = 0; i < V; i++) \n\t\tdist[i] = INT_MAX; \n\tdist[src] = 0; \n\n\t// Step 2: Relax all edges |V| - 1 times. A simple shortest \n\t// path from src to any other vertex can have at-most |V| - 1 \n\t// edges \n\tfor (int i = 1; i <= V - 1; i++) { \n\t\tfor (int j = 0; j < E; j++) { \n\t\t\tint u = graph->edge[j].src; \n\t\t\tint v = graph->edge[j].dest; \n\t\t\tint weight = graph->edge[j].weight; \n\t\t\tif (dist[u] != INT_MAX && dist[u] + weight < dist[v]) \n\t\t\t\tdist[v] = dist[u] + weight; \n\t\t} \n\t} \n\n\t// Step 3: check for negative-weight cycles. The above step \n\t// guarantees shortest distances if graph doesn't contain \n\t// negative weight cycle. If we get a shorter path, then there \n\t// is a cycle. \n\tfor (int i = 0; i < E; i++) { \n\t\tint u = graph->edge[i].src; \n\t\tint v = graph->edge[i].dest; \n\t\tint weight = graph->edge[i].weight; \n\t\tif (dist[u] != INT_MAX && dist[u] + weight < dist[v]) { \n\t\t\tprintf(\"Graph contains negative weight cycle\"); \n\t\t\treturn; // If negative cycle is detected, simply return \n\t\t} \n\t} \n\n\tprintArr(dist, V); \n\n\treturn; \n} \n\n// Driver program to test above functions \nint main() \n{ \n\t/* Let us create the graph given in above example */\n\tint V = 5; // Number of vertices in graph \n\tint E = 8; // Number of edges in graph \n\tstruct Graph* graph = createGraph(V, E); \n\n\t// add edge 0-1 (or A-B in above figure) \n\tgraph->edge[0].src = 0; \n\tgraph->edge[0].dest = 1; \n\tgraph->edge[0].weight = -1; \n\n\t// add edge 0-2 (or A-C in above figure) \n\tgraph->edge[1].src = 0; \n\tgraph->edge[1].dest = 2; \n\tgraph->edge[1].weight = 4; \n\n\t// add edge 1-2 (or B-C in above figure) \n\tgraph->edge[2].src = 1; \n\tgraph->edge[2].dest = 2; \n\tgraph->edge[2].weight = 3; \n\n\t// add edge 1-3 (or B-D in above figure) \n\tgraph->edge[3].src = 1; \n\tgraph->edge[3].dest = 3; \n\tgraph->edge[3].weight = 2; \n\n\t// add edge 1-4 (or A-E in above figure) \n\tgraph->edge[4].src = 1; \n\tgraph->edge[4].dest = 4; \n\tgraph->edge[4].weight = 2; \n\n\t// add edge 3-2 (or D-C in above figure) \n\tgraph->edge[5].src = 3; \n\tgraph->edge[5].dest = 2; \n\tgraph->edge[5].weight = 5; \n\n\t// add edge 3-1 (or D-B in above figure) \n\tgraph->edge[6].src = 3; \n\tgraph->edge[6].dest = 1; \n\tgraph->edge[6].weight = 1; \n\n\t// add edge 4-3 (or E-D in above figure) \n\tgraph->edge[7].src = 4; \n\tgraph->edge[7].dest = 3; \n\tgraph->edge[7].weight = -3; \n\n\tBellmanFord(graph, 0); \n\n\treturn 0; \n} \n"
  },
  {
    "path": "Algorithms/Graph/Bellman_Ford/bellman_ford.c",
    "content": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <limits.h>\n \nstruct Edge\n{\n    // This structure is equal to an edge. Edge contains two end points. These edges are directed edges so they\n\t//contain source and destination and some weight. These 3 are elements in this structure\n    int source, destination, weight;\n};\n \n// a structure to represent a connected, directed and weighted graph\nstruct Graph\n{\n    int V, E;\n\t// V is number of vertices and E is number of edges\n \n    struct Edge* edge;\n\t// This structure contain another structure which we already created edge.\n};\n \nstruct Graph* createGraph(int V, int E)\n{\n    struct Graph* graph = (struct Graph*) malloc( sizeof(struct Graph));\n\t//Allocating space to structure graph\n \n    graph->V = V;   //assigning values to structure elements that taken form user.\n \n    graph->E = E;\n \n    graph->edge = (struct Edge*) malloc( graph->E * sizeof( struct Edge ) );\n\t//Creating \"Edge\" type structures inside \"Graph\" structure, the number of edge type structures are equal to number of edges\n \n    return graph;\n}\n \nvoid FinalSolution(int dist[], int n)\n{\n\t// This function prints the final solution\n    printf(\"\\nVertex\\tDistance from Source Vertex\\n\");\n    int i;\n \n    for (i = 0; i < n; ++i){\n\t\tprintf(\"%d \\t\\t %d\\n\", i, dist[i]);\n\t}\n}\n \nvoid BellmanFord(struct Graph* graph, int source)\n{\n    int V = graph->V;\n \n    int E = graph->E;\n \n    int StoreDistance[V];\n \n    int i,j;\n \n    // This is initial step that we know , we initialize all distance to infinity except source.\n\t// We assign source distance as 0(zero)\n \n    for (i = 0; i < V; i++)\n        StoreDistance[i] = INT_MAX;\n \n    StoreDistance[source] = 0;\n \n    //The shortest path of graph that contain V vertices, never contain \"V-1\" edges. So we do here \"V-1\" relaxations\n    for (i = 1; i <= V-1; i++)\n    {\n        for (j = 0; j < E; j++)\n        {\n            int u = graph->edge[j].source;\n \n            int v = graph->edge[j].destination;\n \n            int weight = graph->edge[j].weight;\n \n            if (StoreDistance[u] + weight < StoreDistance[v])\n                StoreDistance[v] = StoreDistance[u] + weight;\n        }\n    }\n \n    // Actually upto now shortest path found. But BellmanFord checks for negative edge cycle. In this step we check for that\n    // shortest distances if graph doesn't contain negative weight cycle.\n \n    // If we get a shorter path, then there is a negative edge cycle.\n    for (i = 0; i < E; i++)\n    {\n        int u = graph->edge[i].source;\n \n        int v = graph->edge[i].destination;\n \n        int weight = graph->edge[i].weight;\n \n        if (StoreDistance[u] + weight < StoreDistance[v])\n            printf(\"This graph contains negative edge cycle\\n\");\n    }\n \n    FinalSolution(StoreDistance, V);\n \n    return;\n}\n \nint main()\n{\n    int V,E,S;  //V = no.of Vertices, E = no.of Edges, S is source vertex\n \n\tprintf(\"Enter number of vertices in graph\\n\");\n    scanf(\"%d\",&V);\n \n\tprintf(\"Enter number of edges in graph\\n\");\n    scanf(\"%d\",&E);\n \n\tprintf(\"Enter your source vertex number\\n\");\n\tscanf(\"%d\",&S);\n \n    struct Graph* graph = createGraph(V, E);    //calling the function to allocate space to these many vertices and edges\n \n    int i;\n    for(i=0;i<E;i++){\n        printf(\"\\nEnter edge %d properties Source, destination, weight respectively\\n\",i+1);\n        scanf(\"%d\",&graph->edge[i].source);\n        scanf(\"%d\",&graph->edge[i].destination);\n        scanf(\"%d\",&graph->edge[i].weight);\n    }\n \n    BellmanFord(graph, S);\n\t//passing created graph and source vertex to BellmanFord Algorithm function\n \n    return 0;\n}\n"
  },
  {
    "path": "Algorithms/Graph/Bidirectional_search/Bidirectional_Search.py",
    "content": "# Python3 program for Bidirectional BFS \n# Search to check path between two vertices\n\n# Class definition for node to\n# be added to graph\nclass AdjacentNode:\n\t\n\tdef __init__(self, vertex):\n\t\t\n\t\tself.vertex = vertex\n\t\tself.next = None\n\n# BidirectionalSearch implementation\nclass BidirectionalSearch:\n\t\n\tdef __init__(self, vertices):\n\t\t\n\t\t# Initialize vertices and\n\t\t# graph with vertices\n\t\tself.vertices = vertices\n\t\tself.graph = [None] * self.vertices\n\t\t\n\t\t# Initializing queue for forward \n\t\t# and backward search\n\t\tself.src_queue = list()\n\t\tself.dest_queue = list()\n\t\t\n\t\t# Initializing source and \n\t\t# destination visited nodes as False\n\t\tself.src_visited = [False] * self.vertices\n\t\tself.dest_visited = [False] * self.vertices\n\t\t\n\t\t# Initializing source and destination \n\t\t# parent nodes\n\t\tself.src_parent = [None] * self.vertices\n\t\tself.dest_parent = [None] * self.vertices\n\t\t\n\t# Function for adding undirected edge \n\tdef add_edge(self, src, dest):\n\t\t\n\t\t# Add edges to graph\n\t\t\n\t\t# Add source to destination\n\t\tnode = AdjacentNode(dest)\n\t\tnode.next = self.graph[src]\n\t\tself.graph[src] = node\n\n\t\t# Since graph is undirected add\n\t\t# destination to source\n\t\tnode = AdjacentNode(src)\n\t\tnode.next = self.graph[dest]\n\t\tself.graph[dest] = node\n\t\t\n\t# Function for Breadth First Search \n\tdef bfs(self, direction = 'forward'):\n\t\t\n\t\tif direction == 'forward':\n\t\t\t\n\t\t\t# BFS in forward direction\n\t\t\tcurrent = self.src_queue.pop(0)\n\t\t\tconnected_node = self.graph[current]\n\t\t\t\n\t\t\twhile connected_node:\n\t\t\t\tvertex = connected_node.vertex\n\t\t\t\t\n\t\t\t\tif not self.src_visited[vertex]:\n\t\t\t\t\tself.src_queue.append(vertex)\n\t\t\t\t\tself.src_visited[vertex] = True\n\t\t\t\t\tself.src_parent[vertex] = current\n\t\t\t\t\t\n\t\t\t\tconnected_node = connected_node.next\n\t\telse:\n\t\t\t\n\t\t\t# BFS in backward direction\n\t\t\tcurrent = self.dest_queue.pop(0)\n\t\t\tconnected_node = self.graph[current]\n\t\t\t\n\t\t\twhile connected_node:\n\t\t\t\tvertex = connected_node.vertex\n\t\t\t\t\n\t\t\t\tif not self.dest_visited[vertex]:\n\t\t\t\t\tself.dest_queue.append(vertex)\n\t\t\t\t\tself.dest_visited[vertex] = True\n\t\t\t\t\tself.dest_parent[vertex] = current\n\t\t\t\t\t\n\t\t\t\tconnected_node = connected_node.next\n\t\t\t\t\n\t# Check for intersecting vertex \n\tdef is_intersecting(self):\n\t\t\n\t\t# Returns intersecting node \n\t\t# if present else -1\n\t\tfor i in range(self.vertices):\n\t\t\tif (self.src_visited[i] and\n\t\t\t\tself.dest_visited[i]):\n\t\t\t\treturn i\n\t\t\t\t\n\t\treturn -1\n\n\t# Print the path from source to target \n\tdef print_path(self, intersecting_node, \n\t\t\t\tsrc, dest):\n\t\t\t\t\t\t\n\t\t# Print final path from \n\t\t# source to destination\n\t\tpath = list()\n\t\tpath.append(intersecting_node)\n\t\ti = intersecting_node\n\t\t\n\t\twhile i != src:\n\t\t\tpath.append(self.src_parent[i])\n\t\t\ti = self.src_parent[i]\n\t\t\t\n\t\tpath = path[::-1]\n\t\ti = intersecting_node\n\t\t\n\t\twhile i != dest:\n\t\t\tpath.append(self.dest_parent[i])\n\t\t\ti = self.dest_parent[i]\n\t\t\t\n\t\tprint(\"*****Path*****\")\n\t\tpath = list(map(str, path))\n\t\t\n\t\tprint(' '.join(path))\n\t\n\t# Function for bidirectional searching \n\tdef bidirectional_search(self, src, dest):\n\t\t\n\t\t# Add source to queue and mark \n\t\t# visited as True and add its\n\t\t# parent as -1\n\t\tself.src_queue.append(src)\n\t\tself.src_visited[src] = True\n\t\tself.src_parent[src] = -1\n\t\t\n\t\t# Add destination to queue and\n\t\t# mark visited as True and add \n\t\t# its parent as -1\n\t\tself.dest_queue.append(dest)\n\t\tself.dest_visited[dest] = True\n\t\tself.dest_parent[dest] = -1\n\n\t\twhile self.src_queue and self.dest_queue:\n\t\t\t\n\t\t\t# BFS in forward direction from\n\t\t\t# Source Vertex\n\t\t\tself.bfs(direction = 'forward')\n\t\t\t\n\t\t\t# BFS in reverse direction \n\t\t\t# from Destination Vertex\n\t\t\tself.bfs(direction = 'backward')\n\t\t\t\n\t\t\t# Check for intersecting vertex\n\t\t\tintersecting_node = self.is_intersecting()\n\t\t\t\n\t\t\t# If intersecting vertex exists\n\t\t\t# then path from source to \n\t\t\t# destination exists\n\t\t\tif intersecting_node != -1:\n\t\t\t\tprint(f\"Path exists between {src} and {dest}\")\n\t\t\t\tprint(f\"Intersection at : {intersecting_node}\")\n\t\t\t\tself.print_path(intersecting_node, \n\t\t\t\t\t\t\t\tsrc, dest)\n\t\t\t\texit(0)\n\t\treturn -1\n\n# Driver code\nif __name__ == '__main__':\n\t\n\t# Number of Vertices in graph\n\tn = 15\n\t\n\t# Source Vertex\n\tsrc = 0\n\t\n\t# Destination Vertex\n\tdest = 14\n\t\n\t# Create a graph\n\tgraph = BidirectionalSearch(n)\n\tgraph.add_edge(0, 4)\n\tgraph.add_edge(1, 4)\n\tgraph.add_edge(2, 5)\n\tgraph.add_edge(3, 5)\n\tgraph.add_edge(4, 6)\n\tgraph.add_edge(5, 6)\n\tgraph.add_edge(6, 7)\n\tgraph.add_edge(7, 8)\n\tgraph.add_edge(8, 9)\n\tgraph.add_edge(8, 10)\n\tgraph.add_edge(9, 11)\n\tgraph.add_edge(9, 12)\n\tgraph.add_edge(10, 13)\n\tgraph.add_edge(10, 14)\n\t\n\tout = graph.bidirectional_search(src, dest)\n\t\n\tif out == -1:\n\t\tprint(f\"Path does not exist between {src} and {dest}\")\n  \n"
  },
  {
    "path": "Algorithms/Graph/Bidirectional_search/Bidirectional_search.cpp",
    "content": "// C++ program for Bidirectional BFS search\n\n#include <bits/stdc++.h>\nusing namespace std;\n\n// class representing undirected graph\n// using adjacency list\nclass Graph\n{\n\t//number of nodes in graph\n\tint V;\n\n\t// Adjacency list\n\tlist<int> *adj;\npublic:\n\tGraph(int V);\n\tint isIntersecting(bool *s_visited, bool *t_visited);\n\tvoid addEdge(int u, int v);\n\tvoid printPath(int *s_parent, int *t_parent, int s,\n\t\t\t\t\t\t\tint t, int intersectNode);\n\tvoid BFS(list<int> *queue, bool *visited, int *parent);\n\tint biDirSearch(int s, int t);\n};\n\nGraph::Graph(int V)\n{\n\tthis->V = V;\n\tadj = new list<int>[V];\n};\n\n// Method for adding undirected edge\nvoid Graph::addEdge(int u, int v)\n{\n\tthis->adj[u].push_back(v);\n\tthis->adj[v].push_back(u);\n};\n\n// Method for Breadth First Search\nvoid Graph::BFS(list<int> *queue, bool *visited,\n\t\t\t\t\t\t\t\t\tint *parent)\n{\n\tint current = queue->front();\n\tqueue->pop_front();\n\tlist<int>::iterator i;\n\tfor (i=adj[current].begin();i != adj[current].end();i++)\n\t{\n\t\t// If adjacent vertex is not visited earlier\n\t\t// mark it visited by assigning true value\n\t\tif (!visited[*i])\n\t\t{\n\t\t\t// set current as parent of this vertex\n\t\t\tparent[*i] = current;\n\n\t\t\t// Mark this vertex visited\n\t\t\tvisited[*i] = true;\n\n\t\t\t// Push to the end of queue\n\t\t\tqueue->push_back(*i);\n\t\t}\n\t}\n};\n\n// check for intersecting vertex\nint Graph::isIntersecting(bool *s_visited, bool *t_visited)\n{\n\tint intersectNode = -1;\n\tfor(int i=0;i<V;i++)\n\t{\n\t\t// if a vertex is visited by both front\n\t\t// and back BFS search return that node\n\t\t// else return -1\n\t\tif(s_visited[i] && t_visited[i])\n\t\t\treturn i;\n\t}\n\treturn -1;\n};\n\n// Print the path from source to target\nvoid Graph::printPath(int *s_parent, int *t_parent,\n\t\t\t\tint s, int t, int intersectNode)\n{\n\tvector<int> path;\n\tpath.push_back(intersectNode);\n\tint i = intersectNode;\n\twhile (i != s)\n\t{\n\t\tpath.push_back(s_parent[i]);\n\t\ti = s_parent[i];\n\t}\n\treverse(path.begin(), path.end());\n\ti = intersectNode;\n\twhile(i != t)\n\t{\n\t\tpath.push_back(t_parent[i]);\n\t\ti = t_parent[i];\n\t}\n\n\tvector<int>::iterator it;\n\tcout<<\"*****Path*****\\n\";\n\tfor(it = path.begin();it != path.end();it++)\n\t\tcout<<*it<<\" \";\n\tcout<<\"\\n\";\n};\n\n// Method for bidirectional searching\nint Graph::biDirSearch(int s, int t)\n{\n\t// boolean array for BFS started from\n\t// source and target(front and backward BFS)\n\t// for keeping track on visited nodes\n\tbool s_visited[V], t_visited[V];\n\n\t// Keep track on parents of nodes\n\t// for front and backward search\n\tint s_parent[V], t_parent[V];\n\n\t// queue for front and backward search\n\tlist<int> s_queue, t_queue;\n\n\tint intersectNode = -1;\n\n\t// necessary initialization\n\tfor(int i=0; i<V; i++)\n\t{\n\t\ts_visited[i] = false;\n\t\tt_visited[i] = false;\n\t}\n\n\ts_queue.push_back(s);\n\ts_visited[s] = true;\n\n\t// parent of source is set to -1\n\ts_parent[s]=-1;\n\n\tt_queue.push_back(t);\n\tt_visited[t] = true;\n\n\t// parent of target is set to -1\n\tt_parent[t] = -1;\n\n\twhile (!s_queue.empty() && !t_queue.empty())\n\t{\n\t\t// Do BFS from source and target vertices\n\t\tBFS(&s_queue, s_visited, s_parent);\n\t\tBFS(&t_queue, t_visited, t_parent);\n\n\t\t// check for intersecting vertex\n\t\tintersectNode = isIntersecting(s_visited, t_visited);\n\n\t\t// If intersecting vertex is found\n\t\t// that means there exist a path\n\t\tif(intersectNode != -1)\n\t\t{\n\t\t\tcout << \"Path exist between \" << s << \" and \"\n\t\t\t\t<< t << \"\\n\";\n\t\t\tcout << \"Intersection at: \" << intersectNode << \"\\n\";\n\n\t\t\t// print the path and exit the program\n\t\t\tprintPath(s_parent, t_parent, s, t, intersectNode);\n\t\t\texit(0);\n\t\t}\n\t}\n\treturn -1;\n}\n\n// Driver code\nint main()\n{\n\t// no of vertices in graph\n\tint n=15;\n\n\t// source vertex\n\tint s=0;\n\n\t// target vertex\n\tint t=14;\n\n\t// create a graph given in above diagram\n\tGraph g(n);\n\tg.addEdge(0, 4);\n\tg.addEdge(1, 4);\n\tg.addEdge(2, 5);\n\tg.addEdge(3, 5);\n\tg.addEdge(4, 6);\n\tg.addEdge(5, 6);\n\tg.addEdge(6, 7);\n\tg.addEdge(7, 8);\n\tg.addEdge(8, 9);\n\tg.addEdge(8, 10);\n\tg.addEdge(9, 11);\n\tg.addEdge(9, 12);\n\tg.addEdge(10, 13);\n\tg.addEdge(10, 14);\n\tif (g.biDirSearch(s, t) == -1)\n\t\tcout << \"Path don't exist between \"\n\t\t\t<< s << \" and \" << t << \"\\n\";\n\n\treturn 0;\n}\n"
  },
  {
    "path": "Algorithms/Graph/Bidirectional_search_algo.py",
    "content": "\n\nclass AdjacentNode:\n\n    def __init__(self, vertex):\n        self.vertex = vertex\n        self.next = None\n\nclass BidirectionalSearch:\n    def __init__(self, vert):\n        self.vertices = vert\n        self.graph = [None] * self.vertices\n        self.src_queue = list()\n        self.dest_queue = list()\n        self.src_visited = [False] * self.vertices\n        self.dest_visited = [False] * self.vertices\n        self.src_parent = [None] * self.vertices\n        self.dest_parent = [None] * self.vertices\n\n    # Function for adding undirected edge\n    def add_edge(self, src, dest):\n        node = AdjacentNode(dest)\n        node.next = self.graph[src]\n        self.graph[src] = node\n        node = AdjacentNode(src)\n        node.next = self.graph[dest]\n        self.graph[dest] = node\n\n    # Function for Breadth First Search\n    def bfs(self, direction='forward'):\n\n        if direction == 'forward':\n            current = self.src_queue.pop(0)\n            connected_node = self.graph[current]\n\n            while connected_node:\n                vertex = connected_node.vertex\n\n                if not self.src_visited[vertex]:\n                    self.src_queue.append(vertex)\n                    self.src_visited[vertex] = True\n                    self.src_parent[vertex] = current\n                connected_node = connected_node.next\n        else:\n            current = self.dest_queue.pop(0)\n            connected_node = self.graph[current]\n            while connected_node:\n                vertex = connected_node.vertex\n                if not self.dest_visited[vertex]:\n                    self.dest_queue.append(vertex)\n                    self.dest_visited[vertex] = True\n                    self.dest_parent[vertex] = current\n                connected_node = connected_node.next\n\n    def is_intersecting(self):\n                                                            # Returns intersecting node\n                                                            # if present else -1\n        for i in range(self.vertices):\n            if (self.src_visited[i] and\n                    self.dest_visited[i]):\n                return i\n\n        return -1\n\n\n    def print_path(self, intersecting_node,src, dest):                  # Print the path from source to target\n        path = list()\n        path.append(intersecting_node)\n        i = intersecting_node\n\n        while i != src:\n            path.append(self.src_parent[i])\n            i = self.src_parent[i]\n\n        path = path[::-1]\n        i = intersecting_node\n\n        while i != dest:\n            path.append(self.dest_parent[i])\n            i = self.dest_parent[i]\n\n        print(\"PATH:--- \")\n        path = list(map(str, path))\n        print(' '.join(path))\n\n    # Function for bidirectional searching\n    def bidirectional_search(self, src, dest):\n        self.src_queue.append(src)\n        self.src_visited[src] = True\n        self.src_parent[src] = -1\n        self.dest_queue.append(dest)\n        self.dest_visited[dest] = True\n        self.dest_parent[dest] = -1\n\n        while self.src_queue and self.dest_queue:\n            self.bfs(direction='forward')\n            self.bfs(direction='backward')\n            intersecting_node = self.is_intersecting()\n            if intersecting_node != -1:\n                print(f\"Path exists between {src} and {dest}\")\n                print(f\"Intersection at : {intersecting_node}\")\n                self.print_path(intersecting_node,\n                                src, dest)\n                exit(0)\n        return -1\n\n\n# Driver code\nif __name__ == '__main__':\n    n = 10\n    src = 0\n    dest = 9\n\n    # Create a graph\n    graph = BidirectionalSearch(n)\n    graph.add_edge(0, 4)\n    graph.add_edge(1, 4)\n    graph.add_edge(2, 5)\n    graph.add_edge(3, 5)\n    graph.add_edge(4, 6)\n    graph.add_edge(5, 6)\n    graph.add_edge(6, 7)\n    graph.add_edge(7, 8)\n    graph.add_edge(8, 9)\n\n    out = graph.bidirectional_search(src, dest)\n\n    if out == -1:\n        print(f\"There is no path exist between {src} and {dest}\")\n"
  },
  {
    "path": "Algorithms/Graph/DFS/DFS.cpp",
    "content": "// C++ program to print DFS traversal from \n// a given vertex in a  given graph \n#include<bits/stdc++.h> \nusing namespace std; \n  \n// Graph class represents a directed graph \n// using adjacency list representation \nclass Graph \n{ \n    int V;    // No. of vertices \n  \n    // Pointer to an array containing \n    // adjacency lists \n    list<int> *adj; \n  \n    // A recursive function used by DFS \n    void DFSUtil(int v, bool visited[]); \npublic: \n    Graph(int V);   // Constructor \n  \n    // function to add an edge to graph \n    void addEdge(int v, int w); \n  \n    // DFS traversal of the vertices \n    // reachable from v \n    void DFS(int v); \n}; \n  \nGraph::Graph(int V) \n{ \n    this->V = V; \n    adj = new list<int>[V]; \n} \n  \nvoid Graph::addEdge(int v, int w) \n{ \n    adj[v].push_back(w); // Add w to v’s list. \n} \n  \nvoid Graph::DFSUtil(int v, bool visited[]) \n{ \n    // Mark the current node as visited and \n    // print it \n    visited[v] = true; \n    cout << v << \" \"; \n  \n    // Recur for all the vertices adjacent \n    // to this vertex \n    list<int>::iterator i; \n    for (i = adj[v].begin(); i != adj[v].end(); ++i) \n        if (!visited[*i]) \n            DFSUtil(*i, visited); \n} \n  \n// DFS traversal of the vertices reachable from v. \n// It uses recursive DFSUtil() \nvoid Graph::DFS(int v) \n{ \n    // Mark all the vertices as not visited \n    bool *visited = new bool[V]; \n    for (int i = 0; i < V; i++) \n        visited[i] = false; \n  \n    // Call the recursive helper function \n    // to print DFS traversal \n    DFSUtil(v, visited); \n} \n  \n// Driver code \nint main() \n{ \n    // Create a graph given in the above diagram \n    Graph g(4); \n    g.addEdge(0, 1); \n    g.addEdge(0, 2); \n    g.addEdge(1, 2); \n    g.addEdge(2, 0); \n    g.addEdge(2, 3); \n    g.addEdge(3, 3); \n  \n    cout << \"Following is Depth First Traversal\"\n            \" (starting from vertex 2) \\n\"; \n    g.DFS(2); \n  \n    return 0; \n} \n"
  },
  {
    "path": "Algorithms/Graph/DFS/DFS.java",
    "content": "// Java program to print DFS traversal from a given given graph \nimport java.io.*; \nimport java.util.*; \n  \n// This class represents a directed graph using adjacency list \n// representation \nclass Graph \n{ \n    private int V;   // No. of vertices \n  \n    // Array  of lists for Adjacency List Representation \n    private LinkedList<Integer> adj[]; \n  \n    // Constructor \n    @SuppressWarnings(\"unchecked\") \n    Graph(int v) \n    { \n        V = v; \n        adj = new LinkedList[v]; \n        for (int i=0; i<v; ++i) \n            adj[i] = new LinkedList(); \n    } \n  \n    //Function to add an edge into the graph \n    void addEdge(int v, int w) \n    { \n        adj[v].add(w);  // Add w to v's list. \n    } \n  \n    // A function used by DFS \n    void DFSUtil(int v,boolean visited[]) \n    { \n        // Mark the current node as visited and print it \n        visited[v] = true; \n        System.out.print(v+\" \"); \n  \n        // Recur for all the vertices adjacent to this vertex \n        Iterator<Integer> i = adj[v].listIterator(); \n        while (i.hasNext()) \n        { \n            int n = i.next(); \n            if (!visited[n]) \n                DFSUtil(n, visited); \n        } \n    } \n  \n    // The function to do DFS traversal. It uses recursive DFSUtil() \n    void DFS(int v) \n    { \n        // Mark all the vertices as not visited(set as \n        // false by default in java) \n        boolean visited[] = new boolean[V]; \n  \n        // Call the recursive helper function to print DFS traversal \n        DFSUtil(v, visited); \n    } \n  \n    public static void main(String args[]) \n    { \n        Graph g = new Graph(4); \n  \n        g.addEdge(0, 1); \n        g.addEdge(0, 2); \n        g.addEdge(1, 2); \n        g.addEdge(2, 0); \n        g.addEdge(2, 3); \n        g.addEdge(3, 3); \n  \n        System.out.println(\"Following is Depth First Traversal \"+ \n                           \"(starting from vertex 2)\"); \n  \n        g.DFS(2); \n    } \n} \n"
  },
  {
    "path": "Algorithms/Graph/DFS/Depth First Search[DFS].cpp",
    "content": "// DFS algorithm in C++\r\n\r\n#include <iostream>\r\n#include <list>\r\nusing namespace std;\r\n\r\nclass Graph {\r\n  int numVertices;\r\n  list<int> *adjLists;\r\n  bool *visited;\r\n\r\n   public:\r\n  Graph(int V);\r\n  void addEdge(int src, int dest);\r\n  void DFS(int vertex);\r\n};\r\n\r\n// Initialize graph\r\nGraph::Graph(int vertices) {\r\n  numVertices = vertices;\r\n  adjLists = new list<int>[vertices];\r\n  visited = new bool[vertices];\r\n}\r\n\r\n// Add edges\r\nvoid Graph::addEdge(int src, int dest) {\r\n  adjLists[src].push_front(dest);\r\n}\r\n\r\n// DFS algorithm\r\nvoid Graph::DFS(int vertex) {\r\n  visited[vertex] = true;\r\n  list<int> adjList = adjLists[vertex];\r\n\r\n  cout << vertex << \" \";\r\n\r\n  list<int>::iterator i;\r\n  for (i = adjList.begin(); i != adjList.end(); ++i)\r\n    if (!visited[*i])\r\n      DFS(*i);\r\n}\r\n\r\nint main() {\r\n  Graph g(4);\r\n  g.addEdge(0, 1); \r\n  g.addEdge(0, 2); \r\n  g.addEdge(1, 2); \r\n  g.addEdge(2, 0); \r\n  g.addEdge(2, 3); \r\n  g.addEdge(3, 3); \r\n  \r\n\r\n  g.DFS(2); \r\n  return 0;\r\n}\r\n\r\n/* \r\nOutput:\r\n2 3 0\r\n*/\r\n"
  },
  {
    "path": "Algorithms/Graph/DFS/README.md",
    "content": "## This folder is empty.\n"
  },
  {
    "path": "Algorithms/Graph/DFS/dfs.js",
    "content": "function dfs(at) {\n  // if we have been visited the node then return\n  if(visited[at]) return;\n  // mark the node as visited\n  visited[at] = true;\n  \n  result.push(at); // or you can do something with the node\n\n  // find the nodes in depth\n  let nodes = adjList.get(at);\n  for (let neigh of nodes) {\n    dfs(neigh);\n  }\n}\n\nfunction addNode(node) {\n  // adding the node, at first point to nothing\n  adjList.set(node, []);\n}\n\nfunction addEdge(origin, destination) {\n  // finding the node origin and set the edge to destination\n  adjList.get(origin).push(destination);\n  // finding the node destination and set the edge to origin\n  adjList.get(destination).push(origin);\n}\n\n// T E S T\nconst nodes = [0,1,2,3,4,5,6,7,8,9,10];\nconst edges = [\n  [0, 4],\n  [0, 3],\n  [3, 2],\n  [3, 7],\n  [3, 8],\n  [5, 4],\n  [5, 1],\n  [5, 10],\n  [5, 6],\n  [10, 1],\n];\n\n// define a structure to support the graph\nlet adjList = new Map();\n\n// biulding the nodes of the graph\nnodes.forEach(addNode);\n\n// building the edges\nedges.forEach(edge=>addEdge(...edge));\n\n// building an array for the flag of the visited nodes\nlet visited = new Array(nodes.length).fill(false);\n\n// traverse starting from node 0\nlet start_node = 0;\nlet result = [];\ndfs(start_node);\nconsole.log(`the result of traverse the graph from ${start_node} is`, result);"
  },
  {
    "path": "Algorithms/Graph/DFS/dfs.py",
    "content": "\"\"\"\nDepth First Search - DFS\n\nA Graph Traversal Algorithm where the nodes in a graph are visited in a depth-first pattern.\ni.e The start or current node is processed and then its adjacent nodes are explored by going deeper into the graph or tree.\n\nSteps\n1. Pick a starting node or vertex.\n2. Process the node by printing or appending to an array.\n3. Mark the node as 'seen' in a set so it doesn't get visited again.\n3. For each current node get its adjacent nodes or edges and repeat processes 1, 2 and 3.\n\nTime complexity  is O(N) since we visit every node at least once. N is the number of nodes in the graph.\nSpace complexity is O(N) since we mark each visited node in a set data structure of size N. \n\n\nSample Graph:\n\n1 - 2 - 5\n|   |      \n4 - 3         , starting node = 1\n\nDFS of this graph with starting node as 1 gives -> [1,2,5,3,4].\nAnother variant could be ->  [1,2,3,4,5].\n\"\"\"\n\n# Test Case\nclass Graph(object):\n    def __init__(self):\n        self.nodes = {} # Stores all nodes\n\n    # Method to add a node\n    def addNode(self, node):\n        self.nodes[node] = []\n\n    # Method to add an edge\n    def addEdge(self, edge):\n        self.nodes[edge[0]].append(edge[1])\n\n    # Method to view graph (all nodes)\n    def peek(self):\n        return self.nodes\n\ntestGraph = Graph()\nnodes = [1, 2, 3, 4,5]\nedges = [[1,2], [1,4], [2,5], [2,3],[3,2], [3,4], [4,1], [4,3], [2,1]]\n\nfor node in nodes:\n    testGraph.addNode(node)\n\nfor edge in edges:\n    testGraph.addEdge(edge)\n\n# Our graph will now look like this\n\n# testGraph = {\n#     1: [2, 4],\n#     2: [5, 3, 1],\n#     3: [2, 4],\n#     4: [1, 3],\n#     5: []\n# }\n\n# Code Implementation\noutput = []\nseen = set()\ncurrNode = 1\n\ndef dfs(currNode):\n\n    if currNode in seen: # Check to see if the current node has been visited.\n        return\n\n    output.append(currNode) # Process the node\n    seen.add(currNode) # Mark it as seen\n\n    edges = testGraph.nodes[currNode] # Get current node's edges\n    for edge in edges:                 # Explore and repeat the process\n        dfs(edge)\n\n\nprint(testGraph.nodes)\nprint(output) # Prints [1,2,5,3,4]\n\n"
  },
  {
    "path": "Algorithms/Graph/DSU/dsu.cpp",
    "content": "/*\nDisjoint Set Union (Union Find) - DSU\n\nDSU is a data structure which is initialized of N sets with 1 element in each, and supports the following operations:\n\nunion_sets(a, b) - unite two sets (the set where element a is located, and the set where element b is located)\nfind_set(v)- return the head (leader) element of the set by one of it's elements\n\nDSU is usually implemented as a tree, where to find head element of a set we go up till the root.\nUsually two optimisations are implemented:\n\n1. path shortening\nlet's say you have a long chain of elements, you can cache the find_set calls and connect the deepest elements to higher elements in the tree to reduce traversion time\n2. ranking system (either via size of a set, or it's depth)\n\nExample test:\n10 10\n2 1\nDSU1: 1\nDSU2: 1\n2 2\nDSU1: 2\nDSU2: 2\n1 1 2\n2 1\nDSU1: 1\nDSU2: 1\n2 2\nDSU1: 1\nDSU2: 1\n2 8\nDSU1: 8\nDSU2: 8\n1 8 2\n2 8\nDSU1: 1\nDSU2: 1\n2 2\nDSU1: 1\nDSU2: 1\n2 5\nDSU1: 5\nDSU2: 5\n\nYou can see that, when uniting set with element 8 and element 2, the smaller set (with 8) is united with the bigger set (with 2)\n*/\n#include <bits/stdc++.h>\nusing namespace std;\n\nclass AbstractDSU\n{\n    /*\n    Time complexity: worst case O(log n), often almost O(1)\n    Space complexity: O(2n)\n\n    Elements are numbered from 1 to n\n\n    @param n number of elements (number of sets)\n    */\nprotected:\n    vector<int> prev, rank;\n    int DEFAULT_RANK = 1;\n\n    /*\n    Checks that element passed is within the required range\n\n    @param x element to check\n    @return Whether the element is within required range\n    */\n    bool process_set_boundaries(int x)\n    {\n        if (x < 1 or x > prev.size())\n            return false;\n        return true;\n    }\n\npublic:\n    AbstractDSU(int n) : prev(n + 1), rank(n + 1)\n    {\n        for (int i = 1; i <= n; i++)\n        {\n            prev[i] = i;\n            rank[i] = DEFAULT_RANK;\n        }\n    }\n    /*\n    Finds the head element of the set that contains the element passed\n\n    @param v element of the set\n    @return Head element of that set\n    */\n    int find_set(int v)\n    {\n        if (!process_set_boundaries(v))\n            return -1;\n        if (v == prev[v]) // if v is root, we found the head element\n            return v;\n        // re-connect the element higher up in the tree to not traverse the long path again\n        return prev[v] = find_set(prev[v]);\n    }\n    /*\n    Unite two sets that contain the elements passed\n\n    @param a element of the first set\n    @param b element of the second set\n    */\n    void union_sets(int a, int b)\n    {\n        if (!process_set_boundaries(a) || !process_set_boundaries(b))\n            return;\n        // Find head elements of each set, if they are equal-there is no need to unite the same set\n        int x = find_set(a), y = find_set(b);\n        if (x == y)\n            return;\n        if (rank[x] < rank[y])\n            swap(x, y);\n        // union set y into bigger set x\n        // the head element of set y gets connected to head element of set x\n        prev[y] = x;\n        update_rank(x, y);\n    }\n    /*\n    Updates the rank of the set that contains the element passed\n\n    Assumes that set x is the bigger set\n\n    @param x element of the first set\n    @param y element of the second set\n    */\n    virtual void update_rank(int x, int y) = 0;\n};\n\nclass DSUBySize : public AbstractDSU\n{\n    int DEFAULT_RANK = 1;\n\npublic:\n    DSUBySize(int n) : AbstractDSU(n) {}\n    void update_rank(int x, int y)\n    {\n        rank[x] += rank[y];\n    }\n};\n\nclass DSUByRank : public AbstractDSU\n{\n    int DEFAULT_RANK = 0;\n\npublic:\n    DSUByRank(int n) : AbstractDSU(n) {}\n    void update_rank(int x, int y)\n    {\n        if (rank[x] == rank[y])\n        {\n            rank[x] += 1;\n        }\n    }\n};\n\nint main()\n{\n    /*\n    Sample program to test it\n    Reads n - number of elements, q - number of queries\n    Then q lines follow with first number being the query type (t)\n    If t=1, then the query is to union sets by their elements x and y\n    If t=2, then the query is to find the set of element x\n    Output -1 if element doesn't belong to any set\n    */\n    int n, q;\n    cin >> n >> q;\n    DSUBySize dsu1(n);\n    DSUByRank dsu2(n);\n    for (int i = 0; i < q; i++)\n    {\n        int t, a, b;\n        cin >> t;\n        if (t == 1)\n        {\n            cin >> a >> b;\n            dsu1.union_sets(a, b);\n            dsu2.union_sets(a, b);\n        }\n        else if (t == 2)\n        {\n            cin >> a;\n            // The outputs should match, as the only difference is ranking strategy which only affects the asymptotic time complexity\n            cout << \"DSU1: \" << dsu1.find_set(a) << endl;\n            cout << \"DSU2: \" << dsu2.find_set(a) << endl;\n        }\n    }\n    return 0;\n}\n"
  },
  {
    "path": "Algorithms/Graph/DSU/dsu.py",
    "content": "\"\"\"\nDisjoint Set Union (Union Find) - DSU\n\nDSU is a data structure which is initialized of N sets with 1 element in each, and supports the following operations:\n\nunion_sets(a, b) - unite two sets (the set where element a is located, and the set where element b is located)\nfind_set(v)- return the head (leader) element of the set by one of it's elements\n\nDSU is usually implemented as a tree, where to find head element of a set we go up till the root.\nUsually two optimisations are implemented:\n\n1. path shortening\nlet's say you have a long chain of elements, you can cache the find_set calls and connect the deepest elements to higher elements in the tree to reduce traversion time\n2. ranking system (either via size of a set, or it's depth)\n\nExample test:\n10 10\n2 1\nDSU1: 1\nDSU2: 1\n2 2\nDSU1: 2\nDSU2: 2\n1 1 2\n2 1\nDSU1: 1\nDSU2: 1\n2 2\nDSU1: 1\nDSU2: 1\n2 8\nDSU1: 8\nDSU2: 8\n1 8 2\n2 8\nDSU1: 1\nDSU2: 1\n2 2\nDSU1: 1\nDSU2: 1\n2 5\nDSU1: 5\nDSU2: 5\n\nYou can see that, when uniting set with element 8 and element 2, the smaller set (with 8) is united with the bigger set (with 2)\n\"\"\"\n\nfrom abc import abstractmethod\n\n\nclass AbstractDSU:\n    \"\"\"DSU\n\n    Time complexity: worst case O(log n), often almost O(1)\n    Space complexity: O(2n)\n\n    Elements are numbered from 1 to n\n\n    Args:\n        n (int): number of elements (number of sets)\n\n    \"\"\"\n\n    DEFAULT_RANK: int\n\n    def __init__(self, n):\n        self.prev = [i for i in range(n + 1)]\n        self.rank = [self.DEFAULT_RANK for i in range(n + 1)]\n\n    def _process_set_boundaries(self, x):\n        \"\"\"Checks that element passed is within the required range\n\n        Args:\n            x (int): element to check\n\n        Returns:\n            bool: Whether the element is within required range\n        \"\"\"\n        # len(X) is O(1)\n        if x < 1 or x > len(self.prev):\n            return False\n        return True\n\n    def find_set(self, v):\n        \"\"\"Finds the head element of the set that contains the element passed\n\n        Args:\n            v (int): element of the set\n\n        Returns:\n            int: Head element of that set\n        \"\"\"\n        if not self._process_set_boundaries(v):\n            return -1\n        if v == self.prev[v]:  # if v is root, we found the head element\n            return v\n        # re-connect the element higher up in the tree to not traverse the long path again\n        self.prev[v] = self.find_set(self.prev[v])\n        return self.prev[v]\n\n    def union_sets(self, a, b):\n        \"\"\"Unite two sets that contain the elements passed\n\n        Args:\n            a (int): element of the first set\n            b (int): element of the second set\n        \"\"\"\n        if not self._process_set_boundaries(a) or not self._process_set_boundaries(b):\n            return\n        # Find head elements of each set, if they are equal-there is no need to unite the same set\n        x = self.find_set(a)\n        y = self.find_set(b)\n        if x == y:\n            return\n        if self.rank[x] < self.rank[y]:\n            x, y = y, x\n        # union set y into bigger set x\n        # the head element of set y gets connected to head element of set x\n        self.prev[y] = x\n        self.update_ranks(x, y)\n\n    @abstractmethod\n    def update_ranks(self, x, y):\n        \"\"\"Updates the rank of the set that contains the element passed\n\n        Assumes that set x is the bigger set\n\n        Args:\n            x (int): element of the first set\n            y (int): element of the second set\n        \"\"\"\n        raise NotImplementedError()\n\n\nclass DSUBySize(AbstractDSU):\n    DEFAULT_RANK = 1\n\n    def update_ranks(self, x, y):\n        self.rank[x] += self.rank[y]\n\n\nclass DSUByRank(AbstractDSU):\n    DEFAULT_RANK = 0\n\n    def update_ranks(self, x, y):\n        if self.rank[x] == self.rank[y]:\n            self.rank[x] += 1\n\n\nif __name__ == \"__main__\":\n    # Sample program to test it\n    # Reads n - number of elements, q - number of queries\n    # Then q lines follow with first number being the query type (t)\n    # If t=1, then the query is to union sets by their elements x and y\n    # If t=2, then the query is to find the set of element x\n    # Output -1 if element doesn't belong to any set\n    n, q = map(int, input().split())\n    dsu1 = DSUBySize(n)\n    dsu2 = DSUByRank(n)\n    for _ in range(q):\n        t, *args = map(int, input().split())\n        if t == 1:\n            dsu1.union_sets(*args)\n            dsu2.union_sets(*args)\n        elif t == 2:\n            # The outputs should match, as the only difference is ranking strategy which only affects the asymptotic time complexity\n            print(f\"DSU1: {dsu1.find_set(args[0])}\")\n            print(f\"DSU2: {dsu2.find_set(args[0])}\")\n"
  },
  {
    "path": "Algorithms/Graph/Depth First Transversal/DFT.py",
    "content": "class graph:\n\n    def __init__(self,gdict=None):\n        if gdict is None:\n            gdict = {}\n        self.gdict = gdict\n# Check for the visisted and unvisited nodes\ndef dfs(graph, start, visited = None):\n    if visited is None:\n        visited = set()\n    visited.add(start)\n    print(start)\n    for next in graph[start] - visited:\n        dfs(graph, next, visited)\n    return visited\n\ngdict = { \"a\" : set([\"b\",\"c\"]),\n                \"b\" : set([\"a\", \"d\"]),\n                \"c\" : set([\"a\", \"d\"]),\n                \"d\" : set([\"e\"]),\n                \"e\" : set([\"a\"])\n                }\n\n\ndfs(gdict, 'a')\n"
  },
  {
    "path": "Algorithms/Graph/Dijkstra/Dijikstra.java",
    "content": "class Dijikstra { \n\tstatic final int V = 9; \n\tint minDistance(int dist[], Boolean sptSet[]) { \n\t\tint min = Integer.MAX_VALUE, min_index = -1; \n\n\t\tfor (int v = 0; v < V; v++) \n\t\t\tif (sptSet[v] == false && dist[v] <= min) { \n\t\t\t\tmin = dist[v]; \n\t\t\t\tmin_index = v; \n\t\t\t} \n\n\t\treturn min_index; \n\t} \n\n\tvoid printSolution(int dist[]) { \n\t\tSystem.out.println(\"Vertex \\t\\t Distance from Source\"); \n\t\tfor (int i = 0; i < V; i++) \n\t\t\tSystem.out.println(i + \" \\t\\t \" + dist[i]); \n    } \n    \n\tvoid dijkstra(int graph[][], int src) { \n\t\tint dist[] = new int[V]; \n        Boolean sptSet[] = new Boolean[V]; \n        \n\t\tfor (int i = 0; i < V; i++) { \n\t\t\tdist[i] = Integer.MAX_VALUE; \n\t\t\tsptSet[i] = false; \n\t\t}  \n\t\tdist[src] = 0; \n\n\t\tfor (int count = 0; count < V - 1; count++) { \n\t\t\tint u = minDistance(dist, sptSet); \n\n\t\t\tsptSet[u] = true; \n\n\t\t\tfor (int v = 0; v < V; v++) \n\t\t\t\tif (!sptSet[v] && graph[u][v] != 0 && dist[u] != Integer.MAX_VALUE && dist[u] + graph[u][v] < dist[v]) \n\t\t\t\t\tdist[v] = dist[u] + graph[u][v]; \n\t\t} \n\t\tprintSolution(dist); \n\t} \n\tpublic static void main(String[] args) { \n\t\tint graph[][] = new int[][] { { 0, 4, 0, 0, 0, 0, 0, 8, 0 }, \n\t\t\t\t\t\t\t\t\t{ 4, 0, 8, 0, 0, 0, 0, 11, 0 }, \n\t\t\t\t\t\t\t\t\t{ 0, 8, 0, 7, 0, 4, 0, 0, 2 }, \n\t\t\t\t\t\t\t\t\t{ 0, 0, 7, 0, 9, 14, 0, 0, 0 }, \n\t\t\t\t\t\t\t\t\t{ 0, 0, 0, 9, 0, 10, 0, 0, 0 }, \n\t\t\t\t\t\t\t\t\t{ 0, 0, 4, 14, 10, 0, 2, 0, 0 }, \n\t\t\t\t\t\t\t\t\t{ 0, 0, 0, 0, 0, 2, 0, 1, 6 }, \n\t\t\t\t\t\t\t\t\t{ 8, 11, 0, 0, 0, 0, 1, 0, 7 }, \n\t\t\t\t\t\t\t\t\t{ 0, 0, 2, 0, 0, 0, 6, 7, 0 } }; \n\t\tDijikstra t = new Dijikstra(); \n\t\tt.dijkstra(graph, 0); \n\t} \n} \n// This code is contributed by Aakash Hasija \n// Source : (Geeks for Geeks)\n// Cleaned by Harsh Kumar"
  },
  {
    "path": "Algorithms/Graph/Dijkstra/Dijkstra.c",
    "content": "#include <stdio.h>\n#include <limits.h>\n#include <stdlib.h>\n\nint getMinVertex(bool* visited,int* distance,int n){\n\tint minVertex = -1;\n\tfor(int i=0;i<n;i++){\n\t\tif( !visited[i] && ( (minVertex==-1) || (distance[i]<distance[minVertex]) )  ){\n\t\t\tminVertex = i;\n\t\t}\n\t}\n\treturn minVertex;\n}\n\nvoid dijkstra(int** edges,int n){\n\tbool* visited = (bool*) calloc(sizeof(bool),n);\n\tint* distance = (int*) calloc(sizeof(int),n);\n\tfor(int i=1;i<n;i++) distance[i] = INT_MAX;\n\n\tfor(int i=0;i<n-1;i++){\n\t\tint minVertex = getMinVertex(visited,distance,n);\n\t\tvisited[minVertex] = true;\n\t\tfor(int j=0;j<n;j++){\n\t\t\tif(!visited[j] && (edges[minVertex][j]))\n\t\t\t\tif( distance[j] > (edges[minVertex][j]+distance[minVertex]) ){\n\t\t\t\t\tdistance[j] = edges[minVertex][j] + distance[minVertex];\n\t\t\t\t}\n\t\t}\n\n\t}\n\n\tfor(int i=0;i<n;i++){\n\t\tprintf(\"%d %d\\n\",i,distance[i]);\n\t}\n\n}\n\nint main(){\n\tint n,e;\n\tprintf(\"Enter number of vertices and the number of edges:\\n\");\n\tscanf(\"%d%d\",&n,&e);\n\tint** edges = (int**) calloc(sizeof(int*),n);\n\tfor(int i=0;i<n;i++) edges[i] = (int*)calloc(sizeof(int),n);\n\n\tprintf(\"Enter the edges along with its weight:\\n\");\n\tfor(int i=0;i<e;i++){\n\t\tint a,b,w;\n\t\tscanf(\"%d%d%d\",&a,&b,&w);\n\t\tedges[a][b] = edges[b][a] = w;\n\t}\n\n\tdijkstra(edges,n);\n\n\treturn 0;\n}\n"
  },
  {
    "path": "Algorithms/Graph/Dijkstra/Dijkstra.cpp",
    "content": "//This program is used to implement Dijkstra's Algorithm using priority queue(min heap)\n\n//Time Complexity: O(ElogV)\n\n#include<iostream>\n#include<list>\n#include<utility>\n#include<queue>\n\nusing namespace std;\n\ntypedef pair<int,int> ipair;      \n\nclass Graph{\n    int v;\n    list<ipair> *adj;\n    public:\n        Graph(int v);\n        void Edge(int edge,int weight,int vertex);\n        void dijkstra_pq(int src);\n};\n\nGraph::Graph(int v){\n    this->v=v;\n    adj=new list<ipair> [v];\n\n}\nvoid Graph::Edge(int u, int v, int w) \n{ \n    adj[u].push_back(make_pair(v, w)); \n    adj[v].push_back(make_pair(u, w)); \n} \n\nvoid Graph::dijkstra_pq(int src){\n    priority_queue<ipair,vector<ipair>,greater<ipair>> pq;  //This is the syntax of creating a min heap using priority queue\n\n    // Create a vector for distances and initialize all \n    // distances as infinite (INF) \n\n    vector<int> dist(v,INT16_MAX);\n\n    //Insert source itself in priority queue and initialize \n    // its distance as 0. \n\n    pq.push(make_pair(0,src));\n    dist[src]=0;\n    while(!pq.empty()){\n        int u=pq.top().second;\n        pq.pop();\n        \n        for(auto i=adj[u].begin();i!=adj[u].end();i++){\n            int V=(*i).first;\n            int w=(*i).second;\n            if(dist[V]>dist[u]+w){       // Edge Relaxation\n                dist[V]=dist[u]+w;\n                pq.push(make_pair(dist[V],V));\n            }\n        }\n    }\n\n    // Print shortest distances stored in dist[] \n    \n    cout<<\"Vertex\\t\\tDistance\"<<endl;\n    for(int i=0;i<v;i++){\n        cout<<i<<\"\\t\\t\"<<dist[i]<<endl;\n    }\n}\n\nint main(){\n    int v=9;\n Graph g(v);\n    g.Edge(0, 1, 4); \n    g.Edge(0, 7, 8); \n    g.Edge(1, 2, 8); \n    g.Edge(1, 7, 11); \n    g.Edge(2, 3, 7); \n    g.Edge(2, 8, 2); \n    g.Edge(2, 5, 4); \n    g.Edge(3, 4, 9); \n    g.Edge(3, 5, 14); \n    g.Edge(4, 5, 10); \n    g.Edge(5, 6, 2); \n    g.Edge(6, 7, 1); \n    g.Edge(6, 8, 6); \n    g.Edge(7, 8, 7); \n\n    g.dijkstra_pq(0);\n    return 0;\n}\n\n\n"
  },
  {
    "path": "Algorithms/Graph/Dijkstra/Dijkstra.cs",
    "content": "using System; \r\n\r\nclass DA {\r\n    static int V = 9; \r\n    int minDistance(int[] dist, \r\n                    bool[] sptSet) \r\n    { \r\n        int min = int.MaxValue, min_index = -1; \r\n  \r\n        for (int v = 0; v < V; v++)\r\n            if (sptSet[v] == false && dist[v] <= min) { \r\n                min = dist[v]; \r\n                min_index = v; \r\n            }\r\n        return min_index; \r\n    } \r\n  \r\n    void printSolution(int[] dist, int n) \r\n    { \r\n        Console.Write(\"Vertex     Distance \" + \"from Source\\n\"); \r\n        for (int i = 0; i < V; i++) \r\n            Console.Write(i + \" \\t\\t \" + dist[i] + \"\\n\"); \r\n    } \r\n  \r\n    void dijkstra(int[, ] graph, int src) \r\n    { \r\n        int[] dist = new int[V]; // The output array. dist[i] \r\n        bool[] sptSet = new bool[V]; \r\n \r\n        for (int i = 0; i < V; i++) { \r\n            dist[i] = int.MaxValue; \r\n            sptSet[i] = false; \r\n        } \r\n  \r\n        dist[src] = 0; \r\n  \r\n        // To find shortest path for all the vertices \r\n        for (int count = 0; count < V - 1; count++) { \r\n            int u = minDistance(dist, sptSet); \r\n\r\n            sptSet[u] = true; \r\n            for (int v = 0; v < V; v++) \r\n                if (!sptSet[v] && graph[u, v] != 0 &&  \r\n                     dist[u] != int.MaxValue && dist[u] + graph[u, v] < dist[v]) \r\n                    dist[v] = dist[u] + graph[u, v]; \r\n        } \r\n  \r\n        printSolution(dist, V); \r\n    } \r\n  \r\n    public static void Main() \r\n    {  \r\n        int[, ] graph = new int[, ] { { 0, 4, 0, 0, 0, 0, 0, 8, 0 }, \r\n                                      { 4, 0, 8, 0, 0, 0, 0, 11, 0 }, \r\n                                      { 0, 8, 0, 7, 0, 4, 0, 0, 2 }, \r\n                                      { 0, 0, 7, 0, 9, 14, 0, 0, 0 }, \r\n                                      { 0, 0, 0, 9, 0, 10, 0, 0, 0 }, \r\n                                      { 0, 0, 4, 14, 10, 0, 2, 0, 0 }, \r\n                                      { 0, 0, 0, 0, 0, 2, 0, 1, 6 }, \r\n                                      { 8, 11, 0, 0, 0, 0, 1, 0, 7 }, \r\n                                      { 0, 0, 2, 0, 0, 0, 6, 7, 0 } }; \r\n        DA t = new DA(); \r\n        t.dijkstra(graph, 0); \r\n    } \r\n} "
  },
  {
    "path": "Algorithms/Graph/Dijkstra/Dijkstra.go",
    "content": "package main\n\nimport (\n\t\"container/heap\"\n\t\"fmt\"\n)\n\n// A PriorityQueue implements heap.Interface (Golang standard library)\ntype PriorityQueue struct {\n\titems    []Vertex\n\tindex    map[Vertex]int // value to index\n\tpriority map[Vertex]int // value to priority\n}\n\nfunc (pq *PriorityQueue) Len() int {\n\treturn len(pq.items)\n}\n\nfunc (pq *PriorityQueue) Less(i, j int) bool {\n\treturn pq.priority[pq.items[i]] < pq.priority[pq.items[j]]\n}\n\nfunc (pq *PriorityQueue) Swap(i, j int) {\n\tpq.items[i], pq.items[j] = pq.items[j], pq.items[i]\n\tpq.index[pq.items[i]] = i\n\tpq.index[pq.items[j]] = j\n}\n\nfunc (pq *PriorityQueue) Push(x interface{}) {\n\tn := len(pq.items)\n\titem := x.(Vertex)\n\tpq.index[item] = n\n\tpq.items = append(pq.items, item)\n}\n\nfunc (pq *PriorityQueue) Pop() interface{} {\n\told := pq.items\n\tn := len(old)\n\titem := old[n-1]\n\tpq.index[item] = -1\n\tpq.items = old[0 : n-1]\n\treturn item\n}\n\nfunc (pq *PriorityQueue) update(item Vertex, priority int) {\n\tpq.priority[item] = priority\n\theap.Fix(pq, pq.index[item])\n}\n\nfunc (pq *PriorityQueue) addWithPriority(item Vertex, priority int) {\n\theap.Push(pq, item)\n\tpq.update(item, priority)\n}\n\n// Graph is the interface so that this algorithm can run on.\ntype Graph interface {\n\tVertices() []Vertex\n\tNeighbors(v Vertex) []Vertex\n\tWeight(u, v Vertex) int\n}\n\n// Vertex is type alias int\ntype Vertex int\n\n// DijkstraGraph is a graph of strings that satisfies the Graph interface.\n// this graph has label and index, so you can customize the label and the index\ntype DijkstraGraph struct {\n\tids   map[string]Vertex\n\tnames map[Vertex]string\n\tedges map[Vertex]map[Vertex]int\n}\n\n// NewDijkstraGraph is a constructor to DijkstraGraph struct\nfunc NewDijkstraGraph(ids map[string]Vertex) DijkstraGraph {\n\tdg := DijkstraGraph{ids: ids}\n\tdg.names = make(map[Vertex]string, len(ids))\n\tfor k, v := range ids {\n\t\tdg.names[v] = k\n\t}\n\tdg.edges = make(map[Vertex]map[Vertex]int)\n\treturn dg\n}\nfunc (dg DijkstraGraph) edge(u, v string, w int) {\n\tif _, ok := dg.edges[dg.ids[u]]; !ok {\n\t\tdg.edges[dg.ids[u]] = make(map[Vertex]int)\n\t}\n\tdg.edges[dg.ids[u]][dg.ids[v]] = w\n}\nfunc (dg DijkstraGraph) path(v Vertex, path map[Vertex]Vertex) (s string) {\n\ts = dg.names[v]\n\tfor path[v] >= 0 {\n\t\tv = path[v]\n\t\ts = dg.names[v] + s\n\t}\n\treturn s\n}\nfunc (dg DijkstraGraph) Vertices() []Vertex {\n\tvertices := make([]Vertex, 0, len(dg.ids))\n\tfor _, v := range dg.ids {\n\t\tvertices = append(vertices, v)\n\t}\n\treturn vertices\n}\nfunc (dg DijkstraGraph) Neighbors(u Vertex) []Vertex {\n\tvertices := make([]Vertex, 0, len(dg.edges[u]))\n\tfor v := range dg.edges[u] {\n\t\tvertices = append(vertices, v)\n\t}\n\treturn vertices\n}\nfunc (dg DijkstraGraph) Weight(u, v Vertex) int { return dg.edges[u][v] }\n\nconst (\n\tInfinity      = int(^uint(0) >> 1)\n\tUninitialized = -1\n)\n\n// Dijkstra function will receive Graph interface and the source and output the distance and the path\nfunc Dijkstra(g Graph, source Vertex) (dist map[Vertex]int, path map[Vertex]Vertex) {\n\tvertices := g.Vertices()\n\tdist = make(map[Vertex]int, len(vertices))\n\tpath = make(map[Vertex]Vertex, len(vertices))\n\ts := source\n\tdist[s] = 0\n\tq := &PriorityQueue{\n\t\titems:    make([]Vertex, 0, len(vertices)),\n\t\tindex:    make(map[Vertex]int, len(vertices)),\n\t\tpriority: make(map[Vertex]int, len(vertices)),\n\t}\n\tfor _, v := range vertices {\n\t\tif v != s {\n\t\t\tdist[v] = Infinity\n\t\t}\n\t\tpath[v] = Uninitialized\n\t\tq.addWithPriority(v, dist[v])\n\t}\n\tfor len(q.items) != 0 {\n\t\tu := heap.Pop(q).(Vertex)\n\t\tfor _, v := range g.Neighbors(u) {\n\t\t\talt := dist[u] + g.Weight(u, v)\n\t\t\tif alt < dist[v] {\n\t\t\t\tdist[v] = alt\n\t\t\t\tpath[v] = u\n\t\t\t\tq.update(v, alt)\n\t\t\t}\n\t\t}\n\t}\n\treturn dist, path\n}\n\nfunc main() {\n\tg := NewDijkstraGraph(map[string]Vertex{\n\t\t\"a\": 1,\n\t\t\"b\": 2,\n\t\t\"c\": 3,\n\t\t\"d\": 4,\n\t\t\"e\": 5,\n\t\t\"f\": 6,\n\t})\n\tg.edge(\"a\", \"b\", 8)\n\tg.edge(\"a\", \"c\", 9)\n\tg.edge(\"a\", \"f\", 13)\n\tg.edge(\"b\", \"c\", 9)\n\tg.edge(\"b\", \"d\", 14)\n\tg.edge(\"c\", \"d\", 11)\n\tg.edge(\"c\", \"f\", 2)\n\tg.edge(\"d\", \"e\", 7)\n\tg.edge(\"e\", \"f\", 9)\n\n\tdist, path := Dijkstra(g, g.ids[\"a\"])\n\tfmt.Println(\"From a =\")\n\tfmt.Printf(\"Distance to %s: %d, Path: %s\\n\", \"e\", dist[g.ids[\"e\"]], g.path(g.ids[\"e\"], path))\n\tfmt.Printf(\"Distance to %s: %d, Path: %s\\n\", \"f\", dist[g.ids[\"f\"]], g.path(g.ids[\"f\"], path))\n}\n"
  },
  {
    "path": "Algorithms/Graph/Dijkstra/Dijkstra.js",
    "content": "/*EXPLANATION OF THE CODE =>We are using adjacency matrix.\n\nInitialize the distance to the starting node as 0 and\n the distances to all other nodes as infinite\nSet all nodes to “unvisited”\nWhile we haven’t visited all nodes:\n1.Find the node with currently shortest distance from the source (for the first pass, this will be the source node itself)\n2.For all nodes next to it that we haven’t visited yet, check if the currently smallest distance to that neighbor is bigger than if we were to go via the current node\nIf it is, update the smallest distance of that neighbor to be the distance from the source to the current node plus the distance from the current node to that neighbor\nIn the end, the array we used to keep track of the currently shortest distance from the source to all other nodes will contain the (final) shortest distances.\n\n*/\n/*CODE*/\n\nconst dijkstra = function (graph, start) {\n\n    //This contains the distances from the start node to all other nodes\n    var distances = [];\n    //Initializing with a distance of \"Infinity\"\n    for (var i = 0; i < graph.length; i++) distances[i] = Number.MAX_VALUE;\n    //The distance from the start node to itself is of course 0\n    distances[start] = 0;\n\n    //This contains whether a node was already visited\n    var visited = [];\n\n    //While there are nodes left to visit...\n    while (true) {\n        // ... find the node with the currently shortest distance from the start node...\n        var shortestDistance = Number.MAX_VALUE;\n        var shortestIndex = -1;\n        for (var i = 0; i < graph.length; i++) {\n            //... by going through all nodes that haven't been visited yet\n            if (distances[i] < shortestDistance && !visited[i]) {\n                shortestDistance = distances[i];\n                shortestIndex = i;\n            }\n        }\n\n        console.log(\"Visiting node \" + shortestDistance + \" with current distance \" + shortestDistance);\n\n        if (shortestIndex === -1) {\n            // There was no node not yet visited --> We are done\n            return distances;\n        }\n\n        //...then, for all neighboring nodes....\n        for (var i = 0; i < graph[shortestIndex].length; i++) {\n            //...if the path over this edge is shorter...\n            if (graph[shortestIndex][i] !== 0 && distances[i] > distances[shortestIndex] + graph[shortestIndex][i]) {\n                //...Save this path as new shortest path.\n                distances[i] = distances[shortestIndex] + graph[shortestIndex][i];\n                console.log(\"Updating distance of node \" + i + \" to \" + distances[i]);\n            }\n        }\n        // Lastly, note that we are finished with this node.\n        visited[shortestIndex] = true;\n        console.log(\"Visited nodes: \" + visited);\n        console.log(\"Currently lowest distances: \" + distances);\n\n    }\n};\n\nmodule.exports = {dijkstra};"
  },
  {
    "path": "Algorithms/Graph/Dijkstra/Dijkstra.php",
    "content": "<?php\n\nclass Vertex {\n    public $edges;\n\n    public function __construct() {\n        $this->edges = [];\n    }\n\n    public function addEdge($to, $d) {\n        $this->edges[$to] = $d;\n    }\n}\n\nclass MinHeap extends SplPriorityQueue {\n    public function compare($p1, $p2) {\n        parent::compare($p2, $p1);\n    }\n}\n\nclass Graph {\n    private $vList;\n\n    public function __construct() {\n        $this->vList = [];\n    }\n\n    public function insertVertex($label) {\n        $this->vList[$label] = new Vertex();\n    }\n\n    public function insertEdge($from, $to, $d) {\n        $this->vList[$from]->addEdge($to, $d);\n    }\n\n    public function dijkstra($from, $destination) {\n        $distance = [];\n        $prev = [];\n        $visited = [$from];\n        $pq = new MinHeap();\n        $pq->setExtractFlags(SplPriorityQueue::EXTR_BOTH);\n\n        // First we populate the distance and previous matrixes\n        // The we insert each node in the priority queue\n        foreach ($this->vList as $vid => $vertex) {\n            $distance[$vid] = INF;\n            $prev[$vid] = null;\n        }\n\n        $distance[$from] = 0;\n        $pq->insert($from, 0);\n\n        // Then we do the \"main loop\" where we explore the node with least distance to source\n        while(!$pq->isEmpty()) {\n            $v_dist = $pq->extract();\n            $v = $v_dist['data'];\n            $pathdist = $v_dist['priority'];\n            $visited[$v] = True;\n\n            foreach($this->vList[$v]->edges as $to=>$edgedist) {\n                $tmpdist = $distance[$v] + $edgedist;\n\n                if ($tmpdist < $distance[$to]) {\n                    $distance[$to] = $tmpdist;\n                    $prev[$to] = $v;\n                    $pq->insert($to, $tmpdist);\n                }\n            }\n        } \n\n        return $this->pathToString($prev, $destination);\n    }\n\n    public function pathToString($prev, $destination) {\n        $from = $prev[$destination];\n        if (is_null($from)) {\n            return $destination;\n        } else {\n            return $this->pathToString($prev, $from).' -'.$this->vList[$from]->edges[$destination].'-> '.$destination;\n        }\n    }\n}\n\n// Hola\n$g = new Graph();\n$g->insertVertex(\"a\");\n$g->insertVertex(\"b\");\n$g->insertVertex(\"c\");\n$g->insertEdge(\"a\", \"b\", 8);\n$g->insertEdge(\"b\", \"c\", 4);\n$g->insertEdge(\"a\", \"c\", 200);\n\necho $g->dijkstra(\"a\", \"c\").PHP_EOL;\n\n$g2 = new Graph();\n$g2->insertVertex(\"a\");\n$g2->insertVertex(\"b\");\n$g2->insertVertex(\"c\");\n$g2->insertVertex(\"d\");\n$g2->insertEdge(\"a\", \"a\", 0);\n$g2->insertEdge(\"a\", \"b\", 5);\n$g2->insertEdge(\"a\", \"c\", 10);\n$g2->insertEdge(\"a\", \"d\", 34);\n$g2->insertEdge(\"b\", \"c\", 3);\n$g2->insertEdge(\"c\", \"d\", 7);\n\n$path = $g2->dijkstra(\"a\", \"d\").PHP_EOL;\n\necho $path;\n"
  },
  {
    "path": "Algorithms/Graph/Dijkstra/README.md",
    "content": "This folder contains Dijkstra Algorithms in various languages...\n"
  },
  {
    "path": "Algorithms/Graph/Dijkstra/dijkstra_leftist_heap/README.txt",
    "content": "Compilar:\r\n\"g++ src/dijkstra.cpp src/leftistHeap.cpp src/WDGraph.cpp -o dijkstra\"\r\n\r\nEjecutar:\r\n\"./dijkstra N_VERTICES MAX_WEIGHT CHANCE\"\r\n\r\nEl output indica el tiempo de ejecucion del algoritmo en milisegundos"
  },
  {
    "path": "Algorithms/Graph/Dijkstra/dijkstra_leftist_heap/WDGraph.cpp",
    "content": "#include \"WDGraph.h\"\r\n\r\n#define INF 10e6;\r\n\r\n// EdgeNode methods\r\n\r\nEdgeNode::EdgeNode(int src, int dst, float weight, EdgeNode *next) {\r\n\t_src = src;\r\n\t_dst = dst;\r\n\t_weight = weight;\r\n\t_next = next;\r\n}\r\n\r\n// VertexNode methods\r\n\r\nVertexNode::VertexNode(int elem, VertexNode *next, EdgeNode *edges) {\r\n\t_elem = elem;\r\n\t_dist = INF;\r\n\t_nodesPointed = 0;\r\n\t_visited = 0;\r\n\t_parentOnMinPath = NULL;\r\n\t_next = next;\r\n\t_edges = edges;\r\n}\r\n\r\n// WDGraph methods\r\n\r\nWDGraph::WDGraph() {\r\n\t_head = NULL;\r\n\t_nVertex = 0;\r\n\t_map = new std::unordered_map<int, VertexNode*>;\r\n}\r\n\r\nvoid WDGraph::addEdge(int src, int dst, float weight) {\r\n\t// Se encarga de anadir las aristas al grafo, si alguno de los vertices mencionados en la arista no forma parte del grafo, lo anade tambien\r\n\tif (_head == NULL) {\r\n\t\tEdgeNode *edge1 = new EdgeNode(src, dst, weight, NULL); // Creamos la arista src -> dst\r\n\t\tVertexNode *aux = new VertexNode(dst, NULL, NULL); // Creamos el vertice dst\r\n\t\t_head = new VertexNode(src, aux, edge1); // Creamos el vertice src y lo asignamos a _head\r\n\t\t_head->_nodesPointed++;\r\n\t\t_map->insert(std::make_pair(src, _head));\r\n\t\t_map->insert(std::make_pair(dst, aux));\r\n\t\t_nVertex += 2; // Aumentamos el # de vertices\r\n\t} else {\r\n\t\tEdgeNode *aux = NULL;\r\n\t\tVertexNode *vAux = NULL;\r\n\t\tstd::unordered_map<int, VertexNode*>::iterator iter = _map->find(src);\r\n\t\tif (iter != _map->end()) {\r\n\t\t\taux = iter->second->_edges;\r\n\t\t\titer->second->_edges = new EdgeNode(src, dst, weight, aux);\r\n\t\t\titer->second->_nodesPointed++;\r\n\t\t} else {\r\n\t\t\tEdgeNode *eAux = new EdgeNode(src, dst, weight, NULL);\r\n\t\t\tvAux = _head;\r\n\t\t\t_head = new VertexNode(src, vAux, eAux);\r\n\t\t\t_head->_nodesPointed++;\r\n\t\t\t_map->insert(std::make_pair(src, _head));\r\n\t\t\t_nVertex++;\r\n\t\t}\r\n\t\titer = _map->find(dst);\r\n\t\tif (iter == _map->end()) {\r\n\t\t\tvAux = _head;\r\n\t\t\t_head = new VertexNode(dst, vAux, NULL);\r\n\t\t\t_map->insert(std::make_pair(dst, _head));\r\n\t\t\t_nVertex++;\r\n\t\t}\r\n\t}\r\n}\r\n\r\nvoid WDGraph::printGraph() {\r\n\t// DEBUG\r\n\tVertexNode *vertex = _head;\r\n\tfor (int i = 0; i < _nVertex; i++) {\r\n\t\tstd::cerr << \"Adyacency list of: \" << vertex->_elem << '\\n';\r\n\t\tEdgeNode *edge = vertex->_edges;\r\n\t\twhile (edge) {\r\n\t\t\tstd::cerr << \" -> \" << edge->_dst << \" (\" << edge->_weight << ')';\r\n\t\t\tedge = edge->_next;\r\n\t\t}\r\n\t\tstd::cerr << '\\n';\r\n\t\tvertex = vertex->_next;\r\n\t}\r\n}\r\n\r\nvoid WDGraph::printGraphvertices() {\r\n\t// DEBUG\r\n\tVertexNode *vertex = _head;\r\n\tfor (int i = 0; i < _nVertex; i++) {\r\n\t\tstd::cerr << \"Vertex: \" << vertex->_elem << '\\n';\r\n\t\tstd::cerr << \"   # of pointed nodes: \" << vertex->_nodesPointed << '\\n';\r\n\t\tstd::cerr << \"   visited: \"\r\n\t\t\t\t<< (vertex->_visited ? \"True\\n\" : \"False\\n\");\r\n\t\tstd::cerr << \"   distance: \" << vertex->_dist << '\\n';\r\n\t\tif (vertex->_parentOnMinPath != NULL)\r\n\t\t\tstd::cerr << \"   parentOnShortestPath: \"\r\n\t\t\t\t\t<< vertex->_parentOnMinPath->_elem << '\\n';\r\n\t\tstd::cerr << '\\n';\r\n\t\tvertex = vertex->_next;\r\n\t}\r\n}\r\n\r\nvoid WDGraph::getvertices(std::vector<VertexNode*> &ret) {\r\n\tVertexNode *vertex = _head;\r\n\tfor (int i = 0; i < _nVertex; i++) {\r\n\t\tret.push_back(vertex);\r\n\t\tvertex = vertex->_next;\r\n\t}\r\n}\r\n\r\nvoid WDGraph::changeVertexDistance(int e, float newDist) {\r\n\tstd::unordered_map<int, VertexNode*>::iterator iter = _map->find(e);\r\n\tif (iter != _map->end()) {\r\n\t\titer->second->_dist = newDist;\r\n\t} else {\r\n\t\tstd::cerr << e << \" is not currently in the graph.\\n\";\r\n\t}\r\n}\r\n\r\nvoid WDGraph::changeParent(int e, VertexNode *parent) {\r\n\tstd::unordered_map<int, VertexNode*>::iterator iter = _map->find(e);\r\n\tif (iter != _map->end()) {\r\n\t\titer->second->_parentOnMinPath = parent;\r\n\t} else {\r\n\t\tstd::cerr << e << \" is not currently in the graph.\\n\";\r\n\t}\r\n}\r\n\r\nvoid WDGraph::visitVertex(int e) {\r\n\tstd::unordered_map<int, VertexNode*>::iterator iter = _map->find(e);\r\n\tif (iter != _map->end()) {\r\n\t\titer->second->_visited = 1;\r\n\t} else {\r\n\t\tstd::cerr << e << \" is not currently in the graph.\\n\";\r\n\t}\r\n}\r\n\r\nvoid WDGraph::getNeightbours(int e, std::vector<EdgeNode*> &ret) {\r\n\tstd::unordered_map<int, VertexNode*>::iterator iter = _map->find(e);\r\n\tEdgeNode *aux;\r\n\tif (iter != _map->end()) {\r\n\t\taux = iter->second->_edges;\r\n\t\tfor (int i = 0; i < iter->second->_nodesPointed; i++) {\r\n\t\t\tif (!getVertex(aux->_dst)->_visited)\r\n\t\t\t\tret.push_back(aux);\r\n\t\t\taux = aux->_next;\r\n\t\t}\r\n\t} else {\r\n\t\tstd::cerr << e << \" is not currently in the graph.\\n\";\r\n\t}\r\n}\r\n\r\nint WDGraph::getNumberOfNeightbours(int e) {\r\n\tstd::unordered_map<int, VertexNode*>::iterator iter = _map->find(e);\r\n\tif (iter != _map->end()) {\r\n\t\treturn iter->second->_nodesPointed;\r\n\t} else {\r\n\t\tstd::cerr << e << \" is not currently in the graph.\\n\";\r\n\t}\r\n\treturn -1;\r\n}\r\n\r\nVertexNode* WDGraph::getVertex(int e) {\r\n\tstd::unordered_map<int, VertexNode*>::iterator iter = _map->find(e);\r\n\tif (iter != _map->end()) {\r\n\t\treturn iter->second;\r\n\t} else {\r\n\t\tstd::cerr << e << \" is not currently in the graph.\\n\";\r\n\t}\r\n\treturn NULL;\r\n}\r\n"
  },
  {
    "path": "Algorithms/Graph/Dijkstra/dijkstra_leftist_heap/WDGraph.h",
    "content": "#ifndef _WDGraph_\r\n#define _WDGraph_\r\n\r\n#include <iostream>\r\n#include <cstddef>\r\n#include <unordered_map>\r\n#include <vector>\r\n\r\n/*\r\n Implementation of a Weighted Directed Graph using Linked lists.\r\n Each vertex is represented by VertexNode:\r\n _elem       contains the value of the given node\r\n _visited    controls if the visited has been visited by any algorithm\r\n _nodesPointed controls the nomber of nodes in the list\r\n _visited\t stores the result of the dijkstra algorithm, true if visited after the algorithm\r\n _parentOnMinPath stores the parent of the note in the minimum path after dijkstra\r\n _next       pointer to the next VertexNode in the graph\r\n _edges      pointer to the first EdgeNode of the Vertex\r\n\r\n Each edge is represented by EdgeNode:\r\n _src        contains the value from the vertex wich the edge comes out\r\n _dst        contains the value from the vertex wich the edge goes to\r\n _weight     contains the cost of traveling trought the given edge\r\n _next       pointer to the next edge of the given VertexNode\r\n\r\n The complete graph is represented by WDGraph:\r\n _head       pointer to the first VertexNode in the graph\r\n */\r\n\r\nclass EdgeNode {   // Edges\r\n\r\npublic:\r\n\tint _src;\r\n\tint _dst;\r\n\tfloat _weight;\r\n\tEdgeNode *_next;\r\n\tEdgeNode(int src, int dst, float weight, EdgeNode *next);     // Constructor\r\n\r\n};\r\n\r\nclass VertexNode {   // Adyacency list (linked list)\r\n\r\npublic:\r\n\tint _elem;\r\n\tfloat _dist;\r\n\tint _nodesPointed;\r\n\tbool _visited;\r\n\tVertexNode *_parentOnMinPath;\r\n\tVertexNode *_next;\r\n\tEdgeNode *_edges;\r\n\tVertexNode(int elem, VertexNode *next, EdgeNode *edges);    // Constructor\r\n\r\n};\r\n\r\nclass WDGraph {\r\n\r\npublic:\r\n\tVertexNode *_head;\r\n\tint _nVertex;\r\n\tstd::unordered_map<int, VertexNode*> *_map; \t// Stores the current vertex on the graph and a pointer to them in order to insert a new edge in O(1)\r\n\tvoid addEdge(int src, int dst, float weight); \t// Adds an EdgeNode from src to dst with the given weight\r\n\tvoid printGraph(); \t\t\t\t\t\t\t\t// Prints the adyacency list for the graph\r\n\tvoid printGraphvertices(); \t\t\t\t\t\t// Prints all the info of each vertex of the graph\r\n\tvoid getvertices(std::vector<VertexNode*> &ret);// Returns an array with all the vertices of the graph in it\r\n\tvoid changeVertexDistance(int e, float newDist);// Changes the distance attribute of the given node to the desired value\r\n\tvoid changeParent(int e, VertexNode* parent);\t// Changes the parent attribute of the given node to the desired value\r\n\tvoid visitVertex(int e);                        // Marks the node as visited\r\n\tvoid getNeightbours(int e, std::vector<EdgeNode*> &ret); // Returns the neightbours oof the given vertex\r\n\tint getNumberOfNeightbours(int e); \t\t\t\t// Returns the number of neightbours of the given node\r\n\tVertexNode* getVertex(int e); \t\t\t\t\t// Returns the corresponding node to the given element\r\n\tWDGraph();                                      // Constructor\r\n\r\n};\r\n\r\n#endif\r\n"
  },
  {
    "path": "Algorithms/Graph/Dijkstra/dijkstra_leftist_heap/dijkstra.cpp",
    "content": "#include <iostream>\r\n#include <ctime>\r\n#include <chrono>\r\n#include <cmath>\r\n\r\n#include \"leftistHeap.h\"\r\n#include \"WDGraph.h\"\r\n\r\nconst float INF = 10e6;\r\nWDGraph g;\r\nstd::vector<VertexNode*> vertices;\r\nstd::vector<EdgeNode*> EdgesToNeightbours;\r\nLeftistHeap h;\r\n\r\nvoid readGraph(WDGraph &g);\r\nvoid createGraph(int N_VERTICES, int MAX_WEIGHT, float EDGE_CHANCE, long unsigned int &edges);\r\nvoid dijkstra(WDGraph g, int src);\r\n\r\nint main(int argc, char **argv) {\r\n    srand(time(NULL));\r\n\tlong unsigned int edges = 0;\r\n    if (argc != 4){\r\n        std::cerr << \"Wrong # of arguments\\n\";\r\n        std::cerr << \"Correct arguments are: (int) N_VERTICES, (int) MAX_WEIGHT, (float) EDGE_CHANCE\\n\";\r\n        return 1;\r\n    }\r\n    std::cerr << \"Generating a graph with: \" << '\\n';\r\n    std::cerr << \"     \" << argv[1] << \" N_VERTICES\\n\";\r\n    std::cerr << \"     \" << argv[2] << \" MAX_WEIGHT\\n\";\r\n    std::cerr << \"     \" << std::stod(argv[3])*100 << \"% EDGE_CHANCE\\n\";\r\n\tstd::cerr << \"-------------------------\\n\";\r\n\tstd::cerr << std::pow(std::stoi(argv[1]), 2)*std::stod(argv[3]) << \" expected edges (aprox)\\n\";\r\n\t// readGraph(g);\t\t// Descomentar para leer el grafo (./dijkstra < inputFile)\r\n    createGraph(std::stoi(argv[1]), std::stoi(argv[2]), std::stod(argv[3]), edges);\t// Comentar si se desea leer el grafo en lugar de generarlo\r\n\t// g.printGraph();\t\t// Descomentar para imprimir las listas de adyacencia del grafo generado o leido\r\n\tstd::cerr << \"Executing dijkstra...\\n\";\r\n\tauto start = std::chrono::steady_clock::now();\r\n\tdijkstra(g, 0);\r\n\tauto end = std::chrono::steady_clock::now();\r\n\tstd::cout << std::chrono::duration<double, std::milli>(end - start).count()\t<< \"\\n\";\r\n\tstd::cerr << std::chrono::duration<double, std::milli>(end - start).count()\t<< \" ms - Total time\\n\";\r\n\tstd::cerr << edges/std::chrono::duration<double, std::milli>(end - start).count() << \" edges/ms\\n\";\r\n\t// g.printGraphvertices();\t// Descomentar para imprimir los datos de todos los vertices tras la ejecucion del algoritmo\r\n\treturn 0;\r\n}\r\n\r\nvoid dijkstra(WDGraph g, int src) {\r\n\tstd::pair<float, int> minElem;\r\n\tVertexNode *minElemVertex;\r\n\tvertices.clear();\r\n\tg.getvertices(vertices);\r\n\t// Modificamos la distancia del nodo de inicio a 0\r\n\tg.changeVertexDistance(src, 0);\r\n\t// Insertamos todos los vertices en el monticulo, tienen distancia INF, no estan visitados y no tienen nodo previo\r\n\tfor (int i = 0; i < g._nVertex; i++)\r\n\t\th.insert(std::make_pair(vertices[i]->_dist, vertices[i]->_elem));\r\n\t// Mientras el monticulo no este vacio, operamos de la siguiente manera\r\n\twhile (!h.isEmpty()) {\r\n\t\t// Extraemos el minimo elemento y conseguimos acceso a su nodo mediante el la funcion getVertex(), tambien eliminamos dicho elemento del monticulo ya que ya ha sido visitado\r\n\t\th.deleteMin(minElem);\r\n\t\tminElemVertex = g.getVertex(minElem.second);\r\n\t\t// Si el nodo visitado tiene una distancia distinta a INF, implica que ha sido visitado por el algoritmo\r\n\t\tif (minElemVertex->_dist != INF)\r\n\t\t\tg.visitVertex(minElem.second);\r\n\t\tEdgesToNeightbours.clear();\r\n\t\t// Extraemos la lista de adyacencia del vertice a tratar en esta iteraccion\r\n\t\tg.getNeightbours(minElemVertex->_elem, EdgesToNeightbours);\r\n\t\tfor (long unsigned int i = 0; i < EdgesToNeightbours.size(); i++) {\r\n\t\t\t// Para cada vecino al vertice a tratar comprobamos que no haya sido visitado (y eliminado del monticulo) y si la distancia desde le nodo actual mejora la distancia obtenida por el camino anterior\r\n\t\t\tif (!(g.getVertex(EdgesToNeightbours[i]->_dst)->_visited) \r\n\t\t\t\t&& (minElemVertex->_dist + EdgesToNeightbours[i]->_weight < g.getVertex(EdgesToNeightbours[i]->_dst)->_dist)) {\r\n\t\t\t\t// Modificamos la distancia de llegada al vecino a traves de su padre\r\n\t\t\t\tg.changeVertexDistance(EdgesToNeightbours[i]->_dst, minElemVertex->_dist + EdgesToNeightbours[i]->_weight);\r\n\t\t\t\t// Indicamos al vecino que el vertice actual es su padre en el camino minimo\r\n\t\t\t\tg.getVertex(EdgesToNeightbours[i]->_dst)->_parentOnMinPath = minElemVertex;\r\n\t\t\t\t// Decrecemos la  clave de dicho vecino a su nuevo valor en el monticulo\r\n\t\t\t\t// Cabe destacar que esta funcion es un tanto extrana, ya que recibe el ELEMENTO del vertice para modificar su DISTANCIA, esta funcionalidad ha sido implementada\r\n\t\t\t\t// \t\ten la funcion decrecerClave() en el archivo leftistHeap.cpp. Dicho monticulo contiene un mapa que relaciona elemento - puntero al nodo correspondiente. \r\n\t\t\t\th.decreaseKey(g.getVertex(EdgesToNeightbours[i]->_dst)->_elem, g.getVertex(EdgesToNeightbours[i]->_dst)->_dist);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n}\r\n\r\nvoid readGraph(WDGraph &g) {\r\n\tint src;\r\n\tint dst;\r\n\tfloat weight;\r\n\twhile ((std::cin >> src) && (std::cin >> dst) && (std::cin >> weight)) {\r\n\t\tg.addEdge(src, dst, weight);\r\n\t}\r\n}\r\n\r\nvoid createGraph(int N_VERTICES, int MAX_WEIGHT, float EDGE_CHANCE, long unsigned int &edges){\r\n\tfloat r;\r\n    float f;\r\n    for (int row = 0; row < N_VERTICES; row++){\r\n\t\tfor (int col = 0; col < N_VERTICES; col++){\r\n\t\t\tif (row != col){\r\n\t\t\t\tr = static_cast <float> (rand()) / static_cast <float> (RAND_MAX);\r\n\t\t\t\tif (r <= EDGE_CHANCE){\r\n\t\t\t\t\tf = static_cast <float> (rand()) / static_cast <float> (RAND_MAX);\r\n                    g.addEdge(row, col, f*MAX_WEIGHT);\r\n\t\t\t\t\tstd::cerr.flush();\r\n\t\t\t\t\tstd::cerr << edges++  << \" edges generated\\r\";\r\n                }\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tstd::cerr << '\\n';\r\n}"
  },
  {
    "path": "Algorithms/Graph/Dijkstra/dijkstra_leftist_heap/leftistHeap.cpp",
    "content": "#include \"leftistHeap.h\"\r\n\r\n// Node Methods\r\n\r\nNode::Node(std::pair<float, int> e) {\r\n\tthis->_elem = e;\r\n\tthis->_dist = 0;\r\n\tthis->_parent = NULL;\r\n\tthis->_left = NULL;\r\n\tthis->_right = NULL;\r\n}\r\n\r\nNode::Node(std::pair<float, int> e, int d, Node *parent, Node *l, Node *r) {\r\n\tthis->_elem = e;\r\n\tthis->_dist = d;\r\n\tthis->_parent = parent;\r\n\tthis->_left = l;\r\n\tthis->_right = r;\r\n}\r\n\r\n// LeftistHeap Methods\r\n\r\n// Public methods\r\n\r\nLeftistHeap::LeftistHeap() {\r\n\t_root = NULL;\r\n\t_map = new std::unordered_map<int, Node*>;\r\n}\r\n\r\nLeftistHeap::LeftistHeap(Node *newRoot,\r\n\t\tstd::unordered_map<int, Node*> *newMap) {\r\n\t_root = newRoot;\r\n\t_map = newMap;\r\n}\r\n\r\nint LeftistHeap::getMin() {\r\n\treturn _root->_elem.second;\r\n}\r\n\r\nvoid LeftistHeap::deleteMin() {\r\n\tif (!isEmpty()) {\r\n\t\t_map->erase(_root->_elem.first);\r\n\t\tNode *aux = _root;\r\n\t\tif (_root->_left != NULL)\r\n\t\t\t_root->_left->_parent = NULL;\r\n\t\tif (_root->_right != NULL)\r\n\t\t\t_root->_right->_parent = NULL;\r\n\t\t_root = mergeHeaps(_root->_left, _root->_right);\r\n\t\tdelete aux;\r\n\t}\r\n}\r\n\r\nvoid LeftistHeap::deleteMin(std::pair<float, int> &minElem) {\r\n\tminElem = _root->_elem;\r\n\tdeleteMin();\r\n}\r\n\r\nvoid LeftistHeap::insert(std::pair<int, int> elem) {\r\n\tif (_map->find(elem.second) != _map->end()) {\r\n\t\tstd::cerr << elem.second << \" already exists in the heap.\\n\";\r\n\t\treturn;\r\n\t}\r\n\tNode *newElem = new Node(elem);\r\n\t_map->insert(std::make_pair(elem.second, newElem));\r\n\t_root = mergeHeaps(_root, newElem);\r\n}\r\n\r\nvoid LeftistHeap::decreaseKey(int elem, float newDist) {\t// Permite decrementar el valor de la distancia del nodo que contiene al elemento \"elem\"\r\n\t// Busca en el mapa el valor indicado por \"elem\"\r\n\tstd::unordered_map<int, Node*>::iterator iter = _map->find(elem);\r\n\t// Comprueba que exista en el monticulo\r\n\tif (iter != _map->end()) {\r\n\t\t// Si se trata de la raiz, decrece el valor correspondiente\r\n\t\tif (iter->second == _root) {\r\n\t\t\t_root->_elem.first = newDist;\r\n\t\t}\r\n\t\t// En caso de no ser la raiz, crea un nuevo nodo con los valores apropiados\r\n\t\telse {\r\n\t\t\tNode *aux = new Node(\r\n\t\t\t\t\tstd::make_pair(newDist, iter->second->_elem.second),\r\n\t\t\t\t\t0,\r\n\t\t\t\t\titer->second->_parent,\r\n\t\t\t\t\titer->second->_left, \r\n\t\t\t\t\titer->second->_right\r\n\t\t\t\t\t);\r\n\t\t\t// Comprueba si se trata del hijo izquierdo o derecho de su padre\r\n\t\t\tif ((aux->_parent->_left->_elem.second == elem)) {\r\n\t\t\t\t// Si se trata del izquierdo, el puntero _left del padre se apunta a NULL\r\n\t\t\t\taux->_parent->_left = NULL;\r\n\t\t\t\t// Se intercambian los hijos del padre que el derecho no debe ser hijo unico\r\n\t\t\t\tswapChildren(aux->_parent);\r\n\t\t\t} else\r\n\t\t\t\t// Si se trata del derecho, el puntero _right del padre se apunta a NULL\r\n\t\t\t\taux->_parent->_right = NULL;\r\n\t\t\t// Perdemos el puntero _parent, descolgando de forma efectiva nuestro nodo a decrementar del monticulo\r\n\t\t\taux->_parent = NULL;\r\n\t\t\t// Se indica a nuestros hijos _left y _right que aux es el nuevo nodo padre, ya que es una direccion de memoria distinta\r\n\t\t\tif (aux->_left != NULL)\r\n\t\t\t\taux->_left->_parent = aux;\r\n\t\t\tif (aux->_right != NULL)\r\n\t\t\t\taux->_right->_parent = aux;\r\n\t\t\t// Llamamos a mergeHeaps() con la raiz original de nuestro monticulo y el nuevo nodo que hemos descolgado\r\n\t\t\t_root = mergeHeaps(_root, aux);\r\n\t\t\t// Eliminamos la antigua direccion del nodo del mapa e insertamos la nueva\r\n\t\t\t_map->erase(elem);\r\n\t\t\t_map->insert(std::make_pair(elem, aux));\r\n\t\t}\r\n\t}\r\n}\r\n\r\nvoid LeftistHeap::merge(LeftistHeap &b) {\r\n\tif (this == &b)\r\n\t\treturn;\r\n\t_root = mergeHeaps(_root, b._root);\r\n\tb._root = NULL;\r\n}\r\n\r\nbool LeftistHeap::isEmpty() {\r\n\treturn _root == NULL;\r\n}\r\n\r\nvoid LeftistHeap::emptyHeap() {\r\n\tclearMem(_root);\r\n\t_root = NULL;\r\n\t_map->empty();\r\n}\r\n\r\nvoid LeftistHeap::printHeap() {\r\n\tLeftistHeap aux;\r\n\taux = *this;\r\n\tstd::pair<float, int> x;\r\n\twhile (!aux.isEmpty()) {\r\n\t\taux.deleteMin(x);\r\n\t\tstd::cerr << '(' << x.second << ' ' << x.first << ')' << ' ';\r\n\t}\r\n\tstd::cerr << '\\n';\r\n}\r\n\r\nLeftistHeap& LeftistHeap::operator =(LeftistHeap &h) {\r\n\tif (this != &h) {\r\n\t\temptyHeap();\r\n\t\t_root = cloneNode(h._root);\r\n\t}\r\n\treturn *this;\r\n}\r\n\r\nstd::unordered_map<int, Node*>* LeftistHeap::map() {\r\n\treturn _map;\r\n}\r\n\r\n// Private methods\r\n\r\nNode* LeftistHeap::mergeHeaps(Node *heap1, Node *heap2) {\r\n\tif (heap1 == NULL)\r\n\t\treturn heap2;\r\n\tif (heap2 == NULL)\r\n\t\treturn heap1;\r\n\tif (heap1->_elem.first <= heap2->_elem.first) {\r\n\t\treturn MergeRecursive(heap1, heap2);\r\n\t}\r\n\treturn MergeRecursive(heap2, heap1);\r\n}\r\n\r\nNode* LeftistHeap::MergeRecursive(Node *heap1, Node *heap2) {\r\n\t// Aparte de realizar el merge de forma correcta, se encarga de asignar el padre de cada nodo en cada asignacion\r\n\tif (heap1->_left == NULL) {\r\n\t\theap1->_left = heap2;\r\n\t\theap2->_parent = heap1;\r\n\t} else {\r\n\t\theap1->_right = mergeHeaps(heap1->_right, heap2);\r\n\t\theap1->_right->_parent = heap1;\r\n\t\tif (heap1->_left->_dist < heap1->_right->_dist)\r\n\t\t\tswapChildren(heap1);\r\n\t\theap1->_dist = heap1->_right->_dist + 1;\r\n\t}\r\n\treturn heap1;\r\n}\r\n\r\nvoid LeftistHeap::swapChildren(Node *parent) {\r\n\tNode *aux = parent->_right;\r\n\tparent->_right = parent->_left;\r\n\tparent->_left = aux;\r\n}\r\n\r\nvoid LeftistHeap::clearMem(Node *node) {\r\n\tif (node != NULL) {\r\n\t\tclearMem(node->_left);\r\n\t\tclearMem(node->_right);\r\n\t\tdelete node;\r\n\t}\r\n}\r\n\r\nNode* LeftistHeap::cloneNode(Node *node) {\r\n\tif (node == NULL)\r\n\t\treturn NULL;\r\n\treturn new Node(node->_elem, node->_dist, node->_parent,\r\n\t\t\tcloneNode(node->_left), cloneNode(node->_right));\r\n}\r\n"
  },
  {
    "path": "Algorithms/Graph/Dijkstra/dijkstra_leftist_heap/leftistHeap.h",
    "content": "/*\r\n FUNCTION:       COMPLEXITY:\r\n - getMin()       - O(1)\r\n - deleteMin()    - O(log N)\r\n - insert()       - O(log N)\r\n - merge()        - O(log N)\r\n\r\n Node Info:\r\n - element\r\n - distance\r\n - parent\r\n - left child\r\n - right child\r\n\r\n Operations:\r\n - merge() is the main operation, called by deleteMin(), decreaseKey(), getMin() and insert()\r\n - deleteMin() removes the root of the tree and calls merge with both the left and right sons\r\n - getMin() returns the value of the pointer to the root\r\n - insert() creates a leftist heap with a single key and calls merge with the original and this new tree\r\n - decreaseKey() allows you to decrease the value of the first element of the pair given the second one\r\n */\r\n\r\n#ifndef _LeftistHeap_\r\n#define _LeftistHeap_\r\n\r\n#include <cstddef>\r\n#include <unordered_map>\r\n#include <iostream>\r\n#include <algorithm>\r\n\r\nclass Node {\r\n\r\npublic:\r\n\tstd::pair<float, int> _elem;\r\n\tint _dist;\r\n\tNode *_parent;\r\n\tNode *_left;\r\n\tNode *_right;\r\n\tNode(std::pair<float, int> e);     \t\t\t// Constructor\r\n\tNode(std::pair<float, int> e, int d, Node *p, Node *l, Node *r); // Constructor\r\n\r\n};\r\n\r\nclass LeftistHeap {\r\n\r\npublic:\r\n\tLeftistHeap();                              // Constructor\r\n\tint getMin();             \t\t\t\t\t// Returns the smallest element in the heap (root)\r\n\tvoid deleteMin();                \t\t\t// Removes the smallest element in the heap\r\n\tvoid deleteMin(std::pair<float, int> &minElem); // Removes the smallest element in the heap and returns it to avoid using getMin()\r\n\tvoid insert(std::pair<int, int> elem); \t\t// Inserts the given element into the heap\r\n\tvoid decreaseKey(int elem, float newKey); // Modifies the value of the first value of the pair of the given element into the the newKey\r\n\tvoid merge(LeftistHeap &b);   \t\t\t\t// Merges the existing heap with the given one\r\n\tbool isEmpty();                             // Tests if the heap is empty\r\n\tvoid emptyHeap();                           // Empties the heap\r\n\tvoid printHeap(); \t\t\t\t\t\t\t// Prints all the elements of the heap in decreasing order (intended use: debbugin purposes -> O(N logN))\r\n\tLeftistHeap& operator =(LeftistHeap &h);    // Deep copy of a LeftistHeap\r\n\tstd::unordered_map<int, Node*>* map();\t\t// Returns the map so it can be private\r\n\r\nprivate:\r\n\tNode *_root;                      \t\t\t// Root of the heap (also minimum element)\r\n\tstd::unordered_map<int, Node*> *_map;       // Stores pointers to all the nodes of the heap given an element (second element of the pair)\r\n\tNode* mergeHeaps(Node *heap1, Node *heap2); // Merges both heaps, returning the root to the resulting heap\r\n\tNode* MergeRecursive(Node *heap1, Node *heap2); // Called by mergeHeaps() recursively\r\n\tvoid swapChildren(Node *parent); \t\t\t// Swaps the right and left childs of the given node\r\n\tvoid clearMem(Node *node); \t\t\t\t\t// Clears the dinamically allocated memory of the heap\r\n\tNode* cloneNode(Node *node);                // Deep copy of a node\r\n\tLeftistHeap(Node *newRoot, std::unordered_map<int, Node*> *newMap); // Constructor by copy\r\n\r\n};\r\n\r\n#endif\r\n"
  },
  {
    "path": "Algorithms/Graph/Dijkstra/djikstra.py",
    "content": "import sys \n\nclass Graph(): \n\n\tdef __init__(self, vertices): \n\t\tself.V = vertices \n\t\tself.graph = [[0 for column in range(vertices)] \n\t\t\t\t\tfor row in range(vertices)] \n\n\tdef printSolution(self, dist): \n\t\tprint (\"Vertex tDistance from Source\") \n\t\tfor node in range(self.V): \n\t\t\tprint (node, \"t\", dist[node]) \n      \n\tdef minDistance(self, dist, sptSet): \n\n\t\t\n\t\tmin = sys.maxsize \n\t\tfor v in range(self.V): \n\t\t\tif dist[v] < min and sptSet[v] == False: \n\t\t\t\tmin = dist[v] \n\t\t\t\tmin_index = v \n\n\t\treturn min_index \n\n\tdef dijkstra(self, src): \n\n\t\tdist = [sys.maxsize] * self.V \n\t\tdist[src] = 0\n\t\tsptSet = [False] * self.V \n\n\t\tfor cout in range(self.V):\n\t\t\tu = self.minDistance(dist, sptSet) \n\t\t\tsptSet[u] = True\n\t\t\tfor v in range(self.V): \n\t\t\t\tif self.graph[u][v] > 0 and \\ \n\t\t\t\t\tsptSet[v] == False and \\ \n\t\t\t\t\tdist[v] > dist[u] + self.graph[u][v]: \n\t\t\t\t\tdist[v] = dist[u] + self.graph[u][v] \n\n\t\tself.printSolution(dist) \n\n \ng = Graph(9) \ng.graph = [[0, 4, 0, 0, 0, 0, 0, 8, 0], \n\t\t[4, 0, 8, 0, 0, 0, 0, 11, 0], \n\t\t[0, 8, 0, 7, 0, 4, 0, 0, 2], \n\t\t[0, 0, 7, 0, 9, 14, 0, 0, 0], \n\t\t[0, 0, 0, 9, 0, 10, 0, 0, 0], \n\t\t[0, 0, 4, 14, 10, 0, 2, 0, 0], \n\t\t[0, 0, 0, 0, 0, 2, 0, 1, 6], \n\t\t[8, 11, 0, 0, 0, 0, 1, 0, 7], \n\t\t[0, 0, 2, 0, 0, 0, 6, 7, 0] \n\t\t]; \n\ng.dijkstra(0); \n\n\n"
  },
  {
    "path": "Algorithms/Graph/Flood_Fill/Flood_Fill.cpp",
    "content": "#include<iostream>\nusing namespace std;\n\n#define M 5\n#define N 5\n\nvoid floodFillUtil(int screen[][N], int x, int y, int prevC, int newC)\n{\n    if (x < 0 || x >= M || y < 0 || y >= N)\n        return;\n    if (screen[x][y] != prevC)\n        return;\n    if (screen[x][y] == newC)\n        return;\n\n    screen[x][y] = newC;\n\n    floodFillUtil(screen, x+1, y, prevC, newC);\n    floodFillUtil(screen, x-1, y, prevC, newC);\n    floodFillUtil(screen, x, y+1, prevC, newC);\n    floodFillUtil(screen, x, y-1, prevC, newC);\n}\n\nvoid floodFill(int screen[][N], int x, int y, int newC)\n{\n    int prevC = screen[x][y];\n    floodFillUtil(screen, x, y, prevC, newC);\n}\n\nint main()\n{\n    int screen[M][N],x,y,newC;\n\n    cout << \"Enter the colors of the pixels\\n\";\n\n    for(int i=0;i<M;i++)\n    {\n        for(int j=0;j<N;j++)\n        {\n            cin >> screen[i][j];\n        }\n    }\n\n    cout << \"\\nEnter the co-ordinates (x,y) of point in screen\\n\";\n    cin >> x;\n    cin >> y;\n    cout << \"Enter the new color of the point (\" << x << \" , \" << y << \")\\n\";\n    cin >> newC;\n\n    floodFill(screen, x, y, newC);\n\n    cout << \"Updated screen after call to floodFill: \\n\";\n    for (int i=0; i<M; i++)\n    {\n        for (int j=0; j<N; j++)\n        {\n           cout << screen[i][j] << \" \";\n        }\n        cout << endl;\n    }\n}\n"
  },
  {
    "path": "Algorithms/Graph/Flood_Fill/Flood_Fill.java",
    "content": "// Java program to implement flood fill algorithm \nclass GFG \n{ \n  \n// Dimentions of paint screen \nstatic int M = 8; \nstatic int N = 8; \n  \n// A recursive function to replace previous color 'prevC' at '(x, y)'  \n// and all surrounding pixels of (x, y) with new color 'newC' and \nstatic void floodFillUtil(int screen[][], int x, int y,int prevC, int newC) \n{ \n    // Base cases \n    if (x < 0 || x >= M || y < 0 || y >= N) \n        return; \n    if (screen[x][y] != prevC) \n        return; \n  \n    // Replace the color at (x, y) \n    screen[x][y] = newC; \n  \n    // Recur for north, east, south and west \n    floodFillUtil(screen, x+1, y, prevC, newC); \n    floodFillUtil(screen, x-1, y, prevC, newC); \n    floodFillUtil(screen, x, y+1, prevC, newC); \n    floodFillUtil(screen, x, y-1, prevC, newC); \n} \n  \n// It mainly finds the previous color on (x, y) and \n// calls floodFillUtil() \nstatic void floodFill(int screen[][], int x, int y, int newC) \n{ \n    int prevC = screen[x][y]; \n    floodFillUtil(screen, x, y, prevC, newC); \n} \n  \n// Driver code \npublic static void main(String[] args)  \n{ \n    int screen[][] = {{1, 1, 1, 1, 1, 1, 1, 1}, \n                      {1, 1, 1, 1, 1, 1, 0, 0}, \n                      {1, 0, 0, 1, 1, 0, 1, 1}, \n                      {1, 2, 2, 2, 2, 0, 1, 0}, \n                      {1, 1, 1, 2, 2, 0, 1, 0}, \n                      {1, 1, 1, 2, 2, 2, 2, 0}, \n                      {1, 1, 1, 1, 1, 2, 1, 1}, \n                      {1, 1, 1, 1, 1, 2, 2, 1}, \n                    }; \n    int x = 4, y = 4, newC = 3; \n    floodFill(screen, x, y, newC); \n  \n    System.out.println(\"Updated screen after call to floodFill: \"); \n    for (int i = 0; i < M; i++) \n    { \n        for (int j = 0; j < N; j++) \n        System.out.print(screen[i][j] + \" \"); \n        System.out.println(); \n    } \n    } \n} \n  \n"
  },
  {
    "path": "Algorithms/Graph/Flood_Fill/Flood_Fill.js",
    "content": "'use strict'\n\nclass Image {\n  constructor (imageAsMatrix) {\n    this.matrix = imageAsMatrix\n  }\n\n  static get COLORS () {\n    return {\n      BLACK: 'BLACK',\n      AZURE: 'AZURE',\n      WHITE: 'WHITE',\n      GREEN: 'GREEN'\n    }\n  }\n\n  get () {\n    return this.matrix\n  }\n\n  randomColor () {\n    var keys = Object.keys(Image.COLORS)\n    return Image.COLORS[keys[keys.length * Math.random() << 0]]\n  }\n\n  buildWhithRandomColors (rows = 5, cols = 5) {\n    this.matrix = Array.from(\n      { length: rows },\n      () => Array.from({ length: cols }, () => this.randomColor())\n    )\n  }\n}\n\nclass Floodfill {\n  constructor (imageAsMatrix) {\n    this.image = imageAsMatrix\n  }\n\n  get () {\n    return this.image\n  }\n\n  bucket (row, column, newPixel) {\n    const currentPixel = this.image[row][column]\n    if (currentPixel === newPixel) {\n      return this.image\n    }\n    this.fill(row, column, newPixel, currentPixel)\n    return this.image\n  }\n\n  fill (row, column, newPixel, currentPixel) {\n    if (\n      this.rowIsLessThenZero(row) || this.columnIsLessThenZero(column) ||\n      this.rowIsGreaterThenImageLength(row) || this.columnIsGreaterThenImageLength(row, column) ||\n      this.currentPixelNoNeedToFill(row, column, currentPixel)\n    ) {\n      return\n    }\n    this.fillCurrentPixel(row, column, newPixel)\n    this.fillPreviousRow(row, column, newPixel, currentPixel)\n    this.fillNextRow(row, column, newPixel, currentPixel)\n    this.fillPreviousCol(row, column, newPixel, currentPixel)\n    this.fillNextCol(row, column, newPixel, currentPixel)\n  }\n\n  fillCurrentPixel (row, column, newPixel) {\n    this.image[row][column] = newPixel\n  }\n\n  fillPreviousRow (row, column, newPixel, currentPixel) {\n    this.fill(row - 1, column, newPixel, currentPixel)\n  }\n\n  fillNextRow (row, column, newPixel, currentPixel) {\n    this.fill(row + 1, column, newPixel, currentPixel)\n  }\n\n  fillPreviousCol (row, column, newPixel, currentPixel) {\n    this.fill(row, column - 1, newPixel, currentPixel)\n  }\n\n  fillNextCol (row, column, newPixel, currentPixel) {\n    this.fill(row, column + 1, newPixel, currentPixel)\n  }\n\n  rowIsLessThenZero (row) {\n    return (row < 0)\n  }\n\n  columnIsLessThenZero (column) {\n    return (column < 0)\n  }\n\n  rowIsGreaterThenImageLength (row) {\n    return row > this.image.length - 1\n  }\n\n  columnIsGreaterThenImageLength (row, column) {\n    return column > this.image[row].length - 1\n  }\n\n  currentPixelNoNeedToFill (row, column, currentPixel) {\n    return (this.image[row][column] !== currentPixel)\n  }\n}\n\nmodule.exports = {\n  Image,\n  Floodfill\n}\n\n/** \n * Execute for testing:\n * $ node ./Flood_Fill.js \n**/\n\nconst matrixAtBegin = [\n  [Image.COLORS.AZURE, Image.COLORS.AZURE, Image.COLORS.AZURE],\n  [Image.COLORS.AZURE, Image.COLORS.AZURE, Image.COLORS.GREEN],\n  [Image.COLORS.AZURE, Image.COLORS.GREEN, Image.COLORS.AZURE]\n]\n/*\nEXPECTED:\n[\n  [Image.COLORS.BLACK, Image.COLORS.BLACK, Image.COLORS.BLACK],\n  [Image.COLORS.BLACK, Image.COLORS.BLACK, Image.COLORS.GREEN],\n  [Image.COLORS.BLACK, Image.COLORS.GREEN, Image.COLORS.AZURE]\n]\n*/\nconst imageAtBegin = new Image(matrixAtBegin).get()\nconsole.log(imageAtBegin)\nconst floodFill = new Floodfill(imageAtBegin)\nconst matrixAtEnd = floodFill.bucket(0, 1, Image.COLORS.BLACK)\nconsole.log(new Image(matrixAtEnd).get())\n"
  },
  {
    "path": "Algorithms/Graph/Flood_Fill/flood_fill_algorithm.cs",
    "content": "public class Uebung1_2 implements PlugInFilter, MouseListener {\r\n    private ImageProcessor ip;\r\n    boolean[] state;\r\n    int[] pixels;\r\n    Queue<Integer> nextPixels;\r\n    int threshould;\r\n\r\n    /**\r\n     * adds one pixel to the next-pixel queue only if it's not\r\n     * already added.\r\n     */\r\n    void addNextPixel(int p) {\r\n        if(!state[p]) {\r\n            nextPixels.add(p);\r\n            state[p] = true;\r\n        }\r\n    }\r\n\r\n    boolean pixelsSimilar(int color1, int color2) {\r\n        int dr = Math.abs(((color1 >> 16) & 0xff) -\r\n                          ((color2 >> 16) & 0xff));\r\n        int dg = Math.abs(((color1 >>  8) & 0xff) -\r\n                          ((color2 >>  8) & 0xff));\r\n        int db = Math.abs(((color1 >>  0) & 0xff) -\r\n                          ((color2 >>  0) & 0xff));\r\n        return ((double)(dr + dg + db) / 3.0) <= threshould;\r\n    }\r\n\r\n    /**\r\n     * actually does the hard work :)\r\n     * @param x the x position from which to start filling\r\n     * @param y the y position from which to start filling\r\n     */\r\n    private void doFill(int x, int y, boolean connect8) {\r\n        // first, add the start pixel\r\n        int width = ip.getWidth(),\r\n            height = ip.getHeight();\r\n        /* for 8bit, we just gonna take the median of rgb */\r\n        Color colorC = ij.gui.Toolbar.getForegroundColor();\r\n        int color = colorC.getRGB();\r\n        int firstPixel = ip.get(x, y);\r\n\r\n        // go on with the mainloop\r\n        addNextPixel(y * width + x);\r\n        while(!nextPixels.isEmpty()) {\r\n            int nextPixel = nextPixels.remove();\r\n            int pixel = pixels[nextPixel];\r\n            if(pixelsSimilar(pixel, firstPixel)) {\r\n                // yay it matches. put the neighbours.\r\n                int xN = nextPixel % width,\r\n                    yN = nextPixel / width;\r\n                /* the three pixels above */\r\n                if(yN - 1 >= 0) {\r\n                    if(connect8) {\r\n                        if(xN + 1 < width) { \r\n                            addNextPixel(nextPixel - width + 1);\r\n                        }\r\n                        if(xN - 1 >= 0) {\r\n                            addNextPixel(nextPixel - width - 1);\r\n                        }\r\n                    }\r\n                    addNextPixel(nextPixel - width);\r\n                }\r\n\r\n                /* pixels left and right from the current one */\r\n                if(xN > 0) {\r\n                    addNextPixel(nextPixel - 1);\r\n                }\r\n                if(xN + 1 < width) {\r\n                    addNextPixel(nextPixel + 1);\r\n                }\r\n\r\n                /* three pixels below */\r\n                if(yN + 1 < height) {\r\n                    if(connect8) {\r\n                        if(xN + 1 < width) { \r\n                            addNextPixel(nextPixel + width + 1);\r\n                        }\r\n                        if(xN - 1 >= 0) {\r\n                            addNextPixel(nextPixel + width - 1);\r\n                        }\r\n                    }\r\n                    addNextPixel(nextPixel + width);\r\n                }\r\n\r\n                /* color it finally */\r\n                pixels[nextPixel] = color;\r\n            }\r\n        }\r\n    }\r\n\r\n    @Override\r\n    public void run(ImageProcessor ip) {\r\n        ij.WindowManager.getCurrentImage().getCanvas().addMouseListener(this);\r\n        this.ip = ip;\r\n        this.pixels = (int[])ip.getPixels();\r\n        this.state = new boolean[ip.getPixelCount()];\r\n        this.nextPixels = new LinkedList<Integer>();\r\n    }\r\n\r\n    @Override\r\n    public int setup(String arg0, ImagePlus arg1) {\r\n        return DOES_RGB;\r\n    }\r\n\r\n    @Override\r\n    public void mouseClicked(MouseEvent e) {\r\n        ij.WindowManager.getCurrentWindow().getCanvas().removeMouseListener(this);\r\n        ij.gui.GenericDialog g = new GenericDialog(\"Please enter parameters\");\r\n        g.addChoice(\"connection\", new String[]{\"4-connect\", \"8-connect\"}, \"8-connect\");\r\n        g.addNumericField(\"Threshould (0..255)\", 0.0, 3);\r\n        g.showDialog();\r\n\r\n        boolean connect8 = g.getNextChoice().equals(\"8-connect\");\r\n        threshould = (int) g.getNextNumber();\r\n        doFill(e.getX(), e.getY(), connect8);\r\n        ij.WindowManager.getCurrentImage().draw();\r\n    }\r\n}"
  },
  {
    "path": "Algorithms/Graph/Floyd_Warshall/Floyd_Warshall.c",
    "content": "// C Program for Floyd Warshall Algorithm \n#include<stdio.h> \n\n// Number of vertices in the graph \n#define V 4 \n\n/* Define Infinite as a large enough value. This value will be used \nfor vertices not connected to each other */\n#define INF 99999 \n\n// A function to print the solution matrix \nvoid printSolution(int dist[][V]); \n\n// Solves the all-pairs shortest path problem using Floyd Warshall algorithm \nvoid floydWarshall (int graph[][V]) \n{ \n\t/* dist[][] will be the output matrix that will finally have the shortest \n\tdistances between every pair of vertices */\n\tint dist[V][V], i, j, k; \n\n\t/* Initialize the solution matrix same as input graph matrix. Or \n\twe can say the initial values of shortest distances are based \n\ton shortest paths considering no intermediate vertex. */\n\tfor (i = 0; i < V; i++) \n\t\tfor (j = 0; j < V; j++) \n\t\t\tdist[i][j] = graph[i][j]; \n\n\t/* Add all vertices one by one to the set of intermediate vertices. \n\t---> Before start of an iteration, we have shortest distances between all \n\tpairs of vertices such that the shortest distances consider only the \n\tvertices in set {0, 1, 2, .. k-1} as intermediate vertices. \n\t----> After the end of an iteration, vertex no. k is added to the set of \n\tintermediate vertices and the set becomes {0, 1, 2, .. k} */\n\tfor (k = 0; k < V; k++) \n\t{ \n\t\t// Pick all vertices as source one by one \n\t\tfor (i = 0; i < V; i++) \n\t\t{ \n\t\t\t// Pick all vertices as destination for the \n\t\t\t// above picked source \n\t\t\tfor (j = 0; j < V; j++) \n\t\t\t{ \n\t\t\t\t// If vertex k is on the shortest path from \n\t\t\t\t// i to j, then update the value of dist[i][j] \n\t\t\t\tif (dist[i][k] + dist[k][j] < dist[i][j]) \n\t\t\t\t\tdist[i][j] = dist[i][k] + dist[k][j]; \n\t\t\t} \n\t\t} \n\t} \n\n\t// Print the shortest distance matrix \n\tprintSolution(dist); \n} \n\n/* A utility function to print solution */\nvoid printSolution(int dist[][V]) \n{ \n\tprintf (\"The following matrix shows the shortest distances\"\n\t\t\t\" between every pair of vertices \\n\"); \n\tfor (int i = 0; i < V; i++) \n\t{ \n\t\tfor (int j = 0; j < V; j++) \n\t\t{ \n\t\t\tif (dist[i][j] == INF) \n\t\t\t\tprintf(\"%7s\", \"INF\"); \n\t\t\telse\n\t\t\t\tprintf (\"%7d\", dist[i][j]); \n\t\t} \n\t\tprintf(\"\\n\"); \n\t} \n} \n\n// driver program to test above function \nint main() \n{ \n\n\tint graph[V][V] = { {0, 5, INF, 10}, \n\t\t\t\t\t\t{INF, 0, 3, INF}, \n\t\t\t\t\t\t{INF, INF, 0, 1}, \n\t\t\t\t\t\t{INF, INF, INF, 0} \n\t\t\t\t\t}; \n\n\t// Print the solution \n\tfloydWarshall(graph); \n\treturn 0; \n} \n"
  },
  {
    "path": "Algorithms/Graph/Floyd_Warshall/Floyd_Warshall.cpp",
    "content": "#include <iostream>\n#include <algorithm>\n\nusing namespace std;\n\n// defining the number of vertices\n#define nV 4\n\n#define INF 999\n\nvoid printMatrix(int matrix[][nV]);\n\n// Implementing floyd warshall algorithm\nvoid floydWarshall(int graph[][nV]) {\n  int matrix[nV][nV], i, j, k;\n\n  for (i = 0; i < nV; i++)\n    for (j = 0; j < nV; j++)\n      matrix[i][j] = graph[i][j];\n\n  // Adding vertices individually\n  for (k = 0; k < nV; k++) {\n    for (i = 0; i < nV; i++) {\n      for (j = 0; j < nV; j++) {\n        matrix[i][j] = min(matrix[i][j], matrix[i][k] + matrix[k][j]);\n      }\n    }\n  }\n  printMatrix(matrix);\n}\n\nvoid printMatrix(int matrix[][nV]) {\n  for (int i = 0; i < nV; i++) {\n    for (int j = 0; j < nV; j++) {\n      if (matrix[i][j] == INF)\n        printf(\"%4s\", \"INF\");\n      else\n        printf(\"%4d\", matrix[i][j]);\n    }\n    printf(\"\\n\");\n  }\n}\n\nint main() {\n  int graph[nV][nV] = { {0,   3,   INF,   5},\n                        {2,   0,   INF,   4},\n                        {INF, 1,     0, INF},\n                        {INF, INF,   2,   0} };\n  floydWarshall(graph);\n  return 0;\n}"
  },
  {
    "path": "Algorithms/Graph/Floyd_Warshall/Floyd_Warshall.java",
    "content": "package Algorithms.Graph_Algorithms.Floyd_Warshall;\n\npublic class Floyd_Warshall {\n\n    private int INF = Integer.MAX_VALUE;\n\n    /** Number of nodes. Ex: 7 */\n    private int nodes = 7;\n\n    /** Edge matrix (INF if not exist edge) */\n    private int[][] edges = { { INF, 2, INF, 1, INF, INF, INF }, { INF, INF, INF, 3, 10, INF, INF },\n            { 4, INF, INF, INF, INF, 5, INF }, { INF, INF, 2, INF, 2, 8, 4 }, { INF, INF, INF, INF, INF, INF, 6 },\n            { INF, INF, INF, INF, INF, INF, INF }, { INF, INF, INF, INF, INF, 1, INF } };\n\n    /** Warshall - Path */\n    private boolean[][] warshallP = new boolean[nodes][nodes];\n\n    public void warshall() {\n        int i, j, k;\n\n        // Adjacency matrix into warshallP\n        for (i = 0; i < nodes; i++)\n            for (j = 0; j < nodes; j++)\n                warshallP[i][j] = (edges[i][j] != INF);\n\n        // Iterate\n        for (k = 0; k < nodes; k++)\n            for (i = 0; i < nodes; i++)\n                for (j = 0; j < nodes; j++)\n                    warshallP[i][j] = (warshallP[i][j] || (warshallP[i][k] && warshallP[k][j]));\n    }\n\n}"
  },
  {
    "path": "Algorithms/Graph/Floyd_Warshall/Floyd_Warshall.py",
    "content": "# Python Program for Floyd Warshall Algorithm \n\n# Number of vertices in the graph \nV = 4\n\n# Define infinity as the large enough value. This value will be \n# used for vertices not connected to each other \nINF = 99999\n\n# Solves all pair shortest path via Floyd Warshall Algorithm \ndef floydWarshall(graph): \n\n\t\"\"\" dist[][] will be the output matrix that will finally \n\t\thave the shortest distances between every pair of vertices \"\"\"\n\t\"\"\" initializing the solution matrix same as input graph matrix \n\tOR we can say that the initial values of shortest distances \n\tare based on shortest paths considering no \n\tintermediate vertices \"\"\"\n\tdist = map(lambda i : map(lambda j : j , i) , graph) \n\t\n\t\"\"\" Add all vertices one by one to the set of intermediate \n\tvertices. \n\t---> Before start of an iteration, we have shortest distances \n\tbetween all pairs of vertices such that the shortest \n\tdistances consider only the vertices in the set \n\t{0, 1, 2, .. k-1} as intermediate vertices. \n\t----> After the end of a iteration, vertex no. k is \n\tadded to the set of intermediate vertices and the \n\tset becomes {0, 1, 2, .. k} \n\t\"\"\"\n\tfor k in range(V): \n\n\t\t# pick all vertices as source one by one \n\t\tfor i in range(V): \n\n\t\t\t# Pick all vertices as destination for the \n\t\t\t# above picked source \n\t\t\tfor j in range(V): \n\n\t\t\t\t# If vertex k is on the shortest path from \n\t\t\t\t# i to j, then update the value of dist[i][j] \n\t\t\t\tdist[i][j] = min(dist[i][j] , \n\t\t\t\t\t\t\t\tdist[i][k]+ dist[k][j] \n\t\t\t\t\t\t\t\t) \n\tprintSolution(dist) \n\n\n# A utility function to print the solution \ndef printSolution(dist): \n\tprint \"Following matrix shows the shortest distances\\ \nbetween every pair of vertices\" \n\tfor i in range(V): \n\t\tfor j in range(V): \n\t\t\tif(dist[i][j] == INF): \n\t\t\t\tprint \"%7s\" %(\"INF\"), \n\t\t\telse: \n\t\t\t\tprint \"%7d\\t\" %(dist[i][j]), \n\t\t\tif j == V-1: \n\t\t\t\tprint \"\" \n\n\n\n# Driver program to test the above program \n\ngraph = [[0,5,INF,10], \n\t\t\t[INF,0,3,INF], \n\t\t\t[INF, INF, 0, 1], \n\t\t\t[INF, INF, INF, 0] \n\t\t] \n# Print the solution \nfloydWarshall(graph); \n"
  },
  {
    "path": "Algorithms/Graph/Floyd_Warshall/README.md",
    "content": "## This folder is empty.\n"
  },
  {
    "path": "Algorithms/Graph/Hopcroft_Karp/Hopcroft_Karp_algorithm.cpp",
    "content": "// C++ implementation of Hopcroft Karp algorithm for \n// maximum matching \n\n/*\n\nSample test case\n\nEnter the number of vertices on left side of Bipartite Graph: 4\nEnter the number of vertces on Right side of Bipartite Graph: 4\nEnter the number of edges: 6\nEnter the left source vertex and right destination vertex with space\n1 2\n1 3\n2 1\n3 2\n4 2\n4 4\nSize of maximum matching is 4\n*/\n\n\n#include<bits/stdc++.h> \nusing namespace std; \n#define NIL 0 \n#define INF INT_MAX \n  \n// A class to represent Bipartite graph \nclass bipartiteGraph \n{ \n    // m and n are number of vertices on left \n    // and right sides of Bipartite Graph \n    int m, n; \n  \n    // pointers to arrays \n    int *pairU, *pairV, *dist; \n    \n    // adj[u] stores adjacents of left side \n    // vertex 'u'. The value of u ranges from 1 to m. \n    // 0 is used for dummy vertex \n    list<int> *adj; \n  \n  \npublic: \n    bipartiteGraph(int m, int n); // Constructor \n    void addEdge(int u, int v); // To add edge \n  \n    // Checking augmenting path \n    bool bfs(); \n  \n    // Ading augmenting path  \n    bool dfs(int u); \n  \n    // Returns size of maximum matcing \n    int hopcroftKarp(); \n}; \n  \n\nint bipartiteGraph::hopcroftKarp() \n{ \n    // pairU[u] stores pair of u in matching where u \n    // is a vertex on left side of Bipartite Graph.\n    pairU = new int[m+1]; \n  \n    // pairV[v] stores pair of v in matching. If v \n    pairV = new int[n+1]; \n  \n    // dist[u] stores distance of left side vertices \n    // dist[u] is one more than dist[u'] if u is next \n    // to u'in augmenting path \n    dist = new int[m+1]; \n  \n    // Initialize NIL as pair of all vertices \n    for (int u=0; u<=m; u++) \n        pairU[u] = NIL; \n    for (int v=0; v<=n; v++) \n        pairV[v] = NIL; \n  \n    // Initialize result \n    int result = 0; \n  \n    // Keep updating the result while there is an \n    // augmenting path. \n    while (bfs()) \n    { \n        // Find a free vertex \n        for (int u=1; u<=m; u++) \n  \n            // If current vertex is free and there is \n            // an augmenting path from current vertex \n            if (pairU[u]==NIL && dfs(u)) \n                result++; \n    } \n    return result; \n} \n  \n\nbool bipartiteGraph::bfs() \n{ \n    queue<int> Q; //an integer queue \n  \n    // First layer of vertices (set distance as 0) \n    for (int u=1; u<=m; u++) \n    { \n        // If this is a free vertex, add it to queue \n        if (pairU[u]==NIL) \n        { \n            // u is not matched \n            dist[u] = 0; \n            Q.push(u); \n        } \n  \n        // Else set distance as infinite so that this vertex \n        // is considered next time \n        else dist[u] = INF; \n    } \n  \n    // Initialize distance to NIL as infinite \n    dist[NIL] = INF; \n  \n    // Q is going to contain vertices of left side only.  \n    while (!Q.empty()) \n    { \n        // Dequeue a vertex \n        int u = Q.front(); \n        Q.pop(); \n  \n        // If this node is not NIL and can provide a shorter path to NIL \n        if (dist[u] < dist[NIL]) \n        { \n            // Get all adjacent vertices of the dequeued vertex u \n            list<int>::iterator i; \n            for (i=adj[u].begin(); i!=adj[u].end(); ++i) \n            { \n                int v = *i; \n  \n                // If pair of v is not considered so far \n                // (v, pairV[V]) is not yet explored edge. \n                if (dist[pairV[v]] == INF) \n                { \n                    // Consider the pair and add it to queue \n                    dist[pairV[v]] = dist[u] + 1; \n                    Q.push(pairV[v]); \n                } \n            } \n        } \n    } \n  \n    // If we could come back to NIL using alternating path of distinct \n    // vertices then there is an augmenting path \n    return (dist[NIL] != INF); \n} \n  \n// Returns true if there is an augmenting path beginning with free vertex u \nbool bipartiteGraph::dfs(int u) \n{ \n    if (u != NIL) \n    { \n        list<int>::iterator i; \n        for (i=adj[u].begin(); i!=adj[u].end(); ++i) \n        { \n            // Adjacent to u \n            int v = *i; \n  \n            // Follow the distances set by BFS \n            if (dist[pairV[v]] == dist[u]+1) \n            { \n                // If dfs for pair of v also returns \n                // true \n                if (dfs(pairV[v]) == true) \n                { \n                    pairV[v] = u; \n                    pairU[u] = v; \n                    return true; \n                } \n            } \n        } \n  \n        // If there is no augmenting path beginning with u. \n        dist[u] = INF; \n        return false; \n    } \n    return true; \n} \n  \nbipartiteGraph::bipartiteGraph(int m, int n) \n{ \n    this->m = m; \n    this->n = n; \n    adj = new list<int>[m+1]; \n} \n  \nvoid bipartiteGraph::addEdge(int u, int v) \n{ \n    adj[u].push_back(v); \n} \n  \n// Driver Program \nint main() \n{ \n    int m,n,i;\n    cout << \"Enter the number of vertices on left side of Bipartite Graph: \";\n    cin >> m;\n    cout << \"Enter the number of vertces on Right side of Bipartite Graph: \";\n    cin >> n;\n    bipartiteGraph g(m, n);\n    cout << \"Enter the number of edges: \";\n    cin >> i;\n    cout << \"Enter the left source vertex and right destination vertex with space\\n\";\n    while (i)\n    {\n        int temp1, temp2;\n        cin >> temp1>> temp2;\n        g.addEdge(temp1,temp2);\n    }\n    \n  \n    cout << \"Size of maximum matching is \" << g.hopcroftKarp() << endl; \n  \n    return 0; \n} "
  },
  {
    "path": "Algorithms/Graph/Hungarian_algorithm/Hungarian_algorithm.cpp",
    "content": "//////////////////////////////////////////////////////////////////////////\n// Hungarian.cpp: Implementation file for Class HungarianAlgorithm.\n//\n\n\n#include <stdlib.h>\n#include <cfloat> // for DBL_MAX\n#include <cmath>  // for fabs()\n#include \"Hungarian.h\"\n\n\nHungarianAlgorithm::HungarianAlgorithm(){}\nHungarianAlgorithm::~HungarianAlgorithm(){}\n\n\n//********************************************************//\n// A single function wrapper for solving assignment problem.\n//********************************************************//\ndouble HungarianAlgorithm::Solve(vector <vector<double> >& DistMatrix, vector<int>& Assignment)\n{\n\tunsigned int nRows = DistMatrix.size();\n\tunsigned int nCols = DistMatrix[0].size();\n\n\tdouble *distMatrixIn = new double[nRows * nCols];\n\tint *assignment = new int[nRows];\n\tdouble cost = 0.0;\n\n\t// Fill in the distMatrixIn. Mind the index is \"i + nRows * j\".\n\t// Here the cost matrix of size MxN is defined as a double precision array of N*M elements.\n\t// In the solving functions matrices are seen to be saved MATLAB-internally in row-order.\n\t// (i.e. the matrix [1 2; 3 4] will be stored as a vector [1 3 2 4], NOT [1 2 3 4]).\n\tfor (unsigned int i = 0; i < nRows; i++)\n\t\tfor (unsigned int j = 0; j < nCols; j++)\n\t\t\tdistMatrixIn[i + nRows * j] = DistMatrix[i][j];\n\n\t// call solving function\n\tassignmentoptimal(assignment, &cost, distMatrixIn, nRows, nCols);\n\n\tAssignment.clear();\n\tfor (unsigned int r = 0; r < nRows; r++)\n\t\tAssignment.push_back(assignment[r]);\n\n\tdelete[] distMatrixIn;\n\tdelete[] assignment;\n\treturn cost;\n}\n\n\n//********************************************************//\n// Solve optimal solution for assignment problem using Munkres algorithm, also known as Hungarian Algorithm.\n//********************************************************//\nvoid HungarianAlgorithm::assignmentoptimal(int *assignment, double *cost, double *distMatrixIn, int nOfRows, int nOfColumns)\n{\n\tdouble *distMatrix, *distMatrixTemp, *distMatrixEnd, *columnEnd, value, minValue;\n\tbool *coveredColumns, *coveredRows, *starMatrix, *newStarMatrix, *primeMatrix;\n\tint nOfElements, minDim, row, col;\n\n\t/* initialization */\n\t*cost = 0;\n\tfor (row = 0; row<nOfRows; row++)\n\t\tassignment[row] = -1;\n\n\t/* generate working copy of distance Matrix */\n\t/* check if all matrix elements are positive */\n\tnOfElements = nOfRows * nOfColumns;\n\tdistMatrix = (double *)malloc(nOfElements * sizeof(double));\n\tdistMatrixEnd = distMatrix + nOfElements;\n\n\tfor (row = 0; row<nOfElements; row++)\n\t{\n\t\tvalue = distMatrixIn[row];\n\t\tif (value < 0)\n\t\t\tcerr << \"All matrix elements have to be non-negative.\" << endl;\n\t\tdistMatrix[row] = value;\n\t}\n\n\n\t/* memory allocation */\n\tcoveredColumns = (bool *)calloc(nOfColumns, sizeof(bool));\n\tcoveredRows = (bool *)calloc(nOfRows, sizeof(bool));\n\tstarMatrix = (bool *)calloc(nOfElements, sizeof(bool));\n\tprimeMatrix = (bool *)calloc(nOfElements, sizeof(bool));\n\tnewStarMatrix = (bool *)calloc(nOfElements, sizeof(bool)); /* used in step4 */\n\n\t/* preliminary steps */\n\tif (nOfRows <= nOfColumns)\n\t{\n\t\tminDim = nOfRows;\n\n\t\tfor (row = 0; row<nOfRows; row++)\n\t\t{\n\t\t\t/* find the smallest element in the row */\n\t\t\tdistMatrixTemp = distMatrix + row;\n\t\t\tminValue = *distMatrixTemp;\n\t\t\tdistMatrixTemp += nOfRows;\n\t\t\twhile (distMatrixTemp < distMatrixEnd)\n\t\t\t{\n\t\t\t\tvalue = *distMatrixTemp;\n\t\t\t\tif (value < minValue)\n\t\t\t\t\tminValue = value;\n\t\t\t\tdistMatrixTemp += nOfRows;\n\t\t\t}\n\n\t\t\t/* subtract the smallest element from each element of the row */\n\t\t\tdistMatrixTemp = distMatrix + row;\n\t\t\twhile (distMatrixTemp < distMatrixEnd)\n\t\t\t{\n\t\t\t\t*distMatrixTemp -= minValue;\n\t\t\t\tdistMatrixTemp += nOfRows;\n\t\t\t}\n\t\t}\n\n\t\t/* Steps 1 and 2a */\n\t\tfor (row = 0; row<nOfRows; row++)\n\t\t\tfor (col = 0; col<nOfColumns; col++)\n\t\t\t\tif (fabs(distMatrix[row + nOfRows*col]) < DBL_EPSILON)\n\t\t\t\t\tif (!coveredColumns[col])\n\t\t\t\t\t{\n\t\t\t\t\t\tstarMatrix[row + nOfRows*col] = true;\n\t\t\t\t\t\tcoveredColumns[col] = true;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t}\n\telse /* if(nOfRows > nOfColumns) */\n\t{\n\t\tminDim = nOfColumns;\n\n\t\tfor (col = 0; col<nOfColumns; col++)\n\t\t{\n\t\t\t/* find the smallest element in the column */\n\t\t\tdistMatrixTemp = distMatrix + nOfRows*col;\n\t\t\tcolumnEnd = distMatrixTemp + nOfRows;\n\n\t\t\tminValue = *distMatrixTemp++;\n\t\t\twhile (distMatrixTemp < columnEnd)\n\t\t\t{\n\t\t\t\tvalue = *distMatrixTemp++;\n\t\t\t\tif (value < minValue)\n\t\t\t\t\tminValue = value;\n\t\t\t}\n\n\t\t\t/* subtract the smallest element from each element of the column */\n\t\t\tdistMatrixTemp = distMatrix + nOfRows*col;\n\t\t\twhile (distMatrixTemp < columnEnd)\n\t\t\t\t*distMatrixTemp++ -= minValue;\n\t\t}\n\n\t\t/* Steps 1 and 2a */\n\t\tfor (col = 0; col<nOfColumns; col++)\n\t\t\tfor (row = 0; row<nOfRows; row++)\n\t\t\t\tif (fabs(distMatrix[row + nOfRows*col]) < DBL_EPSILON)\n\t\t\t\t\tif (!coveredRows[row])\n\t\t\t\t\t{\n\t\t\t\t\t\tstarMatrix[row + nOfRows*col] = true;\n\t\t\t\t\t\tcoveredColumns[col] = true;\n\t\t\t\t\t\tcoveredRows[row] = true;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\tfor (row = 0; row<nOfRows; row++)\n\t\t\tcoveredRows[row] = false;\n\n\t}\n\n\t/* move to step 2b */\n\tstep2b(assignment, distMatrix, starMatrix, newStarMatrix, primeMatrix, coveredColumns, coveredRows, nOfRows, nOfColumns, minDim);\n\n\t/* compute cost and remove invalid assignments */\n\tcomputeassignmentcost(assignment, cost, distMatrixIn, nOfRows);\n\n\t/* free allocated memory */\n\tfree(distMatrix);\n\tfree(coveredColumns);\n\tfree(coveredRows);\n\tfree(starMatrix);\n\tfree(primeMatrix);\n\tfree(newStarMatrix);\n\n\treturn;\n}\n\n/********************************************************/\nvoid HungarianAlgorithm::buildassignmentvector(int *assignment, bool *starMatrix, int nOfRows, int nOfColumns)\n{\n\tint row, col;\n\n\tfor (row = 0; row<nOfRows; row++)\n\t\tfor (col = 0; col<nOfColumns; col++)\n\t\t\tif (starMatrix[row + nOfRows*col])\n\t\t\t{\n#ifdef ONE_INDEXING\n\t\t\t\tassignment[row] = col + 1; /* MATLAB-Indexing */\n#else\n\t\t\t\tassignment[row] = col;\n#endif\n\t\t\t\tbreak;\n\t\t\t}\n}\n\n/********************************************************/\nvoid HungarianAlgorithm::computeassignmentcost(int *assignment, double *cost, double *distMatrix, int nOfRows)\n{\n\tint row, col;\n\n\tfor (row = 0; row<nOfRows; row++)\n\t{\n\t\tcol = assignment[row];\n\t\tif (col >= 0)\n\t\t\t*cost += distMatrix[row + nOfRows*col];\n\t}\n}\n\n/********************************************************/\nvoid HungarianAlgorithm::step2a(int *assignment, double *distMatrix, bool *starMatrix, bool *newStarMatrix, bool *primeMatrix, bool *coveredColumns, bool *coveredRows, int nOfRows, int nOfColumns, int minDim)\n{\n\tbool *starMatrixTemp, *columnEnd;\n\tint col;\n\n\t/* cover every column containing a starred zero */\n\tfor (col = 0; col<nOfColumns; col++)\n\t{\n\t\tstarMatrixTemp = starMatrix + nOfRows*col;\n\t\tcolumnEnd = starMatrixTemp + nOfRows;\n\t\twhile (starMatrixTemp < columnEnd){\n\t\t\tif (*starMatrixTemp++)\n\t\t\t{\n\t\t\t\tcoveredColumns[col] = true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\n\t/* move to step 3 */\n\tstep2b(assignment, distMatrix, starMatrix, newStarMatrix, primeMatrix, coveredColumns, coveredRows, nOfRows, nOfColumns, minDim);\n}\n\n/********************************************************/\nvoid HungarianAlgorithm::step2b(int *assignment, double *distMatrix, bool *starMatrix, bool *newStarMatrix, bool *primeMatrix, bool *coveredColumns, bool *coveredRows, int nOfRows, int nOfColumns, int minDim)\n{\n\tint col, nOfCoveredColumns;\n\n\t/* count covered columns */\n\tnOfCoveredColumns = 0;\n\tfor (col = 0; col<nOfColumns; col++)\n\t\tif (coveredColumns[col])\n\t\t\tnOfCoveredColumns++;\n\n\tif (nOfCoveredColumns == minDim)\n\t{\n\t\t/* algorithm finished */\n\t\tbuildassignmentvector(assignment, starMatrix, nOfRows, nOfColumns);\n\t}\n\telse\n\t{\n\t\t/* move to step 3 */\n\t\tstep3(assignment, distMatrix, starMatrix, newStarMatrix, primeMatrix, coveredColumns, coveredRows, nOfRows, nOfColumns, minDim);\n\t}\n\n}\n\n/********************************************************/\nvoid HungarianAlgorithm::step3(int *assignment, double *distMatrix, bool *starMatrix, bool *newStarMatrix, bool *primeMatrix, bool *coveredColumns, bool *coveredRows, int nOfRows, int nOfColumns, int minDim)\n{\n\tbool zerosFound;\n\tint row, col, starCol;\n\n\tzerosFound = true;\n\twhile (zerosFound)\n\t{\n\t\tzerosFound = false;\n\t\tfor (col = 0; col<nOfColumns; col++)\n\t\t\tif (!coveredColumns[col])\n\t\t\t\tfor (row = 0; row<nOfRows; row++)\n\t\t\t\t\tif ((!coveredRows[row]) && (fabs(distMatrix[row + nOfRows*col]) < DBL_EPSILON))\n\t\t\t\t\t{\n\t\t\t\t\t\t/* prime zero */\n\t\t\t\t\t\tprimeMatrix[row + nOfRows*col] = true;\n\n\t\t\t\t\t\t/* find starred zero in current row */\n\t\t\t\t\t\tfor (starCol = 0; starCol<nOfColumns; starCol++)\n\t\t\t\t\t\t\tif (starMatrix[row + nOfRows*starCol])\n\t\t\t\t\t\t\t\tbreak;\n\n\t\t\t\t\t\tif (starCol == nOfColumns) /* no starred zero found */\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t/* move to step 4 */\n\t\t\t\t\t\t\tstep4(assignment, distMatrix, starMatrix, newStarMatrix, primeMatrix, coveredColumns, coveredRows, nOfRows, nOfColumns, minDim, row, col);\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tcoveredRows[row] = true;\n\t\t\t\t\t\t\tcoveredColumns[starCol] = false;\n\t\t\t\t\t\t\tzerosFound = true;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t}\n\n\t/* move to step 5 */\n\tstep5(assignment, distMatrix, starMatrix, newStarMatrix, primeMatrix, coveredColumns, coveredRows, nOfRows, nOfColumns, minDim);\n}\n\n/********************************************************/\nvoid HungarianAlgorithm::step4(int *assignment, double *distMatrix, bool *starMatrix, bool *newStarMatrix, bool *primeMatrix, bool *coveredColumns, bool *coveredRows, int nOfRows, int nOfColumns, int minDim, int row, int col)\n{\n\tint n, starRow, starCol, primeRow, primeCol;\n\tint nOfElements = nOfRows*nOfColumns;\n\n\t/* generate temporary copy of starMatrix */\n\tfor (n = 0; n<nOfElements; n++)\n\t\tnewStarMatrix[n] = starMatrix[n];\n\n\t/* star current zero */\n\tnewStarMatrix[row + nOfRows*col] = true;\n\n\t/* find starred zero in current column */\n\tstarCol = col;\n\tfor (starRow = 0; starRow<nOfRows; starRow++)\n\t\tif (starMatrix[starRow + nOfRows*starCol])\n\t\t\tbreak;\n\n\twhile (starRow<nOfRows)\n\t{\n\t\t/* unstar the starred zero */\n\t\tnewStarMatrix[starRow + nOfRows*starCol] = false;\n\n\t\t/* find primed zero in current row */\n\t\tprimeRow = starRow;\n\t\tfor (primeCol = 0; primeCol<nOfColumns; primeCol++)\n\t\t\tif (primeMatrix[primeRow + nOfRows*primeCol])\n\t\t\t\tbreak;\n\n\t\t/* star the primed zero */\n\t\tnewStarMatrix[primeRow + nOfRows*primeCol] = true;\n\n\t\t/* find starred zero in current column */\n\t\tstarCol = primeCol;\n\t\tfor (starRow = 0; starRow<nOfRows; starRow++)\n\t\t\tif (starMatrix[starRow + nOfRows*starCol])\n\t\t\t\tbreak;\n\t}\n\n\t/* use temporary copy as new starMatrix */\n\t/* delete all primes, uncover all rows */\n\tfor (n = 0; n<nOfElements; n++)\n\t{\n\t\tprimeMatrix[n] = false;\n\t\tstarMatrix[n] = newStarMatrix[n];\n\t}\n\tfor (n = 0; n<nOfRows; n++)\n\t\tcoveredRows[n] = false;\n\n\t/* move to step 2a */\n\tstep2a(assignment, distMatrix, starMatrix, newStarMatrix, primeMatrix, coveredColumns, coveredRows, nOfRows, nOfColumns, minDim);\n}\n\n/********************************************************/\nvoid HungarianAlgorithm::step5(int *assignment, double *distMatrix, bool *starMatrix, bool *newStarMatrix, bool *primeMatrix, bool *coveredColumns, bool *coveredRows, int nOfRows, int nOfColumns, int minDim)\n{\n\tdouble h, value;\n\tint row, col;\n\n\t/* find smallest uncovered element h */\n\th = DBL_MAX;\n\tfor (row = 0; row<nOfRows; row++)\n\t\tif (!coveredRows[row])\n\t\t\tfor (col = 0; col<nOfColumns; col++)\n\t\t\t\tif (!coveredColumns[col])\n\t\t\t\t{\n\t\t\t\t\tvalue = distMatrix[row + nOfRows*col];\n\t\t\t\t\tif (value < h)\n\t\t\t\t\t\th = value;\n\t\t\t\t}\n\n\t/* add h to each covered row */\n\tfor (row = 0; row<nOfRows; row++)\n\t\tif (coveredRows[row])\n\t\t\tfor (col = 0; col<nOfColumns; col++)\n\t\t\t\tdistMatrix[row + nOfRows*col] += h;\n\n\t/* subtract h from each uncovered column */\n\tfor (col = 0; col<nOfColumns; col++)\n\t\tif (!coveredColumns[col])\n\t\t\tfor (row = 0; row<nOfRows; row++)\n\t\t\t\tdistMatrix[row + nOfRows*col] -= h;\n\n\t/* move to step 3 */\n\tstep3(assignment, distMatrix, starMatrix, newStarMatrix, primeMatrix, coveredColumns, coveredRows, nOfRows, nOfColumns, minDim);\n}\n"
  },
  {
    "path": "Algorithms/Graph/Johnson_algorithm/Johnson_algorithm.cpp",
    "content": "/* \n\n@ CPP Program to implement Johnson algorithm\n\n    @ Sample Graph with negative weights\n\n\n             5\n         |-------|\n         |       |   \n         v  -3   |\n    --->(0)---->(1)\n    |    | ^     |\n    |    |  \\ 1  |\n-1  |  2 |   \\   | 3\n    |    |    \\  |\n    |    v     \\ v\n    ----(3)-----(2)\n             4\n\n    \n    @ Sample output\n\n\n        Enter the number of vertices : 4\n        Enter the number of edges : 7\n        Enter the edges with source, destination and weight : \n        0 1 -3\n        1 2 3\n        3 2 4\n        2 0 1\n        1 0 5\n        0 3 2\n        3 0 -1\n\n        Shortest distance with vertex 0 as the source : \n        Vertex           Distance from Source\n        0                0\n        1                -3\n        2                0\n        3                2\n\n        Shortest distance with vertex 1 as the source : \n        Vertex           Distance from Source\n        0                4\n        1                0\n        2                3\n        3                6\n\n        Shortest distance with vertex 2 as the source : \n        Vertex           Distance from Source\n        0                1\n        1                -2\n        2                0\n        3                3\n\n        Shortest distance with vertex 3 as the source : \n        Vertex           Distance from Source\n        0                -1\n        1                -4\n        2                -1\n        3                0\n\n*/\t\n\n\n\n\n#include <bits/stdc++.h> \n  \nusing namespace std;\n\n// a structure to represent a weighted edge in graph \nstruct Edge { \n    int src, dest, weight; \n}; \n  \n// a structure to represent a connected, directed and \n// weighted graph \nstruct Graph { \n    // V-> Number of vertices, E-> Number of edges \n    int V, E; \n  \n    // graph is represented as an array of edges. \n    struct Edge* edge; \n}; \n  \n// Creates a graph with V vertices and E edges \nstruct Graph* createGraph(int V, int E) \n{ \n    struct Graph* graph = new Graph; \n    graph->V = V; \n    graph->E = E; \n    graph->edge = new Edge[E]; \n    return graph; \n} \n  \n  \n// The main function that finds shortest distances from src to \n// all other vertices using Bellman-Ford algorithm.  The function \n// also detects negative weight cycle \nvector<int> BellmanFord(struct Graph* graph) \n{ \n    int V = graph->V; \n    int E = graph->E; \n    vector<int> dist; \n  \n    // Step 1:  Add a source s and calculate its min distance from every other node \n\n    for (int i = 0; i <= V; i++) \n        dist.push_back(INT_MAX);\n    dist[V] = 0; \n\n    // An edge is added from s all other vertices...\n\n    for (int i = 0; i < V; i++)\n    {\n        graph->edge[(E-V)+i].src = V;\n        graph->edge[(E-V)+i].dest= i;\n        graph->edge[(E-V)+i].weight = 0;\n    }\n    \n  \n    // Step 2: Relax all edges |V| - 1 times. A simple shortest \n    // path from src to any other vertex can have at-most |V| - 1 \n    // edges \n    for (int i = 0; i < V; i++) { \n        for (int j = 0; j < E; j++) { \n            int u = graph->edge[j].src; \n            int v = graph->edge[j].dest; \n            int weight = graph->edge[j].weight; \n            if (dist[u] != INT_MAX && dist[u] + weight < dist[v]) \n                dist[v] = dist[u] + weight; \n        } \n    } \n  \n    // Step 3: check for negative-weight cycles.  The above step \n    // guarantees shortest distances if graph doesn't contain \n    // negative weight cycle.  If we get a shorter path, then there \n    // is a cycle. \n    for (int i = 0; i < E; i++) { \n        int u = graph->edge[i].src; \n        int v = graph->edge[i].dest; \n        int weight = graph->edge[i].weight; \n        if (dist[u] != INT_MAX && dist[u] + weight < dist[v]) { \n            printf(\"Graph contains negative weight cycle\"); \n            return dist; // If negative cycle is detected, simply return \n        } \n    } \n  \n    dist.pop_back();\n    return dist; \n} \n\nvoid printSolution(int dist[]) \n{ \n    printf(\"Vertex \\t\\t Distance from Source\\n\"); \n    for (int i = 0; i < 4; i++) \n        printf(\"%d \\t\\t %d\\n\", i, dist[i]); \n} \n\n\n//  Returns the vertex with minimum  \n//  distance from the source \nint minDistance(int dist[], bool sptSet[], int V) \n{ \n    // Initialize min value \n    int min = INT_MAX, min_index; \n  \n    for (int v = 0; v < V; v++) \n        if (sptSet[v] == false && dist[v] <= min) \n            min = dist[v], min_index = v; \n  \n    return min_index; \n} \n\n// dijkstra algorithm for graph with \n// modified weights(removing negative weights)\nvoid dijkstra(struct Graph* graph, int src, vector<int> h){\n\n    int V = graph->V;\n    int E = graph->E;\n    int dist[V];\n    bool sptSet[V];\n\n    for (int i = 0; i < V; i++) \n        dist[i] = INT_MAX, sptSet[i] = false;\n\n    dist[src] = 0;\n\n    for (int i = 0; i < V-1; i++)\n    {\n        int u = minDistance(dist, sptSet, V);\n\n        sptSet[u]= true;\n        \n        for (int j = 0; j < E-V; j++)\n        {\n            int tu = graph->edge[j].src;\n            int v = graph->edge[j].dest;\n            int w = graph->edge[j].weight; \n            if (!sptSet[v] && dist[tu] != INT_MAX && dist[tu] + w < dist[v])\n            {\n                dist[v] = dist[tu] + w;\n            }           \n        }\n    }\n\n    // δ (u, v) + h (v) - h (u)\n\n    for (int i = 0; i < V; i++)\n    {\n        dist[i] = dist[i] + h[i] - h[src];\n    }\n    \n    printSolution(dist);\n}\n\n// Johnson's algorithm for finding all pairs shortest paths\n// main algorithm\nvoid johnsonAlgorithm(struct Graph* graph){\n    \n    int V = graph->V;\n    int E = graph->E;\n\n    vector<int> modifiedWeights = BellmanFord(graph);\n\n    cout << endl;\n\n    for (int i = 0; i < E-V; i++)\n    {\n        int u = graph->edge[i].src; \n        int v = graph->edge[i].dest; \n        graph->edge[i].weight = graph->edge[i].weight + modifiedWeights[u] - modifiedWeights[v];\n    }\n\n    for(int src = 0; src < V; src++){\n        cout << \"\\nShortest distance with vertex \" << src << \" as the source : \\n\";\n        dijkstra(graph,src,modifiedWeights);\n    }\n    \n}\n\n  \n// Driver program to test above functions \nint main() \n{ \n    int V; // Number of vertices in graph \n    int E; // Number of edges in graph \n    cout << \"Enter the number of vertices : \";\n    cin >> V;\n    cout << \"Enter the number of edges : \";\n    cin >> E;\n\n    // Array of edges for graph\n    struct Graph* graph = createGraph(V, E+V);\n\n    //------- adding the edges of the graph\n    /*\n            edge(u, v)\n            where \tu = start vertex of the edge (u,v)\n                    v = end vertex of the edge (u,v)\n            \n            w is the weight of the edge (u,v)\n        */\n\n    cout << \"Enter the edges with source, destination and weight : \\n\";\n\n    for (int i = 0; i < E; i++)\n    {\n        int t1, t2, t3;\n        cin >> t1 >> t2 >> t3;\n        graph->edge[i].src = t1;\n        graph->edge[i].dest= t2;\n        graph->edge[i].weight = t3;\n    }; \n  \n    johnsonAlgorithm(graph); \n  \n    return 0; \n} "
  },
  {
    "path": "Algorithms/Graph/Karger_algorithm/Karger_algorithm.cpp",
    "content": "#include <iostream>\n#include <fstream>\n#include <vector>\n#include <time.h>\n#include <math.h>\n#include <cassert>\n\nnamespace std {   };\nusing namespace std;\n\nclass karger_graph\n{\npublic:\n   void   set(size_t r, size_t c, size_t d) {   _data[(r * _rc) + c] = d;   return;   };\n   size_t get(size_t r, size_t c) const {   return _data[(r * _rc) + c];   };\n\n   void   set_size(size_t rc) {   _rc = rc;   _data.resize(_rc * _rc);   return;   };\n   size_t get_size() const {   return _rc;   };\n\n   size_t count_vertices() const;\n   size_t count_edges() const;\n   karger_graph& remove_self_loops();\n   karger_graph& merge_vertices(size_t u, size_t v);\n\nprivate:\n   size_t _rc;\n   vector<size_t> _data;\n};\n\nsize_t karger_graph::count_vertices() const\n{\n   size_t n = 0;\n\n   for (size_t i = 0; i < _rc; ++i)\n   {\n      size_t k = 0;\n      for (size_t j = 0; j < _rc; ++j)\n      {\n         k = k + get(i, j);\n      }\n\n      if (k > 0)\n      {\n         ++n;\n      }\n   }\n\n   return n;\n}\n\nsize_t karger_graph::count_edges() const\n{\n   size_t n = 0;\n\n   for (size_t i = 0; i < _rc; ++i)\n   {\n      for (size_t j = 0; j < _rc; ++j)\n      {\n         n = n + get(i, j);\n      }\n   }\n\n   return n;\n}\n\nkarger_graph& karger_graph::remove_self_loops()\n{\n   for (size_t i = 0; i < _rc; ++i)\n   {\n      set(i, i, 0);\n   }\n\n   return *this;\n}\n\nkarger_graph& karger_graph::merge_vertices(size_t u, size_t v)\n{\n   if (u < _rc && v < _rc)\n   {\n      for (size_t i = 0; i < _rc; ++i)\n      {\n         size_t e = get(v, i);\n         set(v, i, 0);\n\n         size_t n = e + get(u, i);\n         set(u, i, n);\n\n         e = get(i, v);\n         set(i, v, 0);\n\n         n = e + get(i, u);\n         set(i, u, n);\n      }\n   }\n\n   return *this;\n}\n\nvoid random_contraction_algorithm(karger_graph& km)\n{\n   km.remove_self_loops();\n\n   while (km.count_vertices() > 2)\n   {\n   /* Pick an edge. */\n      size_t random_vertex_u = 0, random_vertex_v = 0;\n\n      do\n      {\n         random_vertex_u = rand() % km.get_size();\n         random_vertex_v = rand() % km.get_size();\n      }\n      while (km.get(random_vertex_u, random_vertex_v) == 0);\n\n      assert(random_vertex_u != random_vertex_v);\n\n   /* Merge both vertices. */\n      km.merge_vertices(random_vertex_u, random_vertex_v);\n\n   /* Remove self-loops. */\n      km.remove_self_loops();\n   }\n\n   return;\n}\n\nistream& operator>>(istream& is, karger_graph& km)\n{\n   size_t dim = 0;\n   is >> dim;\n   km.set_size(dim);\n\n   for (size_t i = 0; i < dim; ++i)\n   {\n      for (size_t j = 0; j < dim; ++j)\n      {\n         size_t k = 0;\n         is >> k;\n         if (is.good() != false)\n         {\n            km.set(i, j, k);\n         }\n      }\n   }\n\n   return is;\n}\n\nostream& operator<<(ostream& os, const karger_graph& km)\n{\n   size_t dim = km.get_size();\n\n   os << dim << \" \" << endl;\n\n   for (size_t i = 0; i < dim; ++i)\n   {\n      for (size_t j = 0; j < dim; ++j)\n      {\n         os << km.get(i, j) << \" \";\n      }\n\n      os << endl;\n   }\n\n   return os;\n}\n\nint main(int argc, char* argv[])\n{\n   karger_graph graph, minimum_graph;\n   graph.set_size(0);\n   minimum_graph.set_size(0);\n\n   if (argc > 1)\n   {\n      ifstream ifs;\n      ifs.open(argv[1]);\n      ifs >> graph;\n      ifs.close();\n   }\n\n   if (graph.get_size() > 0)\n   {\n      cout << \"Input vertex count: \" << graph.count_vertices() << endl;\n      cout << \"Input edge count: \" << (graph.count_edges() >> 1) << endl;\n\n      srand((unsigned int) time(NULL));\n\n      size_t n = graph.count_vertices();\n      float ln = log((float) n);\n      size_t runs = n * n * ln, minimum_cut = UINT_MAX;\n\n      for (size_t i = 0; i < runs; ++i)\n      {\n         karger_graph copy = graph;\n         random_contraction_algorithm(copy);\n\n         size_t cut = copy.count_edges();\n         assert((cut % 2) == 0);\n\n         if (cut < minimum_cut)\n         {\n            minimum_cut = cut;\n            minimum_graph = copy;\n         }\n      }\n\n      cout << \"Runs: \" << runs << endl;\n      cout << \"Output vertex count: \" << minimum_graph.count_vertices() << endl;\n      cout << \"Output edge count: \" << (minimum_graph.count_edges() >> 1) << endl;\n\n      assert(minimum_cut == 6);\n\n      if (argc > 2)\n      {\n         ofstream ofs;\n         ofs.open(argv[2]);\n         ofs << minimum_graph;\n         ofs.close();\n      }\n   }\n\n   cin.get();\n\n   return 0;\n}\n"
  },
  {
    "path": "Algorithms/Graph/Karger_algorithm/sample.txt",
    "content": "40 \n0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 1 1 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 1 0 \n0 0 0 1 0 0 0 0 1 0 0 0 0 0 0 0 0 1 0 0 0 0 1 0 0 1 0 0 0 0 0 0 0 0 0 1 0 0 0 0 \n0 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 \n0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 \n0 0 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 \n0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 \n0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 1 0 0 1 0 0 0 0 1 0 0 \n0 0 0 0 1 0 0 0 0 0 0 1 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 1 0 0 0 0 0 0 0 0 0 \n0 1 0 0 0 0 0 0 0 1 0 0 1 0 0 0 1 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 \n0 0 0 0 0 0 0 0 1 0 0 1 0 1 0 0 0 0 0 1 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 \n0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 1 0 0 0 1 0 0 1 0 0 0 0 0 0 0 \n0 0 0 0 0 0 0 1 0 1 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 \n0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 1 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 \n0 0 0 0 1 0 0 1 0 1 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 \n1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 1 0 0 0 0 \n0 0 1 0 0 1 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 1 0 1 0 0 1 0 0 0 0 0 \n0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 1 0 0 0 0 0 1 0 1 \n1 1 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 \n1 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 \n0 0 0 0 0 0 0 0 1 1 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 \n0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 1 0 0 0 0 0 0 0 1 0 0 0 \n0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 1 1 0 0 0 0 1 \n1 1 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 \n0 0 0 1 0 0 0 0 0 0 0 0 1 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 \n0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 1 0 1 0 0 0 0 0 1 0 0 0 \n0 1 0 0 0 0 0 0 0 0 1 0 0 0 1 0 0 0 1 0 0 0 0 0 0 0 1 0 0 0 1 0 0 0 0 0 0 0 0 0 \n0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 1 0 0 1 0 1 0 0 0 0 0 1 0 0 0 \n0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 1 0 0 \n0 0 0 0 1 0 0 1 0 1 0 0 0 0 0 0 0 0 0 0 1 0 0 0 1 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 \n0 0 0 0 0 0 1 0 0 0 1 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 1 0 0 0 \n0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 0 0 0 0 0 0 0 0 0 1 0 0 0 \n0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 1 \n0 0 0 0 0 0 1 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 1 0 0 \n0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 1 \n0 0 1 0 0 1 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 \n1 1 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 \n0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 1 0 1 0 0 1 1 0 0 0 0 0 0 0 0 0 \n0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 1 0 0 0 0 0 0 1 \n1 0 0 0 0 0 0 0 1 0 0 0 1 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 \n0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 1 0 0 0 0 0 0 0 0 0 1 0 1 0 0 0 1 0 0 \n"
  },
  {
    "path": "Algorithms/Graph/Kosarajus_Algorithm/kosajaru.rs",
    "content": "\nuse std::vec;\ntype Node  = usize;           \ntype Graph = Vec<Vec<Node>>; // A directed graph, in adjacency list\ntype Stack = Vec<Node>;      // The rust std does not provides a default stack, but we can use a vector instead\n\n\n// Example\nfn main() {\n    let graph = vec![\n        vec![2,3],\n        vec![0],\n        vec![1],\n        vec![4],\n        vec![],\n    ];\n    let n_nodes = 5;\n\n    println!(\"Provided graph: \");\n    println!(\"  Number of nodes: {}\", n_nodes);\n    println!(\"  Edges:\");\n    for (i, v) in graph.iter().enumerate() {\n        for j in v {\n            println!(\"  {} {}\", i, j);\n        }\n    }\n\n    let components = kosajaru(graph, n_nodes);\n\n    println!(\"Obtained result: \");\n\n    for (node, component) in components.iter().enumerate() {\n        println!(\"  node {} belongs to component {}\", node, component);\n    }\n\n}\n/*\n    Given a graph represented by an adjacency list and the number of nodes, \n    return an array A such that A[i] == m iff the node i belongs to strongly \n    connected component m.\n\n    The Kosajaru algorithm works by traversing the graph with DFS traversal and \n    storing in a stack the finalization order, from the node that ended first in the bottom\n    of the stack, to the node that ended last, at the top of the  stack.\n\n    Next, we have to traverse the inverse graph in the order stored in the stack, meaning\n    that we traverse the nodes in the inverse finalization order. Each DFS tree generated by this\n    second traversal represents a strongly connected component \n*/\nfn kosajaru(graph : Graph, n_nodes : usize) -> Vec<usize> {\n\n    // Order at which each node ends its DFS traversal\n    let mut call_stack = vec![];\n    // remember what nodes were visited so far with the memo array\n    let mut memo = vec::from_elem(0, n_nodes);\n    for node in 0..n_nodes {\n        // visit all non-visited nodes\n        if memo[node] == 0 {\n            dfs_traversal(&graph, node, &mut memo, &mut call_stack)\n        }\n    }\n    \n    // Now that we have the call stack, we compute the strong components by traversing the \n    // inverse graph in the orden given by the call stack\n    let graph_inverse = reverse_graph(&graph);\n    \n    // Reset our memo array\n    for i in &mut memo{\n        *i = 0;\n    }\n    \n    // just a counter\n    let mut numerator = 1..;\n    for node in call_stack.iter().rev() {\n        // traverse every non-visited node in the stack order (left to right in our stack vector)\n        if memo[*node] == 0 {\n            dfs_color(&graph_inverse, *node, &mut memo, numerator.next().unwrap());\n        }\n    }\n\n    memo\n}\n\n// Utility function to reverse the given graph\nfn reverse_graph(graph : &Graph) -> Graph{\n    // init an empty graph\n    let mut graph_inverse : Graph = vec::from_elem(vec![], graph.len());\n    \n    // iterate over our current graph, i is the current node, \n    // v is a list of nodes, such that there's an edge i -> j por every j in v.\n    for (i, v) in graph.iter().enumerate() {\n        for j in v {\n            // we add an edge j -> i to our inverse graph \n            // for every edge i -> j in our graph\n            graph_inverse[*j].push(i);\n        }\n    }   \n\n    graph_inverse\n}\n\n// Given a graph, a source node v, the the list of not visited nodes 'memo' such that the node i \n// has not been visited iff memo[i] == 0, the stack of traversed nodes, \n// perform a dfs traversal over a graph storing the order at which each sub traversal has ended\n// in the given stack\nfn dfs_traversal(graph : &Graph, v : Node, memo : &mut Vec<Node>, stack : &mut Stack) {\n\n    memo[v] = 1;\n    for node in &graph[v] {\n        if memo[*node] == 0 {\n            dfs_traversal(graph, *node, memo, stack);\n        }\n    }\n    stack.push(v);\n}\n\n// Traverse a graph starting in the node v and setting the color of the resulting\n// dfs tree to the given color\nfn dfs_color(graph : &Graph, v : Node, memo : &mut Vec<Node>, color : usize) {\n    memo[v] = color;\n    for node in &graph[v] {\n        if memo[*node] == 0 {\n            dfs_color(graph, *node, memo, color);\n        }\n    }\n}\n\n\n"
  },
  {
    "path": "Algorithms/Graph/Kosarajus_Algorithm/kosaraju.ts",
    "content": "// TypeScript Implementation of Kosarajus's Algorithm\n\nclass Graph {\n  public vertices: number;\n  public adjancency: number[][];\n  constructor(vertices: number) {\n    this.vertices = vertices;\n    this.adjancency = [];\n    for (let i = 0; i < vertices; i++) {\n      this.adjancency.push([]);\n    }\n  }\n\n  addEdge(v: number, w: number): void {\n    this.adjancency[v].push(w);\n  }\n\n  printSCCs(): void {\n    var stack: number[] = [];\n\n    let visited: boolean[] = new Array(this.vertices);\n    for (let i = 0; i < this.vertices; i++) {\n      visited[i] = false;\n    }\n\n    for (let i = 0; i < this.vertices; i++) {\n      if (visited[i] == false) {\n        this.fillOrder(i, visited, stack);\n      }\n    }\n\n    const gr = this.getTranspose();\n    for (let i = 0; i < this.vertices; i++) {\n      visited[i] = false;\n    }\n\n    while (stack.length != 0) {\n      let v = stack.pop() as number;\n\n      if (visited[v] == false) {\n        console.log(gr.DFSUtil(v, visited));\n      }\n    }\n  }\n\n  fillOrder(v: number, visited: boolean[], stack: number[]): void {\n    // Mark the current node as visited and print it\n    visited[v] = true;\n\n    // Recur for all the vertices adjacent to this vertex\n\n    for (let i = 0; i < this.adjancency[v].length; i++) {\n      let n = this.adjancency[v][i];\n      if (!visited[n]) this.fillOrder(n, visited, stack);\n    }\n\n    // All vertices reachable from v are processed by now,\n    // push v to Stack\n    stack.push(v);\n  }\n\n  getTranspose(): Graph {\n    let g = new Graph(this.vertices);\n    for (let v = 0; v < this.vertices; v++) {\n      // Recur for all the vertices adjacent to this vertex\n      for (let i = 0; i < this.adjancency[v].length; i++) {\n        let n = this.adjancency[v][i];\n        g.adjancency[n].push(v);\n      }\n    }\n    return g;\n  }\n\n  DFSUtil(v: number, visited: boolean[]): string {\n    // Mark the current node as visited and print it\n    visited[v] = true;\n    let result = \"\";\n    result += v + \" \";\n\n    // Recur for all the vertices adjacent to this vertex\n\n    for (let i = 0; i < this.adjancency[v].length; i++) {\n      let n = this.adjancency[v][i];\n      if (!visited[n]) result += this.DFSUtil(n, visited);\n    }\n\n    return result;\n  }\n}\n\n// Create a graph given in the above diagram\nlet g = new Graph(5);\ng.addEdge(1, 0);\ng.addEdge(0, 2);\ng.addEdge(2, 1);\ng.addEdge(0, 3);\ng.addEdge(3, 4);\n\nconsole.log(\"Following are strongly connected components \" + \"in given graph \");\ng.printSCCs();\n"
  },
  {
    "path": "Algorithms/Graph/Kosarajus_Algorithm/kosaraju_algorithm_strongly_connected_components.cpp",
    "content": "#include <bits/stdc++.h>\nusing namespace std;\n\nvoid init() {\n#ifndef ONLINE_JUDGE\n\tfreopen(\"input.txt\", \"r\", stdin);\n\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n}\n\nvoid dfs(vector<int> graph[], int node, bool *visited, vector<int> &ordering) {\n\tvisited[node] = true;\n\tfor (int neigh : graph[node]) {\n\t\tif (!visited[neigh]) {\n\t\t\tdfs(graph, neigh, visited, ordering);\n\t\t}\n\t}\n\t// Ordering based on finish time. Finish Time: When you are going back after visiting all its neighbours\n\tordering.push_back(node);\n}\n// Normal dfs call after reversing the graph\nvoid dfs2(vector<int> rev_graph[], int node, bool *visited) {\n\tvisited[node] = true;\n\tcout << node << \",\";\n\tfor (int neigh : rev_graph[node]) {\n\t\tif (!visited[neigh]) {\n\t\t\tdfs2(rev_graph, neigh, visited);\n\t\t}\n\t}\n}\nvoid solve(vector<int> graph[], vector<int> rev_graph[], int V) {\n\tbool visited[V] = {0};\n\tvector<int> ordering;\n\n\tfor (int i = 0; i < V; i++) {\n\t\tif (!visited[i]) {\n\t\t\tdfs(graph, i, visited, ordering);\n\t\t}\n\t}\n\n\tchar component_name = 'A';\n\n\tmemset(visited, 0, V);\n\tfor (int x = ordering.size() - 1; x >= 0; x--) {\n\t\tint node = ordering[x];\n\t\tif (!visited[node]) {\n\t\t\tcout << \"Component \" << component_name << \"--> \";\n\t\t\t// There is a component starting from this node\n\t\t\tdfs2(rev_graph, node, visited);\n\t\t}\n\t\tcout << endl;\n\t\tcomponent_name++;\n\t}\n}\n\nint main() {\n\tinit();\n\tint V, E;\n\tcin >> V >> E;\n\tvector<int> graph[V], rev_graph[V];\n\tfor (int i = 0; i < E; i++) {\n\t\tint x, y;\n\t\tcin >> x >> y;\n\t\tgraph[x].push_back(y);\n\n\t\t// graph where all the directed edges are reversed in the original graph\n\t\trev_graph[y].push_back(x);\n\t}\n\t// Strongly Connected Components\n\tsolve(graph, rev_graph, V);\n\treturn 0;\n}\n"
  },
  {
    "path": "Algorithms/Graph/Kruskal's_MST/KruskalMST.c",
    "content": "// Kruskal's Minimum Spanning Tree\n// C Programming\n\n#include<stdio.h>\n \n#define MAX 30\n\n// GraphEdgeWeights -> Array storing the weights of edges in the graph.\nint GraphEdgeWeights[MAX][MAX];\n\n// nVertices -> No: of vertices in the graph.\nint nVertices;\n \n// Edge -> Structure for an edge with its source vertex, destination vertex and its weight.\ntypedef struct Edge{\n    int src, dest, weight;\n} Edge;\n\n// EdgeList -> Structure for storing an array of Edge along with its size.\ntypedef struct EdgeList{\n    Edge data[MAX];\n    int size;\n} EdgeList;\n\nEdgeList edgeList;\nEdgeList spanList;\n\n// Function name : SortEdges\n// Input         : void\n// Output        : void\n// Logic         : For sorting the edges based on their weights.\nvoid SortEdges(){\n    int i, j;\n    Edge tempEdge;\n    \n    for(i=1; i<edgeList.size; i++)\n        for(j=0; j<edgeList.size-1; j++)\n            if(edgeList.data[j].weight > edgeList.data[j+1].weight){\n                tempEdge            = edgeList.data[j];\n                edgeList.data[j]    = edgeList.data[j+1];\n                edgeList.data[j+1]  = tempEdge;\n            }\n}\n\n// Function name : FindVertexSet\n// Input         : vertexSet array, vertexNo\n// Output        : vertexSet\n// Logic         : For finding the vertexSet of a node in the spanning tree.\nint FindVertexSet(int vertexSet[], int vertexNo){\n    return(vertexSet[vertexNo]);\n}\n\n// Function name : Union\n// Input         : vertexSet array, source node, destination node\n// Output        : void\n// Logic         : For adding the both nodes to the same vertexSet.\nvoid Union(int vertexSet[], int srcNode, int destNode){\n    int i;\n    for(i=0; i<nVertices; i++)\n        if(vertexSet[i] == destNode)\n            vertexSet[i] = srcNode;\n}\n\n// Function name : KruskalMST\n// Input         : void\n// Output        : void\n// Logic         : For generating a minimum spanning tree.\nvoid KruskalMST(){\n\n    // Initialising the variables.\n    int vertexSet[MAX], i, j, srcNode, destNode;\n    \n    // Initialising the edgeList based on user input.\n    edgeList.size = 0;\n    for(i=1; i<nVertices; i++){\n        for(j=0; j<i; j++){\n            if(GraphEdgeWeights[i][j] != 0){\n                edgeList.data[edgeList.size].src     = i;\n                edgeList.data[edgeList.size].dest    = j;\n                edgeList.data[edgeList.size].weight  = GraphEdgeWeights[i][j];\n                edgeList.size++;\n            }\n        }\n    }\n\n    // Sorting the edges based on their weights.\n    SortEdges();\n    \n    // Assigning parents to every node of the tree.\n    for(i=0; i<nVertices; i++)\n        vertexSet[i] = i;\n    \n    // Creating the Minimum Spanning Tree.\n    spanList.size = 0;\n    for(i=0; i<edgeList.size; i++){\n        // Find Operation\n        srcNode = FindVertexSet(vertexSet, edgeList.data[i].src);\n        destNode = FindVertexSet(vertexSet, edgeList.data[i].dest);\n        \n        if(srcNode != destNode){\n            spanList.data[spanList.size] = edgeList.data[i];\n            spanList.size++;\n            // Union Operation\n            Union(vertexSet, srcNode, destNode);\n        }\n    }\n}\n\n// Function name : PrintResult\n// Input         : void\n// Output        : void\n// Logic         : For printing the result that is the cost of traversing the spanning tree.\nvoid PrintResult(){\n    int i,cost=0;\n    \n    for(i=0; i<spanList.size; i++){\n        printf(\"\\n%d->%d:%d\", \n            spanList.data[i].src, \n            spanList.data[i].dest, \n            spanList.data[i].weight);\n        cost = cost + spanList.data[i].weight;\n    }\n    printf(\"\\n=====================================\\n\");\n    printf(\"Cost = %d\", cost);\n}\n\n// Function name : main\n// Input         : void\n// Output        : void\n// Logic         : The driver function of the program.\nvoid main(){\n    int i, j, total_cost, weight;\n    \n    printf(\"\\nNumber of vertices : \");\n    scanf(\"%d\",&nVertices);\n    \n    for(i=0; i<nVertices; i++){\n        for(j=0; j<nVertices; j++){\n            if(i!=j){\n                if(i<j){\n                    printf(\"Edge Weight : \", i, j);\n                    scanf(\"%d\", &weight);\n                    GraphEdgeWeights[i][j] = weight;\n                }\n                else{\n                    GraphEdgeWeights[i][j] = GraphEdgeWeights[j][i];\n                }\n            }\n            else{\n                GraphEdgeWeights[i][j] = 0;\n            }\n        }\n\n    }\n            \n    KruskalMST();\n    PrintResult();\n}\n \n"
  },
  {
    "path": "Algorithms/Graph/Kruskal's_MST/Kruskal_Algorithm.cpp",
    "content": "#include <algorithm>\r\n#include <iostream>\r\n#include <vector>\r\nusing namespace std;\r\n\r\n#define edge pair<int, int>\r\n\r\nclass Graph {\r\n   private:\r\n  vector<pair<int, edge> > G;  // graph\r\n  vector<pair<int, edge> > T;  // mst\r\n  int *parent;\r\n  int V;  // number of vertices/nodes in graph\r\n   public:\r\n  Graph(int V);\r\n  void AddWeightedEdge(int u, int v, int w);\r\n  int find_set(int i);\r\n  void union_set(int u, int v);\r\n  void kruskal();\r\n  void print();\r\n};\r\nGraph::Graph(int V) {\r\n  parent = new int[V];\r\n\r\n  //i 0 1 2 3 4 5\r\n  //parent[i] 0 1 2 3 4 5\r\n  for (int i = 0; i < V; i++)\r\n    parent[i] = i;\r\n\r\n  G.clear();\r\n  T.clear();\r\n}\r\nvoid Graph::AddWeightedEdge(int u, int v, int w) {\r\n  G.push_back(make_pair(w, edge(u, v)));\r\n}\r\nint Graph::find_set(int i) {\r\n  // If i is the parent of itself\r\n  if (i == parent[i])\r\n    return i;\r\n  else\r\n    // Else if i is not the parent of itself\r\n    // Then i is not the representative of his set,\r\n    // so we recursively call Find on its parent\r\n    return find_set(parent[i]);\r\n}\r\n\r\nvoid Graph::union_set(int u, int v) {\r\n  parent[u] = parent[v];\r\n}\r\nvoid Graph::kruskal() {\r\n  int i, uRep, vRep;\r\n  sort(G.begin(), G.end());  // increasing weight\r\n  for (i = 0; i < G.size(); i++) {\r\n    uRep = find_set(G[i].second.first);\r\n    vRep = find_set(G[i].second.second);\r\n    if (uRep != vRep) {\r\n      T.push_back(G[i]);  // add to tree\r\n      union_set(uRep, vRep);\r\n    }\r\n  }\r\n}\r\nvoid Graph::print() {\r\n  cout << \"Edge :\"\r\n     << \" Weight\" << endl;\r\n  for (int i = 0; i < T.size(); i++) {\r\n    cout << T[i].second.first << \" - \" << T[i].second.second << \" : \"\r\n       << T[i].first;\r\n    cout << endl;\r\n  }\r\n}\r\nint main() {\r\n  Graph g(6);\r\n  g.AddWeightedEdge(0, 1, 4);\r\n  g.AddWeightedEdge(0, 2, 4);\r\n  g.AddWeightedEdge(1, 2, 2);\r\n  g.AddWeightedEdge(1, 0, 4);\r\n  g.AddWeightedEdge(2, 0, 4);\r\n  g.AddWeightedEdge(2, 1, 2);\r\n  g.AddWeightedEdge(2, 3, 3);\r\n  g.AddWeightedEdge(2, 5, 2);\r\n  g.AddWeightedEdge(2, 4, 4);\r\n  g.AddWeightedEdge(3, 2, 3);\r\n  g.AddWeightedEdge(3, 4, 3);\r\n  g.AddWeightedEdge(4, 2, 4);\r\n  g.AddWeightedEdge(4, 3, 3);\r\n  g.AddWeightedEdge(5, 2, 2);\r\n  g.AddWeightedEdge(5, 4, 3);\r\n  g.kruskal();\r\n  g.print();\r\n  return 0;\r\n}\r\n\r\n/* Output:\r\nEdge : Weight\r\n1 - 2 : 2\r\n2 - 5 : 2\r\n2 - 3 : 3\r\n3 - 4 : 3\r\n0 - 1 : 4 */\r\n"
  },
  {
    "path": "Algorithms/Graph/Kruskal's_MST/README.md",
    "content": "## This folder is empty.\n"
  },
  {
    "path": "Algorithms/Graph/Kruskal's_MST/cpp/kruskal.cpp",
    "content": "#include <vector>\n#include <queue>\n#include <algorithm>\n#include <stdio.h>\nusing namespace std;\n\n// Typedef to represent a weighted edge: (weight, (node u,node v))\ntypedef pair<int, pair<int,int>> edge;\n\n// Typedef to represent a disjoint set from a node (int) vector:\ntypedef vector<int> disjoint_set;\n\n/*\n    Given an undirected, edge-weighted connected graph, \n    computes the edges of the minimum spanning tree. \n    We use disjoint sets to provide an efficient computation. \n\n    The kruskal algorithm works by selecting the lightest edge at each\n    iteration. The problem with this approach is that it's possible\n    to find an edge with minimum weight such that this edge creates a cycle \n    with our currently added edges. Thus, we have to find a way to check for cycles\n    when we are about to add an edge. We can achieve this using disjoints sets,\n    which is the solution provided below.\n    Given the set of edges of the connected graph and the number of nodes\n    returns the list of edges of the MST\n*/\nvector<edge> kruskal(vector<edge> graph, int n_nodes);\n\n/*\n    The disjoint set data structure  works by representing each subset as\n    a root parent for every sub element. We choose such parent for \n    the subset, and when we add a new element to the subset, \n    we make this element a child of the root or a child of some other\n    child of the root. This way, to check whether an element belongs\n    to an specific subset, we have tu check if its root is the same\n    as the subsets root. Here, we start with a disjoint set such that\n    every element represents its own singleton subset. \n*/\ndisjoint_set create_set(int n);\n\n/*\n    To merge two sets together, we have to make the root of one\n    of the sets be a child of an element of the second subset\n*/\nvoid set_union(disjoint_set &s, int u, int v);\n\n/*\n    The get parent function returns the root \n    of the subset containing i. Also, this function \n    flattens the parents tree by updating the parents of i \n    such that every parent points directly to the root. This way, \n    the next time we need to ask for the parent of some of these elements,\n    we have to traverse a shorter distance to the root.\n*/\nint get_parent(disjoint_set &s, int i);\n\n/*\n    \n*/\nint main() {\n\n    // Example. \n    vector<edge> graph = {\n            {14, {3, 5}}, \n            {11, {1, 7}}, \n            {10, {5, 4}},\n            {1,  {7, 6}},\n            {2,  {8, 2}},\n            {2,  {6, 5}},\n            {4,  {0, 1}},\n            {9,  {3, 4}},\n            {8,  {1, 2}},\n            {8,  {0, 7}},\n            {7,  {7, 8}},\n            {7,  {2, 3}},\n            {6,  {8, 6}},\n            {4,  {2, 5}}  \n        };\n\n    printf(\"Input graph: \\n\");\n    for(auto e : graph)\n        printf(\"(%d, %d) w: %d\\n\", e.second.first, e.second.second, e.first);\n\n    vector<edge> MST = kruskal(graph, 9);\n\n    printf(\"obtained graph: \\n\");\n    for (auto e : MST )\n        printf(\"(%d, %d) w: %d\\n\", e.second.first, e.second.second, e.first);\n\n    return 0;\n}\n\n/*\n    Create a new partition of n sets,\n    enumerated in the range 0 <= i < n\n*/\ndisjoint_set create_set(int n) {\n\n    disjoint_set set(n);\n\n    for (int i = 0; i < n; i++)\n        set[i] = i;\n\n    return set;\n}\n\n/*\n    Get the parent of element i in the disjoint set s and\n    flattens the disjoint set as much as it can\n*/\nint get_parent(disjoint_set &s, int i) {\n\n    // If this node is its own parent, return it. \n    // This is the parent of the subset.\n    if (i == s[i])\n        return i;\n\n    // Get the parent of this node's parent\n    int parent = get_parent(s, s[i]);\n\n    // update the parent and return it\n    return s[i] = parent;\n}\n\n/*\n    Merge two sets in one, making the set v a child of set u\n*/\nvoid set_union(disjoint_set &s, int u, int v) {\n\n    int parent_u = get_parent(s, u);\n    int parent_v = get_parent(s, v);\n\n    // Set the parent of root of v as the parent of root of u\n    s[parent_v] = parent_u;\n}\n\n\n/*\n    Check if node u contains the node v for the set s\n*/\nbool contains(disjoint_set &s, int u, int v) {\n    int u_parent = get_parent(s, u);\n    int v_parent = get_parent(s, v);\n\n    // The subset where u belongs contains the subset v \n    // if they have the same parent.\n    return u_parent == v_parent;\n}\n\nvector<edge> kruskal(vector<edge> graph, const int n_nodes) {\n    \n    priority_queue<edge> edge_queue;        // Use this priority queue to sort the edges by weight within a queue\n    int edge_counter = 0;           // how many edges have been added so far\n    vector<edge> tree(n_nodes - 1); // the resulting spanning tree\n    disjoint_set set = create_set(n_nodes); // Our disjoint set to test for cycles\n\n    for (auto e : graph) {\n        // Note that the priority queue sorts in non-increasing order, \n        // so we have to negate the weight in order to invert the order.\n        edge inverted_weight_edge = {-e.first, e.second };\n        edge_queue.push(inverted_weight_edge);\n    } \n\n    // note that every spanning tree follows: \n    // number of edges = number of nodes - 1 \n    while (edge_counter < n_nodes - 1) {\n        edge current = edge_queue.top(); \n        edge_queue.pop();\n\n        // each side of the edge\n        int u = current.second.first; \n        int v = current.second.second;\n\n        if ( !contains(set, u, v) ) {\n\n            // Add this edge to our tree, since it does not creates a cycle\n            tree[edge_counter++] =  { -current.first, {u,v} }; \n            // (Remember to negate the weight ^, so we have the original edge)\n\n            // Merge the spanning tree containing u with the spanning tree containing v\n            set_union(set, u, v);\n        }\n    }\n        \n    return tree;\n}\n\n"
  },
  {
    "path": "Algorithms/Graph/Kruskal's_MST/python/KruskalMST.py",
    "content": "# Python program for Kruskal's algorithm to find\n# Minimum Spanning Tree of a given connected,\n# undirected and weighted graph\ndef takeInput():\n    \"\"\"\n    Takes input from stdin\n    :return: Graph\n    \"\"\"\n    v = int(input(\"Enter the number of vertices \\t\"))\n    e = int(input(\"Enter the number of edges \\t \"))\n    edges = []\n    for i in range(e):\n        print(\"Enter edge {} in form u v w\".format(str(i+1)))\n        inputEdge = list(map(int, input().split(\" \")))\n        edges.append(inputEdge)\n    graph = Graph(v,edges)\n    return graph\n\n\nclass Graph:\n    def __init__(self, vertices,graph ):\n        \"\"\"\n        constructor for the graph object\n        :param vertices:  No of vertices\n        :param graph: dictionary used to store the graph\n        # Graph is stored as a list of tuples [(u,v,w)]\n        \"\"\"\n        self.V = vertices\n        self.graph = graph\n\n    def find(self, parent, i):\n        \"\"\"\n        Finds the parent or representative element\n        :param parent: Array storing current belongingness of the vertices\n        :param i: vertex whose parent is to be found\n        :return: parent vertex\n        \"\"\"\n        if parent[i] == i:\n            return i\n        return self.find(parent, parent[i])\n\n    def union(self, parent, rank, x, y):\n        \"\"\"\n        union by rank of two sets of x and y\n        :param parent: array storing current belongingness of the vertices\n        :param rank: array storing current rank of the vertices (used to find the rank of parent)\n        :param x: set x\n        :param y: set y\n        :return:\n        \"\"\"\n        xroot = self.find(parent, x)\n        yroot = self.find(parent, y)\n\n        # Attach smaller rank tree under root of high rank tree (Union by Rank)\n        if rank[xroot] < rank[yroot]:\n            parent[xroot] = yroot\n        elif rank[xroot] > rank[yroot]:\n            parent[yroot] = xroot\n        else:\n            # If ranks are same, then make one as root\n            # and increment its rank by one\n            parent[yroot] = xroot\n            rank[xroot] += 1\n\n\n    def KruskalMST(self):\n        \"\"\"\n        main function construct MST using Kruskal's Algo\n        :return: List of edges in the MST\n        \"\"\"\n\n        result = []  # This will store the resultant MST\n\n        i = 0  # An index variable, used for sorted edges\n        e = 0  # An index variable, used for result[]\n\n        # Sorting all the edges in non-decereasing order of the weights\n        self.graph = sorted(self.graph, key=lambda item: item[2])\n\n        parent = []\n        rank = []\n\n        # Create V subsets with single elements\n        for node in range(self.V):\n            parent.append(node)\n            rank.append(0)\n\n        # Number of edges to be taken is equal to V-1\n        while e < self.V - 1:\n\n            # Pick the smallest edge and increment\n            # the index for next iteration\n            u, v, w = self.graph[i]\n            i = i + 1\n            x = self.find(parent, u)\n            y = self.find(parent, v)\n\n            # If including this edge does't cause cycle,\n            # include it in result and increment the index\n            # of result for next edge\n            if x != y:\n                e = e + 1\n                result.append([u, v, w])\n                self.union(parent, rank, x, y)\n            # Else discard the edge\n            else:\n                continue\n\n        # print the contents of result[] to display the built MST\n        print(\"Edges in the MST are as follows \")\n        print(\"Source \\t-> Destination \\t| Weight\")\n        for u, v, weight in result:\n            print(\"%d \\t-> %d \\t\\t|  %d\" % (u, v, weight))\n\n\ngraph = takeInput()\ngraph.KruskalMST()\n"
  },
  {
    "path": "Algorithms/Graph/Kruskal's_MST/rust/kruskal.rs",
    "content": "use std::vec;\n/*\n    The disjoint set data structure we are using to improve performance\n*/\nstruct DisjointSet {\n    partition : vec::Vec<usize>\n}\n\n/*\n    Struct representing a simple weighted edge\n*/\nstruct Edge {\n    weight  : i32,\n    u       : usize,\n    v       : usize\n}\n\n/*\n    Since we are interested in connected graphs, \n    the list of edges is enough to specify the entire graph\n    for our algorithm\n*/\ntype Graph = vec::Vec<Edge>;\n\nfn main() {\n    // Example:\n    let graph = vec![\n        Edge::new(13, 3, 5), \n        Edge::new(11,1, 7), \n        Edge::new(10,5, 4),\n        Edge::new(1, 7, 6),\n        Edge::new(2, 8, 2),\n        Edge::new(2, 6, 5),\n        Edge::new(4, 0, 1),\n        Edge::new(9, 3, 4),\n        Edge::new(8, 1, 2),\n        Edge::new(8, 0, 7),\n        Edge::new(7, 7, 8),\n        Edge::new(7, 2, 3),\n        Edge::new(6, 8, 6),\n        Edge::new(4, 2, 5) \n    ];\n\n    println!(\"Input graph: \");\n    for e in graph.iter() {\n        println!(\"({}, {}) W: {}\", e.u, e.v, e.weight);\n    }\n\n    let tree = kruskal(graph, 9);\n\n    println!(\"Obtained graph: \");\n    for e in tree.iter() {\n        println!(\"({}, {}) W: {}\", e.u, e.v, e.weight);\n    }\n}\n\nimpl Edge {\n    fn new(weight : i32, u : usize, v : usize) -> Edge {\n        Edge{ weight, u, v }\n    }\n}\n\nimpl DisjointSet {\n\n    /*\n        The disjoint set data structure  works by representing each subset as\n        a root parent for every sub element. We choose such parent for \n        the subset, and when we add a new element to the subset, \n        we make this element a child of the root or a child of some other\n        child of the root. This way, to check whether an element belongs\n        to an specific subset, we have tu check if its root is the same\n        as the subset's root. Here, we start with a convenient disjoint set\n        such that every element represents its own singleton subset. \n    */\n    fn new(n_nodes : usize) -> DisjointSet {\n        DisjointSet {\n            partition : (0..n_nodes).collect()\n        }\n    }\n\n    /*\n        Get the parent of element i in the disjoint set s and\n        flattens the disjoint set as much as it can.\n\n        The get parent function returns the root \n        of the subset containing i. Also, this function \n        flattens the parents tree by updating the parents of i \n        such that every parent points directly to the root. This way, \n        the next time we need to ask for the parent of some of these elements,\n        we have to traverse a shorter distance to the root.\n    */\n    fn get_parent(&mut self, i : usize) -> usize {\n\n        // If this node is its own parent, return it. \n        // This is the parent of the subset.\n        if self.partition[i] == i {\n            return i;\n        }\n\n        // Otherwise, get the parent of this node's parent\n        let parent = self.get_parent(self.partition[i]);\n        self.partition[i] = parent; // flattens the tree\n        parent\n    }\n\n    /*\n        Merge two sets in one, making the set v a child of set u\n    */\n    fn union(&mut self, u : usize, v : usize) {\n        let parent_u = self.get_parent(u);\n        let parent_v = self.get_parent(v);\n\n        if parent_u != parent_v {\n            // Set the parent of root of v as the parent of root of u\n            self.partition[parent_v] = parent_u;\n        }   \n    }\n\n    /*\n        Check if u's subset contains v for the set s\n    */\n    fn contains(&mut self, u : usize, v : usize) -> bool {\n\n        // The subset where u belongs contains the subset v \n        // if they have the same parent.\n        self.get_parent(u) == self.get_parent(v)\n    }\n\n}\n\n/*\n    Given an undirected, edge-weighted connected graph, \n    computes the edges of the minimum spanning tree. \n    We use disjoint sets to provide an efficient computation. \n\n    The kruskal algorithm works by selecting the lightest edge at each\n    iteration. The problem with this approach is that it's possible\n    to find an edge with minimum weight such that this edge creates a cycle \n    with our currently added edges. Thus, we have to find a way to check for cycles\n    when we are about to add an edge. We can achieve this using disjoints sets,\n    which is the solution provided below.\n    Given the set of edges of the connected graph and the number of nodes\n    returns the list of edges of the MST\n*/\nfn kruskal(mut graph : Graph, n_nodes : usize) -> Graph {\n\n    let mut n_edges = 0;                                      // how many edges have been added so far\n    let mut tree  : Graph = vec::Vec::with_capacity(n_nodes); // The resulting spanning tree\n    let mut set = DisjointSet::new(n_nodes);                  // Our disjoint set to test for cycles\n\n    // note that we use unstable since it does not requires additional space\n    // and we're conssuming the graph anyways\n    graph.sort_unstable_by_key(|e| e.weight); // Sort edges by their weight\n\n    for edge in graph {\n\n        // if u's subset contains v, then this edge creates a cycle.\n        if !set.contains(edge.u, edge.v) {\n\n            // Merge the spanning tree containing u with the spanning tree containing v\n            set.union(edge.u, edge.v);\n\n            // Add this edge to our tree, since it does not creates a cycle:\n            tree.push(edge);\n            n_edges += 1;\n        }\n\n        // every spanning tree follows: \n        // number of edges = number of nodes - 1 \n        if n_edges >= n_nodes - 1 {\n            break;\n        }\n    }\n\n    tree\n}"
  },
  {
    "path": "Algorithms/Graph/LIS/README.md",
    "content": "## This folder is empty.\n"
  },
  {
    "path": "Algorithms/Graph/Level order traversal.cpp",
    "content": "#include<bits/stdc++.h>\nusing namespace std;\n#define ll long long\nstruct node{\n    ll int data;\n    node* left;\n    node* right;\n};\nnode* newnode(ll int data)\n{\n    node* newnode=new node();\n    newnode->data=data;\n    newnode->left=NULL;\n    newnode->right=NULL;\n    //cout<<newnode<<endl;\n    return newnode;\n\n}\nvoid levelorder(node* root)\n{   if(root==NULL) return;\nelse\n{\n queue<node*>q;\n q.push(root);\n while(!q.empty())\n {\n     node* current= q.front();\n     cout<<current->data<<\" \";\n     if(current->left!=NULL)q.push(current->left);\n     if(current->right!=NULL)q.push(current->right);\n     q.pop();\n }\n}\n} node* inser(node* root,int data)\n{\n    if(root==NULL)\n    {\n        root=newnode(data);\n    }\n    else if(data<=root->data)\n    {\n        root->left=inser(root->left,data);\n    }\n    else\n    {\n        root->right=inser(root->right,data);\n    }\n    return root;\n}\nint main()\n{\n    node* root;\n     root=NULL;\n     root=inser(root,10);\n     root=inser(root,25);\n     root=inser(root,15);\n     root=inser(root,7);\n     root=inser(root,8);\n     root=inser(root,5);\n     root=inser(root,30);\n     levelorder(root);\n}\n\n"
  },
  {
    "path": "Algorithms/Graph/Lowest_Common_Manager/Lowest_Common_Manager.py",
    "content": "# O(N) T | O(d) S\n#numIP = numberOfImportantReports\n#lcm = lowestCommonManager\n\ndef getLowestCommonManager(topManager, reportOne, reportTwo):\n    return getOrgInfo(topManager, reportOne, reportTwo).lcm\n\n\ndef getOrgInfo(manager, reportOne, reportTwo):\n    numIP = 0\n    for dirRep in manager.directReports:\n        orgInfo = getOrgInfo(dirRep, reportOne, reportTwo)\n        if orgInfo.lcm is not None:\n            return orgInfo\n        numIP += orgInfo.numIP\n    if manager == reportOne or manager == reportTwo:\n        numIP += 1\n    lcm = manager if numIP == 2 else None\n    return OrgInfo(lcm, numIP)\n\n\nclass OrgInfo:\n    def __init__(self, lcm, numIP):\n        self.lcm = lcm\n        self.numIP = numIP\n\n# This is an input class. Do not edit.\n\n\nclass OrgChart:\n    def __init__(self, name):\n        self.name = name\n        self.directReports = []\n"
  },
  {
    "path": "Algorithms/Graph/Lowest_Common_Manager/QUESTION.md",
    "content": "### Lowest Common Manager\n\nYou're given three inputs, all of which are instances of an OrgChart class that have a directReports property pointing to their direct reports. The first input is the top manager in an organizational chart (i.e., the only instance that isn't anybody else's direct report), and the other two inputs are reports in the organizational chart. The two reports are guaranteed to be distinct. Write a function that returns the lowest common manager to the two reports.\n\nExample of an input :\ntopManager : node A\nreportOne : node E\nreportTwo : node I\n\n               A\n             /   \\\n            B     C\n           / \\   /  \\\n          D   E F    G\n        /   \\\n       H     I\n"
  },
  {
    "path": "Algorithms/Graph/Prim's_MST/Prim's_MST.py",
    "content": "# Prim's Algorithm in Python\n#Created by Sneha Sai KNVS(snehaa1989)\n#Implementation of Prim's Minimum spanning tree in Python\n#References:\n# - https://www.geeksforgeeks.org/prims-minimum-spanning-tree-mst-greedy-algo-5/\n\nINF = 9999999\n# number of vertices\nN = int(input(\"Enter the number of vertices:\"))\n# adjacency matrix to represent graph\n\n# Initialize list G\nG = []\nprint(\"Enter the entries rowwise:\")\n  \n# For user input\nfor i in range(N):          \n    a =[]\n    for j in range(N):     \n         a.append(int(input()))\n    G.append(a)\n# array to track node that was selected.\nselected_node = [0, 0, 0, 0, 0]\n\nno_edge = 0\n\nselected_node[0] = True\n\n# Let's print for edge and weight\nprint(\"Edge : Weight\\n\")\nwhile (no_edge < N - 1):\n# For every vertex in the set S, Let's find the all adjacent vertices\n# we calculate the distance from the vertex selected and\n# if the vertex is already in the set S, leave it otherwise\n# choose another vertex nearest to selected vertex.    \n    minimum = INF\n    a = 0\n    b = 0\n    for m in range(N):\n        if selected_node[m]:\n            for n in range(N):\n                if ((not selected_node[n]) and G[m][n]):  \n                    # not in selected and there is an edge\n                    if minimum > G[m][n]:\n                        minimum = G[m][n]\n                        a = m\n                        b = n\n    print(str(a) + \"-\" + str(b) + \":\" + str(G[a][b]))\n    selected_node[b] = True\n    no_edge += 1\n"
  },
  {
    "path": "Algorithms/Graph/Prim's_MST/Prims_MST.java",
    "content": "\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.PriorityQueue;\nimport java.util.Scanner;\n\nclass Node {\n\n    int node; // Adjacent node\n    int cost; // weight/cost/distance to adjacent node\n\n    Node (int node, int cost) {\n        this.node = node;\n        this.cost = cost;\n    }\n}\n\npublic class Prims_MST {\n\n    public static int Find_MST(int source_node, List<List<Node>> graph) {\n\n\n        // Priority queue stores the object node-cost into the queue with \n        // the smallest cost node at the top.\n        PriorityQueue<Node> pq = new PriorityQueue<>((a,b)-> a.cost-b.cost);\n\n        // The cost of the source node to itself is 0\n        pq.add(new Node(source_node, 0));\n\n        boolean vis[] = new boolean[graph.size()];\n\n        int mst_cost = 0;\n\n        while (!pq.isEmpty()) {\n\n            // remove the smallest element\n            Node item = pq.poll();\n\n            int node = item.node;\n            int cost = item.cost;\n\n            // If the node is node not yet added to the minimum spanning tree, add it and increment the cost.\n            if ( !vis[node] ) {\n                mst_cost += cost;\n                vis[node] = true;\n\n                // Iterate through all the nodes adjacent to the node taken out of priority queue.\n                // Push only those nodes (node, cost) that are not yet present in the minumum spanning tree.\n                for (Node pair_node_cost : graph.get(node)) {\n                    int adj_node = pair_node_cost.node;\n                    if (vis[adj_node] == false) {\n                        pq.add(pair_node_cost);\n                    }\n                }\n            }\n        }\n        return mst_cost;\n    }\n\n    public static void main(String args[]) {\n    \tScanner sc =new Scanner(System.in);\n\n        int num_nodes = 6; // Nodes (0, 1, 2, 3, 4, 5)\n\n        List<List<Node>> adjGraph = new ArrayList<>(num_nodes);\n        for (int i=0; i < num_nodes; i++) {\n            adjGraph.add(new ArrayList<>());\n        }\n        \n        for (int i=0; i < num_nodes; i++) {\n        \tint v1 = sc.nextInt();\n        \tint v2 = sc.nextInt();\n        \tint cost = sc.nextInt();\n        \tadjGraph.get(v1).add(new Node(v2,cost));\n        }\n        // Start adding nodes to minimum spanning tree with 0 as the souce node\n        System.out.println(\"Cost of the minimum spanning tree in graph 1 : \" + Find_MST(0, adjGraph));\n        \n        sc.close();\n\n    }\n}\n"
  },
  {
    "path": "Algorithms/Graph/Prim's_MST/README.md",
    "content": "## This folder is empty.\n"
  },
  {
    "path": "Algorithms/Graph/README.md",
    "content": "# This folder is empty.\n"
  },
  {
    "path": "Algorithms/Graph/Tarjan's Algorithm/StronglyConnectedComponents.cpp",
    "content": "#include <bits/stdc++.h>\nusing namespace std;\n\nint t;\nvector<int> disc, low, instack;\nvector<vector<int>> ans;\nvoid DFS(int u, vector<int> adj[], stack<int> &st)\n{\n    t += 1;\n    disc[u] = t;\n    low[u] = t;\n    instack[u] = 1;\n    st.push(u);\n    for (int k : adj[u])\n    {\n        if (disc[k] == -1)\n        {\n            DFS(k, adj, st);\n            low[u] = min(low[u], low[k]);\n        }\n        else\n        {\n            if (instack[k])\n            {\n                low[u] = min(low[u], disc[k]);\n            }\n        }\n    }\n    if (disc[u] == low[u])\n    {\n        vector<int> a;\n        while (!st.empty() and st.top() != u)\n        {\n            a.push_back(st.top());\n            instack[st.top()] = 0;\n            st.pop();\n        }\n        a.push_back(st.top());\n        instack[st.top()] = 0;\n        st.pop();\n        sort(a.begin(), a.end());\n        ans.push_back(a);\n    }\n}\nvector<vector<int>> tarjans(int V, vector<int> adj[])\n{\n    t = 0;\n    disc = vector<int>(V, -1);\n    low = vector<int>(V, -1);\n    instack = vector<int>(V, 0);\n    ans.clear();\n    stack<int> st;\n    for (int i = 0; i < V; i++)\n    {\n        if (disc[i] == -1)\n        {\n            DFS(i, adj, st);\n        }\n    }\n    sort(ans.begin(), ans.end());\n    return ans;\n}\n\nint main()\n{\n    int V, E;\n    cin >> V >> E;\n\n    vector<int> adj[V];\n\n    for (int i = 0; i < E; i++)\n    {\n        int u, v;\n        cin >> u >> v;\n        adj[u].push_back(v);\n    }\n\n    vector<vector<int>> ptr = tarjans(V, adj);\n\n    for (int i = 0; i < ptr.size(); i++)\n    {\n        for (int j = 0; j < ptr[i].size(); j++)\n        {\n            if (j == ptr[i].size() - 1)\n                cout << ptr[i][j];\n            else\n                cout << ptr[i][j] << \" \";\n        }\n        cout << ',';\n    }\n    cout << endl;\n    return 0;\n}\n"
  },
  {
    "path": "Algorithms/Graph/Topological Sort/QUESTION.md",
    "content": "### Topological Sort \nYou're given a list of arbitrary jobs that need to be completed; these jobs are represented by distinct integers. You're also given a list of dependencies. A dependency is represented as a pair of jobs where the first job is a prerequisite of the second one. In other words, the second job depends on the first one; it can only be completed once the first job is completed. \nWrite a function that takes in a list of jobs and a list of dependencies and returns a list containing a valid order in which the given jobs can be completed. If no such order exists, the function should return an empty array."
  },
  {
    "path": "Algorithms/Graph/Topological Sort/topo_sort.py",
    "content": "\n# METHOD - 1 : TRAVERSING FROM DEPENDENCIES TO MATCHING PREREQUISITE JOBS\n# O(j+d) T | O(j+d) S\n\n\ndef topologicalSort(jobs, deps):\n    jobGraph = createJobGraph(jobs, deps)\n    return getOrderedJobs(jobGraph)\n\n\ndef createJobGraph(jobs, deps):\n    graph = JobGraph(jobs)\n    for prereq, job in deps:\n        graph.addPrereq(job, prereq)\n    return graph\n\n\ndef getOrderedJobs(graph):\n    orderedJobs = []\n    nodes = graph.nodes\n    while len(nodes):\n        node = nodes.pop()\n        containsCycle = dft(node, orderedJobs)\n        if containsCycle:\n            return []\n    return orderedJobs\n\n\ndef dft(node, orderedJobs):\n    if node.visited:\n        return False\n    if node.visiting:\n        return True\n    node.visiting = True\n    for prereqNode in node.prereqs:\n        containsCycle = dft(prereqNode, orderedJobs)\n        if containsCycle:\n            return True\n    node.visited = True\n    node.visiting = False\n    orderedJobs.append(node.job)\n    return False\n\n\nclass JobGraph:\n    def __init__(self, jobs):\n        self.nodes = []\n        self.graph = {}\n        for job in jobs:\n            self.addNode(job)\n\n    def addNode(self, job):\n        self.graph[job] = JobNode(job)\n        self.nodes.append(self.graph[job])\n\n    def getNode(self, job):\n        if job not in self.graph:\n            self.addNode(job)\n        return self.graph[job]\n\n    def addPrereq(self, job, prereq):\n        jobNode = self.getNode(job)\n        prereqNode = self.getNode(prereq)\n        jobNode.prereqs.append(prereqNode)\n\n\nclass JobNode:\n    def __init__(self, job):\n        self.job = job\n        self.prereqs = []\n        self.visited = False\n        self.visiting = False\n\n\n# METHOD 2 : TRAVERSING FROM PREREQUISITE JOB TO MATCHING DEPENDENCIES\n# O(j+d) T | 0(j+d) S\n\ndef topologicalSort(jobs, deps):\n    jobGraph = createJobGraph(jobs, deps)\n    return getOrderedJobs(jobGraph)\n\n\ndef createJobGraph(jobs, deps):\n    graph = JobGraph(jobs)\n    for job, dep in deps:\n        graph.addDep(job, dep)\n    return graph\n\n\ndef getOrderedJobs(graph):\n    orderedJobs = []\n    nwnp = list(filter(lambda node: node.numOfPrereqs == 0, graph.nodes))\n    while len(nwnp):\n        node = nwnp.pop()\n        orderedJobs.append(node.job)\n        removeDeps(node, nwnp)\n    graphHasEdges = any(node.numOfPrereqs for node in graph.nodes)\n    return [] if graphHasEdges else orderedJobs\n\n\ndef removeDeps(node, nwnp):\n    while len(node.deps):\n        dep = node.deps.pop()\n        dep.numOfPrereqs -= 1\n        if dep.numOfPrereqs == 0:\n            nwnp.append(dep)\n\n\nclass JobGraph:\n    def __init__(self, jobs):\n        self.nodes = []\n        self.graph = {}\n        for job in jobs:\n            self.addNode(job)\n\n    def addNode(self, job):\n        self.graph[job] = JobNode(job)\n        self.nodes.append(self.graph[job])\n\n    def addDep(self, job, dep):\n        jobNode = self.getNode(job)\n        depNode = self.getNode(dep)\n        jobNode.deps.append(depNode)\n        depNode.numOfPrereqs += 1\n\n    def getNode(self, job):\n        if job not in self.graph:\n            self.addNode(job)\n        return self.graph[job]\n\n\nclass JobNode:\n    def __init__(self, job):\n        self.job = job\n        self.deps = []\n        self.numOfPrereqs = 0\n"
  },
  {
    "path": "Algorithms/Graph/Topological sort/README.md",
    "content": "Topological sorting for Directed Acyclic Graph (DAG) is a linear ordering of vertices such that for every directed edge u v, vertex u comes before v in the ordering. \nTopological Sorting for a graph is not possible if the graph is not a DAG.\n\nFor example, a topological sorting of the following graph is “5 4 2 3 1 0”. \nThere can be more than one topological sorting for a graph.\nFor example, another topological sorting of the following graph is “4 5 2 3 1 0”. \nThe first vertex in topological sorting is always a vertex with in-degree as 0 (a vertex with no incoming edges).\nWe can modify DFS to find Topological Sorting of a graph. In DFS, we start from a vertex, we first print it and then recursively call DFS for its adjacent vertices. \nIn topological sorting, we use a temporary stack. We don’t print the vertex immediately, \nwe first recursively call topological sorting for all its adjacent vertices, then push it to a stack. \nFinally, print contents of the stack. \nNote that a vertex is pushed to stack only when all of its adjacent vertices (and their adjacent vertices and so on) are already in the stack. \n\nComplexity Analysis: \n\nTime Complexity: O(V+E). \nThe above algorithm is simply DFS with an extra stack. So time complexity is the same as DFS which is.\nAuxiliary space: O(V). \nThe extra space is needed for the stack.\nNote: Here, we can also use vector instead of the stack. If the vector is used then print the elements in reverse order to get the topological sorting.\n"
  },
  {
    "path": "Algorithms/Graph/Topological sort/Topological_sort.cpp",
    "content": "\nusing namespace std;\n\nvector <int> topoSort(int N, vector<int> adj[]);\n\n/*  Function to check if elements returned by user\n*   contains the elements in topological sorted form\n*   V: number of vertices\n*   *res: array containing elements in topological sorted form\n*   adj[]: graph input\n*/\nbool check(int V, vector <int> &res, vector<int> adj[]) {\n    vector<int> map(V, -1);\n    for (int i = 0; i < V; i++) {\n        map[res[i]] = i;\n    }\n    for (int i = 0; i < V; i++) {\n        for (int v : adj[i]) {\n            if (map[i] > map[v]) return false;\n        }\n    }\n    return true;\n}\n\n// Driver Code\nint main() {\n    int T;\n    cin >> T;\n    while (T--) {\n        int N, E;\n        cin >> E >> N;\n        int u, v;\n\n        vector<int> adj[N];\n\n        for (int i = 0; i < E; i++) {\n            cin >> u >> v;\n            adj[u].push_back(v);\n        }\n\n        vector <int> res = topoSort(N, adj);\n\n        cout << check(N, res, adj) << endl;\n    }\n}// } Driver Code Ends\n\n\n// The Graph structure is as folows\n\n/*  Function which sorts the graph vertices in topological form\n*   N: number of vertices\n*   adj[]: input graph\n*/\nstack<int> st;\nunordered_map<int,bool> mp;\nvoid dfs(int s,vector<int> adj[])\n{\n    mp[s]=true;\n    for(int i=0;i<adj[s].size();i++)\n    {\n        if(mp[adj[s][i]]==false)\n        {\n            dfs(adj[s][i],adj);\n        }\n    }\n    st.push(s);\n}\nvector<int> topoSort(int V, vector<int> adj[]) {\n    for(int i=0;i<V;i++)\n    {\n        if(mp[i]==false)\n        {\n            dfs(i,adj);\n        }\n    }\n    vector<int> v;\n    while(!st.empty())\n    {\n        v.push_back(st.top());st.pop();\n    }\n    mp.clear();\n    return v;\n}\n"
  },
  {
    "path": "Algorithms/Graph/Youngest_Common_Ancestor/QUESTION.md",
    "content": "### Youngest Common Ancestor\nYou're given three inputs, all of which are instances of an AncestralTree class that have an ancestor property pointing to their youngest ancestor. The first input is the top ancestor in an ancestral tree (i.e., the only instance that has no ancestor--its ancestor property points to None / null ), and the other two inputs are descendants in the ancestral tree. Write a function that returns the youngest common ancestor to the two descendants.\nNote that a descendant is considered its own ancestor. So in the simple ancestral tree below, the youngest common ancestor to nodes A and B is node A.\n"
  },
  {
    "path": "Algorithms/Graph/Youngest_Common_Ancestor/YoungerCommonAncestor.cpp",
    "content": "// C++ Program for Lowest Common Ancestor in a Binary Tree \n// A O(n) solution to find LCA of two given values n1 and n2 \n#include <iostream> \n#include <vector> \n  \nusing namespace std; \n  \n// A Binary Tree node \nstruct Node \n{ \n    int key; \n    struct Node *left, *right; \n}; \n  \n// Utility function creates a new binary tree node with given key \nNode * newNode(int k) \n{ \n    Node *temp = new Node; \n    temp->key = k; \n    temp->left = temp->right = NULL; \n    return temp; \n} \n  \n// Finds the path from root node to given root of the tree, Stores the \n// path in a vector path[], returns true if path exists otherwise false \nbool findPath(Node *root, vector<int> &path, int k) \n{ \n    // base case \n    if (root == NULL) return false; \n  \n    // Store this node in path vector. The node will be removed if \n    // not in path from root to k \n    path.push_back(root->key); \n  \n    // See if the k is same as root's key \n    if (root->key == k) \n        return true; \n  \n    // Check if k is found in left or right sub-tree \n    if ( (root->left && findPath(root->left, path, k)) || \n         (root->right && findPath(root->right, path, k)) ) \n        return true; \n  \n    // If not present in subtree rooted with root, remove root from \n    // path[] and return false \n    path.pop_back(); \n    return false; \n} \n  \n// Returns LCA if node n1, n2 are present in the given binary tree, \n// otherwise return -1 \nint findLCA(Node *root, int n1, int n2) \n{ \n    // to store paths to n1 and n2 from the root \n    vector<int> path1, path2; \n  \n    // Find paths from root to n1 and root to n1. If either n1 or n2 \n    // is not present, return -1 \n    if ( !findPath(root, path1, n1) || !findPath(root, path2, n2)) \n          return -1; \n  \n    /* Compare the paths to get the first different value */\n    int i; \n    for (i = 0; i < path1.size() && i < path2.size() ; i++) \n        if (path1[i] != path2[i]) \n            break; \n    return path1[i-1]; \n} \n  \n// Driver program to test above functions \nint main() \n{ \n    // Let us create the Binary Tree shown in above diagram. \n    Node * root = newNode(1); \n    root->left = newNode(2); \n    root->right = newNode(3); \n    root->left->left = newNode(4); \n    root->left->right = newNode(5); \n    root->right->left = newNode(6); \n    root->right->right = newNode(7); \n    cout << \"LCA(4, 5) = \" << findLCA(root, 4, 5); \n    cout << \"nLCA(4, 6) = \" << findLCA(root, 4, 6); \n    cout << \"nLCA(3, 4) = \" << findLCA(root, 3, 4); \n    cout << \"nLCA(2, 4) = \" << findLCA(root, 2, 4); \n    return 0; \n} \n"
  },
  {
    "path": "Algorithms/Graph/Youngest_Common_Ancestor/YoungestCommonAncestor.java",
    "content": "public class YoungestCommonAncestor {\n\n    static Integer[] treeNodes = new Integer[]{1, 4, 5, 6, 7, null, null, 8, 9, 10, 11, null, null, null, null,\n            null, null, 13};\n\n    static int sizeOfTree = treeNodes.length;\n\n    static NodeWrap youngestCommonAncestorNode = null;\n\n    public static void main(String[] args) {\n\n        /**\n         *              1\n         *          4       5\n         *      6     7\n         *    8   9  10 11\n         *      13\n         */\n        TreeNode root = insert(0);\n        findYoungestCommon(root, 8, 13);\n        if (youngestCommonAncestorNode != null) {\n            System.out.println(youngestCommonAncestorNode.treeNode.val);\n        }\n    }\n\n    static boolean findYoungestCommon(TreeNode node, int val1, int val2) {\n        if (node == null) {\n            return false;\n        }\n\n        if (node.val == val1 || node.val == val2) {\n            youngestCommonAncestorNode = new NodeWrap(node);\n            return true;\n        }\n        boolean left = findYoungestCommon(node.left, val1, val2);\n        boolean right = findYoungestCommon(node.right, val1, val2);\n        if (left && right) {\n            youngestCommonAncestorNode = new NodeWrap(node);\n        }\n        return left || right;\n    }\n\n    static TreeNode insert(int index) {\n        if (index < sizeOfTree) {\n            if (treeNodes[index] == null) {\n                return null;\n            }\n            TreeNode node = new TreeNode(treeNodes[index]);\n            node.left = insert(2 * index + 1);\n            node.right = insert(2 * index + 2);\n            return node;\n        }\n        return null;\n    }\n\n    static void inOrder(TreeNode root) {\n\n        if (root == null) {\n            return;\n        }\n\n        inOrder(root.left);\n        System.out.print(root.val + \" \");\n        inOrder(root.right);\n    }\n\n    static class TreeNode {\n        int val;\n        TreeNode left;\n        TreeNode right;\n\n        public TreeNode(int val) {\n            this.val = val;\n        }\n    }\n\n    static class NodeWrap {\n        TreeNode treeNode;\n\n        public NodeWrap(TreeNode treeNode) {\n            this.treeNode = treeNode;\n        }\n    }\n}"
  },
  {
    "path": "Algorithms/Graph/Youngest_Common_Ancestor/youngest-comm-anc.py",
    "content": "\n# O(d) T | O(1)S\n\n\nclass AncestralTree:\n    def __init__(self, name):\n        self.name = name\n        self.ancestor = None\n\n\ndef getYoungestCommonAncestor(topAncestor, descendantOne, descendantTwo):\n    depOne = getDescDep(descendantOne, topAncestor)\n    depTwo = getDescDep(descendantTwo, topAncestor)\n       if depOne > depTwo:\n            return youngCommon(descendantOne, descendantTwo, depOne-depTwo)\n        else:\n            return youngCommon(descendantTwo, descendantOne, depTwo-depOne)\n\n\ndef getDescDep(desc, top):\n    depth = 1\n    while desc != top:\n        depth += 1\n        desc = desc.ancestor\n    return depth\n\ndef youngCommon(lowerDesc, higherDesc, diff):\n    while diff > 0:\n        lowDesc = lowerDesc.ancestor\n        diff -= 1\n\n    while higherDesc != lowerDesc:\n        higherDesc = higherDesc.ancestor\n        lowerDesc = lowerDesc.ancestor\n    return lowerDesc\n"
  },
  {
    "path": "Algorithms/Graph/articulation_points.py",
    "content": "from collections import defaultdict\nclass Graph:\n\tdef __init__(self,vertices): \n\t\tself.V= vertices #No. of vertices \n\t\tself.graph = defaultdict(list) # default dictionary to store graph \n\t\tself.Time = 0\n\n\t# function to add an edge to graph \n\tdef addEdge(self,u,v): \n\t\tself.graph[u].append(v) \n\t\tself.graph[v].append(u) \n    \n    \n\tdef APUtil(self,u, visited, ap, parent, low, disc): \n\n\t\t#Count of children in current node \n\t\tchildren =0\n\n\t\t# Mark the current node as visited and print it \n\t\tvisited[u]= True\n\n\t\t# Initialize discovery time and low value \n\t\tdisc[u] = self.Time \n\t\tlow[u] = self.Time \n\t\tself.Time += 1\n\n\t\t#Recur for all the vertices adjacent to this vertex \n\t\tfor v in self.graph[u]:  \n\t\t\tif visited[v] == False : \n\t\t\t\tparent[v] = u \n\t\t\t\tchildren += 1\n\t\t\t\tself.APUtil(v, visited, ap, parent, low, disc) \n\n\t\t\t\t# Check if the subtree rooted with v has a connection to \n\t\t\t\t# one of the ancestors of u \n\t\t\t\tlow[u] = min(low[u], low[v]) \n\n\t\t\t\t# u is an articulation point in following cases \n\t\t\t\t# (1) u is root of DFS tree and has two or more chilren. \n\t\t\t\tif parent[u] == -1 and children > 1: \n\t\t\t\t\tap[u] = True\n\n\t\t\t\t#(2) If u is not root and low value of one of its child is more \n\t\t\t\t# than discovery value of u. \n\t\t\t\tif parent[u] != -1 and low[v] >= disc[u]: \n\t\t\t\t\tap[u] = True\t\n\t\t\t\t\t\n\t\t\t\t# Update low value of u for parent function calls\t \n\t\t\telif v != parent[u]: \n\t\t\t\tlow[u] = min(low[u], disc[v]) \n\n\n\t#The function to do DFS traversal. It uses recursive APUtil() \n\tdef AP(self): \n\n\t\t# Mark all the vertices as not visited \n\t\t# and Initialize parent and visited, \n\t\t# and ap(articulation point) arrays \n\t\tvisited = [False] * (self.V) \n\t\tdisc = [float(\"Inf\")] * (self.V) \n\t\tlow = [float(\"Inf\")] * (self.V) \n\t\tparent = [-1] * (self.V) \n\t\tap = [False] * (self.V) #To store articulation points \n\n\t\t# Call the recursive helper function \n\t\t# to find articulation points \n\t\t# in DFS tree rooted with vertex 'i' \n\t\tfor i in range(self.V): \n\t\t\tif visited[i] == False: \n\t\t\t\tself.APUtil(i, visited, ap, parent, low, disc) \n\n\t\tfor index, value in enumerate (ap): \n\t\t\tif value == True: print(index, end=\",\")\n\n# Create a graph given in the above diagram \ng1 = Graph(5) \ng1.addEdge(1, 0) \ng1.addEdge(0, 2) \ng1.addEdge(2, 1) \ng1.addEdge(0, 3) \ng1.addEdge(3, 4) \n\nprint(\"\\nArticulation points in first graph \")\ng1.AP() \n\n"
  },
  {
    "path": "Algorithms/Graph/flood_fill.py",
    "content": "M = 8\nN = 8\n\ndef floodFillUtil(screen, x, y, prevC, newC): \n\t\n\t# Base cases \n\tif (x < 0 or x >= M or y < 0 or\n\t\ty >= N or screen[x][y] != prevC or\n\t\tscreen[x][y] == newC): \n\t\treturn\n\tscreen[x][y] = newC \n\n\t# Recur for north, east, south and west \n\tfloodFillUtil(screen, x + 1, y, prevC, newC) \n\tfloodFillUtil(screen, x - 1, y, prevC, newC) \n\tfloodFillUtil(screen, x, y + 1, prevC, newC) \n\tfloodFillUtil(screen, x, y - 1, prevC, newC) \n\n\ndef floodFill(screen, x, y, newC): \n\tprevC = screen[x][y] \n\tfloodFillUtil(screen, x, y, prevC, newC) \nscreen = [[1, 1, 1, 1, 1, 1, 1, 1], \n\t\t[1, 1, 1, 1, 1, 1, 0, 0], \n\t\t[1, 0, 0, 1, 1, 0, 1, 1], \n\t\t[1, 2, 2, 2, 2, 0, 1, 0], \n\t\t[1, 1, 1, 2, 2, 0, 1, 0], \n\t\t[1, 1, 1, 2, 2, 2, 2, 0], \n\t\t[1, 1, 1, 1, 1, 2, 1, 1], \n\t\t[1, 1, 1, 1, 1, 2, 2, 1]] \n\nx = 4\ny = 4\nnewC = 3\nfloodFill(screen, x, y, newC) \n\nprint (\"Updated screen after call to floodFill:\") \nfor i in range(M): \n\tfor j in range(N): \n\t\tprint(screen[i][j], end = ' ') \n\tprint() \n\n\n"
  },
  {
    "path": "Algorithms/Graph/lagrange_interpolation.cpp",
    "content": "#include<iostream>\n\nusing namespace std;\n\nint main()\n{\n\t float x[100], y[100], xp, yp=0, p;\n\t int i,j,n;\n\n\t cout<<\"Enter number of data: \";\n\t cin>>n;\n\t cout<<\"Enter data:\"<< endl;\n\t for(i=1;i<=n;i++)\n\t {\n\t\t  cout<<\"x[\"<< i<<\"] = \";\n\t\t  cin>>x[i];\n\t\t  cout<<\"y[\"<< i<<\"] = \";\n\t\t  cin>>y[i];\n\t }\n\t cout<<\"Enter interpolation point: \";\n\t cin>>xp;\n\n\t /* Implementing Lagrange Interpolation */\n\t for(i=1;i<=n;i++)\n\t {\n\t\t  p=1;\n\t\t  for(j=1;j<=n;j++)\n\t\t  {\n\t\t\t   if(i!=j)\n\t\t\t   {\n\t\t\t    \tp = p* (xp - x[j])/(x[i] - x[j]);\n\t\t\t   }\n\t\t  }\n\t\t  yp = yp + p * y[i];\n\t }\n\t cout<< endl<<\"Interpolated value at \"<< xp<< \" is \"<< yp;\n\n\t return 0;\n}\n"
  },
  {
    "path": "Algorithms/Graph/lowest_common_manager/lowest_common_manager.java",
    "content": "public class Employee {\n\t  private String name;\n\t  private List<Employee> reportee;\n\t  private Employee manager;\n\t  Employee(String name) {\n\t\t  this.name = name;\t\t\n\t\t  reportee = new ArrayList<>();\n\t  }\n\t  public  void setManager(Employee m) {\n\t\t  manager = m;\n\t  }\n\t  public  void addReprotee(Employee e) {\t\t \n\t\t\t  reportee.add(e);\n\t\t\t  e.manager = this;\n\t  }\t  \n\t  \n\t  //O(log(n)) time complexity, O(1) memory\n\t  static Employee closestCommonManager2(Employee a, Employee b) {\n\t\t  Employee e1 = a;\n\t\t  Employee e2 = b;\n\t\t  int h1 = 0;\n\t\t  int h2 = 0;\n\t\t  while (e1 != null || e2 != null) {\n\t\t\t  if (e1 != null) {\t\t\t\t\n\t\t\t  \te1 = e1.manager ;\n\t\t\t  \th1++;\n\t\t\t  }\n\t\t\t  if (e2 != null) {\t\t\t\t\n\t\t\t\t  \te2 = e2.manager ;\n\t\t\t\t  \th2++;\n\t\t\t  }\t  \n\t\t  }\t\t\t\t  \n\t\t  int diff = Math.abs(h1 - h2);\n\t\t  if(h1 > h2) {\n\t\t\t  e1 = a;\n\t\t\t  e2 = b;\t\t\t  \n\t\t  } else {\t\t\t \n\t\t\t  e1 = b;\n\t\t\t  e2 = a;\n\t\t  }\n\t\t  while (diff > 0) {\n\t\t\t  e1 = e1.manager;\n\t\t\t  diff--;\n\t\t  }\n\t\t  while (e1 != e2) {\n\t\t\t  e1 = e1.manager ;\n\t\t\t  e2 = e2.manager ;\n\t\t  }\n\t\t  return e1;\n\t  }\n\t  \n\t  //O(log(n)) time complexity, O(log(n)) memory\n\t  static Employee closestCommonManager(Employee a, Employee b) {\n\t\t \n\t\t  Stack<Employee> ls1 = new Stack<Employee>();\n\t\t  Stack<Employee> ls2 = new Stack<Employee>();\t\t\n\t\t  while (a != null || b != null) {\n\t\t\t  if (a != null) {\n\t\t\t\tls1.push(a);\n\t\t\t  \ta = a.manager ;\n\t\t\t  }\n\t\t\t  if (b != null) {\n\t\t\t\t  ls2.push(b);\n\t\t\t\t  b = b.manager;\n\t\t\t  }\n\t\t\t  \n\t\t  }\t\t\n\t\t  while(!ls1.isEmpty() && !ls2.isEmpty()) {\n\t\t\t  if (ls1.peek() != ls2.peek()) {\n\t\t\t\t  break;\n\t\t\t  }\n\t\t\t  a = ls1.pop();\n\t\t\t  ls2.pop();\t\t\t  \n\t\t  }\n\t\t  return a;\n\t  }\n\t  \n\t  public String toString() {\n\t\t  return name;\n\t  }\n  }\n"
  },
  {
    "path": "Algorithms/Graph/newton_raphson_method.c",
    "content": "#include<stdio.h>\n#include<conio.h>\n#include<math.h>\n#include<stdlib.h>\n\n#define    f(x)    3*x - cos(x) -1\n#define   g(x)   3 + sin(x)\n\nvoid main()\n{\n\t float x0, x1, f0, f1, g0, e;\n\t int step = 1, N;\n\t\n\t printf(\"\\nEnter initial guess:\\n\");\n\t scanf(\"%f\", &x0);\n\t printf(\"Enter tolerable error:\\n\");\n\t scanf(\"%f\", &e);\n\t printf(\"Enter maximum iteration:\\n\");\n\t scanf(\"%d\", &N);\n\t printf(\"\\nStep\\t\\tx0\\t\\tf(x0)\\t\\tx1\\t\\tf(x1)\\n\");\n\t do\n\t {\n\t\t  g0 = g(x0);\n\t\t  f0 = f(x0);\n\t\t  if(g0 == 0.0)\n\t\t  {\n\t\t\t   printf(\"Mathematical Error.\");\n\t\t\t   exit(0);\n\t\t  }\n\n\t\t\n\t\t  x1 = x0 - f0/g0;\n\n\t\t\n\t\t  printf(\"%d\\t\\t%f\\t%f\\t%f\\t%f\\n\",step,x0,f0,x1,f1);\n\t\t  x0 = x1;\n\t\t  \n\t\t  step = step+1;\n\t\t\n\t\t  if(step > N)\n\t\t  {\n\t\t\t   printf(\"Not Convergent.\");\n\t\t\t   exit(0);\n\t\t  }\n\t\t  \n\t\t  f1 = f(x1);\n\t\t  \n\t }while(fabs(f1)>e);\n\t\n\t printf(\"\\nRoot is: %f\", x1);\n\t getch();\n}\n\n"
  },
  {
    "path": "Algorithms/Hashing/Amicable/Amicable_Number.rb",
    "content": "class AmicableNumber\n  class << self\n    def are_amicables?(number_1, number_2)\n      # Prevents for not valid arguments errors\n      raise ArgumentError, \"Both arguments must be Integer positive number. Argumens: (#{number_1}, #{number_2})\" unless is_valid?(number_1) && is_valid?(number_2)\n      sum_divisors_of(number_1) === sum_divisors_of(number_2)\n    end\n\n    private\n    # Validates if params are positive integer numbers\n    def is_valid?(number)\n      number.is_a?(Integer) && number > 0\n    end\n\n    # Returns the sum of the divisors\n    def sum_divisors_of(number)\n      divisors = divisors_of(number)\n      divisors.sum\n    end\n\n    # Finds all divisor of each number\n    def divisors_of(number)\n      (1..number).select { |divisor| number % divisor === 0 }\n    end\n  end\nend\n\nputs AmicableNumber.are_amicables?(220, 284) # true\nputs AmicableNumber.are_amicables?(1184, 1210) # true\nputs AmicableNumber.are_amicables?(1184, 121) # false\nputs AmicableNumber.are_amicables?(\"A\", 98) # Raise error"
  },
  {
    "path": "Algorithms/Hashing/Amicable/Amicable_Numbers..c",
    "content": "#include<stdio.h>\nint main(){\nint i,a,b,c=0;\nprintf(\"To check whether the given two numbers are Amicable numbers or not.\\n\\n\");                  \nprintf(\"Enter two numbers : \");\nscanf(\"%d%d\",&a,&b);\nfor(i=0;i<=a/2;i++){\n        if(a%i==0)\n                c+=i;\n}\nif(c==b)\n      printf(\"%d and %d are Amicable numbers .\\n\",a,b);\nelse\n      printf(\"%d and %d are not Amicable numbers .\\n\",a,b);\n\nprintf(\"\\n\\nSome Amicable Numbers under 100,000 are :- \\n\");\nint x,y,m,n,j;\nfor(i=220;i<100000;i++){\n        x=0,y=0;\n        for(j=1;j<=i/2;j++){\n                if(i%j==0)\n                        x+=j;}\n        m=1,n=0;\n        while(m<=x/2){\n                if(x%m==0)\n                        y+=m;\n                m++;}\nif(i==y){\n        if(x!=y){\n                printf(\"%d and %d \\n\",x,y);\n        i+=500;}\n}}\nreturn 0;\n}\n"
  },
  {
    "path": "Algorithms/Hashing/Amicable/Amicable_Numbers.cpp",
    "content": "#include<iostream>\nusing namespace std;\nint main(){                                                                                                          \nint i,a,b,c=0;\ncout<<\"To check for the entered pair of numbers are Amicable Numbers or not.\\n\"<<endl;\ncout<<\"Enter any two Numbers : \";\ncin>>a>>b;\n\nfor(i=1;i<=a/2;i++)\n{\n        if(a%i==0)\n                c+=i;                                        \n}\nif(c==b)                                                                                                                      \n        cout<<a<<\" and \"<<b<<\" are Amicable Numbers.\"<<endl;\nelse\n        cout<<a<<\" and \"<<b<<\" are Not Amicable Numbers.\"<<endl;\n\ncout<<\"\\n\\nSome Amicable Numbers under 100,000 are :-\"<<endl;\nint x,y,j,m,n;\nfor(i=220;i<100000;i++){\n        x=0,y=0;\n        for(j=1;j<=i/2;j++){\n                if(i%j==0){\n                       x+=j;\n                       //cout<<j<<endl;\n                       }}\n        m=1,n=0;\n        while(m<=x/2){\n                if(x%m==0)\n                y+=m;\n        m++;\n        }\n        if(i==y){\n                if(x!=y){\n                       cout<<x<<\" and \"<<y<<endl;\n                       i+=800;    //to save time\n        }}}\nreturn 0;\n}\n"
  },
  {
    "path": "Algorithms/Hashing/Amicable/Amicable_Numbers.java",
    "content": "\n//Java program to check given numbers are Amicable Numbers or not\n\nimport java.util.*;\n\n\n//Driver Class\nclass AmicableNum{\n\n\t//Checks for valid Amicable Number\n\tboolean findAmicable(int num1, int num2){\n\t\tint sumofDiv1 =0;\n\t\tint sumofDiv2 =0;\n\n\t\t//Calculate sum of divisor for number 1\n\t\tfor(int i=1; i <= num1/2; i++){\n\n\t\t\tif(num1%i==0){\n\t\t\t\tsumofDiv1 += i;\n\t\t\t}\n\n\t\t}\n\n\t\t//Calculate sum of divisor for number 2\n\t\tfor(int j=1; j <= num2/2; j++){\n\n\t\t\tif(num2%j==0){\n\t\t\t\tsumofDiv2 += j;\n\t\t\t}\n\n\t\t}\n\n\n\t\t//Validate amicable numbers conditions\n\t\tif((num1 == sumofDiv2) && (num2 == sumofDiv1)){\n\t\t\t\n\t\t\treturn true;\n\n\t\t}\n\t\telse{\n\n\t\t\treturn false;\n\n\t\t}\n\n\n\t}\n\n\n\t//Driver Code\n\tpublic static void main(String[] args) {\n\t\t\n\t\tScanner sc = new Scanner(System.in); //Create object\n\n\t\tint num1,num2;\n\n\t\tSystem.out.print(\"Enter first Number: \");\n\t\tnum1 = sc.nextInt(); //first number\n\n\t\tSystem.out.print(\"Enter second Number: \");\n\t\tnum2 = sc.nextInt(); //second number\n\n\n\t\t//Create object for class AmicableNum\n\t\tAmicableNum ami = new AmicableNum();\n\n\t\t//valdiating numbers\n\t\tif(ami.findAmicable(num1, num2)){\n\n\t\t\tSystem.out.println( num1 + \" and \" + num2 + \" are Amicable Numbers.\");\n\n\t\t}\n\t\telse{\n\n\t\t\tSystem.out.println( num1 + \" and \" + num2 + \" are not Amicable Numbers.\");\n\n\t\t}\n\n\t}\n}"
  },
  {
    "path": "Algorithms/Hashing/Amicable/amicable.cs",
    "content": "using System;\nusing System.Collections.Generic;\n//Two numbers are amicable if the first is equal to the sum of divisors of the second, \n//and if the second number is equal to the sum of divisors of the first.\n\npublic class AmicableNumbersCS {\n    public bool AreAmicable(int x, int y) \n    {\n        if (EqualsDivisorsOf(x, y) && EqualsDivisorsOf(y, x))\n        {\n            return true;\n        }\n        \n        return false;\n    }\n    \n    private bool EqualsDivisorsOf(int x, int y)\n    {\n        int sumOfDivisors = 0;\n        \n        foreach(int divisor in GetDivisors(y))\n        {\n            sumOfDivisors += divisor;\n        }\n        \n        if (x == sumOfDivisors)\n        {\n            return true;\n        }\n        \n        return false;\n    }\n    \n    //https://codereview.stackexchange.com/a/237442\n    private int[] GetDivisors(int n)\n        {\n            if (n <= 0)\n            {\n                return null;\n            }\n            List<int> divisors = new List<int>();\n            for (int i = 1; i <= Math.Sqrt(n); i++)\n            {\n                if (n % i == 0)\n                {\n                    divisors.Add(i);\n                    if (i != n / i)\n                    {\n                        divisors.Add(n / i);\n                    }\n                }\n            }\n            divisors.Remove(n);\n            divisors.Sort();\n            return divisors.ToArray();\n        }\n    \n}"
  },
  {
    "path": "Algorithms/Hashing/Amicable/amicable.js",
    "content": "/*\nprojecteuler.net\nAmicable numbers\nProblem 21\nLet d(n) be defined as the sum of proper divisors of n (numbers less than n which divide evenly into n).\nIf d(a) = b and d(b) = a, where a ≠ b, then a and b are an amicable pair and each of a and b are called amicable numbers.\n\nFor example, the proper divisors of 220 are 1, 2, 4, 5, 10, 11, 20, 22, 44, 55 and 110; therefore d(220) = 284. The proper divisors of 284 are 1, 2, 4, 71 and 142; so d(284) = 220.\n\nEvaluate the sum of all the amicable numbers under 10000.\n*/\n\nvar total = 10000;\nvar halfTotal = total / 2;\nvar amicableNumbers = [];\nvar sum = 0;\n\nfor (var i = 0; i < halfTotal; i++){\n  if (total % i === 0){\n    amicableNumbers.push(i);\n    sum += i;\n  }\n}\n\nconsole.log(\"Sum of all amicable numbers under \" + total + \" is \" + sum);\nconsole.log(amicableNumbers);"
  },
  {
    "path": "Algorithms/Hashing/Amicable/amicable.swift",
    "content": "// returns true if two numbers are amicable\nfunc isAmicable(_ a : Int, _ b : Int) -> Bool {\n    return getSum(num: a) == b && getSum(num: b) == a\n}\n\n// returns a sum of all of the factors of a Int\nfunc getSum(num a: Int) -> Int {\n    var sum : Int = 0;\n    // check for factors\n    for i in 1 ..< a {\n        // add to sum if remainder is 0\n        if a % i == 0 {\n            sum += i;\n        }\n        \n    }\n    return sum;\n}\n\n// driver code\nprint(isAmicable(284, 220)) // true\nprint(isAmicable(6, 12))    // false\n"
  },
  {
    "path": "Algorithms/Hashing/Amicable/amicable_numbers.php",
    "content": "<?php\nfunction sumOfDiv( $x) \n{ \n\n    $sum = 1; \n    for ( $i = 2; $i <= sqrt($x); $i++)  \n    { \n        if ($x % $i == 0)  \n        { \n            $sum += $i; \n  \n           \n            if ($x / $i != $i) \n                $sum += $x / $i; \n        } \n    } \n    return $sum; \n} \n\nfunction isAmicable( $a, $b) \n{ \n    return (sumOfDiv($a) == $b and \n            sumOfDiv($b) == $a); \n} \n  \n$n1=(int)readline('Enter first number to check :');\n$n2=(int)readline('Enter second number to check : ');\nif (isAmicable($n1, $n2))\n{\n echo \"Pair is amicable\";\n}\nelse\n{\n echo \"Pair is not amicable\";\n}\n\n?>\n"
  },
  {
    "path": "Algorithms/Hashing/Amicable/amicable_numbers.py",
    "content": "import math \n\n# Calculating the sum \n# of proper divisors \ndef sumOfDiv(x): \n\t\n\t# 1 is a proper divisor \n\tsum = 1; \n\tfor i in range(2,int(math.sqrt(x))): \n\t\tif x % i==0: \n\t\t\tsum += i \n\t\t\t\n\t\t\t# To handle perfect squares \n\t\t\tif i != x/i: \n\t\t\t\tsum += x/i \n\treturn int(sum); \n\n\ndef isAmbicle(a, b): \n\treturn (sumOfDiv(a) == b and\n\t\t\tsumOfDiv(b) == a) \n\n\ndef countPairs(arr,n): \n\ts = set() \n\tcount = 0\n\tfor i in range(n): \n\t\ts.add(arr[i]) \n\t\n\tfor i in range(n):\t \n\t\tif sumOfDiv(arr[i]) in s: \n\t\t\t\n\t\t\t# It's sum of proper divisors \n\t\t\tsum = sumOfDiv(arr[i]) \n\t\t\tif isAmbicle(arr[i], sum): \n\t\t\t\tcount += 1\t\t\n\t\n\n\treturn int(count/2); \n\t\n# Driver Code \narr1 = [220, 284, 1184, \n\t\t1210, 2, 5] \nn1 = len(arr1) \nprint(countPairs(arr1, n1)) \n\n\n"
  },
  {
    "path": "Algorithms/Hashing/Brick_Wall/Brick_wall.cpp",
    "content": "class Solution\n{\npublic:\n    int leastBricks(vector<vector<int>> &wall)\n    {\n        unordered_map<int, int> m;\n        //Maintain a sort of prefix array with counts for each sum\n        int max_surpass = 0;\n        int res = wall.size();\n        int sum;\n        for (int i = 0; i < wall.size(); i++)\n        {\n            sum = 0;\n            for (int j = 0; j < wall[i].size() - 1; j++)\n            {\n                sum += wall[i][j];\n                m[sum] += 1;\n                max_surpass = max(max_surpass, m[sum]);\n            }\n        }\n        return wall.size() - max_surpass;\n    }\n};"
  },
  {
    "path": "Algorithms/Hashing/Brick_Wall/QUESTION.md",
    "content": "### Brick Wall\n\nThere is a brick wall in front of you. The wall is rectangular and has several rows of bricks. The bricks have the same height but different width. You want to draw a vertical line from the top to the bottom and cross the least bricks.\n\nThe brick wall is represented by a list of rows. Each row is a list of integers representing the width of each brick in this row from left to right.\n\nIf your line go through the edge of a brick, then the brick is not considered as crossed. You need to find out how to draw the line to cross the least bricks and return the number of crossed bricks.\n\nYou cannot draw a line just along one of the two vertical edges of the wall, in which case the line will obviously cross no bricks.\n"
  },
  {
    "path": "Algorithms/Hashing/Chaining/chainingHashing.cpp",
    "content": "#include <iostream>\n#include <math.h>\nusing namespace std;\n\nstruct Node\n{\n\tint data;\n\tstruct Node *next;\n} * head[100], *curr /*points to the current node*/;\n\n/*initialize hash table i.e., head[] with null*/\nvoid init()\n{\n\tfor (int i = 0; i < 100; i++)\n\t\thead[i] = NULL;\n}\n\n/*\n* given the data and hash\n* add a new Node with given data in the hash table\n*/\nvoid add(int x, int h)\n{\n\tstruct Node *temp = new Node;\n\ttemp->data = x;\n\ttemp->next = NULL;\n\tif (!head[h])\n\t{\n\t\thead[h] = temp;\n\t\tcurr = head[h];\n\t}\n\telse\n\t{\n\t\tcurr = head[h];\n\t\twhile (curr->next)\n\t\t\tcurr = curr->next;\n\t\tcurr->next = temp;\n\t}\n}\n\n/*\n* given the mod\n* prints the hash table in console\n*/\nvoid display(int mod)\n{\n\tstruct Node *temp;\n\tint i;\n\tfor (i = 0; i < mod; i++)\n\t{\n\t\tif (!head[i])\n\t\t{\n\t\t\tcout << \"Key \" << i << \" is empty\" << endl;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tcout << \"Key \" << i << \" has values = \";\n\t\t\ttemp = head[i];\n\t\t\twhile (temp->next)\n\t\t\t{\n\t\t\t\tcout << temp->data << \" \";\n\t\t\t\ttemp = temp->next;\n\t\t\t}\n\t\t\tcout << temp->data;\n\t\t\tcout << endl;\n\t\t}\n\t}\n}\n\n/*return hash*/\nint get_hash(int x, int mod)\n{\n\treturn x % mod;\n}\n\n/*\n* given the data and hash\n* finds the Node in the hash table\n*/\nvoid find(int x, int h)\n{\n\tstruct Node *temp = head[h];\n\tif (!head[h])\n\t{\n\t\tcout << \"Element not found\";\n\t\treturn;\n\t}\n\twhile (temp->data != x && temp->next)\n\t\ttemp = temp->next;\n\tif (temp->next)\n\t\tcout << \"Element found\";\n\telse\n\t{\n\t\tif (temp->data == x)\n\t\t\tcout << \"Element found\";\n\t\telse\n\t\t\tcout << \"Element not found\";\n\t}\n}\n\nint main(void)\n{\n\tinit();\n\tint choice, x /*buffer to store user input in each switch case*/;\n\tint  mod /*size of the hash table*/, h;\n\tcout << \"Enter the size of Hash Table. = \";\n\tcin >> mod;\n\tbool loop = true;\n\twhile (loop)\n\t{\n\t\tcout << endl;\n\t\tcout << \"PLEASE CHOOSE -\" << endl;\n\t\tcout << \"1. Add element.\" << endl;\n\t\tcout << \"2. Find element.\" << endl;\n\t\tcout << \"3. Generate Hash.\" << endl;\n\t\tcout << \"4. Display Hash table.\" << endl;\n\t\tcout << \"5. Exit.\" << endl;\n\t\tcin >> choice;\n\t\tswitch (choice)\n\t\t{\n\t\tcase 1:\n\t\t\tcout << \"Enter element to add = \";\n\t\t\tcin >> x;\n\t\t\th = get_hash(x, mod);\n\t\t\th = fabs(h);\n\t\t\tadd(x, h);\n\t\t\tbreak;\n\t\tcase 2:\n\t\t\tcout << \"Enter element to search = \";\n\t\t\tcin >> x;\n\t\t\th = get_hash(x, mod);\n\t\t\tfind(x, h);\n\t\t\tbreak;\n\t\tcase 3:\n\t\t\tcout << \"Enter element to generate hash = \";\n\t\t\tcin >> x;\n\t\t\tcout << \"Hash of \" << x << \" is = \" << get_hash(x, mod);\n\t\t\tbreak;\n\t\tcase 4:\n\t\t\tdisplay(mod);\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tloop = false;\n\t\t\tbreak;\n\t\t}\n\t\tcout << endl;\n\t}\n\t/*add(1,&head1);\n\tadd(2,&head1);\n\tadd(3,&head2);\n\tadd(5,&head1);\n\tdisplay(&head1);\n\tdisplay(&head2);*/\n\treturn 0;\n}"
  },
  {
    "path": "Algorithms/Hashing/Cuckoo_Hashing/Cuckoo_Hashing.cpp",
    "content": "\r\n//C++ program to perform Cuckoo Hashing\r\n\r\n#include<bits/stdc++.h>\r\nusing namespace std;\r\n\r\n#define hashTableNum 2 //Number of table hash consist\r\n\r\n//Number of element to be hashed\r\nstatic int tableSize=0;  //Initialized to zero\r\n\r\n//Array to store hash value\r\nint cuckooTable[hashTableNum][100];\r\n\r\n//Array to store hashed position of element\r\nint Position[hashTableNum];\r\n\r\n//Initialize cuckooTable with minimum value of Integer type\r\nvoid fillTable(){\r\n\t\r\n\tfor (int j=0; j<tableSize; j++){\r\n\t\r\n\t\tfor(int i=0; i<hashTableNum; i++){\r\n\t\r\n\t\t\tcuckooTable[i][j]= INT_MIN;  //for minimum Integer value\r\n\t\r\n\t\t}\t\r\n\t}\r\n\r\n}\r\n\r\n//Print the hash table after performing Cuckoo Hashing\r\nvoid printTable(){\r\n\r\n\tcout<<\"\\nHash Tables are:\\n\"<<endl;\r\n\t\r\n\t//Print both hash table\r\n\tfor(int i=0; i<hashTableNum; i++, printf(\"\\n\")){\r\n\t\t\r\n\t\tint tableNum=i+1;\r\n\t\tcout<<\"Table: \" << tableNum << \"-> \";\r\n\r\n\t\t//Print hash position of various element\r\n\t\tfor(int j=0; j<tableSize; j++){\r\n\t\t\r\n\t\t\tif(cuckooTable[i][j]==INT_MIN){\r\n\r\n\t\t\t\tcout<<\" N \";\r\n\r\n\t\t\t}\r\n\t\t\r\n\t\t\telse{\r\n\r\n\t\t\t\tcout<<\" \"<<cuckooTable[i][j];\r\n\r\n\t\t\t}\r\n\r\n\t\t}\r\n\t}\r\n\t\r\n\tcout<<endl;\r\n\r\n}\r\n\r\n//Evaluates hash position for elements\r\nint getHashValue(int function, int key){\r\n\t\r\n\tswitch(function){\r\n\t\r\n\t\tcase 1: return key%tableSize; //first hash position\r\n\t\r\n\t\tcase 2: return (key/tableSize)%tableSize; //second hash position\r\n\t\r\n\t}\r\n\r\n}\r\n\r\n//Arrange the position element and perform relocations\r\nvoid getArrange(int key, int hashTable, int currPosition, int n){\r\n\r\n\t//If an element has not allocated any position in hash table\r\n\tif(currPosition == n){\r\n\r\n\t\tcout << key << \" do not have a position\\n\" << endl;\r\n\t\treturn;\r\n\r\n\t}\r\n\r\n\t//Generate the hash position for the key\r\n\tfor(int i=0; i < hashTableNum; i++){\r\n\r\n\t\tPosition[i]= getHashValue(i+1, key);\r\n\r\n\t\tif(cuckooTable[i][Position[i]] == key){\r\n\r\n\t\t\treturn;\r\n\r\n\t\t}\r\n\t}\r\n\r\n\t//If an old key already exist at generated position\r\n\t//relocates the old key in another hash table\r\n\tif(cuckooTable[hashTable][Position[hashTable]]!=INT_MIN){\r\n\r\n\t\tint oldKey = cuckooTable[hashTable][Position[hashTable]];\r\n\r\n\t\tcuckooTable[hashTable][Position[hashTable]] = key;\r\n\r\n\t\t//Perform relocation of old key\r\n\t\tgetArrange(oldKey, (hashTable+1) % hashTableNum, currPosition+1, n);\r\n\r\n\t}\r\n\r\n\telse{\r\n\r\n\t\t//Allocates new key at generated position\r\n\t\tcuckooTable[hashTable][Position[hashTable]]= key;\r\n\r\n\t}\r\n}\r\n\r\n\r\n//Perform Cuckoo Hashing\r\nvoid cuckooFunction(int keys[], int n){\r\n\r\n\tfillTable();\r\n\r\n\t//Perform allocation for every element or key\r\n\tfor(int i=0, currPosition=0; i<n; i++, currPosition=0){\r\n\r\n\t\tgetArrange(keys[i], 0, currPosition, n);\r\n\r\n\t}\r\n\r\n\t//Displays the final hash table\r\n\tprintTable();\r\n\r\n}\r\n\r\n\r\n//Driver Code\r\nint main(){\r\n\r\n\tint n;\r\n\r\n\t//Number of keys on Cuckoo Hashing is to be performed\r\n\tcout<<\"Enter number of terms to be inserted:\";\r\n\tcin>>n;\r\n\r\n\ttableSize=n;\r\n\r\n\tint keyTable[n];  //Array to store keys or elements\r\n\tcout<<\"Enter desired numbers:\\n\";\r\n\r\n\t//Initialize each key or elment in array\r\n\tfor(int i=0; i<n; i++){\r\n\r\n\t\tcin>>keyTable[i];\r\n\r\n\t}\r\n\r\n\tcuckooFunction(keyTable, n);\r\n\r\n\treturn 0;\r\n}"
  },
  {
    "path": "Algorithms/Hashing/Cuckoo_Hashing/Cuckoo_Hashing.java",
    "content": "import java.util.*; \n  \nclass Cuckoo_Hashing\n{ \nstatic int MAXN = 11; \nstatic int ver = 2; \nstatic int [][]hashtable = new int[ver][MAXN]; \n  \n\nstatic int []pos = new int[ver]; \n  \nstatic void initTable() \n{ \n    for (int j = 0; j < MAXN; j++) \n        for (int i = 0; i < ver; i++) \n            hashtable[i][j] = Integer.MIN_VALUE; \n} \n  \nstatic int hash(int function, int key) \n{ \n    switch (function) \n    { \n        case 1: return key % MAXN; \n        case 2: return (key / MAXN) % MAXN; \n    } \n    return Integer.MIN_VALUE; \n} \nstatic void place(int key, int tableID, int cnt, int n) \n{ \n    \n    if (cnt == n) \n    { \n        System.out.printf(\"%d unpositioned\\n\", key); \n        System.out.printf(\"Cycle present. REHASH.\\n\"); \n        return; \n    } \n    for (int i = 0; i < ver; i++) \n    { \n        pos[i] = hash(i + 1, key); \n        if (hashtable[i][pos[i]] == key) \n        return; \n    } \n    if (hashtable[tableID][pos[tableID]] != Integer.MIN_VALUE) \n    { \n        int dis = hashtable[tableID][pos[tableID]]; \n        hashtable[tableID][pos[tableID]] = key; \n        place(dis, (tableID + 1) % ver, cnt + 1, n); \n    } \n    else \n    hashtable[tableID][pos[tableID]] = key; \n} \nstatic void printTable() \n{ \n    System.out.printf(\"Final hash tables:\\n\"); \n  \n    for (int i = 0; i < ver; i++, System.out.printf(\"\\n\")) \n        for (int j = 0; j < MAXN; j++) \n            if(hashtable[i][j] == Integer.MIN_VALUE)  \n                System.out.printf(\"- \"); \n            else\n                System.out.printf(\"%d \", hashtable[i][j]); \n  \n    System.out.printf(\"\\n\"); \n} \n  \nstatic void cuckoo(int keys[], int n) \n{ \n    initTable(); \n    for (int i = 0, cnt = 0; i < n; i++, cnt = 0) \n        place(keys[i], 0, cnt, n); \n    printTable(); \n} \npublic static void main(String[] args)  \n{ \n    int keys_1[] = {20, 50, 53, 75, 100,  \n                    67, 105, 3, 36, 39}; \n  \n    int n = keys_1.length; \n  \n    cuckoo(keys_1, n); \n    int keys_2[] = {20, 50, 53, 75, 100,  \n                    67, 105, 3, 36, 39, 6}; \n  \n    int m = keys_2.length; \n  \n    cuckoo(keys_2, m); \n} \n}"
  },
  {
    "path": "Algorithms/Hashing/Divisible_Pair_Count/DivisiblePairCount.c",
    "content": "#include \"stdio.h\"\n#include <stdlib.h>\n\nint DivisiblePairsCount(int arr[], int n)\n{\n    int res = 0;\n    for (int i = 0; i < n; ++i) {                             // Iterating through each pair.\n       for (int j = i+1; j < n; ++j) {\n            if (arr[i] % arr[j] == 0 || arr[j] % arr[i] == 0)              // Checking for problem condition.\n              res++;\n       }\n    }\n    return res;\n}\n\nint main()\n{\n    int n;\n    int *arr;\n    printf(\"Enter Size of the Array:  \");\n    scanf(\"%d\", &n);\n\n    arr = malloc(sizeof(int) * n);\n\n    printf(\"Enter the Array Elements:  \");\n    for(int i = 0; i<n; i++)\n    {\n        scanf(\"%d\",&arr[i]);\n    }\n\n    printf(\"Number of Divisible Pairs: %d \\n\", DivisiblePairsCount(arr, n));\n\n    return 0;\n}\n"
  },
  {
    "path": "Algorithms/Hashing/Divisible_Pair_Count/DivisiblePairCount.go",
    "content": "package main\n\nimport (\n\t\"fmt\"\n)\n\nfunc main() {\n\tcount := 0\n\tfmt.Printf(\"Enter the total number of elements in the array :\")\n\tvar n int\n\tfmt.Scan(&n)\n\n\tarr := make([]int, n)\n\n\tfor i := 0; i < n; i++ {\n\t\tfmt.Printf(\"Enter %dst element and press enter --> \", i+1)\n\t\tfmt.Scan(&arr[i])\n\t}\n\n\tfor j := 0; j < n; j++ {\n\t\tfor k := j + 1; k < n; k++ {\n\t\t\tif arr[j]%arr[k] == 0 || arr[k]%arr[j] == 0 {\n\t\t\t\tcount++\n\t\t\t}\n\t\t}\n\t}\n\n\tfmt.Printf(\"The number of divisible pair in the array %d is %d\\n\", arr, count)\n}\n"
  },
  {
    "path": "Algorithms/Hashing/Divisible_Pair_Count/DivisiblePairCount.java",
    "content": "import java.io.*;\nimport java.lang.*;\nimport java.util.*;\nclass DivisiblePairCount{ \n\npublic static int countDivisibles(int arr[],int n) \n{ \n    int res = 0; \n    for (int i = 0; i < n; i++)  \n    {\n\tfor (int j = i + 1; j < n; j++)  \n        {\n\t    if (arr[i] % arr[j] == 0 ||  arr[j] % arr[i] == 0)  \n\t    {\n\t            res++; \n\t    }\t\n  \t}\n    }\n    return res; \n} \n  \npublic static void main(String[] args) \n{\n    Scanner sc  = new Scanner(System.in);\n    int num = sc.nextInt();\n    int a[] = new int[num];\n    for(int i=0;i<num;i++)\n    {\n\ta[i] = sc.nextInt();\n    }\n    System.out.print(countDivisibles(a, num)); \n} \n} "
  },
  {
    "path": "Algorithms/Hashing/Divisible_Pair_Count/DivisiblePairCount.js",
    "content": "\nlet DivisiblePairCount = (arr, n) => {\n    let count = 0; // set count = 0\n    for (let i = 0; i < n; i++) // iterate through the array from i = 0\n    {\n        for (let j = i + 1; j < n; j++) // iterate through the array start from the element next to arr[i]\n        {\n            if (\n                (arr[i] % arr[j] == 0)  \n                || (arr[j] % arr[i] == 0)\n                )\n                {\n                    count++; // increase count by 1, if it is under the condition\n                }\n        }\n    }\n    return count;    \n}\nlet arr = [2,3,5,8,9];\nconsole.log(DivisiblePairCount(arr, arr.length));"
  },
  {
    "path": "Algorithms/Hashing/Divisible_Pair_Count/DivisiblePairCount.py",
    "content": "def DivisiblePairCount(arr, n) :\n\n    res = 0\n\n    for i in range(0, n):\n        for j in range(i+1, n):\n\n            if (arr[i] % arr[j] == 0 or arr[j] % arr[i] == 0):\n                res+=1\n\n    return res\n\nif __name__=='__main__':\n    arr = [int(item) for item in input(\"Enter the array items : \").split()]\n    n = len(arr);\n    print(\"Number of divisible pairs are:\", DivisiblePairCount(arr, n) )\n\n"
  },
  {
    "path": "Algorithms/Hashing/Divisible_Pair_Count/DivsiblePairCount.cpp",
    "content": "#include <bits/stdc++.h>\n\n\n// C++ program to count divisible pairs.\nusing namespace std;\n\nint DivisiblePairsCount(vector<int> v, int n)\n{\n    int res = 0;\n    for (int i = 0; i < n; ++i) {                             // Iterating through each pair.\n       for (int j = i+1; j < n; ++j) {\n            if (v[i] % v[j] == 0 || v[j] % v[i] == 0)              // Checking for problem condition.\n              res++;\n       }\n    }\n    return res;\n}\n\nint main()\n{\n    int n;\n\n    cout << \"Enter Size of the Array:  \";\n    cin >> n;\n\n    vector<int> v(n);\n\n    cout << \"Enter Array Elements:  \";\n    for (auto &i : v) {                  // Vector Input\n        cin >> i;\n    }\n\n    cout << \"Number of Divisible Pairs:  \";\n\n    cout << DivisiblePairsCount(v, n);\n\n\n    return 0;\n}\n"
  },
  {
    "path": "Algorithms/Hashing/Group_Anagrams/Group_Anagrams.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <unordered_map>\n#include <bits/stdc++.h>\n\nusing namespace std;\nvector<vector<string>> groupAnagrams(vector<string> &strs)\n{\n    //basically what we need to do is that we need to create a map that will store the characters of a particular string\n    // Now compare it with every other string\n    //O(n3) solution\n    vector<vector<string>> res;\n    unordered_map<string, vector<string>> m;\n\n    for (int i = 0; i < strs.size(); i++)\n    {\n        string eq = strs[i];\n        sort(eq.begin(), eq.end());\n        m[eq].push_back(strs[i]);\n    }\n\n    for (auto it = m.begin(); it != m.end(); it++)\n    {\n        res.push_back(it->second);\n    }\n    return res;\n}\n\nint main()\n{\n    int n;\n    cout << \"Input number of words in string: \";\n    cin >> n;\n    vector<string> strs(n);\n    for (int i = 0; i < n; i++)\n    {\n        cout << \"Enter word: \";\n        cin >> strs[i];\n    }\n    vector<vector<string>> res = groupAnagrams(strs);\n    cout << \"[\";\n    for (int i = 0; i < res.size(); i++)\n    {\n        cout << \"[\";\n        for (int j = 0; j < res[i].size(); j++)\n        {\n            cout << res[i][j];\n            if (j != res[i].size() - 1)\n            {\n                cout << \",\";\n            }\n        }\n        cout << \"]\";\n        if (i != res.size() - 1)\n            cout << \",\";\n    }\n    cout << \"]\";\n    return 0;\n}"
  },
  {
    "path": "Algorithms/Hashing/Group_Anagrams/QUESTIONS.md",
    "content": "### Group Anagrams\n\nGiven an array of strings strs, group the anagrams together. You can return the answer in any order.\n\nAn Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once."
  },
  {
    "path": "Algorithms/Hashing/Group_Anagrams/group_anagrams.js",
    "content": "function groupAnagrams(stringValue) {\n    //create dictionary object to keep track of which strings are made up of which letters\n\n    let anagrams = {};\n\n    for (let str of stringValue) {\n        // loop through strings and  sort them alphabetically\n        let letters = str.split(\"\").sort().join(\"\");\n\n        //if the sorted string already exists as a key on the dictionary, push string \n        if (anagrams[letters])\n            anagrams[letters].push(str)\n\n        //else it as a key to the dictionary\n        else\n            anagrams[letters] = [str]\n    }\n    // use objects.values on the dictionary to return all values as an array\n    return Object.values(anagrams);\n};\n\n//Test\nlet array = []\nlet array_len = parseInt(prompt(\"Input number of words in string array:\"))\nfor(var i =0; i< array_len; i++){\n    let word = prompt(\"Enter a word\");\n    array.push(word)\n}\nconsole.log(groupAnagrams(array))\n"
  },
  {
    "path": "Algorithms/Hashing/Group_Anagrams/group_anagrams.py",
    "content": "from itertools import groupby\nprint(\"Please input the required data seperated with space\")\ntest_list=input(\"Enter data:\").split()\n\n\ntemp = lambda test_list: sorted(test_list) \nres = [list(val) for key, val in groupby(sorted(test_list, key = temp), temp)] \n\n# print result \nprint(\"The grouped Anagrams : \" + str(res)) \n"
  },
  {
    "path": "Algorithms/Hashing/Open Addressing/doubleHashHashingTable.cpp",
    "content": "#include<stdlib.h>\n#include<iostream>\n#include<functional>\n#include<string>\n#include<cmath>\n\nusing std::endl;\nusing std::cout;\nusing std::cin;\nusing std::string;\n\n// fwd declarations\nstruct Entry;\nbool putProber(Entry entry, int key);\nbool searchingProber(Entry entry, int key);\nvoid add(int key);\n\n// globals\nint notPresent;\nstruct Entry* table;\nint totalSize;\nint tomb = -1;\nint size;\nbool rehashing;\n\n// Node that holds key\nstruct Entry {\n    explicit Entry(int key = notPresent) : key(key) {}\n    int key;\n};\n\n// Hash a key\nint hashFxn(int key) {\n    std::hash<int> hash;\n    return hash(key);\n}\n\n// Used for second hash function\nint otherHashFxn(int key) {\n    std::hash<int> hash;\n    return 1 + (7 - (hash(key) % 7));\n}\n\n// Performs double hashing to resolve collisions\nint doubleHash(int key, bool searching) {\n    int hash = static_cast<int>(fabs(hashFxn(key)));\n    int i = 0;\n    Entry entry;\n    do {\n        int index = static_cast<int>(fabs((hash +\n            (i * otherHashFxn(key))))) % totalSize;\n        entry = table[index];\n        if (searching) {\n            if (entry.key == notPresent) {\n                return notPresent;\n            }\n            if (searchingProber(entry, key)) {\n                cout << \"Found key!\" << endl;\n                return index;\n            }\n            cout << \"Found tombstone or equal hash, checking next\" << endl;\n            i++;\n        } else {\n            if (putProber(entry, key)) {\n                if (!rehashing) cout << \"Spot found!\" << endl;\n                return index;\n            }\n            if (!rehashing) cout << \"Spot taken, looking at next (next index:\"\n                << \" \" << static_cast<int>(fabs((hash +\n                (i * otherHashFxn(key))))) % totalSize << \")\" << endl;\n            i++;\n        }\n        if (i == totalSize * 100) {\n            cout << \"DoubleHash probe failed\" << endl;\n            return notPresent;\n        }\n    } while (entry.key != notPresent);\n    return notPresent;\n}\n\n// Finds empty spot\nbool putProber(Entry entry, int key) {\n    if (entry.key == notPresent || entry.key == tomb) {\n        return true;\n    }\n    return false;\n}\n\n// Looks for a matching key\nbool searchingProber(Entry entry, int key) {\n    if (entry.key == key) return true;\n    return false;\n}\n\n// Displays the table\nvoid display() {\n    for (int i = 0; i < totalSize; i++) {\n        if (table[i].key == notPresent) {\n            cout << \" Empty \";\n        } else if (table[i].key == tomb) {\n            cout << \" Tomb \";\n        } else {\n            cout << \" \";\n            cout << table[i].key;\n            cout << \" \";\n        }\n    }\n    cout << endl;\n}\n\n// Rehashes the table into a bigger table\nvoid rehash() {\n    // Necessary so wall of add info isn't printed all at once\n    rehashing = true;\n    int oldSize = totalSize;\n    Entry* oldTable = table;\n    // Really this should use the next prime number greater than totalSize * 2\n    table = new Entry[totalSize * 2];\n    totalSize *= 2;\n    for (int i = 0; i < oldSize; i++) {\n        if (oldTable[i].key != -1 && oldTable[i].key != notPresent) {\n            size--;  // Size stays the same (add increments size)\n            add(oldTable[i].key);\n        }\n    }\n    delete[] oldTable;\n    rehashing = false;\n    cout << \"Table was rehashed, new size is: \" << totalSize << endl;\n}\n\n// Checks for load factor here\nvoid add(int key) {\n    Entry * entry = new Entry();\n    entry->key = key;\n    int index = doubleHash(key, false);\n    table[index] = *entry;\n    // Load factor greater than 0.5 causes resizing\n    if (++size/ static_cast<double>(totalSize) >= 0.5) {\n        rehash();\n    }\n}\n\n// Removes key. Leaves tombstone upon removal.\nvoid remove(int key) {\n    int index = doubleHash(key, true);\n    if (index == notPresent) {\n        cout << \"key not found\" << endl;\n    }\n    table[index].key = tomb;\n    cout << \"Removal successful, leaving tombstone\" << endl;\n    size--;\n}\n\n// Information about the adding process\nvoid addInfo(int key) {\n    cout << \"Initial table: \";\n    display();\n    cout << endl;\n    cout << \"hash of \" << key << \" is \" << hashFxn(key)\n        << \" % \" << totalSize << \" == \" << fabs(hashFxn(key) % totalSize);\n    cout << endl;\n    add(key);\n    cout << \"New table: \";\n    display();\n}\n\n// Information about removal process\nvoid removalInfo(int key) {\n    cout << \"Initial table: \";\n    display();\n    cout << endl;\n    cout << \"hash of \" << key << \" is \" << hashFxn(key)\n        << \" % \" << totalSize << \" == \" << hashFxn(key) % totalSize;\n    cout << endl;\n    remove(key);\n    cout << \"New table: \";\n    display();\n}\n\n// I/O\nint main(void) {\n    int cmd, hash, key;\n    cout << \"Enter the initial size of Hash Table. = \";\n    cin >> totalSize;\n    table = new Entry[totalSize];\n    bool loop = true;\n    while (loop) {\n        system(\"pause\");\n        cout << endl;\n        cout << \"PLEASE CHOOSE -\" << endl;\n        cout << \"1. Add key. (Numeric only)\" << endl;\n        cout << \"2. Remove key.\" << endl;\n        cout << \"3. Find key.\" << endl;\n        cout << \"4. Generate Hash. (Numeric only)\" << endl;\n        cout << \"5. Display Hash table.\" << endl;\n        cout << \"6. Exit.\" << endl;\n        cin >> cmd;\n        switch (cmd) {\n        case 1:\n            cout << \"Enter key to add = \";\n            cin >> key;\n            addInfo(key);\n            break;\n        case 2:\n            cout << \"Enter key to remove = \";\n            cin >> key;\n            removalInfo(key);\n            break;\n        case 3: {\n            cout << \"Enter key to search = \";\n            cin >> key;\n            Entry entry = table[doubleHash(key, true)];\n            if (entry.key == notPresent) {\n                cout << \"Key not present\";\n            }\n            break;\n        }\n        case 4:\n            cout << \"Enter element to generate hash = \";\n            cin >> key;\n            cout << \"Hash of \" << key << \" is = \" << fabs(hashFxn(key));\n            break;\n        case 5:\n            display();\n            break;\n        default:\n            loop = false;\n            break;\n            delete[] table;\n        }\n        cout << endl;\n    }\n    return 0;\n}\n"
  },
  {
    "path": "Algorithms/Hashing/Open Addressing/linearProbingHashTable.cpp",
    "content": "#include<stdlib.h>\n#include<iostream>\n#include<functional>\n#include<string>\n#include<cmath>\n\nusing std::endl;\nusing std::cout;\nusing std::cin;\nusing std::string;\n\n// fwd declarations\nstruct Entry;\nbool putProber(Entry entry, int key);\nbool searchingProber(Entry entry, int key);\nvoid add(int key);\n\n// globals\nint notPresent;\nstruct Entry* table;\nint totalSize;\nint tomb = -1;\nint size;\nbool rehashing;\n\n// Node that holds key\nstruct Entry {\n    explicit Entry(int key = notPresent) : key(key) {}\n    int key;\n};\n\n// Hash a key\nint hashFxn(int key) {\n    std::hash<int> hash;\n    return hash(key);\n}\n\n// Performs linear probing to resolve collisions\nint linearProbe(int key, bool searching) {\n    int hash = static_cast<int>(fabs(hashFxn(key)));\n    int i = 0;\n    Entry entry;\n    do {\n        int index = static_cast<int>(fabs((hash + i) % totalSize));\n        entry = table[index];\n        if (searching) {\n            if (entry.key == notPresent) {\n                return notPresent;\n            }\n            if (searchingProber(entry, key)) {\n                cout << \"Found key!\" << endl;\n                return index;\n            }\n            cout << \"Found tombstone or equal hash, checking next\" << endl;\n            i++;\n        } else {\n            if (putProber(entry, key)) {\n                if (!rehashing) cout << \"Spot found!\" << endl;\n                return index;\n            }\n            if (!rehashing) cout << \"Spot taken, looking at next\" << endl;\n            i++;\n        }\n        if (i == totalSize) {\n            cout << \"Linear probe failed\" << endl;\n            return notPresent;\n        }\n    } while (entry.key != notPresent);\n    return notPresent;\n}\n\n// Finds empty spot\nbool putProber(Entry entry, int key) {\n    if (entry.key == notPresent || entry.key == tomb) {\n        return true;\n    }\n    return false;\n}\n\n// Looks for a matching key\nbool searchingProber(Entry entry, int key) {\n    if (entry.key == key) return true;\n    return false;\n}\n\n// Displays the table\nvoid display() {\n    for (int i = 0; i < totalSize; i++) {\n        if (table[i].key == notPresent) {\n            cout << \" Empty \";\n        } else if (table[i].key == tomb) {\n            cout << \" Tomb \";\n        } else {\n            cout << \" \";\n            cout << table[i].key;\n            cout << \" \";\n        }\n    }\n    cout << endl;\n}\n\n// Rehashes the table into a bigger table\nvoid rehash() {\n    // Necessary so wall of add info isn't printed all at once\n    rehashing = true;\n    int oldSize = totalSize;\n    Entry* oldTable = table;\n    // Really this should use the next prime number greater than totalSize * 2\n    table = new Entry[totalSize * 2];\n    totalSize *= 2;\n    for (int i = 0; i < oldSize; i++) {\n        if (oldTable[i].key != -1 && oldTable[i].key != notPresent) {\n            size--;  // Size stays the same (add increments size)\n            add(oldTable[i].key);\n        }\n    }\n    delete[] oldTable;\n    rehashing = false;\n    cout << \"Table was rehashed, new size is: \" << totalSize << endl;\n}\n\n// Adds entry using linear probing. Checks for load factor here\nvoid add(int key) {\n    Entry * entry = new Entry();\n    entry->key = key;\n    int index = linearProbe(key, false);\n    table[index] = *entry;\n    // Load factor greater than 0.5 causes resizing\n    if (++size/ static_cast<double>(totalSize) >= 0.5) {\n        rehash();\n    }\n}\n\n// Removes key. Leaves tombstone upon removal.\nvoid remove(int key) {\n    int index = linearProbe(key, true);\n    if (index == notPresent) {\n        cout << \"key not found\" << endl;\n    }\n    cout << \"Removal Successful, leaving tomb\" << endl;\n    table[index].key = tomb;\n    size--;\n}\n\n// Information about the adding process\nvoid addInfo(int key) {\n    cout << \"Initial table: \";\n    display();\n    cout << endl;\n    cout << \"hash of \" << key << \" is \" << hashFxn(key) << \" % \"\n        << totalSize << \" == \" << fabs(hashFxn(key) % totalSize);\n    cout << endl;\n    add(key);\n    cout << \"New table: \";\n    display();\n}\n\n// Information about removal process\nvoid removalInfo(int key) {\n    cout << \"Initial table: \";\n    display();\n    cout << endl;\n    cout << \"hash of \" << key << \" is \" << hashFxn(key)\n        << \" % \" << totalSize << \" == \" << hashFxn(key) % totalSize;\n    cout << endl;\n    remove(key);\n    cout << \"New table: \";\n    display();\n}\n\n// I/O\nint main(void) {\n    int cmd, hash, key;\n    cout << \"Enter the initial size of Hash Table. = \";\n    cin >> totalSize;\n    table = new Entry[totalSize];\n    bool loop = true;\n    while (loop) {\n        system(\"pause\");\n        cout << endl;\n        cout << \"PLEASE CHOOSE -\" << endl;\n        cout << \"1. Add key. (Numeric only)\" << endl;\n        cout << \"2. Remove key.\" << endl;\n        cout << \"3. Find key.\" << endl;\n        cout << \"4. Generate Hash. (Numeric only)\" << endl;\n        cout << \"5. Display Hash table.\" << endl;\n        cout << \"6. Exit.\" << endl;\n        cin >> cmd;\n        switch (cmd) {\n        case 1:\n            cout << \"Enter key to add = \";\n            cin >> key;\n            addInfo(key);\n            break;\n        case 2:\n            cout << \"Enter key to remove = \";\n            cin >> key;\n            removalInfo(key);\n            break;\n        case 3: {\n            cout << \"Enter key to search = \";\n            cin >> key;\n            Entry entry = table[linearProbe(key, true)];\n            if (entry.key == notPresent) {\n                cout << \"Key not present\";\n            }\n            break;\n        }\n        case 4:\n            cout << \"Enter element to generate hash = \";\n            cin >> key;\n            cout << \"Hash of \" << key << \" is = \" << fabs(hashFxn(key));\n            break;\n        case 5:\n            display();\n            break;\n        default:\n            loop = false;\n            break;\n            delete[] table;\n        }\n        cout << endl;\n    }\n    return 0;\n}\n"
  },
  {
    "path": "Algorithms/Hashing/Open Addressing/quadraticProbingHashTable.cpp",
    "content": "#include<stdlib.h>\n#include<iostream>\n#include<functional>\n#include<string>\n#include<cmath>\n\nusing std::endl;\nusing std::cout;\nusing std::cin;\nusing std::string;\n\n// fwd declarations\nstruct Entry;\nbool putProber(Entry entry, int key);\nbool searchingProber(Entry entry, int key);\nvoid add(int key);\n\n// globals\nint notPresent;\nstruct Entry* table;\nint totalSize;\nint tomb = -1;\nint size;\nbool rehashing;\n\n// Node that holds key\nstruct Entry {\n    explicit Entry(int key = notPresent) : key(key) {}\n    int key;\n};\n\n// Hash a key\nint hashFxn(int key) {\n    std::hash<int> hash;\n    return hash(key);\n}\n\n// Performs quadratic probing to resolve collisions\nint quadraticProbe(int key, bool searching) {\n    int hash = static_cast<int>(fabs(hashFxn(key)));\n    int i = 0;\n    Entry entry;\n    do {\n        int index = std::round(fabs((hash +\n            static_cast<int>(std::round(std::pow(i, 2)))) % totalSize));\n        entry = table[index];\n        if (searching) {\n            if (entry.key == notPresent) {\n                return notPresent;\n            }\n            if (searchingProber(entry, key)) {\n                cout << \"Found key!\" << endl;\n                return index;\n            }\n            cout << \"Found tombstone or equal hash, checking next\" << endl;\n            i++;\n        } else {\n            if (putProber(entry, key)) {\n                if (!rehashing) cout << \"Spot found!\" << endl;\n                return index;\n            }\n            if (!rehashing) {\n                cout << \"Spot taken, looking at next (next index = \" <<\n                    std::round(fabs((hash + static_cast<int>(std::round(\n                        std::pow(i + 1, 2)))) % totalSize)) << endl;\n            }\n            i++;\n        }\n        if (i == totalSize * 100) {\n            cout << \"Quadratic probe failed (infinite loop)\" << endl;\n            return notPresent;\n        }\n    } while (entry.key != notPresent);\n    return notPresent;\n}\n\n// Finds empty spot\nbool putProber(Entry entry, int key) {\n    if (entry.key == notPresent || entry.key == tomb) {\n        return true;\n    }\n    return false;\n}\n\n// Looks for a matching key\nbool searchingProber(Entry entry, int key) {\n    if (entry.key == key) return true;\n    return false;\n}\n\n// Helper\nEntry find(int key) {\n    int index = quadraticProbe(key, true);\n    if (index == notPresent) return Entry();\n    return table[index];\n}\n\n// Displays the table\nvoid display() {\n    for (int i = 0; i < totalSize; i++) {\n        if (table[i].key == notPresent) {\n            cout << \" Empty \";\n        } else if (table[i].key == tomb) {\n            cout << \" Tomb \";\n        } else {\n            cout << \" \";\n            cout << table[i].key;\n            cout << \" \";\n        }\n    }\n    cout << endl;\n}\n\n// Rehashes the table into a bigger table\nvoid rehash() {\n    // Necessary so wall of add info isn't printed all at once\n    rehashing = true;\n    int oldSize = totalSize;\n    Entry* oldTable = table;\n    // Really this should use the next prime number greater than totalSize * 2\n    table = new Entry[totalSize * 2];\n    totalSize *= 2;\n    for (int i = 0; i < oldSize; i++) {\n        if (oldTable[i].key != -1 && oldTable[i].key != notPresent) {\n            size--;  // Size stays the same (add increments size)\n            add(oldTable[i].key);\n        }\n    }\n    delete[] oldTable;\n    rehashing = false;\n    cout << \"Table was rehashed, new size is: \" << totalSize << endl;\n}\n\n// Checks for load factor here\nvoid add(int key) {\n    Entry * entry = new Entry();\n    entry->key = key;\n    int index = quadraticProbe(key, false);\n    table[index] = *entry;\n    // Load factor greater than 0.5 causes resizing\n    if (++size/ static_cast<double>(totalSize) >= 0.5) {\n        rehash();\n    }\n}\n\n// Removes key. Leaves tombstone upon removal.\nvoid remove(int key) {\n    int index = quadraticProbe(key, true);\n    if (index == notPresent) {\n        cout << \"key not found\" << endl;\n    }\n    table[index].key = tomb;\n    cout << \"Removal successful, leaving tombstone\" << endl;\n    size--;\n}\n\n// Information about the adding process\nvoid addInfo(int key) {\n    cout << \"Initial table: \";\n    display();\n    cout << endl;\n    cout << \"hash of \" << key << \" is \" << hashFxn(key) << \" % \"\n        << totalSize << \" == \" << fabs(hashFxn(key) % totalSize);\n    cout << endl;\n    add(key);\n    cout << \"New table: \";\n    display();\n}\n\n// Information about removal process\nvoid removalInfo(int key) {\n    cout << \"Initial table: \";\n    display();\n    cout << endl;\n    cout << \"hash of \" << key << \" is \" << hashFxn(key)\n        << \" % \" << totalSize << \" == \" << hashFxn(key) % totalSize;\n    cout << endl;\n    remove(key);\n    cout << \"New table: \";\n    display();\n}\n\n// I/O\nint main(void) {\n    int cmd, hash, key;\n    cout << \"Enter the initial size of Hash Table. = \";\n    cin >> totalSize;\n    table = new Entry[totalSize];\n    bool loop = true;\n    while (loop) {\n        system(\"pause\");\n        cout << endl;\n        cout << \"PLEASE CHOOSE -\" << endl;\n        cout << \"1. Add key. (Numeric only)\" << endl;\n        cout << \"2. Remove key.\" << endl;\n        cout << \"3. Find key.\" << endl;\n        cout << \"4. Generate Hash. (Numeric only)\" << endl;\n        cout << \"5. Display Hash table.\" << endl;\n        cout << \"6. Exit.\" << endl;\n        cin >> cmd;\n        switch (cmd) {\n        case 1:\n            cout << \"Enter key to add = \";\n            cin >> key;\n            addInfo(key);\n            break;\n        case 2:\n            cout << \"Enter key to remove = \";\n            cin >> key;\n            removalInfo(key);\n            break;\n        case 3: {\n            cout << \"Enter key to search = \";\n            cin >> key;\n            Entry entry = table[quadraticProbe(key, true)];\n            if (entry.key == notPresent) {\n                cout << \"Key not present\";\n            }\n            break;\n        }\n        case 4:\n            cout << \"Enter element to generate hash = \";\n            cin >> key;\n            cout << \"Hash of \" << key << \" is = \" << fabs(hashFxn(key));\n            break;\n        case 5:\n            display();\n            break;\n        default:\n            loop = false;\n            break;\n            delete[] table;\n        }\n        cout << endl;\n    }\n    return 0;\n}\n"
  },
  {
    "path": "Algorithms/Hashing/Recaman_Sequence/Recamans_Sequence.java",
    "content": "\r\n//Java program to generate Recaman's Sequence upto nth term\r\n\r\nimport java.util.*;\r\n\r\n\r\nclass Sequence{\r\n\r\n\t//Prints Sequence upto first n term\r\n\tvoid recamansSeq(int n){\r\n\r\n\t\t//Array to store sequence\r\n\t\tint seqenceArray[] = new int [n];\r\n\r\n\t\t//First term of Sequence is always 0\r\n\t\tseqenceArray[0] = 0;\r\n\r\n\t\tSystem.out.print(\"Recanman's Sequence is: \"+seqenceArray[0] + \", \");\r\n\r\n\t\t\r\n\t\t//Generate remaining terms using recursive formula\r\n\t\tfor(int i=1; i<n; i++){\r\n\r\n\t\t\tint currentValue = seqenceArray[i-1] - i;\r\n\r\n\t\t\tfor(int j=0; j<i; j++){\r\n\r\n\r\n\t\t\t\t//If seqenceArray[i-1] -i is Negative or already exists\r\n\t\t\t\t//then add i in sequenceArray[i-1]\r\n\t\t\t\tif((seqenceArray[j] == currentValue) || currentValue < 0){\r\n\r\n\t\t\t\t\tcurrentValue = seqenceArray[i-1] + i;\r\n\t\t\t\t\tbreak;\r\n\t\t\t\t}\r\n\t\t\t} \r\n\r\n\t\t\t//Insert new term in array\r\n\t\t\tseqenceArray[i] = currentValue;\r\n\t\t\tSystem.out.print( seqenceArray[i] + \", \");\r\n\t\t}\r\n\t}\r\n\r\n\r\n\tpublic static void main (String[] args)\r\n\t{\r\n\t\t\r\n\t\tScanner sc = new Scanner(System.in);  //Create object\r\n\t\t\r\n\t\tint n;\r\n\r\n\t\tSystem.out.print(\"Enter nth term (upto which sequence should be generated): \");\r\n\t\tn = sc.nextInt();  \r\n\r\n\t\t//Create object for class Sequence\r\n\t\tSequence sq = new Sequence();\r\n\r\n\t\tsq.recamansSeq(n);\r\n\t}\r\n}"
  },
  {
    "path": "Algorithms/Hashing/Recaman_Sequence/Recamans_Sequence.ts",
    "content": "// This is required for console input\nvar readline = require('readline');\nvar rl = readline.createInterface({\n  input: process.stdin,\n  output: process.stdout\n});\n\nrl.question(\"Number of terms to be found: \", function(answer) {\n  let list = [];\n  list[0] = 0;\n  console.log(list[0]);\n  for (let n = 1; n < +answer; n++) {\n    if (list[n-1] - n > 0 && !list.includes(list[n-1] - n)) {\n        list[n] = list[n-1] - n;\n    } else {\n        list[n] = list[n-1] + n;\n    }\n    console.log(list[n]);\n  }\n  rl.close();\n});\n"
  },
  {
    "path": "Algorithms/Hashing/Recaman_Sequence/recaman.py",
    "content": "def recaman(n):\n\tarr = [0] * n \n\tarr[0] = 0\n\tprint(arr[0], end=\", \") \n\tfor i in range(1, n): \n\t\n\t\tcurr = arr[i-1] - i \n\t\tfor j in range(0, i):  \n\t\t\tif ((arr[j] == curr) or curr < 0): \n\t\t\t\tcurr = arr[i-1] + i \n\t\t\t\tbreak\n\t\t\t\n\t\tarr[i] = curr \n\t\tprint(arr[i], end=\", \") \n\n# Driver code \nn = 10\n\nrecaman(n) \n \n"
  },
  {
    "path": "Algorithms/Hashing/Recaman_Sequence/recaman_sequence.cpp",
    "content": "#include <bits/stdc++.h>\nusing namespace std;\n\nint get_recaman_sequence(int n)\n{\n  int *arr = new int[n];\n  arr[0] = 0;\n  cout << arr[0];\n\n  for (int i = 1; i < n; i++)\n  {\n    int curr_element = arr[i - 1] - i;\n    for (int j = 0; j < i; j++)\n    {\n      if ((arr[j] == curr_element) || curr_element < 0)\n      {\n        curr_element = arr[i - 1] + i;\n        break;\n      }\n    }\n    arr[i] = curr_element;\n    cout << arr[i];\n  }\n\n  delete[] arr;\n}\nint main()\n{\n  int n;\n  cout << \"enter the number\";\n  cin >> n;\n  cout << get_recaman_sequence(n);\n  return 0;\n}"
  },
  {
    "path": "Algorithms/Hashing/Recaman_Sequence/recamans_sequence.cs",
    "content": "sing System;\nusing System.Collections.Generic;\n\n\nclass Program\n{\n    static void Main(string[] args)\n    {\n        Console.WriteLine(\"How many numbers do you want to write out?\");\n        int count = int.Parse(Console.ReadLine());\n        List<long> numbers = new List<long>(); \n        numbers.Add(0);\n        long last = numbers[0];\n        Console.WriteLine(numbers[0]);\n        for (int i = 1; i < count; i++)\n        {\n            if (last - i > 0 && !numbers.Contains(last - i)) \n            {\n                numbers.Add(last - i);\n                Console.WriteLine(numbers[i]);\n                last = numbers[i];\n            } else\n            {\n                numbers.Add(last + i);\n                Console.WriteLine(numbers[i]);\n                last = numbers[i];\n            }\n        }\n        Console.ReadLine(); // otherwise the console closes\n    }\n}\n"
  },
  {
    "path": "Algorithms/Heap/README.md",
    "content": "\n"
  },
  {
    "path": "Algorithms/LinkedList/Floyd_Cylce_detection/floyd_cycle_detection.cpp",
    "content": "#include<bits/stdc++.h> \nusing namespace std;\n//Definition for singly-linked list-\nstruct ListNode {\n    int val;\n    ListNode *next;\n};\n//Utility function-\nvoid push(ListNode** head, int new_val) { \n    ListNode* new_node = new ListNode(); \n    new_node->val = new_val;\n    //link the old list off the new node-\n    new_node->next = (*head);\n    //move the head to point to the new node-\n    (*head) = new_node; \n}\n//Floyd cycle-finding algorithm uses two pointers: fast_ptr (moving two nodes at a time) and slow_ptr (moving one node at a time). \n//The concept used is that if these two pointers meet at any time, then a cycle exists, otherwise it does not.\nint isCyclePresent(ListNode* head) {\n    //both pointers start at the head node of the list-\n    ListNode* slow=head;\n    ListNode* fast=head;\n    bool cycle=false;                //cycle is not yet detected\n    //Floyd Algorithm-\n    while(fast!=NULL){\n        slow=slow->next;             //move forward one node\n        if(fast->next!=NULL)\n           fast=fast->next->next;    //move forward two nodes\n        else\n           fast=NULL;                //reached end of list\n        \n        if(slow==fast){              //the pointers meet\n           cycle=true;\n           break;\n        }\n    }\n    if(cycle) \n       return 1;                     //cycle exists\n    else\n       return 0;                     //cycle doesn't exist\n}\n\nint main() { \n    //Start with the empty list\n    ListNode* head = NULL;\n    push(&head, 20); \n    push(&head, 4); \n    push(&head, 15); \n    push(&head, 10);\n    //making cycle-\n    head->next->next->next->next = head;    \n    if (isCyclePresent(head)) \n        cout << \"Loop found\"; \n    else\n        cout << \"No Loop\"; \n    return 0; \n} \n"
  },
  {
    "path": "Algorithms/LinkedList/Floyd_Cylce_detection/floyd_cycle_detection.java",
    "content": "// Java program to detect loop in a linked list using Floyd’s Cycle-Finding Algorithm \n\nclass LinkedList { \n    Node head; // head of list \n  \n    /* Linked list Node*/\n    class Node { \n        int data; \n        Node next; \n        Node(int d) \n        { \n            data = d; \n            next = null; \n        } \n    } \n  \n    /* Inserts a new Node at front of the list. */\n    public void push(int new_data) \n    { \n        /* 1 & 2: Allocate the Node &  \n                Put in the data*/\n        Node new_node = new Node(new_data); \n  \n        /* 3. Make next of new Node as head */\n        new_node.next = head; \n  \n        /* 4. Move the head to point to new Node */\n        head = new_node; \n    } \n  \n    boolean detectLoop() \n    { \n        Node slow_p = head, fast_p = head; \n        int flag = 0; \n        while (slow_p != null && fast_p != null && fast_p.next != null) { \n            slow_p = slow_p.next; \n            fast_p = fast_p.next.next; \n            if (slow_p == fast_p) { \n                flag = 1; \n                break; \n            } \n        } \n        if (flag == 1) \n            return true;\n        else\n            return false; \n    } \n  \n    /* Driver program to test above functions */\n    public static void main(String args[]) \n    { \n        LinkedList llist = new LinkedList(); \n  \n        llist.push(20); \n        llist.push(4); \n        llist.push(15); \n        llist.push(10); \n        llist.push(77);\n  \n        /*Create loop for testing */\n        llist.head.next.next.next.next.next = llist.head; \n  \n        boolean v = llist.detectLoop();\n        if (v) \n            System.out.println(\"Cycle found\"); \n        else\n            System.out.println(\"Cycle not found\");  \n        \n    } \n} \n"
  },
  {
    "path": "Algorithms/LinkedList/Floyd_Cylce_detection/floyd_cycle_detection.kt",
    "content": "class LinkedList<T> {\n    class Node<T>(val value: T, var next: Node<T>? = null)\n\n    var head: Node<T>? = null\n    private lateinit var tail: Node<T>\n\n    fun insert(item: T) {\n        if (head == null) {\n            tail = Node(item)\n            head = tail\n        } else {\n            tail.next = Node(item)\n            tail = tail.next!!\n        }\n    }\n\n    fun detectLoop(): Boolean {\n        var slowPointer = head?.next\n        var fastPointer = head?.next?.next\n\n        while (slowPointer != null && fastPointer != null) {\n            if (slowPointer == fastPointer) return true\n            slowPointer = slowPointer.next\n            fastPointer = fastPointer.next?.next\n        }\n\n        return false\n    }\n\n    fun forceLoop() {\n        tail.next = head\n    }\n}\n\nfun main() {\n    val linkedList = LinkedList<Int>()\n    linkedList.apply {\n        insert(1)\n    }\n    println(\"linkedList has loop: \" + linkedList.detectLoop())\n\n    linkedList.forceLoop()\n    println(\"linkedList has loop: \" + linkedList.detectLoop())\n}"
  },
  {
    "path": "Algorithms/LinkedList/Floyd_Cylce_detection/floyd_cycle_detection.py",
    "content": " class Node:  \n\tdef __init__(self, data): \n\t\tself.data = data \n\t\tself.next = None\n\nclass LinkedList:  \n\tdef __init__(self): \n\t\tself.head = None\n\n\n\tdef push(self, new_data): \n\t\tnew_node = Node(new_data) \n\t\tnew_node.next = self.head \n\t\tself.head = new_node \n\n\n\tdef printList(self): \n\t\ttemp = self.head \n\t\twhile(temp): \n\t\t\tprint (temp.data, end =\" \") \n\t\t\ttemp = temp.next\n\n\n\tdef detectLoop(self): \n\t\ts = set() \n\t\ttemp = self.head \n\t\twhile (temp): \n\t\t\tif (temp in s): \n\t\t\t\treturn True\n\n\t\t\ts.add(temp) \n\t\t\ttemp = temp.next\n\t\t\n\t\n\t\treturn False\n\n\n\n# Driver program for testing \nllist = LinkedList() \nllist.push(10) \nllist.push(4) \nllist.push(15) \nllist.push(40) \n\n# Create a loop for testing \nllist.head.next.next.next.next = llist.head; \n\nif( llist.detectLoop()): \n\tprint (\"Loop found\") \nelse : \n\tprint (\"No Loop \") \n\n"
  },
  {
    "path": "Algorithms/LinkedList/Floyd_Cylce_detection/floyd_cycle_detection.swift",
    "content": "//  floyd_cycle_detection.swift\n//\n//  Swift implementation of a linked list with cycle detection functionality\n//\n//  How to run: type on terminal `swift floyd_cycle_detection.swift` and type enter. \n//              The test program will populate two lists, one with loop and one without\n//              and will print test both for if theres a loop or not.\n\n// A class representing one node of the list\nclass Node<T> {\n\n    // Public properties\n    public var value: T\n    public var next: Node<T>?\n\n    // Create a new node with a given value\n    public init (value: T) {\n        self.value = value\n    }\n}\n\n// A class representing the list\nclass LinkedList<T> {\n\n    // Current head of list\n    var head: Node<T>\n\n    // Create a new list with a given node\n    public init(node: Node<T>) {\n        head = node\n    }\n\n    // Insert a node at the start of the list\n    public func insert(_ node: Node<T>) {\n        node.next = head\n        head = node\n    }\n\n    // Detects if there is a loop on the list using the Floyd`s Cycle-Finding Algorithm\n    public func detectLoop() -> Bool {\n        var slowPointer = head.next\n        var fastPointer = head.next?.next \n\n        // Transverse the list with two pointers going on different speeds.\n        // If there is a loop on the list, eventually the fastest pointer will catch up the slower, and they will be equal.\n        // If not, eventually they will reach the end of the list.\n        while slowPointer != nil && fastPointer != nil {\n            if fastPointer! === slowPointer! {\n                return true\n            }\n            slowPointer = slowPointer!.next\n            fastPointer = fastPointer!.next?.next\n        }\n        return false\n    }\n}\n\n/*********** Testing the detect loop method ***********/\n\n// Adding a print funcionality just so we can see the list elements\nextension LinkedList {\n    public func description(maxElements: Int) -> String {\n        var count = 0\n        var currentNode = Optional(head)\n        var listDescription = \"\"\n        while currentNode != nil {\n            listDescription += (String(describing: currentNode!.value) + \" -> \")\n            count += 1\n            if count >= maxElements {\n                return listDescription + \" (list continues...) \"\n            }\n            currentNode = currentNode?.next\n        }\n        return listDescription + \"(End of list)\"\n    }\n}\n\n// Populating a list without loop\nlet linkedListWithoutLoop = LinkedList(node: Node(value: \"1\"))\nlinkedListWithoutLoop.insert(Node(value:\"2\"))\nlinkedListWithoutLoop.insert(Node(value:\"3\"))\nlinkedListWithoutLoop.insert(Node(value:\"4\"))\nlinkedListWithoutLoop.insert(Node(value:\"5\"))\nlinkedListWithoutLoop.insert(Node(value:\"6\"))\nlinkedListWithoutLoop.insert(Node(value:\"7\"))\n\nprint(\"List: \\(linkedListWithoutLoop.description(maxElements: 20))\")\nprint(\"Loop detected: \\(linkedListWithoutLoop.detectLoop())\")\n\n\n// Populating a list with loop\nlet listTail = Node(value: \"A\")\nlet linkedListWithLoop = LinkedList(node: listTail)\nlinkedListWithLoop.insert(Node(value:\"B\"))\nlinkedListWithLoop.insert(Node(value:\"C\"))\nlinkedListWithLoop.insert(Node(value:\"D\"))\nlinkedListWithLoop.insert(Node(value:\"E\"))\nlinkedListWithLoop.insert(Node(value:\"F\"))\nlinkedListWithLoop.insert(listTail)\n\nprint(\"List: \\(linkedListWithLoop.description(maxElements: 20))\")\nprint(\"Loop detected: \\(linkedListWithLoop.detectLoop())\")"
  },
  {
    "path": "Algorithms/Matrix/README.md",
    "content": "# This folder is empty.\n"
  },
  {
    "path": "Algorithms/Matrix/Spiral-Matrix/Spiral-Matrix.cpp",
    "content": "// Code contributed by Vatsalya Gupta\r\n#include <iostream>\r\n#include <vector>\r\nusing namespace std;\r\n#define R 4\r\n#define C 4\r\n\r\nbool isInBounds(int i, int j)\r\n{\r\n\tif (i < 0 || i >= R || j < 0 || j >= C)\r\n\t\treturn false;\r\n\treturn true;\r\n}\r\n\r\nbool isBlocked(int matrix[R][C], int i, int j)\r\n{\r\n\tif (!isInBounds(i, j))\r\n\t\treturn true;\r\n\tif (matrix[i][j] == -1)\r\n\t\treturn true;\r\n\treturn false;\r\n}\r\n\r\nvoid spirallyDFSTravserse(int matrix[R][C], int i, int j,\r\n\t\t\t\t\t\tint dir, vector<int>& res)\r\n{\r\n\tif (isBlocked(matrix, i, j))\r\n\t\treturn;\r\n\tbool allBlocked = true;\r\n\tfor (int k = -1; k <= 1; k += 2) {\r\n\t\tallBlocked = allBlocked\r\n\t\t\t\t\t&& isBlocked(matrix, k + i, j)\r\n\t\t\t\t\t&& isBlocked(matrix, i, j + k);\r\n\t}\r\n\tres.push_back(matrix[i][j]);\r\n\tmatrix[i][j] = -1;\r\n\tif (allBlocked) {\r\n\t\treturn;\r\n\t}\r\n\r\n\t// dir: 0 - right, 1 - down, 2 - left, 3 - up\r\n\tint nxt_i = i;\r\n\tint nxt_j = j;\r\n\tint nxt_dir = dir;\r\n\tif (dir == 0) {\r\n\t\tif (!isBlocked(matrix, i, j + 1)) {\r\n\t\t\tnxt_j++;\r\n\t\t}\r\n\t\telse {\r\n\t\t\tnxt_dir = 1;\r\n\t\t\tnxt_i++;\r\n\t\t}\r\n\t}\r\n\telse if (dir == 1) {\r\n\t\tif (!isBlocked(matrix, i + 1, j)) {\r\n\t\t\tnxt_i++;\r\n\t\t}\r\n\t\telse {\r\n\t\t\tnxt_dir = 2;\r\n\t\t\tnxt_j--;\r\n\t\t}\r\n\t}\r\n\telse if (dir == 2) {\r\n\t\tif (!isBlocked(matrix, i, j - 1)) {\r\n\t\t\tnxt_j--;\r\n\t\t}\r\n\t\telse {\r\n\t\t\tnxt_dir = 3;\r\n\t\t\tnxt_i--;\r\n\t\t}\r\n\t}\r\n\telse if (dir == 3) {\r\n\t\tif (!isBlocked(matrix, i - 1, j)) {\r\n\t\t\tnxt_i--;\r\n\t\t}\r\n\t\telse {\r\n\t\t\tnxt_dir = 0;\r\n\t\t\tnxt_j++;\r\n\t\t}\r\n\t}\r\n\tspirallyDFSTravserse(matrix, nxt_i, nxt_j, nxt_dir, res);\r\n}\r\n\r\nvector<int> spirallyTraverse(int matrix[R][C])\r\n{\r\n\tvector<int> res;\r\n\tspirallyDFSTravserse(matrix, 0, 0, 0, res);\r\n\treturn res;\r\n}\r\n\r\nint main()\r\n{\r\n\tint a[R][C] = { { 1, 2, 3, 4 },\r\n\t\t\t{ 5, 6, 7, 8 },\r\n\t\t\t{ 9, 10, 11, 12 },\r\n\t\t\t{ 13, 14, 15, 16 } };\r\n\r\n\tvector<int> res = spirallyTraverse(a);\r\n\tint size = res.size();\r\n\tfor (int i = 0; i < size; ++i)\r\n\t\tcout << res[i] << \" \";\r\n\tcout << endl;\r\n\treturn 0;\r\n}\r\n"
  },
  {
    "path": "Algorithms/Merging-Interval/#999 merging_intervals.py",
    "content": "def mergeIntervals(arr):\n        arr.sort(key = lambda x: x[0]) \n        m = []\n        s = -10000\n        max = -100000\n        for i in range(len(arr)):\n            a = arr[i]\n            if a[0] > max:\n                if i != 0:\n                    m.append([s,max])\n                max = a[1]\n                s = a[0]\n            else:\n                if a[1] >= max:\n                    max = a[1]\n        if max != -100000 and [s, max] not in m:\n            m.append([s, max])\n        print(\"The Merged Intervals are :\", end = \" \")\n        for i in range(len(m)):\n            print(m[i], end = \" \")\n            \n            \narr = [[6, 8], [1, 9], [2, 4], [4, 7]]\nmergeIntervals(arr)"
  },
  {
    "path": "Algorithms/Merging-Interval/Merging_Intervals.java",
    "content": "import java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.List;\n\npublic class Merging_Intervals {\n\t\n\tpublic static void main(String args[]) {\n\t\t//Given 2D array containing intervals\n\t\tint[][] ans = {{1,3},{2,6},{8,10},{15,18}};\n\t\t\n\t\t//This function returns 2D array having our merged intervals\n\t\tans = merge(ans);\n\t\t\n\t\t//Each merged interval will be displayed on each line\n\t\tfor (int i = 0; i < ans.length; i++) {\n\t\t\tfor (int j = 0; j < ans[0].length; j++) {\n\t\t\t\tSystem.out.print(ans[i][j] + \" \");\n\t\t\t}\n\t\t\tSystem.out.println();\n\t\t}\n\t\n\t}\n\t\n\tpublic static int[][] merge(int[][] intervals) {\n        \n        if (intervals.length <= 1) {\n            return intervals;\n        }\n        \n        //Perform sorting in increasing order of first element of each interval\n        Arrays.sort(intervals, (a1, a2) -> a1[0] - a2[0]);\n        \n        List<int[]> output_arr = new ArrayList<int[]>();\n        \n        int[] curr_interval = intervals[0];\n        output_arr.add(curr_interval);\n        \n        for (int[] interval : intervals) {\n            int curr_beg = curr_interval[0];\n            int curr_end = curr_interval[1];\n            int next_beg = interval[0];\n            int next_end = interval[1];\n            \n            if (curr_end >= next_beg) {\n                curr_interval[1] = Math.max(curr_end, next_end);\n            }\n            else {\n                curr_interval = interval;\n                output_arr.add(curr_interval);\n            }\n        }\n        \n        return output_arr.toArray(new int[output_arr.size()][]);\n        \n    }\n\t\n}\n"
  },
  {
    "path": "Algorithms/Merging-Interval/README.md",
    "content": "# This folder is empty.\n"
  },
  {
    "path": "Algorithms/Merging-Interval/merge_intervals.cpp",
    "content": "#include<bits/stdc++.h>\nusing namespace std;\n \n// An interval has start time and end time\nstruct Interval\n{\n    int start, end;\n};\n \n// To compare two intervals accoridng to their start time\nbool myComp(Interval interval1, Interval interval2)\n{\n    return (interval1.start < interval2.start);\n}\n \n// This function takes a set of intervals, merges\n// overlapping intervals and prints the result\nvoid mergeIntervals(Interval arr[], int n)\n{\n    // Test if the given set has at least one interval\n    if (n <= 0)\n        return;\n \n    // Create an empty stack of intervals\n    stack<Interval> s;\n \n    // sorting the intervals in increasing order of start time\n    sort(arr, arr+n, myComp);\n \n    // push the first interval to stack\n    s.push(arr[0]);\n \n    // Start from the next interval and merge if necessary\n    for (int i = 1 ; i < n; i++)\n    {\n        // get interval from stack top\n        Interval top = s.top();\n \n        // if current interval is not overlapping with stack top,\n        // push it to the stack\n        if (top.end < arr[i].start)\n            s.push(arr[i]);\n \n        // Otherwise update the ending time of top if ending of current\n        // interval is more\n        else if (top.end < arr[i].end)\n        {\n            top.end = arr[i].end;\n            s.pop();\n            s.push(top);\n        }\n    }\n \n    // Print contents of stack\n    cout << \"\\n After merging Intervals are: \";\n    while (!s.empty())\n    {\n        Interval t = s.top();\n        cout << \"[\" << t.start << \",\" << t.end << \"] \";\n        s.pop();\n    }\n    return;\n}\nint main()\n{\n  Interval arr[]= {{1,6},{3,9},{11,13},{2,5}};  //creating an array\n    int n = sizeof(arr)/sizeof(arr[0]); //size of the array\n    mergeIntervals(arr,n);\n    return 0;\n}\n"
  },
  {
    "path": "Algorithms/Merging-Interval/merge_intervals.js",
    "content": "// list of intervals as an array of objects\nconst arr = [\n    { start: 1, end: 3 },\n    { start: 2, end: 4 },\n    { start: 5, end: 8 },\n    { start: 6, end: 7 }\n];\n\n\nfunction mergeIntervals(arr) {\n    // sort the array of intervals in ascending order based on the start value of each interval\n    arr.sort(function(a, b) {\n        if (a.start < b.start) return -1;\n        if (a.start > b.start) return 1;\n        return 0;\n    });\n\n    // result array which will work as stack\n    let res = [];\n\n    // push first interval into result array\n    res.push(arr[0]);\n\n    for (let i = 1; i < arr.length; i++) {\n        // get the top of the result array\n        // we will call it top interval\n        const top = res[res.length - 1]\n\n        // top interval's end is less than the current interval's start that means disjoint intervals\n        // we can push the current interval to our result\n        if (top.end < arr[i].start) {\n            res.push(arr[i]);\n        }\n        // top interval's end is between the current interval's start and end\n        // we can merge intervals with the ending at current interval's end\n        else if (top.end < arr[i].end) {\n            top.end = arr[i].end;\n            // delete the top interval\n            res.pop();\n            // insert new modified interval\n            res.push(top);\n        }\n        // Otherwise top interval's end is after the current interval's end\n        // i.e after merge we will get top interval, hence no change required\n    }\n\n    // print the array of merged intervals\n    console.log(res);\n}\n\nmergeIntervals(arr);"
  },
  {
    "path": "Algorithms/Pattern-Searching/Aho-Corasick/Readme.md",
    "content": "# This folder is created.\n"
  },
  {
    "path": "Algorithms/Pattern-Searching/Binary_Search/search_in_2D_matrix.java",
    "content": "public class search_in_2D_matrix {\n    public static boolean searchMatrix(int[][] matrix, int target) {\n        int colLength = matrix[0].length-1; // each row length\n        for(int i = 0; i < matrix.length; i++) { // iterate over every row\n            if(target > matrix[i][colLength]) continue; // if target is greater than the highest number in that row then skip that row\n            int start = 0, end = colLength;\n            while(start <= end) { // using binary search algorithm to search through the row for the target\n                int mid = start + (end-start)/2;\n                if(matrix[i][mid] == target) return true;\n                if(matrix[i][mid] > target) end = mid-1;\n                else if(matrix[i][mid] < target) start = mid+1;\n            }\n        }\n        return false;\n    }\n    public static void main(String[] args)\n    {\n        Scanner sc = new Scanner(System.in);\n        System.out.println(\"Enter number of rows\");\n        int row = sc.nextInt();\n        System.out.println(\"Enter number of coloumns\");\n        int col = sc.nextInt();\n  \n        int mat[][] = new int[row][col];\n        \n        System.out.println(\"Enter matrix elements in sorted manner\");\n        for(int i=0;i<row;i++){\n            for(int j=0;j<col;j++){\n                mat[i][j] = sc.nextInt();\n            }\n        }\n        System.out.println(\"Enter element to be searched\");\n        int target = sc.nextInt();\n        boolean isFound = searchMatrix(mat,target);\n        if(isFound) {\n            System.out.println(\"Target element found in matrix\");\n        }\n        else {\n            System.out.println(\"Target element not found in matrix\");\n        }\n    }\n}\n"
  },
  {
    "path": "Algorithms/Pattern-Searching/README.md",
    "content": "# This folder is empty.\n"
  },
  {
    "path": "Algorithms/Pattern-Searching/Substring_Check/search.php",
    "content": "<?php \n$d = 256; \n\nfunction search($pat, $txt, $q) \n{ \n\t$M = strlen($pat); \n\t$N = strlen($txt); \n\t$i; $j; \n    $p = 0; //hash value for pattern\n    \n\t$t = 0; // hash value for text\n\t\n\t$h = 1; \n\t$d =1; \n\n\n\tfor ($i = 0; $i < $M - 1; $i++) \n\t\t$h = ($h * $d) % $q; \n\n\n\tfor ($i = 0; $i < $M; $i++) \n\t{ \n\t\t$p = ($d * $p + $pat[$i]) % $q; \n\t\t$t = ($d * $t + $txt[$i]) % $q; \n\t} \n\n\t\n\tfor ($i = 0; $i <= $N - $M; $i++) \n\t{ \n\n\t\t\n\t\tif ($p == $t) \n\t\t{ \n\t\t\tfor ($j = 0; $j < $M; $j++) \n\t\t\t{ \n\t\t\t\tif ($txt[$i + $j] != $pat[$j]) \n\t\t\t\t\tbreak; \n\t\t\t} \n\n\t\t\tif ($j == $M) \n\t\t\t\techo \"Pattern found at index \", $i, \"\\n\"; \n\t\t} \n\n\t\tif ($i < $N - $M) \n\t\t{ \n\t\t\t$t = ($d * ($t - $txt[$i] * $h) + $txt[$i + $M]) % $q; \n\n\t\t\n\t\t\tif ($t < 0) \n\t\t\t$t = ($t + $q); \n\t\t} \n\t} \n} \n\n$txt = \"GEEKS FOR GEEKS\"; \n$pat = \"GEEK\"; \n$q = 101;  \nsearch($pat, $txt, $q); \n\n?> \n"
  },
  {
    "path": "Algorithms/Queue/first_negative_integer_in_window.cpp",
    "content": "/*\nGiven an array and a positive integer k, find the first negative integer for each and every window(contiguous subarray) of size k.\nInput:\nThe first line of input contains an integer T denoting the number of test cases. Then T test cases follow. Each test case contains an integer n denoting the size of the array. The next line contains n space separated integers forming the array. The last line contains the window size k.\nOutput:\nPrint the space separated negative integer starting from the first till the end for every window size k. If a window does not contain a negative integer , then print 0 for that window.\nConstraints:\n1<=T<=10^5\n1<=n<=10^5\n1<=a[i]<=10^5\n1<=k<=n\nExample:\nInput:\n2\n5\n-8 2 3 -6 10\n2\n8\n12 -1 -7 8 -15 30 16 28\n3\nOutput:\n-8 0 -6 -6\n-1 -1 -7 -15 -15 0\n*/\n#include<bits/stdc++.h>\nusing namespace std;\nint findd(int low,int high,int a[]){\n    for(int i=low;i<high;i++)\n        if(a[i]<0)\n            return a[i];\n    return 0;\n}\nint main() {\n\t//code\n\tint t;\n\tcin>>t;\n\twhile(t--){\n\t    int n,k;\n\t    cin>>n;\n\t    int a[n];\n\t    for(int i=0;i<n;i++)\n\t        cin>>a[i];\n\t    cin>>k;\n\t    for(int i=0;i<=n-k;i++)\n\t        cout<<findd(i,i+k,a)<<\" \";\n\t        cout<<endl;\n\t}\n\treturn 0;\n}\n"
  },
  {
    "path": "Algorithms/Queue/first_nonrepeating_char_in_stream.cpp",
    "content": "/*Given an input stream of N characters consisting only of lower case alphabets. The task is to find the first non repeating character, each time a character is inserted to the stream. If no non repeating element is found print -1.\nInput:\nThe first line of input contains an integer T denoting the no of test cases. Then T test cases follow. Each test case contains an integer N denoting the size of the stream. Then in the next line are x characters which are inserted to the stream.\nOutput:\nFor each test case in a new line print the first non repeating elements separated by spaces present in the stream at every instinct when a character is added to the stream, if no such element is present print -1.\nConstraints:\n1 <= T <= 200\n1 <= N <= 500\nExample:\nInput:\n2\n4\na a b c\n3\na a c\nOutput:\na -1 b b\na -1 c\n*/\n#include<bits/stdc++.h>\nusing namespace std;\nint main(){\n    int t;\n    cin>>t;\n    while(t--){\n        int n;\n        cin>>n;\n        vector<char> ch(n);\n        for(int i=0;i<n;i++)\n            cin>>ch[i];\n        int freq[26];\n        for(int i=0;i<n;i++)\n            freq[i]=0;\n        queue<char> q;\n        for(int i=0;i<n;i++){\n            freq[ch[i]-'a']++;\n            q.push(ch[i]);\n            while(!q.empty()){\n                if(freq[q.front()-'a']>1)\n                    q.pop();\n                else{\n                    cout<<q.front()<<\" \";\n                    break;\n                }\n            }\n            if(q.empty())\n                cout<<-1<<\" \";\n        }\n        cout<<endl;\n    }\n    return 0;\n}\n"
  },
  {
    "path": "Algorithms/Queue/reversing a queue.cpp",
    "content": "#include <bits/stdc++.h>\nusing namespace std;\n\n// Utility function to print the queue\nvoid Print(queue<int>& Queue)\n{\n    while (!Queue.empty()) {\n        cout << Queue.front() << \" \";\n        Queue.pop();\n    }\n}\n\n// Function to reverse the queue\nvoid reverseQueue(queue<int>& Queue)\n{\n    stack<int> Stack;\n    while (!Queue.empty()) {\n        Stack.push(Queue.front());\n        Queue.pop();\n    }\n    while (!Stack.empty()) {\n        Queue.push(Stack.top());\n        Stack.pop();\n    }\n}\n\n// Driver code\nint main()\n{\n    queue<int> Queue;\n    Queue.push(10);\n    Queue.push(20);\n    Queue.push(30);\n    Queue.push(40);\n    Queue.push(50);\n    Queue.push(60);\n    Queue.push(70);\n    Queue.push(80);\n    Queue.push(90);\n    Queue.push(100);\n\n    reverseQueue(Queue);\n    Print(Queue);\n}\n"
  },
  {
    "path": "Algorithms/README.md",
    "content": "# Index\n\n\n* [DP](DP/) \n* [Heap](Heap/)\n* [Tree](Tree/) \n* [Array](Array/)\n* [Graph](Graph/) \n* [Queue](Queue/) \n* [Graph](Graph/) \n* [String](String/) \n* [Matrix](Matrix/)\n* [Sorting](Sorting/) \n* [Hashing](Hashing/)\n* [Recursion](Recursion/) \n* [Searching](Searching/) \n* [LinkedList](LinkedList/) \n* [Backtracking](Backtracking/)\n* [Cryptography](Cryptography/)\n* [Merging-Interval](Merging-Interval/) \n* [Pattern-Searching](Pattern-Searching/) \n"
  },
  {
    "path": "Algorithms/Recursion/All_Subsets.c",
    "content": "/**\n * Generate all subsets of a set comprised of 0 <= N ({0 1 2 3 ... N}).\n * \n * @author Ytalo Ramon\n*/\n\n#include \"stdio.h\"\n#include \"stdlib.h\"\n\ntypedef struct _Stack{\n    int posi, length;\n    int *items;\n} Stack;\n\nint is_empty(Stack *stack);\n\nvoid push(Stack *stack, int value);\n\nint pop(Stack *stack);\n\nvoid show_stack(Stack *stack);\n\nvoid set_value_seq(Stack *stack, int start, int end);\n\nvoid generate(Stack *stack, int max);\n\nint main(int argc, char const *argv[]){\n    \n    int max = 6;\n    Stack stack = {posi: -1, length: max, items: malloc(sizeof(int) * max + 1)} ;\n\n    printf(\"----- All Subsets {0 ... %d} -----\\n\", max);\n    set_value_seq(&stack, 0, max);\n    if(max > 0) generate(&stack, max);\n    printf(\"{ }\\n\");\n\n    return 0;\n}\n\nint is_empty(Stack *stack){\n    return stack->posi == -1;\n}\n\nvoid push(Stack *stack, int value){\n    stack->items[++stack->posi] = value;\n}\n\nint pop(Stack *stack){\n    return stack->items[stack->posi--];\n}\n\nvoid show_stack(Stack *stack){\n    printf(\"{\");\n    for (int i = 0; i <= stack->posi; i++)\n        printf(\" %d\", stack->items[i]);\n    printf(\" }\\n\");\n}\n\nvoid set_value_seq(Stack *stack, int start, int end){\n    for (int i = start; i <= end; i++) push(stack, i);\n}\n\n\nvoid generate(Stack *stack, int max){\n    show_stack(stack);\n    int v = pop(stack), q;\n    set_value_seq(stack, v + 1, max);\n\n    if(!is_empty(stack))\n        generate(stack, max);\n}"
  },
  {
    "path": "Algorithms/Recursion/Combination_Sum/Combination_Sum.php",
    "content": "<?php\n\n/**\n * Calculate combinational sum\n * \n * @param array $elements\n * @param int $target Target number\n */\nfunction combinationalSum(array $elements, int $target)\n{\n    if(count($elements) !== count(array_unique($elements))) {\n        throw \"Element array is not distict.\";\n    }\n\n    if($target < 0) {\n        throw \"Target should be a posivite number.\";\n    }\n\n    $combinations = [];\n\n    for($i = 0; $i < count($elements); $i++) {\n        $combination = findCombination(array_slice($elements, $i), $target, []);\n        \n        if(count($combination) > 0) {\n            $combinations[] = $combination;\n        }\n    }\n\n    printCombinations($combinations);\n}\n\n/**\n * Find the combination for a specific target\n * \n * @param array $elements\n * @param int $target\n * @param array $combination possible combinations from previous iteration\n */\nfunction findCombination(array $elements, int $target, array $combination): array\n{\n    for($i = 0; $i < count($elements); $i++) {\n        $newTarget = $target - $elements[$i];\n\n        if($newTarget == 0) {\n            $combination[] = $elements[$i];\n            return $combination;\n        }\n\n        if($newTarget < 0) {\n            continue;\n        }\n\n        $combination[] = $elements[$i];\n        return findCombination(array_slice($elements, $i + 1), $newTarget, $combination);\n    }\n    return [];\n}\n\n/**\n * Print the combinations\n * \n * @param array $combinations\n */\nfunction printCombinations(array $combinations) \n{\n    for($i = 0; $i < count($combinations); $i++) {\n        for($j = 0; $j < count($combinations[$i]); $j++) {\n            echo $combinations[$i][$j] . \" \";\n        }\n        echo \"\\n\";\n    }\n}\n\n//Test\n$elements = [1, 5, 2, 8, 6, 4, 3, 10];\n$target = 10;\ncombinationalSum($elements, $target);\n\n//Result: 5 2 3\n//        2 8\n//        6 4\n//        10"
  },
  {
    "path": "Algorithms/Recursion/Combination_Sum/combination_sum.cpp",
    "content": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nvoid generatePermutation(vector<int> &arr, int target, int currSum, int currIndex, vector<vector<int>> &ans,\n                         vector<int> &currCandidates) {\n    if (currSum == target) {\n        ans.push_back(currCandidates);\n        return;\n    }\n    if (currSum > target) return;\n    for (int i = currIndex; i < arr.size(); i++) {\n        currCandidates.push_back(arr[i]);\n        currSum += arr[i];\n        generatePermutation(arr, target, currSum, i, ans, currCandidates);\n        currCandidates.pop_back();\n        currSum -= arr[i];\n    }\n}\n\nvector<vector<int>> combinationSum(vector<int> &candidates, int target) {\n    vector<vector<int>> ans;\n    vector<int> temp;\n    generatePermutation(candidates, target, 0, 0, ans, temp);\n    return ans;\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    int n, target;\n    cin >> n >> target;\n    vector<int> candidates(n, 0);\n    for (int i = 0; i < n; i++) {\n        cin >> candidates[i];\n    }\n    vector<vector<int>> solution = combinationSum(candidates, target);\n    for (auto &i : solution) {\n        for (int j : i) {\n            cout << j << \" \";\n        }\n        cout << \"\\n\";\n    }\n    return 0;\n}\n//Input\n4 7\n2 3 6 7\n//Output\n2 2 3\n7\n"
  },
  {
    "path": "Algorithms/Recursion/Factorial/Factorial.c",
    "content": "/**\n * Factorial\n * \n * @author Ytalo Ramon\n*/\n\n#include \"stdio.h\"\n#include \"stdlib.h\"\n\nint run(int value){\n    if(value <= 1) return 1;\n    return value * run(value - 1);\n}\n\nint main(int argc, char const *argv[]){\n\n    int number = 6;\n    printf(\"Factorial of %d: %d\\n\", number, run(number));\n    \n    return 0;\n}\n"
  },
  {
    "path": "Algorithms/Recursion/Factorial/Factorial.cs",
    "content": "using System;\n\nnamespace Demo {\n\n   class Factorial {\n\n      public int checkFact(int n) {\n         if (n == 1)\n         return 1;\n         else\n         return n * checkFact(n - 1);\n      }\n\n      static void Main(string[] args) {\n\n         int value = 9;\n         int ret;\n\n         Factorial fact = new Factorial();\n         ret = fact.checkFact(value);\n         Console.WriteLine(\"Value is : {0}\", ret );\n         Console.ReadLine();\n      }\n   }\n}\n"
  },
  {
    "path": "Algorithms/Recursion/Factorial/Factorial.go",
    "content": "package main\nimport \"fmt\"\n \nfunc fact(n int) int {\n   if n == 0 {\n      return 1\n   }\n   return n * fact(n-1)\n}\n \nfunc main() {\n   for i := 1; i <= 10; i++ {\n      fmt.Printf(\"%2d: %d \\n\", i, fact(i))\n   }\n}\n \n"
  },
  {
    "path": "Algorithms/Recursion/Factorial/Factorial_Algorithm.cpp",
    "content": "\n#include<iostream>  \n  \nusing namespace std; \n     \nint main()    // main function: the execution of the program starts from here\n{    \nint factorial(int);  // function prototype\nint f,value;    \ncout<<\"Enter any number: \";    \ncin>>value;    \nf=factorial(value);    \ncout<<\"Factorial of \"<<value<<\" is \"<<f<<endl;    \nreturn 0;    \n}    \nint factorial(int n)  // funtion definition  \n{    \nif(n<0)    \nreturn(-1); /*Wrong value*/      \nif(n==0)    \nreturn(1);  /*Terminating condition*/    \nelse    \n{    \nreturn(n*factorial(n-1));        \n}    \n}  \n\n#include <iostream>\n//  Factorial Recursive Algorithm C++ Implementation\nint n{ 0 }; // Initialize\nint answer{ 0 };\nint recursiveFactorial(int n) { // takes int n, to calculate n!\n\tif (n > 1) { // Since 1! = 1 and 0! = 1, and n must be positive;\n\t\tanswer = (n-1) * answer; // n! = (n * n-1) repeating until n < 1\n\t\tn -= 1; \n\t\trecursiveFactorial(n); // We keep calling back until\n\t}\n\telse if (n == 0) { // Special case if n = 0; 0! = 1;\n\t\tanswer = 1;\n\t\treturn answer;\n\t}\n\telse { // We finished our recursive calculation now we return our result.\n\t\treturn answer; // Side note: we don't need a special if-case for n = 1 since the returned answer already equals 1.\n\t}\n}\n\nint main() {\n\t\n\tstd::cout << \"Enter n for n!\" << \"\\n\" << \"n = \"; // Prompt user for n\n\tstd::cin >> n; // Get User Response\n\tanswer = n; \n\tstd::cout << \"n! = \" << recursiveFactorial(n); // print result of our calculation;\n}\n\n"
  },
  {
    "path": "Algorithms/Recursion/Factorial/Factorial_Algorithm.py",
    "content": "'''\nThe factorial of a positive integer n, detoned by n! is the product of all positive integers less than or equal to n.\nExamples: \n1) The factorial of 3 is 6, because: 3*2*1 = 6\n2) The factorial of 5 is 120, because: 5*4*3*2 = 120\n\nThe value of 0! is 1\n\nThe following method shows how recursion can be used to calculate the factorial of any given number\n\n'''\n\ndef factorial(n):\n    if(n == 1 or n == 0):\n        return 1\n    else:\n        return n * factorial(n-1)\n\n#The following code is used to test the code with an input from the user\nwhile True:\n    try:\n        user_input = int(input(\"Please enter the number to be computed: \"))\n        if(user_input < 0):\n            print(\"The number cannot be negative!\")\n            continue\n        else:\n            print(factorial(user_input))\n    except ValueError:\n        print(\"The number should be a integer!\")\n        continue\n    else:\n        break"
  },
  {
    "path": "Algorithms/Recursion/Factorial/factorial.js",
    "content": "function factorial(n) {\n    if (n<0) {\n        return(\"Negatives don't have factorial\")\n    }\n    else if (n==0 || n==1) {\n        return (1)\n    }\n    else {\n        while(n>1) {\n            return (n*factorial(n-1))\n        }\n    }\n}\nnumber = prompt(\"Enter number\")\nconsole.log(factorial(number))\n"
  },
  {
    "path": "Algorithms/Recursion/Factorial/factorial.py",
    "content": "def factorial(n):\n    if (n<0): \n        return (\"ERROR - Negatives can't have factorials !!\")\n    if (n==0 or n==1):\n        return 1\n    while (n>1):\n        return n*factorial(n-1)\n\nnumber = int(input(\"Enter number\"))\nprint (factorial(number))\n"
  },
  {
    "path": "Algorithms/Recursion/Josephus/Josephus.c",
    "content": "#include <stdio.h>\r\n#include <stdlib.h>\r\n\r\ntypedef struct person\r\n{\r\n    int position;\r\n    struct person *next;\r\n} person;\r\n\r\nint findWinner(int n, int k)\r\n{\r\n    int i, count;\r\n    person *p, *q, *r;\r\n\r\n    p = (person *)malloc(sizeof(person));\r\n    p->position = 1;\r\n    p->next = p;\r\n    q = p;\r\n\r\n    for (i = 2; i <= n; i++)\r\n    {\r\n        r = (person *)malloc(sizeof(person));\r\n        r->position = i;\r\n        r->next = p;\r\n        q->next = r;\r\n        q = r;\r\n    }\r\n\r\n    while (p->next != p)\r\n    {\r\n        q = p;\r\n        r = q;\r\n        for (count = 1; count < k; count++)\r\n        {\r\n            r = q;\r\n            q = q->next;\r\n        }\r\n        r->next = q->next;\r\n        p = r->next;\r\n        q->next = NULL;\r\n        free(q);\r\n        q = NULL;\r\n    }\r\n\r\n    return p->position;\r\n}\r\n\r\nint main()\r\n{\r\n    int n, k;\r\n    scanf(\"%d\", &n);\r\n    scanf(\"%d\", &k);\r\n    int w = findWinner(n, k);\r\n    printf(\"%d\", w);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Algorithms/Recursion/Josephus/Josephus.cs",
    "content": "using System;\n\nclass TEMP {\n\n\tstatic int josephus(int n, int k)\n\t{\n\t\tif (n == 1)\n\t\t\treturn 1;\n\t\telse\n\n\t\t\treturn (josephus(n - 1, k) + k - 1) % n + 1;\n\t}\n\n\n\tpublic static void Main()\n\t{\n\t\tint n ;\n\t\tint k ;\n        n= Convert.ToInt32(Console.ReadLine());\n        k= Convert.ToInt32(Console.ReadLine());\n\t\tConsole.WriteLine(\"The chosen \"\n                          + \"place is \" + josephus(n, k));\n\t}\n}\n"
  },
  {
    "path": "Algorithms/Recursion/Josephus/Josephus.java",
    "content": "import java.util.*;\n \npublic class Josephus {\n    public static int execute(int n, int k) {\n        int killIndex = 0;//stores index of person to be executed\n        ArrayList<Integer> prisoners = new ArrayList<Integer>(n);\n        for(int i = 0;i < n;i++){\n            prisoners.add(i);\n        }\n        System.out.println(\"Prisoners executed in order:\");\n        while(prisoners.size() > 1) {//until only one person remains alive\n            killIndex = (killIndex + k - 1) % prisoners.size();\n            System.out.print(prisoners.get(killIndex) + \" \");\n            prisoners.remove(killIndex);\n        }\n        System.out.println();\n        return prisoners.get(0);\n    }\n \n    public static void main(String[] args){\n        Scanner sc = new Scanner(System.in);\n        int n = sc.nextInt();\n        int k = sc.nextInt();\n        System.out.println(\"Survivor : \" + execute(n,k));\n    }\n}\n"
  },
  {
    "path": "Algorithms/Recursion/Josephus/josephus.cpp",
    "content": "#include <bits/stdc++.h>\nusing namespace std;\n\nint Josephus(int, int);\n\nint main()\n{\n\tint n, k;\n\tcin >> n >> k;\n\tcout << Josephus(n, k);\n\treturn 0;\n}\n\nint Josephus(int n, int k)\n{\n\tk--;\n\tint arr[n];\n\tfor (int i = 0; i < n; i++) {\n\t\tarr[i] = 1; // Makes all the 'n' people alive by\n\t\t\t\t\t// assigning them value = 1\n\t}\n\tint cnt = 0, cut = 0,\n\t\tnum = 1; // Cut = 0 gives the sword to 1st person.\n\twhile (\n\t\tcnt\n\t\t< (n - 1)) // Loop continues till n-1 person dies.\n\t{\n\t\twhile (num <= k) // Checks next (kth) alive persons.\n\t\t{\n\t\t\tcut++;\n\t\t\tcut = cut % n; // Checks and resolves overflow\n\t\t\t\t\t\t// of Index.\n\t\t\tif (arr[cut] == 1) {\n\t\t\t\tnum++; // Updates the number of persons\n\t\t\t\t\t// alive.\n\t\t\t}\n\t\t}\n\t\tnum = 1; // refreshes value to 1 for next use.\n\t\tarr[cut]\n\t\t\t= 0; // Kills the person at position of 'cut'\n\t\tcnt++; // Updates the no. of killed persons.\n\t\tcut++;\n\t\tcut = cut\n\t\t\t% n; // Checks and resolves overflow of Index.\n\t\twhile (arr[cut]\n\t\t\t== 0) // Checks the next alive person the\n\t\t\t\t\t// sword is to be given.\n\t\t{\n\t\t\tcut++;\n\t\t\tcut = cut % n; // Checks and resolves overflow\n\t\t\t\t\t\t// of Index.\n\t\t}\n\t}\n\treturn cut + 1; // Output is the position of the last\n\t\t\t\t\t// man alive(Index + 1);\n}\n\n/********************THIS CODE IS PRESENTED BY VIKASH PATEL ***************************/\n"
  },
  {
    "path": "Algorithms/Recursion/Josephus/josephus.kt",
    "content": "fun main(args: Array<String>){\n    //Taking n, k as input values\n    val (n, k) = readLine()!!.split(' ').map{it.toInt()}\n    \n    //array to store status dead/alive of a person\n    //initially all persons are alive so we set the staus to false, meaning all are       //not dead\n    val is_dead = BooleanArray(n) \n\n    var index = 0 //index of a person in the circle\n\n    var died_count = 0 //count of died people so far\n    \n    while(true){\n\n        //if only one person is alive, indeed that's our answer so break\n        if(died_count == n-1)\n            break\n\n        //next we move until we reach the kth alive person from the current index\n        var count = k-1//to keep track of alive people\n\n        while(count > 0){\n            index = (index + 1)%n // to move around the circle so that after the last index we move to the first index\n            if(!is_dead[index])count--\n        }\n\n        //kth person would die\n        is_dead[index] = true\n\n        //count of person died so far would be incremented\n        died_count++\n\n        //now start from the next alive person\n        while(is_dead[index])index = (index + 1)%n\n    }\n    \n    //after the loop the only person alive is at the position of the 'index'.\n    println(index + 1)//index + 1 to make it 1 based indexing\n}"
  },
  {
    "path": "Algorithms/Recursion/Keypadcodes.cpp",
    "content": "#include <bits/stdc++.h>\n    using namespace std;\n\nint sub(string s,string output[],string s1[])\n{\n    if(s.length()==1)\n    {\n        string s2=s1[s[0]-48];\n        for(int i=0;i<s2.length();i++)\n        {\n            output[i]=s2[i];\n        }\n        return s2.length();\n    }\n    string smallstr=s.substr(1);\n    int smallsize=sub(smallstr, output,s1);\n    string s3=s1[s[0]-48];\n    for(int i=0;i<s3.length();i++)\n    {\n        for(int j=0;j<smallsize;j++)\n        {\n          output[j+smallsize+i]=output[j];\n        }\n    }\n    int x=s3.length()*smallsize,y=0,z=0;\n    for(int i=0;i<x;i++)\n    {\n        output[i]=s3[z]+output[i];\n        y++;\n        if(y==smallsize)\n        {\n            z++;\n            y=0;\n        }\n    }\n\n    return s3.length()*smallsize;\n}\nint main() {\n    string s;\n    cin>>s;\n    string* output= new string[10000000];\n    string s1[10];\n    s1[0]=\".;\";\n    s1[1]=\"abc\";\n    s1[2]=\"def\";\n    s1[3]=\"ghi\";\n    s1[4]=\"jkl\";\n    s1[5]=\"mno\";\n    s1[6]=\"pqrs\";\n    s1[7]=\"tu\";\n    s1[8]=\"vwx\";\n    s1[9]=\"yz\";\n\n    int n=sub(s,output,s1);\n    cout<<\"[\";\n    for(int i=0;i<n;i++)\n    {\n        cout<<output[i];\n        if(i!=n-1)\n        {\n            cout<<\",\";\n        }\n    }\n    cout<<\"]\";\n}\n"
  },
  {
    "path": "Algorithms/Recursion/Permutation/Permutation.cs",
    "content": "﻿using System;\nusing System.Collections.Generic;\nusing System.Text;\n\nnamespace LeetCode46\n{\n    class Permutations\n    {\n        public static List<string> SinglePermutations(string s)\n        {\n\t\t\t// Example: s = \"abc\"\n\t\t\t\n\t\t\t// Set is used to avoid duplicates\n            var hash = new SortedSet<string>();\n            var stack = \"\";\n            int len = s.Length;\n            GetPermutations(s, hash, stack, len);\n            return new List<string>(hash);\n\t\t\t\n\t\t\t// returned value is [\"abc\", \"acb\", \"bac\", \"bca\", \"cab\", \"cba\"] \n        }\n\n        private static void GetPermutations(string item, SortedSet<string> hash, string stack, int len)\n        {\n\t\t\t// Checks length of stack if equal to that of item\n            if (stack.Length == len)\n            {\n                hash.Add(stack);\n            }\n            else\n            {\n\t\t\t\t// lops through the \n                for (var i = 0; i < item.Length; i++)\n                {\n\t\t\t\t\t// Adds an item to the stack\n                    stack += item[i];\n\t\t\t\t\t// Populates available combinations and permutation\n\t\t\t\t\t// with the elements in stack\n                    GetPermutations(item.Remove(i, 1), hash, stack, len);\n                    // Removes the last item in stack\n\t\t\t\t\tstack = stack.Remove(stack.Length - 1, 1);\n                }\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "Algorithms/Recursion/Permutation/Permutation.js",
    "content": "function getPermutations(input) {\n    // Input should be a string.\n    if (!input || typeof input !== \"string\") {\n        return \"Input must be a string.\"\n    }\n\n    // No permutation.\n    if (input.length < 2) {\n        return [input];\n    }\n    var output = [];\n    var counter = 0;\n    for (counter = 0; counter < input.length; counter++) {\n        var computeChar = input[counter];\n        // No character repetitions allowed.\n        if (input.indexOf(computeChar) != counter)\n            continue;\n        var characterYetToBeComputed = input.slice(0, counter) + input.slice(counter + 1, input.length);\n        // For...of is supported in ECMAScript 5 and higher.\n        for (var permutation of getPermutations(characterYetToBeComputed)) {\n            output.push(computeChar + permutation);\n        }\n    }\n    return output;\n}\n"
  },
  {
    "path": "Algorithms/Recursion/Permutation/Permutation.ts",
    "content": "class Permutation {\n    getPermutations(input: string): string | string[] {\n        // No permutation.\n        if (input.length < 2) {\n            return input;\n        }\n\n        const output: string[] = [];\n        let counter: number = 0;\n        for (counter = 0; counter < input.length; counter++) {\n            const computeChar = input[counter];\n\n            // No character repetitions allowed.\n            if (input.indexOf(computeChar) != counter)\n                continue;\n\n            const characterYetToBeComputed = input.slice(0, counter) + input.slice(counter + 1, input.length);\n\n            // For...of is supported in ECMAScript 5 and higher.\n            for (const permutation of this.getPermutations(characterYetToBeComputed)) {\n                output.push(computeChar + permutation);\n            }\n        }\n        return output;\n    }\n}\n"
  },
  {
    "path": "Algorithms/Recursion/Permutation/Permutations_Recursion.cpp",
    "content": "// C++ program to print all \n// permutations with duplicates allowed \n\n#include <bits/stdc++.h> \nusing namespace std; \n\nvoid permute(string a, int l, int r) \n{ \n\tif (l == r) \n\t\tcout<<a<<endl; \n\telse\n\t{ \n\t\tfor (int i = l; i <= r; i++) \n\t\t{ \n\t\t\tswap(a[l], a[i]); \n\t\t\tpermute(a, l+1, r); \n\t\t\tswap(a[l], a[i]); \n\t\t} \n\t} \n} \n\nint main() \n{ \n\tstring str = \"ABC\"; \n\tint n = str.size(); \n\tpermute(str, 0, n-1); \n\treturn 0; \n} \n"
  },
  {
    "path": "Algorithms/Recursion/Permutation/Permutations_Recursion.py",
    "content": "def convert(a):\n    new_list = []\n    for i in a:\n        demo = \"\".join(i)\n        new_list.append(demo)\n\n    return new_list\n\ndef permutation(s):\n    if len(s) == 1:\n        return [s]\n\n    perm_list = [] # resulting list\n    for a in s:\n        remaining_elements = [x for x in s if x != a]\n        z = permutation(remaining_elements) # permutations of sublist using recursion\n\n        for t in z:\n            perm_list.append([a] + t)\n\n    return perm_list\n\n\nsample = input()\nprint(convert(permutation(sample)))\n"
  },
  {
    "path": "Algorithms/Recursion/README.md",
    "content": "# This folder is empty.\n"
  },
  {
    "path": "Algorithms/Searching/A-Star Search/A_Star.ipynb",
    "content": "{\n \"cells\": [\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 1,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"name\": \"stdout\",\n     \"output_type\": \"stream\",\n     \"text\": [\n      \"[[0, -1, -1, -1, -1, -1], [1, 2, 3, 4, 5, -1], [-1, -1, -1, -1, 6, 7], [-1, -1, -1, -1, -1, 8], [-1, -1, -1, -1, -1, 9]]\\n\"\n     ]\n    }\n   ],\n   \"source\": [\n    \"import numpy as np\\n\",\n    \"\\n\",\n    \"class Node:\\n\",\n    \"    \\\"\\\"\\\"\\n\",\n    \"        A node class for A* Pathfinding\\n\",\n    \"        parent is parent of the current Node\\n\",\n    \"        position is current position of the Node in the maze\\n\",\n    \"        g is cost from start to current Node\\n\",\n    \"        h is heuristic based estimated cost for current Node to end Node\\n\",\n    \"        f is total cost of present node i.e. :  f = g + h\\n\",\n    \"    \\\"\\\"\\\"\\n\",\n    \"\\n\",\n    \"    def __init__(self, parent=None, position=None):\\n\",\n    \"        self.parent = parent\\n\",\n    \"        self.position = position\\n\",\n    \"\\n\",\n    \"        self.g = 0\\n\",\n    \"        self.h = 0\\n\",\n    \"        self.f = 0\\n\",\n    \"    def __eq__(self, other):\\n\",\n    \"        return self.position == other.position\\n\",\n    \"\\n\",\n    \"#This function return the path of the search\\n\",\n    \"def return_path(current_node,maze):\\n\",\n    \"    path = []\\n\",\n    \"    no_rows, no_columns = np.shape(maze)\\n\",\n    \"    # here we create the initialized result maze with -1 in every position\\n\",\n    \"    result = [[-1 for i in range(no_columns)] for j in range(no_rows)]\\n\",\n    \"    current = current_node\\n\",\n    \"    while current is not None:\\n\",\n    \"        path.append(current.position)\\n\",\n    \"        current = current.parent\\n\",\n    \"    # Return reversed path as we need to show from start to end path\\n\",\n    \"    path = path[::-1]\\n\",\n    \"    start_value = 0\\n\",\n    \"    # we update the path of start to end found by A-star serch with every step incremented by 1\\n\",\n    \"    for i in range(len(path)):\\n\",\n    \"        result[path[i][0]][path[i][1]] = start_value\\n\",\n    \"        start_value += 1\\n\",\n    \"    return result\\n\",\n    \"\\n\",\n    \"\\n\",\n    \"def search(maze, cost, start, end):\\n\",\n    \"    \\\"\\\"\\\"\\n\",\n    \"        Returns a list of tuples as a path from the given start to the given end in the given maze\\n\",\n    \"        :param maze:\\n\",\n    \"        :param cost\\n\",\n    \"        :param start:\\n\",\n    \"        :param end:\\n\",\n    \"        :return:\\n\",\n    \"    \\\"\\\"\\\"\\n\",\n    \"\\n\",\n    \"    # Create start and end node with initized values for g, h and f\\n\",\n    \"    start_node = Node(None, tuple(start))\\n\",\n    \"    start_node.g = start_node.h = start_node.f = 0\\n\",\n    \"    end_node = Node(None, tuple(end))\\n\",\n    \"    end_node.g = end_node.h = end_node.f = 0\\n\",\n    \"\\n\",\n    \"    # Initialize both yet_to_visit and visited list\\n\",\n    \"    # in this list we will put all node that are yet_to_visit for exploration. \\n\",\n    \"    # From here we will find the lowest cost node to expand next\\n\",\n    \"    yet_to_visit_list = []  \\n\",\n    \"    # in this list we will put all node those already explored so that we don't explore it again\\n\",\n    \"    visited_list = [] \\n\",\n    \"    \\n\",\n    \"    # Add the start node\\n\",\n    \"    yet_to_visit_list.append(start_node)\\n\",\n    \"    \\n\",\n    \"    # Adding a stop condition. This is to avoid any infinite loop and stop \\n\",\n    \"    # execution after some reasonable number of steps\\n\",\n    \"    outer_iterations = 0\\n\",\n    \"    max_iterations = (len(maze) // 2) ** 10\\n\",\n    \"\\n\",\n    \"    # what squares do we search . serarch movement is left-right-top-bottom \\n\",\n    \"    #(4 movements) from every positon\\n\",\n    \"\\n\",\n    \"    move  =  [[-1, 0 ], # go up\\n\",\n    \"              [ 0, -1], # go left\\n\",\n    \"              [ 1, 0 ], # go down\\n\",\n    \"              [ 0, 1 ]] # go right\\n\",\n    \"\\n\",\n    \"\\n\",\n    \"    \\\"\\\"\\\"\\n\",\n    \"        1) We first get the current node by comparing all f cost and selecting the lowest cost node for further expansion\\n\",\n    \"        2) Check max iteration reached or not . Set a message and stop execution\\n\",\n    \"        3) Remove the selected node from yet_to_visit list and add this node to visited list\\n\",\n    \"        4) Perofmr Goal test and return the path else perform below steps\\n\",\n    \"        5) For selected node find out all children (use move to find children)\\n\",\n    \"            a) get the current postion for the selected node (this becomes parent node for the children)\\n\",\n    \"            b) check if a valid position exist (boundary will make few nodes invalid)\\n\",\n    \"            c) if any node is a wall then ignore that\\n\",\n    \"            d) add to valid children node list for the selected parent\\n\",\n    \"            \\n\",\n    \"            For all the children node\\n\",\n    \"                a) if child in visited list then ignore it and try next node\\n\",\n    \"                b) calculate child node g, h and f values\\n\",\n    \"                c) if child in yet_to_visit list then ignore it\\n\",\n    \"                d) else move the child to yet_to_visit list\\n\",\n    \"    \\\"\\\"\\\"\\n\",\n    \"    #find maze has got how many rows and columns \\n\",\n    \"    no_rows, no_columns = np.shape(maze)\\n\",\n    \"    \\n\",\n    \"    # Loop until you find the end\\n\",\n    \"    \\n\",\n    \"    while len(yet_to_visit_list) > 0:\\n\",\n    \"        \\n\",\n    \"        # Every time any node is referred from yet_to_visit list, counter of limit operation incremented\\n\",\n    \"        outer_iterations += 1    \\n\",\n    \"\\n\",\n    \"        \\n\",\n    \"        # Get the current node\\n\",\n    \"        current_node = yet_to_visit_list[0]\\n\",\n    \"        current_index = 0\\n\",\n    \"        for index, item in enumerate(yet_to_visit_list):\\n\",\n    \"            if item.f < current_node.f:\\n\",\n    \"                current_node = item\\n\",\n    \"                current_index = index\\n\",\n    \"                \\n\",\n    \"        # if we hit this point return the path such as it may be no solution or \\n\",\n    \"        # computation cost is too high\\n\",\n    \"        if outer_iterations > max_iterations:\\n\",\n    \"            print (\\\"giving up on pathfinding too many iterations\\\")\\n\",\n    \"            return return_path(current_node,maze)\\n\",\n    \"\\n\",\n    \"        # Pop current node out off yet_to_visit list, add to visited list\\n\",\n    \"        yet_to_visit_list.pop(current_index)\\n\",\n    \"        visited_list.append(current_node)\\n\",\n    \"\\n\",\n    \"        # test if goal is reached or not, if yes then return the path\\n\",\n    \"        if current_node == end_node:\\n\",\n    \"            return return_path(current_node,maze)\\n\",\n    \"\\n\",\n    \"        # Generate children from all adjacent squares\\n\",\n    \"        children = []\\n\",\n    \"\\n\",\n    \"        for new_position in move: \\n\",\n    \"\\n\",\n    \"            # Get node position\\n\",\n    \"            node_position = (current_node.position[0] + new_position[0], current_node.position[1] + new_position[1])\\n\",\n    \"\\n\",\n    \"            # Make sure within range (check if within maze boundary)\\n\",\n    \"            if (node_position[0] > (no_rows - 1) or \\n\",\n    \"                node_position[0] < 0 or \\n\",\n    \"                node_position[1] > (no_columns -1) or \\n\",\n    \"                node_position[1] < 0):\\n\",\n    \"                continue\\n\",\n    \"\\n\",\n    \"            # Make sure walkable terrain\\n\",\n    \"            if maze[node_position[0]][node_position[1]] != 0:\\n\",\n    \"                continue\\n\",\n    \"\\n\",\n    \"            # Create new node\\n\",\n    \"            new_node = Node(current_node, node_position)\\n\",\n    \"\\n\",\n    \"            # Append\\n\",\n    \"            children.append(new_node)\\n\",\n    \"\\n\",\n    \"        # Loop through children\\n\",\n    \"        for child in children:\\n\",\n    \"            \\n\",\n    \"            # Child is on the visited list (search entire visited list)\\n\",\n    \"            if len([visited_child for visited_child in visited_list if visited_child == child]) > 0:\\n\",\n    \"                continue\\n\",\n    \"\\n\",\n    \"            # Create the f, g, and h values\\n\",\n    \"            child.g = current_node.g + cost\\n\",\n    \"            ## Heuristic costs calculated here, this is using eucledian distance\\n\",\n    \"            child.h = (((child.position[0] - end_node.position[0]) ** 2) + \\n\",\n    \"                       ((child.position[1] - end_node.position[1]) ** 2)) \\n\",\n    \"\\n\",\n    \"            child.f = child.g + child.h\\n\",\n    \"\\n\",\n    \"            # Child is already in the yet_to_visit list and g cost is already lower\\n\",\n    \"            if len([i for i in yet_to_visit_list if child == i and child.g > i.g]) > 0:\\n\",\n    \"                continue\\n\",\n    \"\\n\",\n    \"            # Add the child to the yet_to_visit list\\n\",\n    \"            yet_to_visit_list.append(child)\\n\",\n    \"\\n\",\n    \"\\n\",\n    \"if __name__ == '__main__':\\n\",\n    \"\\n\",\n    \"    maze = [[0, 1, 0, 0, 0, 0],\\n\",\n    \"            [0, 0, 0, 0, 0, 0],\\n\",\n    \"            [0, 1, 0, 1, 0, 0],\\n\",\n    \"            [0, 1, 0, 0, 1, 0],\\n\",\n    \"            [0, 0, 0, 0, 1, 0]]\\n\",\n    \"    \\n\",\n    \"    start = [0, 0] # starting position\\n\",\n    \"    end = [4,5] # ending position\\n\",\n    \"    cost = 1 # cost per movement\\n\",\n    \"\\n\",\n    \"    path = search(maze,cost, start, end)\\n\",\n    \"    print(path)\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"## Final result path \"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 2,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"name\": \"stdout\",\n     \"output_type\": \"stream\",\n     \"text\": [\n      \"  0 -1 -1 -1 -1 -1\\n\",\n      \"  1  2  3  4  5 -1\\n\",\n      \" -1 -1 -1 -1  6  7\\n\",\n      \" -1 -1 -1 -1 -1  8\\n\",\n      \" -1 -1 -1 -1 -1  9\\n\"\n     ]\n    }\n   ],\n   \"source\": [\n    \"print('\\\\n'.join([''.join([\\\"{:\\\" \\\">3d}\\\".format(item) for item in row]) \\n\",\n    \"      for row in path]))\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": []\n  }\n ],\n \"metadata\": {\n  \"kernelspec\": {\n   \"display_name\": \"Python 3\",\n   \"language\": \"python\",\n   \"name\": \"python3\"\n  },\n  \"language_info\": {\n   \"codemirror_mode\": {\n    \"name\": \"ipython\",\n    \"version\": 3\n   },\n   \"file_extension\": \".py\",\n   \"mimetype\": \"text/x-python\",\n   \"name\": \"python\",\n   \"nbconvert_exporter\": \"python\",\n   \"pygments_lexer\": \"ipython3\",\n   \"version\": \"3.6.8\"\n  }\n },\n \"nbformat\": 4,\n \"nbformat_minor\": 1\n}\n"
  },
  {
    "path": "Algorithms/Searching/A-Star Search/README.md",
    "content": "# A* Search Algorithm\n\nThe  most widely  known  form  of  best-first  search  is  called  A*  Search.\n\nFew terminologies:\n - Node (also called State) — All potential position or stops with a unique identification\n - Transition — The act of moving between states or nodes.\n - Starting Node — Whereto start searching\n - Goal Node — The target to stop searching.\n - Search Space — A collection of nodes, like all board positions of a board game\n - Cost — Numerical value (say distance, time, or financial expense) for the path from a node to another node.\n - g(n) — this represents the exact cost of the path from the starting node to any node n\n - h(n) — this represents the heuristic estimated cost from node n to the goal node.\n - f(n) — lowest cost in the neighboring node n\n\nIt  evaluates  nodes  by  combining  g(n),  the  cost  to  reach  the  node,  and  h(n),  the  cost  to  get  from  the  node  to  the  goal:\n\nF(n)  =  g(n)  +  h(n)\n\nSince  g(n)  gives  the  path  cost  from  the  start  node  to  node  n,  and  h(n)  is  the  estimated  cost  of  the  cheapest  path  from  n  to  the  goal,  we  have:\n\nF(n)=  estimated  cost  of  the  cheapest  solution  through  n.\n\nThus,  if  we  are  trying  to  find  the  cheapest  solution,  a  reasonable  thing  to  try  first  is  the  node  with  the  lowest  of  f(n).\n\nIt  turns  out  that  this  strategy  is  more  reasonable:  provided  that  the  heuristic  function  h(n)  satisfies  certain  conditions,  A*  search  is  both  complete  and  optimal.  The  algorithm  is  identical  to  Uniform-cost-search  exceptthat  A*  uses  g(h)  and  h(n)  instead  of  g(h).\n\nThe  way  of  how  the  A*  Search  works  is  illustrated  in the figure below. Each  time,  the  node  having  the  lowest  f(n)  value  is  the  node  expanded.  The  targets  nodes  will  be  expanded  until  reaching  the  goal  destination,  which  is  Bucharest.\n\n## How it works \n![A Star Search](algo.png)\n\n## Demo\n![A Star Search](screenshot.png)\n"
  },
  {
    "path": "Algorithms/Searching/Binary-Search/Binary_Search_CubicRoot.cpp",
    "content": "#include <iostream> \n#include <cmath>\n#define EPS 1e-8\nusing namespace std;\n\ndouble a, b, c, d;\n\ndouble f(double x){\n    return a*x*x*x + b*x*x + c*x + d;\n}\n\ndouble binsearch(double l, double r)\n{\n    double x = (l + r)/2;\n    \n    \n    if(fabs(f(x)) < EPS) return x;\n\n    if(f(x) > EPS) return binsearch(l, x);\n    else return binsearch(x, r);\n    \n}\n\nint main(){\n\n    cin >> a >> b >> c >> d;\n    \n    if(a < 0){\n        a *= -1;\n        b *= -1;\n        c *= -1;\n        d *= -1;\n    }\n\n    int r = 1;\n    while(f(r) * f(-r) >= 0){\n        r *= 2;\n    }\n    \n    printf(\"%.8f\\n\", binsearch(-r, r));\n    return 0;\n}\n"
  },
  {
    "path": "Algorithms/Searching/Binary-Search/Binary_search_javascript.js",
    "content": "<script> \nlet recursiveFunction = function (arr, x, start, end) { \n\t\n\t// Base Condition \n\tif (start > end) return false; \n\n\t// Middle index \n\tlet mid=Math.floor((start + end)/2); \n\n\t// Compare mid with given key x \n\tif (arr[mid]===x) return true; \n\t\t\n\t// search left half of mid \n\tif(arr[mid] > x) \n\t\treturn recursiveFunction(arr, x, start, mid-1); \n\telse\n\t\t// search in the right half of mid \n\t\treturn recursiveFunction(arr, x, mid+1, end); \n} \n \nlet arr = [1, 3, 5, 7, 8, 9]; \nlet x = 5; \n\nif (recursiveFunction(arr, x, 0, arr.length-1)) \n\tdocument.write(\"Element found!<br>\"); \nelse document.write(\"Element not found!<br>\"); \n\nx = 6; \n\nif (recursiveFunction(arr, x, 0, arr.length-1)) \n\tdocument.write(\"Element found!<br>\"); \nelse document.write(\"Element not found!<br>\"); \n</script>\t\t\t\t\t\t\t\t\t \n"
  },
  {
    "path": "Algorithms/Searching/Binary-Search/Koko_Eating_Bananas/KEB.java",
    "content": "//Code contributed by Aditya Prakash(@PrakashAditya)\n\nimport java.io.*;\nimport java.util.*;\npublic class KEB\n{\n        public static boolean check(int p[],int h,int K)    //check if bananas can be eaten in 'h' hrs with speed K\n        {\n                int t=0;\n                for(int i=0;i<p.length;i++)\n                {\n                        t+=(p[i]-1)/K+1;\n                }\n                boolean val=t<=h?true:false;\n                return val;\n        }\n        public static void main(String args[])throws IOException\n        {\n                Scanner sc=new Scanner(System.in);\n                System.out.println(\"Enter the no. of piles of bananas\");\n                int n=sc.nextInt();\n                int a[]=new int[n];\n                for(int i=0;i<n;i++)\n                        a[i]=sc.nextInt();\n                \n                System.out.println(\"Enter H\");\n                int H=sc.nextInt();\n                \n                //We use Binary search Technique\n                int low=1,high=n;\n                while(low<high)\n                {\n                        int mid=(low+high)/2;\n                        if(check(a,H,mid)==false)\n                        {\n                                low=mid+1;\n                        }\n                        else\n                                high=mid;\n                }\n                \n                System.out.println(low);\n         }\n}\n\n                \n"
  },
  {
    "path": "Algorithms/Searching/Binary-Search/Koko_Eating_Bananas/Koko_Eating_Bananas.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <cmath>\n\nusing namespace std;\nint computeMinHours(vector<int> &piles, int speed)\n{\n    int n = piles.size();\n    int res = 0;\n    int i = 0;\n    for (i = 0; i < n; i++)\n        res += ceil((float)piles[i] / speed);\n    return res;\n}\nint computeMax(vector<int> &piles)\n{\n    int n = piles.size();\n    int maxval = INT_MIN;\n    for (int i = 0; i < n; i++)\n        maxval = max(maxval, piles[i]);\n    return maxval;\n}\nint minEatingSpeed(vector<int> &piles, int H)\n{\n    int n = piles.size();\n    if (n == 1)\n    {\n        double b = (double)piles[0];\n        int temp = ceil(b / H);\n        return temp;\n    }\n    int lo = 1;\n    int hi = computeMax(piles);\n    int mid;\n    int intval;\n    while (lo < hi)\n    {\n        mid = lo + (hi - lo) / 2;\n        intval = computeMinHours(piles, mid);\n        if (intval <= H)\n        {\n            hi = mid;\n        }\n        else\n        {\n            lo = mid + 1;\n        }\n    }\n    return lo;\n}\n\nint main()\n{\n    vector<int> piles;\n    int H;\n    cout << \"Enter contents of each pile (enter any negative number to stop)\\n\";\n    while (true)\n    {\n        int x;\n        cout << \"Enter content of pile: \";\n        cin >> x;\n        if (x < 0)\n            break;\n        piles.push_back(x);\n    }\n    cout << \"Enter number of hours for guards to return \\n\";\n    cin >> H;\n    int res = minEatingSpeed(piles, H);\n    cout << \"The minimum eating speed should be \" << res << \" bananas per hour\";\n    return 0;\n}"
  },
  {
    "path": "Algorithms/Searching/Binary-Search/Koko_Eating_Bananas/Koko_Eating_Bananas.py",
    "content": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed Oct 14 23:34:35 2020\r\n\r\n@author: Abhinav Tiwari\r\n\r\nSolution to question as per QUESTION.md's\r\n \r\n    Koko eating bananas\r\n    finds eating rate K bananas/hr \r\n    So, that she can finish the pile \r\n    before the guards arrive.\r\n\"\"\"\r\nimport math\r\n\r\n\r\ndef min_rate(pile,hrs):\r\n    res = 0\r\n    for i in range(len(pile)):\r\n        res += math.ceil(pile[i]/hrs)\r\n    return res    \r\n        \r\ndef banana_per_hour(pile,hrs):\r\n    \r\n    if len(pile)==1:\r\n        return math.ceil(pile[0]/hrs)\r\n    \r\n    lo = 1\r\n    hi = max(pile)\r\n    \r\n    value = -986765\r\n    while(lo<hi):\r\n        mid = lo + (hi-lo)//2\r\n        value = min_rate(pile, mid)\r\n        if value<=hrs:\r\n            hi = mid\r\n        else:\r\n            lo = mid + 1\r\n    \r\n    return lo\r\n       \r\n    \r\n    \r\ndef main():\r\n    bananas = []\r\n    print(\"Enter the bananas in pile one by one\",end = \"\\n\")\r\n    print(\"Enter any negative no to quit\",end ='\\n')\r\n    n = int(input())\r\n    while(n>0):\r\n        bananas.append(n)\r\n        n = int(input())\r\n    H = int(input(\"Enter hours till the guards arrive:    \")) \r\n    K = banana_per_hour(bananas, H)\r\n    print(\"For her to eat all the bananas till the guards arrive, she must eat @ \",K,\"bananas per hour\")\r\nmain()"
  },
  {
    "path": "Algorithms/Searching/Binary-Search/Koko_Eating_Bananas/QUESTION.md",
    "content": "### Koko Eating Bananas\n\nKoko loves to eat bananas.  There are N piles of bananas, the i-th pile has piles[i] bananas.  The guards have gone and will come back in H hours.\n\nKoko can decide her bananas-per-hour eating speed of K.  Each hour, she chooses some pile of bananas, and eats K bananas from that pile.  If the pile has less than K bananas, she eats all of them instead, and won't eat any more bananas during this hour.\n\nKoko likes to eat slowly, but still wants to finish eating all the bananas before the guards come back.\n\nReturn the minimum integer K such that she can eat all the bananas within H hours."
  },
  {
    "path": "Algorithms/Searching/Binary-Search/README.md",
    "content": "## This folder is empty.\n"
  },
  {
    "path": "Algorithms/Searching/Binary-Search/Rotated-Sorted-Array-Search.cs",
    "content": "// C# program to find a pair with a given \n// sum in a sorted and rotated array \n// Written By - Ayush Sharma (belphegor-s) \nusing System; \n\nclass PairInSortedRotated \n{ \n\t// This function returns true if arr[0..n-1] \n\t// has a pair with sum equals to x. \n\tstatic bool pairInSortedRotated(int []arr, \n\t\t\t\t\t\t\t\t\tint n, int x) \n\t{ \n\t\t// Find the pivot element \n\t\tint i; \n\t\tfor (i = 0; i < n - 1; i++) \n\t\t\tif (arr[i] > arr[i + 1]) \n\t\t\t\tbreak; \n\t\t\t\t\n\t\t// l is now index of smallest element\t\t \n\t\tint l = (i + 1) % n; \n\t\t\n\t\t// r is now index of largest element\t\t\t\t \n\t\tint r = i; \n\t\n\t\t// Keep moving either l or r till they meet \n\t\twhile (l != r) \n\t\t{ \n\t\t\t// If we find a pair with sum x, we \n\t\t\t// return true \n\t\t\tif (arr[l] + arr[r] == x) \n\t\t\t\treturn true; \n\t\n\t\t\t// If current pair sum is less, \n\t\t\t// move to the higher sum \n\t\t\tif (arr[l] + arr[r] < x) \n\t\t\t\tl = (l + 1) % n; \n\t\t\t\n\t\t\t// Move to the lower sum side\t \n\t\t\telse\n\t\t\t\tr = (n + r - 1) % n; \n\t\t} \n\t\treturn false; \n\t} \n\n\t// Driver Code \n\tpublic static void Main () \n\t{ \n\t\tint []arr = {11, 15, 6, 8, 9, 10}; \n\t\tint sum = 16; \n\t\tint n = arr.Length; \n\t\n\t\tif (pairInSortedRotated(arr, n, sum)) \n\t\t\tConsole.WriteLine(\"Array has two elements\" + \n\t\t\t\t\t\t\t\t\t\" with sum 16\"); \n\t\telse\n\t\tConsole.WriteLine(\"Array doesn't have two\" + \n\t\t\t\t\t\t\t\" elements with sum 16 \"); \n\t} \n} \n"
  },
  {
    "path": "Algorithms/Searching/Binary-Search/Rotated-Sorted-Array-Search.js",
    "content": "function rotatedSearch(arr, target) {\n    let left = 0 ,right = arr.length-1;\n    // First part : Find the pivot that is point from array is rotated\n    // For example pivot(index) in 5 6 7 1 2 is 2\n    while(left < right){\n        let mid = left + Math.floor((right-left)/2) ;\n        if(arr[right] < arr[mid]){\n            left = mid+1;\n        }else{\n            right = mid;\n        }\n    }   \n\n    let pivot = left;\n    \n    // reassign left and right for next binary search\n    left = 0 ; \n    right = arr.length-1;\n\n    // select the part of array where the target lie.\n    // we have two sorted part of array divided by pivot\n    if(target <= arr[right] && arr[pivot]<=target ){\n        left = pivot;\n    }else{\n        right = pivot;\n    }\n\n    // binary search on the part containing target\n    while(left<=right){\n        let mid = left + Math.floor((right-left)/2);\n        if(arr[mid] == target){\n            return mid;\n        }\n        if(arr[mid]<target){\n            left = mid+1;\n        }\n        else{\n            right = mid-1;\n        }\n    }\n    return -1;\n};\n\n// testing\nvar testArray = [] ;\nvar size = prompt('Enter the size of the array\\n') ;\n\nfor(var i = 0 ; i < size ; i++){\n\ttestArray[i] = prompt('Enter next element ');\n}\nvar target = prompt('Enter target number to be searched\\n');\n\nconsole.log(rotatedSearch(testArray,target));\n// edge cases\n// console.log(rotatedSearch([8,7,6,5,2,1],6));\n// console.log(rotatedSearch([1,2,3,4,5,6],6));\n"
  },
  {
    "path": "Algorithms/Searching/Binary-Search/Rotated-Sorted-Array-Search.py",
    "content": " def pivotedBinarySearch(arr, n, key):\n\n    pivot = findPivot(arr, 0, n-1);\n\n    # If we didn't find a pivot,\n    # then array is not rotated at all\n    if pivot == -1:\n        return binarySearch(arr, 0, n-1, key);\n\n    # If we found a pivot, then first\n    # compare with pivot and then\n    # search in two subarrays around pivot\n    if arr[pivot] == key:\n        return pivot\n    if arr[0] <= key:\n        return binarySearch(arr, 0, pivot-1, key);\n    return binarySearch(arr, pivot + 1, n-1, key);\n\n\n# Function to get pivot. For array\n# 3, 4, 5, 6, 1, 2 it returns 3\n# (index of 6)\ndef findPivot(arr, low, high):\n\n    # base cases\n    if high < low:\n        return -1\n    if high == low:\n        return low\n\n    # low + (high - low)/2;\n    mid = int((low + high)/2)\n\n    if mid < high and arr[mid] > arr[mid + 1]:\n        return mid\n    if mid > low and arr[mid] < arr[mid - 1]:\n        return (mid-1)\n    if arr[low] >= arr[mid]:\n        return findPivot(arr, low, mid-1)\n    return findPivot(arr, mid + 1, high)\n\ndef binarySearch(arr, low, high, key):\n\n    if high < low:\n        return -1\n\n    # low + (high - low)/2;\n    mid = int((low + high)/2)\n\n    if key == arr[mid]:\n        return mid\n    if key > arr[mid]:\n        return binarySearch(arr, (mid + 1), high,\n                                            key);\n    return binarySearch(arr, low, (mid -1), key);\n\narr1 = []\nprint(\"Please Enter number of elements in array\")\nn = int(input())\nfor i in range(n):\n    demo = int(input())\n    arr1.append(demo)\n\nprint(\"Please enter the element in array\")\nkey = int(input())\n\nif key not in arr1:\n    print(\"Element not in array\")\n\nprint(\"Index of the element is : \",\n      pivotedBinarySearch(arr1, n, key))\n"
  },
  {
    "path": "Algorithms/Searching/Binary-Search/binarySearch.c",
    "content": "#include <stdio.h>\n\nint binarySearch(int arr[], int l, int r, int x) \n{ \n    if (r >= l) { \n        int mid = l + (r - l) / 2; \n  \n        // If the element is present at the middle \n        // itself \n        if (arr[mid] == x) \n            return mid; \n  \n        // If element is smaller than mid, then \n        // it can only be present in left subarray \n        if (arr[mid] > x) \n            return binarySearch(arr, l, mid - 1, x); \n  \n        // Else the element can only be present \n        // in right subarray \n        return binarySearch(arr, mid + 1, r, x); \n    } \n  \n    // We reach here when element is not \n    // present in array \n    return -1; \n} \n\nint main(void) \n{ \n    int arr[] = { 2, 3, 4, 10, 40 }; \n    int n = sizeof(arr) / sizeof(arr[0]); \n    int x = 10; \n    int result = binarySearch(arr, 0, n - 1, x); \n    (result == -1) ? printf(\"Element is not present in array\") \n                   : printf(\"Element is present at index %d\", \n                            result); \n    return 0; \n} \n"
  },
  {
    "path": "Algorithms/Searching/Binary-Search/binarySearch.cpp",
    "content": "#include <iostream>\nusing namespace std;\n\nint main()\n{\n\tint count, i, arr[30], num, first, last, middle;\n\tcout<<\"Enter Number of Elements:\";  //Count for number of elements\n        cin>>count;\n\n\tfor (i=0; i<count; i++)\n\t{\n\t\tcout<<\"Enter number \"<<(i+1)<<\": \"; \n                cin>>arr[i];\n\t}\n\tcout<<\"Enter the number you want to search:\"; //Query Input\n        cin>>num;\n\tfirst = 0;\n\tlast = count-1;\n\tmiddle = (first+last)/2;\n\twhile (first <= last)\n\t{\n\t   if(arr[middle] < num)\n\t   {\n\t\tfirst = middle + 1;\n\n\t   }\n\t   else if(arr[middle] == num)\n\t   {\n\t\tcout<<num<<\" found in the array at the location \"<<middle+1<<\"\\n\"; \n                break; \n           } \n           else { \n                last = middle - 1; \n           } \n           middle = (first + last)/2; \n        } \n        if(first > last)\n\t{\n\t   cout<<num<<\" not found in the array\";\n\t}\n\treturn 0;\n}\n"
  },
  {
    "path": "Algorithms/Searching/Binary-Search/binarySearch.js",
    "content": "< script >\n    let recursiveFunction = function(arr, x, start, end) {\n\n        // Base Condition \n        if (start > end) return false;\n\n        // Find the middle index \n        let mid = Math.floor((start + end) / 2);\n\n        // Compare mid with given key x \n        if (arr[mid] === x) return true;\n\n        // If element at mid is greater than x, \n        // search in the left half of mid \n        if (arr[mid] > x)\n            return recursiveFunction(arr, x, start, mid - 1);\n        else\n\n        // If element at mid is smaller than x, \n        // search in the right half of mid \n            return recursiveFunction(arr, x, mid + 1, end);\n    }\n\n// Driver code \nlet arr = [1, 3, 5, 7, 8, 9];\nlet x = 5;\n\nif (recursiveFunction(arr, x, 0, arr.length - 1))\n    document.write(\"Element found!<br>\");\nelse document.write(\"Element not found!<br>\");\n\nx = 6;\n\nif (recursiveFunction(arr, x, 0, arr.length - 1))\n    document.write(\"Element found!<br>\");\nelse document.write(\"Element not found!<br>\"); <\n/script>\n"
  },
  {
    "path": "Algorithms/Searching/Binary-Search/binarySearch.kt",
    "content": "fun binarySearch(arr: List<Int>, lo: Int, hi: Int, target: Int): Int{\n    //base case: if the left index crosses right index\n    //it means target is not present\n    if(lo > hi)return -1\n\n    //calculate the middle index of the current range [lo, hi]\n    val mid = lo + (hi - lo)/2\n\n    //return the index if the target is present at that index\n    if(arr[mid] == target)\n        return mid\n    \n    //do a recursive binary search on the basis of the whether the found element is \n    //lesser or greater than the target\n    return if(arr[mid] < target)\n            binarySearch(arr, mid+1, hi, target)\n           else \n            binarySearch(arr, lo, mid - 1, target)\n}\n\nfun main(){\n    //read the input array\n    val arr = readLine()!!.split(' ').map{it.toInt()}\n    //read the target to be found\n    val target = readLine()!!.toInt()\n    //do a binary search in the range of index [0, arr.size - 1]\n    val index = binarySearch(arr, 0, arr.size - 1, target)\n    \n    //if the target if not in the array\n    if(index == -1)\n        println(\"$target not found\")\n        \n    //if target is present in the array prints its index\n    //note: if there are multiple occurences of the target, the index could be any of     //those\n    else println(\"$target found at index $index\")\n}"
  },
  {
    "path": "Algorithms/Searching/Binary-Search/binarySearch.scala",
    "content": "\nobject GFG{ \n  \n// Creating Binary Search function \ndef RecursiveBinarySearch(arr: Array[Int], \n                          Element_to_Search: Int) \n                         (low: Int = 0, \n                          high: Int = arr.length - 1): Int = \n{ \n                                    \n    if (low > high)  \n        return -1\n      \n    var middle = low + (high - low) / 2\n      \n    // If element found \n    if (arr(middle) == Element_to_Search) \n        return middle \n      \n    else if (arr(middle) > Element_to_Search) \n        return RecursiveBinarySearch(arr,  \n               Element_to_Search)(low, middle - 1) \n      \n    // Searching in the right half \n    else\n        return RecursiveBinarySearch(arr,  \n               Element_to_Search)(middle + 1, high) \n} \n  \n// Creating main function \ndef main(args: Array[String]){ \n      \n    var index = RecursiveBinarySearch(Array(1, 2, 3, 4, 55,  \n                                            65, 75), 4)(0, 6); \n      \n    // If value not found  \n    if(index == -1) \n       print(\"Cannot be Found\") \n          \n    // Else print the index where the value is found \n    else\n       print(\"Found element at Index = \" + index) \n} \n} \n"
  },
  {
    "path": "Algorithms/Searching/Binary-Search/binary_search.cpp",
    "content": "       // binary search\n\n #include<bits/stdc++.h>\n using namespace std ;\n\n int binarySearch(int arr[], int l,int r,int x)\n {\n      \n    if (r >= l) { \n        int mid = l + (r - l) / 2; \n  \n        // If the element is present at the middle \n        // itself \n        if (arr[mid] == x) \n            return mid; \n  \n        // If element is smaller than mid, then \n        // it can only be present in left subarray \n        if (arr[mid] > x) \n            return binarySearch(arr, l, mid - 1, x); \n  \n        // Else the element can only be present \n        // in right subarray \n        return binarySearch(arr, mid + 1, r, x); \n    } \n    // We reach here when element is not \n    // present in array \n    return -1; \n }\n\nint main()\n{\n    int n ,i ,l , h , key ;\n    cin >> n ;\n    int arr[n] ;\n    for(i=0;i<n;i++)\n    {\n        cin >> arr[i] ;\n    }\n        \n    l=0 ;\n    h=n-1 ;\n     \n        cout   << \"enter the key you want to search : \";\n        cin >> key ;\n    //     while(h>=l)\n    // {\n    //     mid=(l+h)/2 ;\n\n    //     if(arr[mid]==key)\n    //     {\n    //         cout  << \"found\\n\" ;\n    //         return 0 ;\n    //     }\n    //     else if (key>mid)\n    //     {\n    //         l=mid+1 ;\n    //     }\n    //     else if (key<mid)\n    //     {\n    //         h=mid-1 ;\n    //     }  \n       \n    // }\n        int value = binarySearch(arr, l, h, key);\n        if(value)\n            {\n                cout << \"found\\n\";\n                return 0;\n            }\n        cout << \"element not found \\n\"\n             << endl;\n\n        return 0;\n }"
  },
  {
    "path": "Algorithms/Searching/Binary-Search/binary_search.java",
    "content": "  \nclass Binary \n{ \n\tint Search(int array[], int r, int l, int y) \n\t{ \n\t\tif (l >= l) \n    { \n\t\t\tint midvalue = l + (l - r) / 2; \n\t\t\tif (array[midvalue] == y) // mid value to start in both directions\n\t\t\treturn midvalue; \n\t\t\tif (array[midvalue] > x) \n\t\t\treturn binarySearch(arr, r, midvalue - 1, y); \n\t\t\treturn binarySearch(array, midvalue + 1, l, y); \n\t\t} \n\t\treturn -1; \n\t} \n\tpublic static void main(String args[]) \n\t{ \n\t\tBinarySearch ob = new BinarySearch(); \n\t\tint array[] = { 17, 34, 54, 65, 87, 99, 129, 135 }; \n\t\tint n = array.length; \n\t\tint y = 37; \n\t\tint index = ob.binarySearch(array, 0, n - 1, y); //check if selection is present\n\t\tif (index == -1) \n\t\t\tSystem.out.println(\"Selection not found\"); \n\t\telse\n\t\t\tSystem.out.println(\"Selection found at index \" + index); \n\t} \n} \n"
  },
  {
    "path": "Algorithms/Searching/Binary-Search/binarysearch.java",
    "content": "class Solution {\n\n    public int BinarySearch(int[] nums, int target) {\n\n      int left = 0;\n      int right = nums.length - 1;\n\n      while (left <= right) {\n        int pivot = left + (right - left) / 2;\n\n        if (nums[pivot] == target) return pivot;\n\n        if (target < nums[pivot]) right = pivot - 1;\n        \n        else left = pivot + 1;\n      }\n      return -1;\n    }\n\n  }"
  },
  {
    "path": "Algorithms/Searching/Binary-Search/binarysearch.js",
    "content": "< script >\n    let recursiveFunction = function(arr, x, start, end) {\n\n        // Base Condition \n        if (start > end) return false;\n\n        // Find the middle index \n        let mid = Math.floor((start + end) / 2);\n\n        // Compare mid with given key x \n        if (arr[mid] === x) return true;\n\n        // If element at mid is greater than x, \n        // search in the left half of mid \n        if (arr[mid] > x)\n            return recursiveFunction(arr, x, start, mid - 1);\n        else\n\n        // If element at mid is smaller than x, \n        // search in the right half of mid \n            return recursiveFunction(arr, x, mid + 1, end);\n    }\n\n// Driver code \nlet arr = [1, 3, 5, 7, 8, 9];\nlet x = 5;\n\nif (recursiveFunction(arr, x, 0, arr.length - 1))\n    document.write(\"Element found!<br>\");\nelse document.write(\"Element not found!<br>\");\n\nx = 6;\n\nif (recursiveFunction(arr, x, 0, arr.length - 1))\n    document.write(\"Element found!<br>\");\nelse document.write(\"Element not found!<br>\"); <\n/script>\n"
  },
  {
    "path": "Algorithms/Searching/Binary-Search/binarysearch.php",
    "content": "<?php \n  \nfunction binarySearch(Array $arr, $x) \n{ \n    // check for empty array \n    if (count($arr) === 0) return false; \n    $low = 0; \n    $high = count($arr) - 1; \n      \n    while ($low <= $high) { \n          \n        // compute middle index \n        $mid = floor(($low + $high) / 2); \n   \n        // element found at mid \n        if($arr[$mid] == $x) { \n            return true; \n        } \n  \n        if ($x < $arr[$mid]) { \n            // search the left side of the array \n            $high = $mid -1; \n        } \n        else { \n            // search the right side of the array \n            $low = $mid + 1; \n        } \n    } \n      \n    // If we reach here element x doesnt exist \n    return false; \n} \n  \n// Driver code \n$arr = array(1, 2, 3, 4, 5); \n$value = 5; \nif(binarySearch($arr, $value) == true) { \n    echo $value.\" Exists\"; \n} \nelse { \n    echo $value.\" Doesnt Exist\"; \n}\n\n"
  },
  {
    "path": "Algorithms/Searching/Binary-Search/binarysearch.py",
    "content": "def binarySearch (arr, l, r, x): \n  \n    # Check base case \n    if r >= l: \n  \n        mid = l + (r - l) // 2\n  \n        # If element is present at the middle itself \n        if arr[mid] == x: \n            return mid \n          \n        # If element is smaller than mid, then it  \n        # can only be present in left subarray \n        elif arr[mid] > x: \n            return binarySearch(arr, l, mid-1, x) \n  \n        # Else the element can only be present  \n        # in right subarray \n        else: \n            return binarySearch(arr, mid + 1, r, x) \n  \n    else: \n        # Element is not present in the array \n        return -1"
  },
  {
    "path": "Algorithms/Searching/Binary-Search/binarysearch.sh",
    "content": "#!/bin/bash\n\necho “Enter the limit:”\nread n\necho “Enter the numbers”\nfor(( i=0 ;i<n; i++ ))\n  do\n  read m\n  a[i]=$m\ndone\nfor(( i=1; i<n; i++ ))\n  do\n  for(( j=0; j<n-i; j++))\n    do\n    if [ ${a[$j]} -gt ${a[$j+1]} ]\n      then\n       t=${a[$j]}\n       a[$j]=${a[$j+1]}\n       a[$j+1]=$t\n      fi\n  done\ndone\n\necho “Sorted array is”\nfor(( i=0; i<n; i++ ))\n  do\n  echo “${a[$i]}”\ndone\n\necho “Enter the element to be searched :”\nread s\nl=0\nc=0\nu=$(($n-1))\nwhile [ $l -le $u ]\n  do\n  mid=$(((( $l+$u ))/2 ))\n  if [ $s -eq ${a[$mid]} ]\n    then\n    c=1\n    break\n  elif [ $s -lt ${a[$mid]} ]\n    then\n    u=$(($mid-1))\n  else\n    l=$(($mid+1))\n  fi\n  \ndone\nif [ $c -eq 1 ]\n  then\n  echo “Element found at position $(($mid+1))”\nelse\n  echo “Element not found”\nfi\n"
  },
  {
    "path": "Algorithms/Searching/Binary-Search/matrix_binary_search.py",
    "content": "def searchMatrix(matrix:list,target:int)->bool:\n    # Dimensions of the matrix\n    row=len(matrix)\n    col=len(matrix[0]) if len(matrix)>0 else 0\n    # In case of empty matrix\n    if col==0:\n        return False\n    # Row limits to iterate the row\n    row_low,row_high=0,row\n    # the row and column position of the target, if found.\n    target_row,target_col=-1,-1\n    while row_low<row_high:\n        mid= row_low+(row_high-row_low)//2\n        # If the mid row contains the target\n        if target>=matrix[mid][0] and target<=matrix[mid][col-1]:\n            target_row=mid\n            break\n        # if the target might be after the mid row\n        elif target>matrix[mid][col-1]:\n            row_low=mid+1\n        else:\n            row_high=mid-1\n    # if no row contains the target element \n    if target_row==-1:\n        return False\n    col_low,col_high=0,col\n    while col_low<col_high:\n        mid=col_low+(col_high-col_low)//2\n        if target==matrix[target_row][mid]:\n            return True\n        elif target>matrix[target_row][mid]:\n            col_low=mid+1\n        else:\n            col_high=mid-1\n    # If the element was not found in the selected row.\n    return False\n\nr,c=map(int,input().split())\nmatrix=[[]]*r\nfor i in range(r):\n    for j in range(c):\n        matrix[i].append(int(input()))\ntarget=int(input())\nprint(\"Target Found\" if searchMatrix(matrix,target) else \"Target Not Found\")\n   \n"
  },
  {
    "path": "Algorithms/Searching/Binary-Search/search_in_2d_matrix.cpp",
    "content": "#include<bits/stdc++.h>\n\nusing namespace std;\n\nbool searchMatrix(vector<vector<int>>& mat, int target)\n{\n    int n=mat.size();\n    int m=mat[0].size();\n    int l=0,h=n;\n    int mid;\n    while(l<h)\n    {\n        mid=l+(h-l)/2;\n        if(target>=mat[mid][0] && target <=mat[mid][m-1])\n            break;\n        else if(target>=mat[mid][m-1])\n            l=mid+1;\n        else h=mid;\n    }\n    \n    \n    l=0,h=m;\n    while(l<h)\n    {\n        int x=l+(h-l)/2;\n        \n            if(mat[mid][x]==target)\n                return true;\n        if(mat[mid][x]<target)\n            l=x+1;\n        else \n            h=x;\n    }\n    return false;\n}\nint main()\n{\n    int n,m,target;\n    cin>>n>>m>>target;\n    vector<vector<int>>mat(n,vector<int>(m));\n\n    for(int i=0;i<n;i++)\n    for(int j=0;j<m;j++)\n    cin>>mat[i][j];\n\n    if(searchMatrix(mat,target))\n     cout<<\"ELEMENT FOUND\";\n     else\n     cout<<\"ELEMENT NOT FOUND\";\n     return 0;\n\n}"
  },
  {
    "path": "Algorithms/Searching/Exponential-Search/exponential_search.cpp",
    "content": "#include <bits/stdc++.h>\nusing namespace std;\n\n//Templates start here\n#define pb push_back\n#define mp make_pair\n#define F first\n#define S second\n#define ll long long\n#define fo(i, j, k, in) for (int i = j; i < k; i += in)\n#define refo(i, j, k, in) for (int i = j; i >= k; i -= in)\n#define rep(i, j) fo(i, 0, j, 1)\n#define rerep(i, j) fo(i, j, 0, 1)\n#define all(cont) cont.begin(), cont.end()\n#define reall(cont) cont.end(), cont.begin()\n#define foreach(it, l) for (auto it = l.begin() l it != l.end(); it++)\n#define in(A, B, C) assert(B <= A && A <= C)\n#define MOD (int)1e9\n#define MOD7 1000000007\n#define PI 3.1415926535897932384626433832795\ntypedef pair<int, int> PII;\ntypedef pair<long long, long long> PLL;\ntypedef vector<int> VI;\ntypedef vector<long long> VL;\ntypedef vector<string> VS;\ntypedef vector<PII> VII;\ntypedef vector<PLL> VLL;\ntypedef vector<VI> VVI;\ntypedef vector<VL> VVL;\ntypedef map<int, int> MPII;\ntypedef map<long long, long long> MPLL;\ntypedef set<int> SETI;\ntypedef multiset<int> MSETI;\n//Templates end here\n\n//I'm not using my templates for better understanding, else above templates can be easily used, you can alse benefit yourself just copy above templates and use them\n\nint binSearch(int arr[], int, int, int);\nint expoSearch(int arr[], int n, int x) \n{ \n    if (arr[0] == x) \n        return 0; \n    int i = 1; \n    while (i < n && arr[i] <= x) \n        i = i*2; \n    return binSearch(arr, i/2, min(i, n), x); \n} \nint binSearch(int arr[], int l, int r, int x) \n{ \n    if (r >= l) \n    { \n        int mid = l + (r - l)/2; \n        if (arr[mid] == x) \n            return mid; \n        if (arr[mid] > x) \n            return binSearch(arr, l, mid-1, x); \n        return binSearch(arr, mid+1, r, x); \n    } \n    return -1; \n} \nint main(void) \n{ \n    int n,x;\n    cout<<\"\\nEnter the size of input array : \";\n    cin>>n;\n    int arr[n];\n    cout<<\"\\nEnter the array elements : \";\n    for(int i=0 ; i<n ; i++)\n        cin>>arr[i];\n    cout<<\"\\nEnter the number to be searched : \";\n    cin>>x; \n   int result = expoSearch(arr, n, x); \n   (result == -1)? printf(\"\\nElement is not present in array\") : printf(\"\\nElement is present at index %d\", result); \n   return 0; \n} "
  },
  {
    "path": "Algorithms/Searching/Exponential-Search/exponential_search.php",
    "content": "<?php \nfunction expoSearch($arr, $n, $x) \n{ \n    if ($arr[0] == $x) \n        return 0; \n    $i = 1; \n    while ($i< $n and $arr[$i] <=$x) \n        $i = $i * 2; \n    return binSearch($arr, $i / 2, min($i, $n), $x); \n} \nfunction binSearch($arr, $l, $r, $x) \n{ \n    if ($r >= $l) \n    { \n        $mid = $l + ($r - $l)/2; \n        if ($arr[$mid] == $x) \n            return $mid; \n        if ($arr[$mid] > $x) \n            return binSearch($arr, $l, $mid - 1, $x); \n        return binSearch($arr, $mid + 1, $r, $x); \n    } \n    return -1; \n} \n$arr = array(2, 3, 4, 10, 40); \n$n = count($arr); \n$x = 10; \n$result = expoSearch($arr, $n, $x); \nif($result == -1) \n    echo \"Element is not present in array\"; \nelse\n    echo \"Element is present at index \", $result; \n?> "
  },
  {
    "path": "Algorithms/Searching/Exponential-Search/exponential_search.py",
    "content": "def bin_search(arr, x, low=0, high=None):\n    if high is None:\n        high = len(arr) - 1\n    if high < low:\n        return -1\n    mid = (high + low) // 2\n    if arr[mid] == x:\n        return mid\n    elif arr[mid] < x:\n        return bin_search(arr, x, mid+1, high)\n    elif arr[mid] > x:\n        return bin_search(arr, x, low, mid)\n    return -1\n\n\ndef exp_search(arr, x):\n    i = 1\n    while True:\n        if 2**i >= len(arr):\n            return bin_search(arr, x, 2**(i-1)-1)\n        elif arr[2**i] == x:\n            return 2**i\n        elif arr[2**i] > x:\n            return bin_search(arr, x, 2**(i-1), 2**i - 1)\n        i += 1\n\n\n    \nuser_input = input(\"Enter numbers separated by comma:\\n\").strip()\nsequence = [int(item.strip()) for item in user_input.split(\",\")]\ntarget = int(input(\"Enter a single number to be found in the list:\\n\").strip())\nresult = exp_search(sequence, target)\nif result == -1:\n    print(f\"{target} was not found in list.\")\nelse:\n    print(f\"{target} was found in position {result} of list.\")"
  },
  {
    "path": "Algorithms/Searching/Fibonacci-Search/Fibonacci_Search.cpp",
    "content": "// Cpp program for Fibonacci Search \r\n\r\n#include<bits/stdc++.h>\r\nusing namespace std ;\r\n\r\n// Utility function to find minimum of two elements \r\nint min(int x, int y) {\r\n     return (x<=y)? x : y; \r\n} \r\n\r\n/* Returns index of x if present, else returns -1 */\r\nint fibMonaccianSearch(int arr[], int x, int n) \r\n{ \r\n\t/* Initialize fibonacci numbers */\r\n\tint fibMMm2 = 0; // (m-2)'th Fibonacci No. \r\n\tint fibMMm1 = 1; // (m-1)'th Fibonacci No. \r\n\tint fibM = fibMMm2 + fibMMm1; // m'th Fibonacci \r\n\r\n\t/* fibM is going to store the smallest Fibonacci \r\n\tNumber greater than or equal to n */\r\n\twhile (fibM < n) \r\n\t{ \r\n\t\tfibMMm2 = fibMMm1; \r\n\t\tfibMMm1 = fibM; \r\n\t\tfibM = fibMMm2 + fibMMm1; \r\n\t} \r\n\r\n\t// Marks the eliminated range from front \r\n\tint offset = -1; \r\n\r\n\t/* while there are elements to be inspected. Note that \r\n\twe compare arr[fibMm2] with x. When fibM becomes 1, \r\n\tfibMm2 becomes 0 */\r\n\twhile (fibM > 1) \r\n\t{ \r\n\t\t// Check if fibMm2 is a valid location \r\n\t\tint i = min(offset+fibMMm2, n-1); \r\n\r\n\t\t/* If x is greater than the value at index fibMm2, \r\n\t\tcut the subarray array from offset to i */\r\n\t\tif (arr[i] < x) \r\n\t\t{ \r\n\t\t\tfibM = fibMMm1; \r\n\t\t\tfibMMm1 = fibMMm2; \r\n\t\t\tfibMMm2 = fibM - fibMMm1; \r\n\t\t\toffset = i; \r\n\t\t} \r\n\r\n\t\t/* If x is greater than the value at index fibMm2, \r\n\t\tcut the subarray after i+1 */\r\n\t\telse if (arr[i] > x) \r\n\t\t{ \r\n\t\t\tfibM = fibMMm2; \r\n\t\t\tfibMMm1 = fibMMm1 - fibMMm2; \r\n\t\t\tfibMMm2 = fibM - fibMMm1; \r\n\t\t} \r\n\r\n\t\t/* element found. return index */\r\n\t\telse \r\n            return i; \r\n\t} \r\n\r\n\t/* comparing the last element with x */\r\n\tif(fibMMm1 && arr[offset+1]==x)\r\n        return offset+1; \r\n\r\n\t/*element not found. return -1 */\r\n\treturn -1; \r\n} \r\n\r\n/* driver function */\r\nint main(void) \r\n{ \r\n\tint arr[] = {10, 22, 35, 40, 45, 50, 80, 82, 85, 90, 100}; \r\n\tint n = sizeof(arr)/sizeof(arr[0]); \r\n\tint x = 85; \r\n\tcout<<\"Found at index: \"<<fibMonaccianSearch(arr, x, n); \r\n\treturn 0; \r\n} \r\n"
  },
  {
    "path": "Algorithms/Searching/Fibonacci-Search/Fibonacci_search.java",
    "content": "// Java program for Fibonacci Search \nimport java.util.*; \n\nclass Fibonacci \n{ \n\t// Utility function to find minimum \n\t// of two elements \n\tpublic static int min(int x, int y) \n\t{ return (x <= y)? x : y; } \n\n\t/* Returns index of x if present, else returns -1 */\n\tpublic static int fibMonaccianSearch(int arr[], \n\t\t\t\t\t\t\t\t\t\tint x, int n) \n\t{ \n\t\t/* Initialize fibonacci numbers */\n\t\tint fibMMm2 = 0; // (m-2)'th Fibonacci No. \n\t\tint fibMMm1 = 1; // (m-1)'th Fibonacci No. \n\t\tint fibM = fibMMm2 + fibMMm1; // m'th Fibonacci \n\n\t\t/* fibM is going to store the smallest \n\t\tFibonacci Number greater than or equal to n */\n\t\twhile (fibM < n) \n\t\t{ \n\t\t\tfibMMm2 = fibMMm1; \n\t\t\tfibMMm1 = fibM; \n\t\t\tfibM = fibMMm2 + fibMMm1; \n\t\t} \n\n\t\t// Marks the eliminated range from front \n\t\tint offset = -1; \n\n\t\t/* while there are elements to be inspected. \n\t\tNote that we compare arr[fibMm2] with x. \n\t\tWhen fibM becomes 1, fibMm2 becomes 0 */\n\t\twhile (fibM > 1) \n\t\t{ \n\t\t\t// Check if fibMm2 is a valid location \n\t\t\tint i = min(offset+fibMMm2, n-1); \n\n\t\t\t/* If x is greater than the value at \n\t\t\tindex fibMm2, cut the subarray array \n\t\t\tfrom offset to i */\n\t\t\tif (arr[i] < x) \n\t\t\t{ \n\t\t\t\tfibM = fibMMm1; \n\t\t\t\tfibMMm1 = fibMMm2; \n\t\t\t\tfibMMm2 = fibM - fibMMm1; \n\t\t\t\toffset = i; \n\t\t\t} \n\n\t\t\t/* If x is less than the value at index \n\t\t\tfibMm2, cut the subarray after i+1 */\n\t\t\telse if (arr[i] > x) \n\t\t\t{ \n\t\t\t\tfibM = fibMMm2; \n\t\t\t\tfibMMm1 = fibMMm1 - fibMMm2; \n\t\t\t\tfibMMm2 = fibM - fibMMm1; \n\t\t\t} \n\n\t\t\t/* element found. return index */\n\t\t\telse return i; \n\t\t} \n\n\t\t/* comparing the last element with x */\n\t\tif(fibMMm1 == 1 && arr[offset+1] == x) \n\t\t\treturn offset+1; \n\n\t\t/*element not found. return -1 */\n\t\treturn -1; \n\t} \n\t\n\t// driver code \n\tpublic static void main(String[] args) \n\t{ \n\t\tint arr[] = {10, 22, 35, 40, 45, 50, \n\t\t\t\t\t80, 82, 85, 90, 100}; \n\t\tint n = 11; \n\t\tint x = 85; \n\t\tSystem.out.print (\"Found at index: \"+ \n\t\t\t\tfibMonaccianSearch(arr, x, n)); \n\t} \n} \n"
  },
  {
    "path": "Algorithms/Searching/Fibonacci-Search/Fibonacci_search.php",
    "content": "<?php \n\n/* Returns index of x if present, else returns -1 */\nfunction fibMonaccianSearch($arr, $x, $n) \n{ \n\t/* Initialize fibonacci numbers */\n\t$fibMMm2 = 0; // (m-2)'th Fibonacci No. \n\t$fibMMm1 = 1; // (m-1)'th Fibonacci No. \n\t$fibM = $fibMMm2 + $fibMMm1; // m'th Fibonacci \n\n\t/* fibM is going to store the smallest Fibonacci \n\tNumber greater than or equal to n */\n\twhile ($fibM < $n) \n\t{ \n\t\t$fibMMm2 = $fibMMm1; \n\t\t$fibMMm1 = $fibM; \n\t\t$fibM = $fibMMm2 + $fibMMm1; \n\t} \n\n\t// Marks the eliminated range from front \n\t$offset = -1; \n\n\t/* while there are elements to be inspected. Note that \n\twe compare arr[fibMm2] with x. When fibM becomes 1, \n\tfibMm2 becomes 0 */\n\twhile ($fibM > 1) \n\t{ \n\t\t// Check if fibMm2 is a valid location \n\t\t$i = min($offset+$fibMMm2, $n-1); \n\n\t\t/* If x is greater than the value at index fibMm2, \n\t\tcut the subarray array from offset to i */\n\t\tif ($arr[$i] < $x) \n\t\t{ \n\t\t\t$fibM = $fibMMm1; \n\t\t\t$fibMMm1 = $fibMMm2; \n\t\t\t$fibMMm2 = $fibM - $fibMMm1; \n\t\t\t$offset = $i; \n\t\t} \n\n\t\t/* If x is less than the value at index fibMm2, \n\t\tcut the subarray after i+1 */\n\t\telse if ($arr[$i] > $x) \n\t\t{ \n\t\t\t$fibM = $fibMMm2; \n\t\t\t$fibMMm1 = $fibMMm1 - $fibMMm2; \n\t\t\t$fibMMm2 = $fibM - $fibMMm1; \n\t\t} \n\n\t\t/* element found. return index */\n\t\telse return $i; \n\t} \n\n\t/* comparing the last element with x */\n\tif($fibMMm1 && $arr[$offset + 1] == $x)return $offset+1; \n\n\t/*element not found. return -1 */\n\treturn -1; \n} \n\n\t$arr = array(10, 22, 35, 40, 45, 50, 80, 82,85, 90, 100); \n\t$n = count($arr); \n\t$x = 85; \n\tprintf(\"Found at index: \".fibMonaccianSearch($arr, $x, $n)); \n \n?> \n"
  },
  {
    "path": "Algorithms/Searching/Fibonacci-Search/Fibonacci_search_in_C.c",
    "content": "// C program for Fibonacci Search \n#include <stdio.h> \n\n// Utility function to find minimum of two elements \nint min(int x, int y) { return (x<=y)? x : y; } \n\n/* Returns index of x if present, else returns -1 */\nint fibMonaccianSearch(int arr[], int x, int n) \n{ \n\t/* Initialize fibonacci numbers */\n\tint fibMMm2 = 0; // (m-2)'th Fibonacci No. \n\tint fibMMm1 = 1; // (m-1)'th Fibonacci No. \n\tint fibM = fibMMm2 + fibMMm1; // m'th Fibonacci \n\n\t/* fibM is going to store the smallest Fibonacci \n\tNumber greater than or equal to n */\n\twhile (fibM < n) \n\t{ \n\t\tfibMMm2 = fibMMm1; \n\t\tfibMMm1 = fibM; \n\t\tfibM = fibMMm2 + fibMMm1; \n\t} \n\n\t// Marks the eliminated range from front \n\tint offset = -1; \n\n\t/* while there are elements to be inspected. Note that \n\twe compare arr[fibMm2] with x. When fibM becomes 1, \n\tfibMm2 becomes 0 */\n\twhile (fibM > 1) \n\t{ \n\t\t// Check if fibMm2 is a valid location \n\t\tint i = min(offset+fibMMm2, n-1); \n\n\t\t/* If x is greater than the value at index fibMm2, \n\t\tcut the subarray array from offset to i */\n\t\tif (arr[i] < x) \n\t\t{ \n\t\t\tfibM = fibMMm1; \n\t\t\tfibMMm1 = fibMMm2; \n\t\t\tfibMMm2 = fibM - fibMMm1; \n\t\t\toffset = i; \n\t\t} \n\n\t\t/* If x is greater than the value at index fibMm2, \n\t\tcut the subarray after i+1 */\n\t\telse if (arr[i] > x) \n\t\t{ \n\t\t\tfibM = fibMMm2; \n\t\t\tfibMMm1 = fibMMm1 - fibMMm2; \n\t\t\tfibMMm2 = fibM - fibMMm1; \n\t\t} \n\n\t\t/* element found. return index */\n\t\telse return i; \n\t} \n\n\t/* comparing the last element with x */\n\tif(fibMMm1 && arr[offset+1]==x)return offset+1; \n\n\t/*element not found. return -1 */\n\treturn -1; \n} \n\n/* driver function */\nint main(void) \n{ \n\tint arr[] = {10, 22, 35, 40, 45, 50, 80, 82, \n\t\t\t\t85, 90, 100}; \n\tint n = sizeof(arr)/sizeof(arr[0]); \n\tint x = 85; \n\tprintf(\"Found at index: %d\", \n\t\t\tfibMonaccianSearch(arr, x, n)); \n\treturn 0; \n} \n"
  },
  {
    "path": "Algorithms/Searching/Fibonacci-Search/fibonacciSearch.py",
    "content": "arr = [10, 22, 30, 44, 56, 58, 60, 72, 105, 110, 160]\nx = 60\n\n\ndef FibonacciGenerator(n):\n    if n < 1:\n        return 0\n    elif n == 1:\n        return 1\n    else:\n        return FibonacciGenerator(n - 1) + FibonacciGenerator(n - 2)\n\n\ndef FibonacciSearch(arr, x):\n    m = 0\n    while FibonacciGenerator(m) < len(arr):\n        m = m + 1\n    offset = -1\n    while (FibonacciGenerator(m) > 1):\n        i = min(offset + FibonacciGenerator(m - 2), len(arr) - 1)\n        print('Current Element : ', arr[i])\n        if (x > arr[i]):\n            m = m - 1\n            offset = i\n        elif (x < arr[i]):\n            m = m - 2\n        else:\n            return i\n    if(FibonacciGenerator(m - 1) and arr[offset + 1] == x):\n        return offset + 1\n    return -1\n\n\nprint('Number found at index : ', FibonacciSearch(arr, x))\n"
  },
  {
    "path": "Algorithms/Searching/Fibonacci-Search/fibonacci_search.c",
    "content": "// C program for Fibonacci Search \r\n#include <stdio.h> \r\n  \r\n// Utility function to find minimum of two elements \r\nint min(int x, int y) { return (x<=y)? x : y; } \r\n  \r\n/* Returns index of x if present,  else returns -1 */\r\nint fibMonaccianSearch(int arr[], int x, int n) \r\n{ \r\n    /* Initialize fibonacci numbers */\r\n    int fibMMm2 = 0;   // (m-2)'th Fibonacci No. \r\n    int fibMMm1 = 1;   // (m-1)'th Fibonacci No. \r\n    int fibM = fibMMm2 + fibMMm1;  // m'th Fibonacci \r\n  \r\n    /* fibM is going to store the smallest Fibonacci \r\n       Number greater than or equal to n */\r\n    while (fibM < n) \r\n    { \r\n        fibMMm2 = fibMMm1; \r\n        fibMMm1 = fibM; \r\n        fibM  = fibMMm2 + fibMMm1; \r\n    } \r\n  \r\n    // Marks the eliminated range from front \r\n    int offset = -1; \r\n  \r\n    /* while there are elements to be inspected. Note that \r\n       we compare arr[fibMm2] with x. When fibM becomes 1, \r\n       fibMm2 becomes 0 */\r\n    while (fibM > 1) \r\n    { \r\n        // Check if fibMm2 is a valid location \r\n        int i = min(offset+fibMMm2, n-1); \r\n  \r\n        /* If x is greater than the value at index fibMm2, \r\n           cut the subarray array from offset to i */\r\n        if (arr[i] < x) \r\n        { \r\n            fibM  = fibMMm1; \r\n            fibMMm1 = fibMMm2; \r\n            fibMMm2 = fibM - fibMMm1; \r\n            offset = i; \r\n        } \r\n  \r\n        /* If x is greater than the value at index fibMm2, \r\n           cut the subarray after i+1  */\r\n        else if (arr[i] > x) \r\n        { \r\n            fibM  = fibMMm2; \r\n            fibMMm1 = fibMMm1 - fibMMm2; \r\n            fibMMm2 = fibM - fibMMm1; \r\n        } \r\n  \r\n        /* element found. return index */\r\n        else return i; \r\n    } \r\n  \r\n    /* comparing the last element with x */\r\n    if(fibMMm1 && arr[offset+1]==x)return offset+1; \r\n  \r\n    /*element not found. return -1 */\r\n    return -1; \r\n} \r\n  \r\n/* driver function */\r\nint main(void) \r\n{ \r\n    int arr[] = {10, 22, 35, 40, 45, 50, 80, 82, \r\n                 85, 90, 100}; \r\n    int n = sizeof(arr)/sizeof(arr[0]); \r\n    int x = 85; \r\n    printf(\"Found at index: %d\", \r\n            fibMonaccianSearch(arr, x, n)); \r\n    return 0; \r\n} "
  },
  {
    "path": "Algorithms/Searching/Fibonacci-Search/fibonacci_search.js",
    "content": "//JavaScript program for Fibonacci Search \n\n /* \n  * Find an element in the given sorted array with the help of Fibonacci series\n    in O(log N) time complexity. \n  * Let the length of given array be n [0...n-1] and the element to be searched be x.\n  * Find the smallest Fibonacci number greater than or equal to n.\n  * source: https://iq.opengenus.org/fibonacci-search/\n  */\n\n  //length/size: n , element to search: x\n  function fibonacciSearch(n, arr, x){\n    //Let this number be fb(M) [m’th Fibonacci number].\n    //Let the two Fibonacci numbers preceding it be fb(M-1) [(m-1)’th Fibonacci number] \n    let fbMm2 = 0;\n    let fbMm1 = 1;\n    let fbM = fbMm1 + fbMm2;\n    let offset = -1;\n\n    //Find the smallest Fibonacci number greater than or equal to n\n    while(fbM < n){\n        fbMm2 = fbMm1;\n        fbMm1 = fbM;\n        fbM = fbMm1 + fbMm2;\n    }\n\n\n    //While the array has elements to be checked:\n    //-> Compare x with the last element of the range covered by fb(M-2)\n    //-> If x matches, return index value\n    //-> Else if x is less than the element, move the third Fibonacci variable two Fibonacci down,\n\n     let i = 0;\n\n     while(fbM > 1){\n        i = Math.min(offset + fbMm2, n - 1);\n\n        if(arr[i] < x){\n            fbM  = fbMm1;\n            fbMm1 = fbMm2;\n            fbMm2 = fbM - fbMm1;\n            offset = i;\n        } else if(arr[i] > x){\n            fbM  = fbMm2;\n            fbMm1 = fbMm1 - fbMm2;\n            fbMm2 = fbM - fbMm1;\n        } else\n            return i;\n     }\n\n    //comparing the last element\n    if(fbMm1 && arr[offset + 1] == x)\n        return offset + 1;\n\n    return -1;\n}\n\nlet arr = [10, 15, 30, 60, 90, 100, 120];\nlet n = 7;\nlet x = 92;\nconsole.log(fibonacciSearch(n, arr, x)); "
  },
  {
    "path": "Algorithms/Searching/Interpolation-Search/IS.cpp",
    "content": "#include<iostream>\nusing namespace std;\nint interpolationSearch(int array[], int start, int end, int key) {\n   int dist, valRange, indexRange, estimate;\n   float fraction;\n   while(start <= end && key >= array[start] && key <= array[end]) {\n      dist = key - array[start];\n      valRange = array[end] - array[start];     //range of value\n      fraction = dist / valRange;\n      indexRange = end - start;\n      estimate = start + (fraction * indexRange);      //estimated position of the key\n      if(array[estimate] == key)\n         return estimate;\n      if(array[estimate] < key)\n         start = estimate +1;\n      else\n         end = estimate - 1;\n   }\n   return -1;\n}\nint main() {\n   int n, searchKey, loc;\n   cout << \"Enter number of items: \";\n   cin >> n;\n   int arr[n];      //create an array of size n\n   cout << \"Enter items: \" << endl;\n   for(int i = 0; i< n; i++) {\n      cin >> arr[i];\n   }\n   cout << \"Enter search key to search in the list: \";\n   cin >> searchKey;\n   if((loc = interpolationSearch(arr, 0, n-1, searchKey)) >= 0)\n      cout << \"Item found at location: \" << loc << endl;\n   else\n      cout << \"Item is not found in the list.\" << endl;\n}\n"
  },
  {
    "path": "Algorithms/Searching/Interpolation-Search/IS.py",
    "content": "def intpolsearch(values,x ):\n    idx0 = 0\n    idxn = (len(values) - 1)\n\n    while idx0 <= idxn and x >= values[idx0] and x <= values[idxn]:\n\n# Find the mid point\n\tmid = idx0 +\\\n               int(((float(idxn - idx0)/( values[idxn] - values[idx0]))\n                    * ( x - values[idx0])))\n\n# Compare the value at mid point with search value \n        if values[mid] == x:\n            return \"Found \"+str(x)+\" at index \"+str(mid)\n\n        if values[mid] < x:\n            idx0 = mid + 1\n    return \"Searched element not in the list\"\n\n\nl = [2, 6, 11, 19, 27, 31, 45, 121]\nprint(intpolsearch(l, 2))\n"
  },
  {
    "path": "Algorithms/Searching/Jump-Search/JumpSearch.java",
    "content": "// Java program to implement Jump Search. \npublic class JumpSearch \n{ \n\tpublic static int jumpSearch(int[] arr, int x) \n\t{ \n\t\tint n = arr.length; \n\n\t\t// Finding block size to be jumped \n\t\tint step = (int)Math.floor(Math.sqrt(n)); \n\n\t\t// Finding the block where element is \n\t\t// present (if it is present) \n\t\tint prev = 0; \n\t\twhile (arr[Math.min(step, n)-1] < x) \n\t\t{ \n\t\t\tprev = step; \n\t\t\tstep += (int)Math.floor(Math.sqrt(n)); \n\t\t\tif (prev >= n) \n\t\t\t\treturn -1; \n\t\t} \n\n\t\t// Doing a linear search for x in block \n\t\t// beginning with prev. \n\t\twhile (arr[prev] < x) \n\t\t{ \n\t\t\tprev++; \n\n\t\t\t// If we reached next block or end of \n\t\t\t// array, element is not present. \n\t\t\tif (prev == Math.min(step, n)) \n\t\t\t\treturn -1; \n\t\t} \n\n\t\t// If element is found \n\t\tif (arr[prev] == x) \n\t\t\treturn prev; \n\n\t\treturn -1; \n\t} \n\n\t// Driver program\n\tpublic static void main(String [ ] args) \n\t{ \n\t\tint arr[] = { 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610}; \n\t\tint x = 55; \n\n\t\t// Find the index of 'x' using Jump Search \n\t\tint index = jumpSearch(arr, x); \n\n\t\t// Print the index where 'x' is located \n\t\tSystem.out.println(\"\\nNumber \" + x + \" is at index \" + index); \n\t} \n} \n"
  },
  {
    "path": "Algorithms/Searching/Jump-Search/Jump_Search.cpp",
    "content": "// C++ program to implement Jump Search \n\n#include <bits/stdc++.h> \nusing namespace std; \n\nint jumpSearch(int arr[], int x, int n) \n{ \n\t// Finding block size to be jumped \n\tint step = sqrt(n); \n\n\t// Finding the block where element is \n\t// present (if it is present) \n\tint prev = 0; \n\twhile (arr[min(step, n)-1] < x) \n\t{ \n\t\tprev = step; \n\t\tstep += sqrt(n); \n\t\tif (prev >= n) \n\t\t\treturn -1; \n\t} \n\n\t// Doing a linear search for x in block \n\t// beginning with prev. \n\twhile (arr[prev] < x) \n\t{ \n\t\tprev++; \n\n\t\t// If we reached next block or end of \n\t\t// array, element is not present. \n\t\tif (prev == min(step, n)) \n\t\t\treturn -1; \n\t} \n\t// If element is found \n\tif (arr[prev] == x) \n\t\treturn prev; \n\n\treturn -1; \n} \n\n// Driver program to test function \nint main() \n{ \n\tint arr[] = { 0, 1, 1, 2, 3, 5, 8, 13, 21, \n\t\t\t\t34, 55, 89, 144, 233, 377, 610 }; \n\tint x = 55; \n\tint n = sizeof(arr) / sizeof(arr[0]); \n\t\n\t// Find the index of 'x' using Jump Search \n\tint index = jumpSearch(arr, x, n); \n\n\t// Print the index where 'x' is located \n\tcout << \"\\nNumber \" << x << \" is at index \" << index; \n\treturn 0; \n} \n\n// Contributed by nuclode \n"
  },
  {
    "path": "Algorithms/Searching/Jump-Search/jumpSearch.cs",
    "content": "//Jump Search implementation in C#.\n\nusing System;\n\nclass MainClass {\n  public static void Main (string[] args) {\n\n    double[] arr = {0, 1, 2, 4, 9, 16, 25, 36, 64, 81, 100, 121, 144, 189, 400, 625};\n    double n = arr.Length;\n    double x = 144;\n\n\n    double step = Math.Sqrt(n);\n    step = Math.Truncate(step);\n    double j = n-step-1;\n    for (double i=0; i<n; i=i+step)\n    {\n        if(arr[(int)i]>x)\n        {\n          j = i - step;\n          break;\n        }\n    }\n    \n    double ub = j + step + 1;\n    for ( ; j<ub; j++)\n    {\n      if(arr[(int)j]==x)\n      {\n        Console.WriteLine(\"Number found at index \"+(int)j);\n      }\n    }\n\n  }\n}\n"
  },
  {
    "path": "Algorithms/Searching/Jump-Search/jumpSearch.go",
    "content": "//Jump Search implementation in Golang.\n\npackage main\nimport \"fmt\"\nimport \"math\"\n\n\nfunc main() {\n\n  arr := []int{ 0, 1, 2, 4, 9, 16, 25, 36, 64, 81, 100, 121, 144, 189, 400, 625}\n  n:= len(arr)\n  x:= 144\n\n\n  z:= jumpSearch(arr, x, n)\n  fmt.Println(\"Number found at index\",z)\n\n}\n\nfunc jumpSearch(arr []int, x int, n int) (inx float64){\n\n  step:= math.Round(math.Sqrt(float64(n)))\n  var i float64\n  for i= 0; i < float64(n); i+=step {\n    if (arr[int(i)] > x){\n      break;\n    }\n  }\n  i = i - step\n  ub:= i + step\n  for ; i < ub; i++{\n    if(arr[int(i)]==x){\n      return i;\n    }\n  }\n  return -1;\n}\n"
  },
  {
    "path": "Algorithms/Searching/Jump-Search/jumpSearch.js",
    "content": "//Jump Search implementation in JavaScript.\n\nvar arr = [0, 1, 2, 4, 9, 16, 25, 36, 64, 81, 100, 121, 144, 189, 400, 625];\nvar n = arr.length;\nvar x = 144;\n\nvar step = Math.floor((Math.sqrt(n)));\nvar j = n-step-1;\nfor (var i = 0; i<n; i = i + step)\n{\n  if(arr[i]>x)\n  {\n    j = i - step;\n    break;\n  }\n}\nvar ub = j + step;\nfor ( ; j<ub; j++)\n{\n  if(arr[j]==x)\n  {\n    console.log(\"Number found at index \",j);\n  }\n}\n"
  },
  {
    "path": "Algorithms/Searching/Jump-Search/jumpSearch.ts",
    "content": "//Jump Search implementation in Typescript.\n\nlet arr: number[] = [0, 1, 2, 4, 9, 16, 25, 36, 64, 81, 100, 121, 144, 189, 400, 625];\nlet x = 144;\nlet n = arr.length;\n\nlet step = Math.floor((Math.sqrt(n)));\nlet j = n-step-1;\nfor (let i = 0; i<n; i = i + step)\n{\n  if(arr[i]>x)\n  {\n    j = i - step;\n    break;\n  }\n}\nlet ub = j + step;\nfor ( ; j<ub; j++)\n{\n  if(arr[j]==x)\n  {\n    console.log(\"Number found at index \",j,arr[0]);\n  }\n}\n"
  },
  {
    "path": "Algorithms/Searching/Jump-Search/jump_search.py",
    "content": "import math \n  \ndef jumpSearch( arr , x , n ): \n      \n    step = math.sqrt(n) \n    \n    prev = 0\n    while arr[int(min(step, n)-1)] < x: \n        prev = step \n        step += math.sqrt(n) \n        if prev >= n: \n            return -1\n      \n     \n    while arr[int(prev)] < x: \n        prev += 1\n          \n     \n        if prev == min(step, n): \n            return -1\n      \n    if arr[int(prev)] == x: \n        return prev \n      \n    return -1\n\narr = [ 0,0, 1, 1, 2, 4, 5, 8, 17, 21,29, \n    34, 70, 89, 200, 377] \nx = 200\nn = len(arr) \n  \nindex = jumpSearch(arr, x, n) \n\nif(index == -1):\n    print(\"Number\" , x , \"is not present in array\")\nelse:\n    print(\"Number\" , x, \"is at index\" ,\"%.0f\"%index) "
  },
  {
    "path": "Algorithms/Searching/Linear-Search/LINEAR_SEARH.cpp",
    "content": "#include<iostream>\nusing namespace std;\n\nint main() \n{\n    cout<<\"Enter The Size Of Array:   \";\n    int size;\n    cin>>size;\n\n\n    int array[size], key,i;\n\n    // Taking Input In Array\n     for(int j=0;j<size;j++)\n    {\n        cout<<\"Enter \"<<j<<\" Element: \";\n        cin>>array[j];\n    }\n\n     //Your Entered Array Is\n    for(int a=0;a<size;a++)\n    {\n       cout<<\"array[ \"<<a<<\" ]  =  \";\n       cout<<array[a]<<endl;\n    }\n\n     cout<<\"Enter Key To Search  in Array\";\n     cin>>key;\n\n    for(i=0;i<size;i++)\n   {\n      if(key==array[i])\n      {\n        cout<<\"Key Found At Index Number :  \"<<i<<endl;\n        break;\n       }\n    }\n\n\n    if(i != size)\n    {\n        cout<<\"KEY FOUND at index :  \"<<i;\n    }\n    else\n    {\n        cout<<\"KEY NOT FOUND in Array  \";\n    }\n   return 0;\n}\n"
  },
  {
    "path": "Algorithms/Searching/Linear-Search/LinearSearch.js",
    "content": "var colors = [\"red\", \"orange\", \"yellow\", \"green\", \"blue\", \"indigo\", \"violet\", \"black\"];\n\nfunction linearSearch(arr, ele) {\n  for (var i=0; i<arr.length; i++) {\n    if (arr[i] == ele) {\n      return i;\n    }\n  } return null;\n}\n\nlinearSearch(colors, \"black\"); // returns 7 i.e. colors[7] = 'black'\nlinearSearch(colors, \"white\"); // returns null - Element not found.\n"
  },
  {
    "path": "Algorithms/Searching/Linear-Search/Linear_Search.cpp",
    "content": "#include<bits/stdc++.h>\nusing namespace std;\n\nint main(){\n\tint n;\t\n\tcin>>n;\t\t\t\t\t\t//size of the array\n\tint element;\t\n\tcin>>element;\t\t//element that have to searched\n\tint arr[n];\n\tfor(int i=0;i<n;i++){\t\t\t\t\n\t\tcin>>arr[i];\t\t\t\t\t//taking array input\n\t}\n\tfor(int i=0;i<n;i++){\n\t\tif(arr[i]==element){\n\t\t\tcout<<\"YES\"<<endl;\t\t\t//doing linearly searching and prints \"YES\" if found else \"NO\"\n\t\t\treturn 0;\n\t\t}\n\t}\n\tcout<<\"NO\"<<endl;\n}"
  },
  {
    "path": "Algorithms/Searching/Linear-Search/Linear_Search.go",
    "content": "package main\nimport \"fmt\"\n\n/*\nTakes in an int array to search and an int value for searching.\nReturns true if value is found and false otherwise.\nLinearSearch runs in O(n) time.\n*/ \nfunc LinearSearch(array []int, target int) bool {\n    for _, item := range array {\n        if item == target {\n            return true\n        }\n    }\n    return false\n} \n\n// main function tests the LinearSearch function  \nfunc main() {\n    items := []int{82,78,46,28,79,28,68,321,145, 1089}\n    fmt.Println(LinearSearch(items,28))\n}\n"
  },
  {
    "path": "Algorithms/Searching/Linear-Search/Linear_Search.py",
    "content": "# The below given code implements Linear Search algorithm.\n# The program prints the index number of the element if the searched element is present in the list, else it prints -1.\n\ndef LinearSearch(arr, element):\n    for i in range (len(arr)):\n        if arr[i] == element:\n            return i\n    return -1\n\nA = list(map(int, input(\"Enter the elements of list: \").split()))\nsearchKey = int(input(\"Enter element to be searched: \"))\nprint(LinearSearch(A, searchKey))"
  },
  {
    "path": "Algorithms/Searching/Linear-Search/Linearsearch.c",
    "content": "/*\n * C program to input N numbers and store them in an array.\n * Do a linear search for a given key and report success\n * or failure.\n */\n#include <stdio.h>\n \nvoid main()\n{  int num;\n \n    int i,  keynum, found = 0;\n \n    printf(\"Enter the number of elements \");\n    scanf(\"%d\", &num);\n    int array[num];\n    printf(\"Enter the elements one by one \\n\");\n    for (i = 0; i < num; i++)\n    {\n        scanf(\"%d\", &array[i]);\n    }\n \n    printf(\"Enter the element to be searched \");\n    scanf(\"%d\", &keynum);\n    /*  Linear search begins */\n    for (i = 0; i < num ; i++)\n    {\n        if (keynum == array[i] )\n        {\n            found = 1;\n            break;\n        }\n    }\n    if (found == 1)\n        printf(\"Element is present in the array at position %d\",i+1);\n    else\n        printf(\"Element is not present in the array\\n\");\n}\n"
  },
  {
    "path": "Algorithms/Searching/Linear-Search/README.md",
    "content": "## This folder is empty.\n"
  },
  {
    "path": "Algorithms/Searching/Linear-Search/linear_search.java",
    "content": "class Search  \n{  \npublic static int Linear (int array[], int num) \n{ \n    int length = array.length; //to calculate array length\n    for(int i = 0; i < length; i++) \n    { \n       if(array[i] == num)\n       return i; \n    } \n    return -1; \n}  \npublic static void main(String args[]) \n{ \n    int array[] = { 5, 13, 29, 38, 44, 59, 63, 69, 84, 90, 208 };  \n    int num = 69;     \n    int index = search(array, num); //looking for the selection in array\n    if(result == -1) \n    System.out.print(\"Could not find the selection in the array.\"); \n    else\n    System.out.print(\"Selection found at index: \" + index); \n} \n} \n"
  },
  {
    "path": "Algorithms/Searching/Linear-Search/linear_search.sh",
    "content": "#!/bin/bash\n\necho 'Enter the array elements:'\nread -a arr\n\necho 'Enter the element to search for: '\nread s\n\nfor i in ${arr[@]}; do\n        if [ $i -eq $s ]; then\n                echo 'Element found!'\n                exit 0\n        fi\ndone\n\necho 'Element not found'\n"
  },
  {
    "path": "Algorithms/Searching/README.md",
    "content": "# This folder is empty.\n"
  },
  {
    "path": "Algorithms/Searching/Sublist-Search/Sublist_Search.php",
    "content": "<?php\n\nclass Node {\n    public int $key;\n    public ?Node $next;\n}\n\n/**\n * Create a new node\n * \n * @param int $key node identifier\n */\nfunction createNewNode (int $key) {\n    $node = new Node();\n    $node->key = $key;\n    $node->next = null;\n    return $node;\n}\n\n/**\n * Search sublist\n * \n * @param Node $first First node\n * @param Node $second Second node\n * @return bool\n */\nfunction subListSearch(Node $first, Node $second): bool\n{\n    $fNode = $first;\n    $sNode = $second; \n  \n    if ($first == null && $second == null) {\n        return true;\n    }\n     \n    if ($first == null || ($first != null && $second == null)) {\n        return false; \n    }\n    \n    while ($second != null) {\n        $sNode = $second; \n\n        while ($fNode != null) {\n\n            if ($sNode == null) {\n                return false;\n            } elseif ($fNode->key == $sNode->key) { \n                $fNode = $fNode->next; \n                $sNode = $sNode->next; \n            } else {\n                break;\n            }\n        } \n\n        if ($fNode == null) {\n            return true;\n        }\n\n        $fNode = $first;\n        $second = $second->next;\n    } \n    return false; \n}\n\n/**\n * Print a specific node\n * \n * @param Node $node\n */\nfunction printList(Node $node)\n{\n    while($node != null) {\n        echo $node->key . ' ';\n        $node = $node->next;\n    }\n    echo \"\\n\";\n}\n\n/**\n * Test sublist search\n */\nfunction testSubListSearch()\n{\n    $first = createNewNode(1); \n    $first->next = createNewNode(2);\n    $first->next->next = createNewNode(3);\n    $first->next->next->next = createNewNode(4); \n  \n    $second = createNewNode(1); \n    $second->next = createNewNode(2); \n    $second->next->next = createNewNode(1); \n    $second->next->next->next = createNewNode(2); \n    $second->next->next->next->next = createNewNode(3); \n    $second->next->next->next->next->next = createNewNode(4);\n\n    echo \"First list:\\n\";\n    printList($first);\n    echo \"Second list: \\n\";\n    printList($second);\n    echo \"\\n\";\n  \n    if(subListSearch($first, $second)) {\n        echo 'List Found'; \n    } else {\n        echo 'List Not Found';\n    }\n    echo \"\\n\";\n}\n\n// Test:\ntestSubListSearch();\n// Result:\n// First list:\n// 1 2 3 4\n// Second list:\n// 1 2 1 2 3 4\n\n// List Found"
  },
  {
    "path": "Algorithms/Searching/Sublist-Search/sublist_search.cpp",
    "content": "#include <bits/stdc++.h> \nusing namespace std; \n\n//Templates start here\n#define pb push_back\n#define mp make_pair\n#define F first\n#define S second\n#define ll long long\n#define fo(i, j, k, in) for (int i = j; i < k; i += in)\n#define refo(i, j, k, in) for (int i = j; i >= k; i -= in)\n#define rep(i, j) fo(i, 0, j, 1)\n#define rerep(i, j) fo(i, j, 0, 1)\n#define all(cont) cont.begin(), cont.end()\n#define reall(cont) cont.end(), cont.begin()\n#define foreach(it, l) for (auto it = l.begin() l it != l.end(); it++)\n#define in(A, B, C) assert(B <= A && A <= C)\n#define MOD (int)1e9\n#define MOD7 1000000007\n#define PI 3.1415926535897932384626433832795\ntypedef pair<int, int> PII;\ntypedef pair<long long, long long> PLL;\ntypedef vector<int> VI;\ntypedef vector<long long> VL;\ntypedef vector<string> VS;\ntypedef vector<PII> VII;\ntypedef vector<PLL> VLL;\ntypedef vector<VI> VVI;\ntypedef vector<VL> VVL;\ntypedef map<int, int> MPII;\ntypedef map<long long, long long> MPLL;\ntypedef set<int> SETI;\ntypedef multiset<int> MSETI;\n//Templates end here\n\n//I'm not using my templates for better understanding, else above templates can be easily used, you can alse benefit yourself just copy above templates and use them\n\nstruct Node \n{ \n    int data; \n    Node* next; \n}; \nbool findList(Node* first, Node* second) \n{ \n    Node* ptr1 = first, *ptr2 = second; \n    if (first == NULL && second == NULL) \n        return true; \n    if ( first == NULL || (first != NULL && second == NULL)) \n        return false; \n    while (second != NULL) \n    { \n        ptr2 = second; \n        while (ptr1 != NULL) \n        { \n            if (ptr2 == NULL) \n                return false; \n            else if (ptr1->data == ptr2->data) \n            { \n                ptr1 = ptr1->next; \n                ptr2 = ptr2->next; \n            } \n            else break; \n        } \n        if (ptr1 == NULL) \n            return true; \n        ptr1 = first; \n        second = second->next; \n    } \n  \n    return false; \n} \nvoid printList(Node* node) \n{ \n    while (node != NULL) \n    { \n        printf(\"%d \", node->data); \n        node = node->next; \n    } \n} \nNode *newNode(int key) \n{ \n    Node *temp = new Node; \n    temp-> data= key; \n    temp->next = NULL; \n    return temp; \n}\nint main() \n{\n    Node *a = newNode(1); \n    a->next = newNode(2); \n    a->next->next = newNode(3); \n    a->next->next->next = newNode(4); \n    Node *b = newNode(1); \n    b->next = newNode(2); \n    b->next->next = newNode(1); \n    b->next->next->next = newNode(2); \n    b->next->next->next->next = newNode(3); \n    b->next->next->next->next->next = newNode(4); \n    findList(a,b) ? cout << \"LIST FOUND\" : cout << \"LIST NOT FOUND\"; \n    return 0; \n} "
  },
  {
    "path": "Algorithms/Searching/Sublist-Search/sublist_search.cs",
    "content": "/******************************************** \n*  C# program to find a list in second list \n*\n*  Author - Ayush Sharma (belphegor-s)\n*\n*\n********************************************/\nusing System; \n\nclass GFG \n{ \n\n// A Linked List node \nclass Node \n{ \n\tpublic int data; \n\tpublic Node next; \n}; \n\n// Returns true if first list is \n// present in second list \nstatic Boolean findList(Node first, \n\t\t\t\t\t\tNode second) \n{ \n\tNode ptr1 = first, ptr2 = second; \n\n\t// If both linked lists are empty, \n\t// return true \n\tif (first == null && second == null) \n\t\treturn true; \n\n\t// Else If one is empty and \n\t// other is not, return false \n\tif (first == null || \n\t(first != null && second == null)) \n\t\treturn false; \n\n\t// Traverse the second list by \n\t// picking nodes one by one \n\twhile (second != null) \n\t{ \n\t\t// Initialize ptr2 with \n\t\t// current node of second \n\t\tptr2 = second; \n\n\t\t// Start matching first list \n\t\t// with second list \n\t\twhile (ptr1 != null) \n\t\t{ \n\t\t\t// If second list becomes empty and \n\t\t\t// first not then return false \n\t\t\tif (ptr2 == null) \n\t\t\t\treturn false; \n\n\t\t\t// If data part is same, go to next \n\t\t\t// of both lists \n\t\t\telse if (ptr1.data == ptr2.data) \n\t\t\t{ \n\t\t\t\tptr1 = ptr1.next; \n\t\t\t\tptr2 = ptr2.next; \n\t\t\t} \n\n\t\t\t// If not equal then break the loop \n\t\t\telse break; \n\t\t} \n\n\t\t// Return true if first list gets traversed \n\t\t// completely that means it is matched. \n\t\tif (ptr1 == null) \n\t\t\treturn true; \n\n\t\t// Initialize ptr1 with first again \n\t\tptr1 = first; \n\n\t\t// And go to next node of second list \n\t\tsecond = second.next; \n\t} \n\treturn false; \n} \n\n/* Function to print nodes \nin a given linked list */\nstatic void printList(Node node) \n{ \n\twhile (node != null) \n\t{ \n\t\tConsole.Write(\"{0} \", node.data); \n\t\tnode = node.next; \n\t} \n} \n\n// Function to add new node to linked lists \nstatic Node newNode(int key) \n{ \n\tNode temp = new Node(); \n\ttemp.data= key; \n\ttemp.next = null; \n\treturn temp; \n} \n\n// Driver Code \npublic static void Main(String[] args) \n{ \n\t/* Let us create two linked lists to test \n\tthe above functions. Created lists shall be \n\t\ta: 1->2->3->4 \n\t\tb: 1->2->1->2->3->4*/\n\tNode a = newNode(1); \n\ta.next = newNode(2); \n\ta.next.next = newNode(3); \n\ta.next.next.next = newNode(4); \n\n\tNode b = newNode(1); \n\tb.next = newNode(2); \n\tb.next.next = newNode(1); \n\tb.next.next.next = newNode(2); \n\tb.next.next.next.next = newNode(3); \n\tb.next.next.next.next.next = newNode(4); \n\n\tif(findList(a, b) == true) \n\t\tConsole.Write(\"LIST FOUND\"); \n\telse\n\t\tConsole.Write(\"LIST NOT FOUND\"); \n} \n} \n"
  },
  {
    "path": "Algorithms/Searching/Sublist-Search/sublist_search.java",
    "content": "import java.util.*; \nclass GFG  \n{  \n    static class Node  \n    { \n        int data; \n        Node next; \n    }; \n    static boolean findList(Node first, Node second) \n    { \n        Node ptr1 = first, ptr2 = second; \n        if (first == null && second == null) \n            return true; \n        if (first == null || (first != null && second == null)) \n            return false; \n        while (second != null) \n        { \n            ptr2 = second; \n            while (ptr1 != null) \n            { \n                if (ptr2 == null) \n                    return false; \n                else if (ptr1.data == ptr2.data) \n                { \n                    ptr1 = ptr1.next; \n                    ptr2 = ptr2.next; \n                } \n                else break; \n            } \n            if (ptr1 == null) \n                return true; \n            ptr1 = first; \n            second = second.next; \n        } \n        return false; \n    } \n    static void printList(Node node) \n    { \n        while (node != null) \n        { \n            System.out.printf(\"%d \", node.data); \n            node = node.next; \n        } \n    } \n    static Node newNode(int key) \n    { \n        Node temp = new Node(); \n        temp.data= key; \n        temp.next = null; \n        return temp; \n    } \n    public static void main(String[] args)  \n    { \n        Node a = newNode(1); \n        a.next = newNode(2); \n        a.next.next = newNode(3); \n        a.next.next.next = newNode(4); \n        Node b = newNode(1); \n        b.next = newNode(2); \n        b.next.next = newNode(1); \n        b.next.next.next = newNode(2); \n        b.next.next.next.next = newNode(3); \n        b.next.next.next.next.next = newNode(4); \n        if(findList(a, b) == true)  \n            System.out.println(\"LIST FOUND\"); \n        else\n            System.out.println(\"LIST NOT FOUND\"); \n    } \n} "
  },
  {
    "path": "Algorithms/Searching/Sublist-Search/sublist_search.js",
    "content": "class node {\n    constructor(value) {\n        this.value = value;\n        this.next = null;\n    }\n}\n\nvar findList = function(first, second) {\n    if(!first && !second) {\n        return true;\n    }\n    if(!first || !second) {\n        return false;\n    }\n\n    ptr1 = first;\n    ptr2 = second;\n\n    while(ptr2) {\n        ptr2 = second;\n\n        while(ptr1) {\n            if(!ptr2) {\n                return false;\n            } else if(ptr1.value === ptr2.value) {\n                ptr1 = ptr1.next;\n                ptr2 = ptr2.next;\n            } else {\n                break;\n            }\n        }\n        if(!ptr1) {\n            return true;\n        }\n        ptr1 = first;\n        second = second.next;\n    }\n    return false;\n}\n\nnode_a = new node(1);\nnode_a.next = new node(2);\nnode_a.next.next = new node(3); \nnode_a.next.next.next = new node(4); \nnode_b = new node(1); \nnode_b.next = new node(2); \nnode_b.next.next = new node(1); \nnode_b.next.next.next = new node(2); \nnode_b.next.next.next.next = new node(3); \nnode_b.next.next.next.next.next = new node(4);  \n\nif(findList(node_a, node_b)) {\n    console.log(\"List Found\");\n} else {\n    console.log(\"List Not Found\");\n}\n\n"
  },
  {
    "path": "Algorithms/Searching/Sublist-Search/sublist_search.py",
    "content": "class Node: \n    def __init__(self, value = 0): \n        self.value = value \n        self.next = None\ndef findList(first, second):\n    if not first and not second: \n        return True\n    if not first or not second: \n        return False\n    ptr1 = first \n    ptr2 = second\n    while ptr2:\n        ptr2 = second\n        while ptr1:\n            if not ptr2: \n                return False\n            elif ptr1.value == ptr2.value: \n                ptr1 = ptr1.next\n                ptr2 = ptr2.next\n            else: \n                break\n        if not ptr1: \n            return True\n        ptr1 = first\n        second = second.next\n    return False\n\nnode_a = Node(1) \nnode_a.next = Node(2) \nnode_a.next.next = Node(3) \nnode_a.next.next.next = Node(4) \nnode_b = Node(1) \nnode_b.next = Node(2) \nnode_b.next.next = Node(1) \nnode_b.next.next.next = Node(2) \nnode_b.next.next.next.next = Node(3) \nnode_b.next.next.next.next.next = Node(4) \nif findList(node_a, node_b): \n    print(\"LIST FOUND\") \nelse: \n    print(\"LIST NOT FOUND\") \n  "
  },
  {
    "path": "Algorithms/Searching/Ternary-Search/README.md",
    "content": "## This folder is empty.\n"
  },
  {
    "path": "Algorithms/Searching/Ternary-Search/Ternary-String.c",
    "content": "/*\nYou are given a string s such that each its character is either 1, 2, or 3. \nYou have to choose the shortest contiguous substring of s such that it contains each of these three characters at least once.\nA contiguous substring of string s is a string that can be obtained from s\nby removing some (possibly zero) characters from the beginning of s \nand some (possibly zero) characters from the end of s.\n*/\n\n#include <iostream>\n#include<stdio.h> \n#include <bits/stdc++.h> \n#include <cmath>\n#include <vector>\n#include <map>\n#include <string>\n#include <algorithm>\n#include <iomanip>\n#include<utility>\nusing namespace std;\n#define ll long long\n#define len length()\n#define vi vector<int>\n#define vl vector<ll>\n\n#define fr(i,n) for(ll i=0;i<n;i++)\nll max(ll i,ll j){\n    return i>j?i:j;\n}\n \nint main(){\n    \nll t; cin>>t;\nwhile(t--){\nstring s;\ncin>>s;\nll l=0;\n \nll x1 =-1,x2=-1,x3=-1;\nll ans=INT_MAX;\nfr(i,s.len){\n    \n    {\n          if(s[i]=='1') x1=i;\n      \n           if(s[i]=='2') x2=i;\n           \n           if(s[i]=='3') x3=i;\n           \n           if(x1!=-1&&x2!=-1&&x3!=-1){\n               l=(max(x1,max(x2,x3))-min(x1,min(x2,x3)));\n               ans=min(ans,l+1);\n               \n           }\n                  \n    }    \n}\n \nif(ans==INT_MAX) ans=0;\ncout<<ans<<endl;\n \n}\nreturn 0;\n}\n"
  },
  {
    "path": "Algorithms/Searching/Ternary-Search/ternarySearch.cpp",
    "content": "#include <iostream>\nusing namespace std;\n\n\nint ternarySearch(int l, int r, int key, int ar[])\n\n{\n    while (r >= l) {\n\n        int mid1 = l + (r - l) / 3;\n        int mid2 = r - (r - l) / 3;\n\n        if (ar[mid1] == key) {\n            return mid1;\n        }\n        if (ar[mid2] == key) {\n            return mid2;\n        }\n\n\n\n        if (key < ar[mid1]) {\n\n\n            r = mid1 - 1;\n        }\n        else if (key > ar[mid2]) {\n\n\n            l = mid2 + 1;\n        }\n        else {\n\n            l = mid1 + 1;\n            r = mid2 - 1;\n        }\n    }\n\n    return -1;\n}\n\n// Driver code\nint main()\n{\n    int l, r, p, key, n;\n    cin >> n;\n    int arr[n];\n\n    for (int i = 0; i < n; i++) {\n        cin >> arr[i];\n    }\n    l = 0;\n    r = n - 1;\n\n    cin >> key;\n\n    // Search the key using ternarySearch\n    p = ternarySearch(l, r, key, arr);\n\n    // Print the result\n    cout << \"Index of \" << key << \" is \" << p << endl;\n\n    return 0;\n}"
  },
  {
    "path": "Algorithms/Searching/Ternary-Search/unimodal_func.cpp",
    "content": "#include<bits/stdc++.h>\nusing namespace std;\n\n// This is the amount of error we are ready to tolerate in our answer.\n#define PRECISION 0.0000001\n\n// The main aim of this problem is to find the \n// minimum and maximum value of a unimodal function\n// using the ternary search algorithm.\n\n\n// the unimodal function whose maxima has to be found\n// Let the range be [-10^9,10^9]\ndouble func1(double x){\n    return -x*x-2*x+3;\n}\n// the unimodal function whose minima has to be found\n// let the range be [-10^9,10^9]\ndouble func2(double x){\n    return x*x-2*x+3;\n}\n\n/*To find the maxima of a function we go in the following way:\n1. We choose any two points m1 and m2 such that l<=m1<=m2<=r.\n2. if func(m1)<func(m2){\n        we go for the range [m1,r]\n    }\n    else if func(m1)>func(m2){\n        we go for the range [l,m2]\n    }\n    else{\n        we reduce our space to [m1,m2]\n    }\n 3. Step 2 is repeated with same conditions until we reach our desired precision value in\n    our result.  \n*/\n\ndouble find_maxima(double l, double r){\n    if(abs(l-r)<=PRECISION) return func1(l);\n    else{\n        double m1 = l+(r-l)/3;\n        double m2 = l+2*(r-l)/3;\n        if(func1(m1)<func1(m2))\n            return find_maxima(m1,r);\n        else if(func1(m1)>func1(m2))\n            return find_maxima(l,m2);\n        return find_maxima(m1,m2);\n    }\n}\n\n/*\nTo find the minima of a unimodal function we have to do the following task:\n1. We choose any two points m1 and m2 such that l<=m1<=m2<=r.\n2. if func(m1)<func(m2){\n        we go for the range [l,m2]\n    }\n    else if func(m1)>func(m2){\n        we go for the range [m1,r]\n    }\n    else{\n        we reduce our space to [m1,m2]\n    }\n 3. Step 2 is repeated with same conditions until we reach our desired precision value in\n    our result. \n*/\n\ndouble find_minima(double l, double r){\n    if(abs(l-r)<=PRECISION) return func2(l);\n    else{\n        double m1 = l+(r-l)/3;\n        double m2 = l+2*(r-l)/3;\n        if(func2(m1)<func2(m2))\n            return find_minima(l,m2);\n        else if(func2(m1)>func2(m2))\n            return find_minima(m1,r);\n        return find_minima(m1,m2);\n    }\n}\n\n\nint main(){\n    cout<<\"maxima for func1: \";\n    cout<<find_maxima(-1000000000,1000000000)<<endl;\n    cout<<\"minima for func2: \";\n    cout<<find_minima(-1000000000,1000000000)<<endl;\n    return 0;\n}"
  },
  {
    "path": "Algorithms/Searching/Ternary-Search/unimodal_func.java",
    "content": "// The main aim of this problem is to find the \n// minimum and maximum value of a unimodal function\n// using the ternary search algorithm.\n\n\nimport java.util.Scanner;\n\npublic class TernarySearch\n{\n    // the unimodal function whose maxima has to be found\n    // Let the range be [-10^9,10^9]\n    public static double func1(double x){\n    return -x*x-2*x+3;\n    }\n    // the unimodal function whose minima has to be found\n    // let the range be [-10^9,10^9]\n    public static double func2(double x){\n        return x*x-2*x+3;\n    }\n    /*To find the maxima of a function we go in the following way:\n    1. We choose any two points m1 and m2 such that l<=m1<=m2<=r.\n    2. if func(m1)<func(m2){\n            we go for the range [m1,r]\n        }\n        else if func(m1)>func(m2){\n            we go for the range [l,m2]\n        }\n        else{\n            we reduce our space to [m1,m2]\n        }\n    3. Step 2 is repeated with same conditions until we reach our desired precision value in\n        our result.  \n    */\n\n    public static double find_maxima(double l, double r){\n        if(Math.abs(l-r)<=0.0000001) return func1(l);\n        else{\n            double m1 = l+(r-l)/3;\n            double m2 = l+2*(r-l)/3;\n            if(func1(m1)<func1(m2))\n                return find_maxima(m1,r);\n            else if(func1(m1)>func1(m2))\n                return find_maxima(l,m2);\n            return find_maxima(m1,m2);\n        }\n    }\n\n    /*\n    To find the minima of a unimodal function we have to do the following task:\n    1. We choose any two points m1 and m2 such that l<=m1<=m2<=r.\n    2. if func(m1)<func(m2){\n            we go for the range [l,m2]\n        }\n        else if func(m1)>func(m2){\n            we go for the range [m1,r]\n        }\n        else{\n            we reduce our space to [m1,m2]\n        }\n    3. Step 2 is repeated with same conditions until we reach our desired precision value in\n        our result. \n    */\n\n    public static double find_minima(double l, double r){\n        if(Math.abs(l-r)<=0.0000001) return func2(l);\n        else{\n            double m1 = l+(r-l)/3;\n            double m2 = l+2*(r-l)/3;\n            if(func2(m1)<func2(m2))\n                return find_minima(l,m2);\n            else if(func2(m1)>func2(m2))\n                return find_minima(m1,r);\n            return find_minima(m1,m2);\n        }\n    }\n\n\n\n    // Main method\n    public static void main(String args[]){\n        System.out.println(\"The maximum value of func1 is: \"+find_maxima(-10000000000.0, 10000000000.0));\n        System.out.println(\"The maximum value of func1 is: \"+find_minima(-10000000000.0, 10000000000.0));\n\n    }\n        \n}"
  },
  {
    "path": "Algorithms/Searching/Ternary-Search/unimodal_func.js",
    "content": "// This is the amount of error we are ready to tolerate in our answer.\nconst PRECISION = 0.0000001\n\n// The main aim of this problem is to find the \n// minimum and maximum value of a unimodal function\n// using the ternary search algorithm.\n\n\n// the unimodal function whose maxima has to be found\n// Let the range be [-10^9,10^9]\nfunction func1(x) {\n    return -x * x - 2 * x + 3;\n}\n// the unimodal function whose minima has to be found\n// let the range be [-10^9,10^9]\nfunction func2(x) {\n    return x * x - 2 * x + 3;\n}\n\n/*To find the maxima of a function we go in the following way:\n1. We choose any two points m1 and m2 such that l<=m1<=m2<=r.\n2. if func(m1)<func(m2){\n        we go for the range [m1,r]\n    }\n    else if func(m1)>func(m2){\n        we go for the range [l,m2]\n    }\n    else{\n        we reduce our space to [m1,m2]\n    }\n 3. Step 2 is repeated with same conditions until we reach our desired precision value in\n    our result.  \n*/\n\nfunction find_maxima(l, r) {\n    if (Math.abs(l - r) <= PRECISION) return func1(l);\n    else {\n        var m1 = l + (r - l) / 3;\n        var m2 = l + 2 * (r - l) / 3;\n        if (func1(m1) < func1(m2))\n            return find_maxima(m1, r);\n        else if (func1(m1) > func1(m2))\n            return find_maxima(l, m2);\n        return find_maxima(m1, m2);\n    }\n}\n\n/*\nTo find the minima of a unimodal function we have to do the following task:\n1. We choose any two points m1 and m2 such that l<=m1<=m2<=r.\n2. if func(m1)<func(m2){\n        we go for the range [l,m2]\n    }\n    else if func(m1)>func(m2){\n        we go for the range [m1,r]\n    }\n    else{\n        we reduce our space to [m1,m2]\n    }\n 3. Step 2 is repeated with same conditions until we reach our desired precision value in\n    our result. \n*/\n\nfunction find_minima(l, r) {\n    if (Math.abs(l - r) <= PRECISION) return func2(l);\n    else {\n        var m1 = l + (r - l) / 3;\n        var m2 = l + 2 * (r - l) / 3;\n        if (func2(m1) < func2(m2))\n            return find_minima(l, m2);\n        else if (func2(m1) > func2(m2))\n            return find_minima(m1, r);\n        return find_minima(m1, m2);\n    }\n}\n\n\nvar s1 = \"The maxima for func1 is \" + find_maxima(-1000000.0, 1000000.0);\nvar s2 = \"The minima for func2 is \" + find_minima(-1000000.0, 10000000.0);\nconsole.log(s1);\nconsole.log(s2);"
  },
  {
    "path": "Algorithms/Searching/Ternary-Search/unimodal_func.py",
    "content": "\"\"\" The main aim of this problem is to find the \nminimum and maximum value of a unimodal function\nusing the ternary search algorithm.\"\"\"\n\n\n\"\"\"This is the amount of error we are ready to tolerate in our answer.\"\"\"\nPRECISION = 0.0000001\n\n\"\"\" the unimodal function whose maxima has to be found.\nLet the range be [-10^9,10^9]\"\"\"\ndef func1(x):\n    return -x*x-2*x+3;\n\n\"\"\"the unimodal function whose minima has to be found.\nLet the range be [-10^9,10^9]\"\"\"\ndef func2(x):\n    return x*x-2*x+3;\n\n\n\"\"\"To find the maxima of a function we go in the following way:\n1. We choose any two points m1 and m2 such that l<=m1<=m2<=r.\n2. if func(m1)<func(m2){\n        we go for the range [m1,r]\n    }\n    else if func(m1)>func(m2){\n        we go for the range [l,m2]\n    }\n    else{\n        we reduce our space to [m1,m2]\n    }\n 3. Step 2 is repeated with same conditions until we reach our desired precision value in\n    our result.  \n\"\"\"\n\ndef find_maxima(l,r):\n    if(abs(l-r)<=PRECISION):\n        return func1(l)\n    else:\n        m1 = l+(r-l)/3;\n        m2 = l+2*(r-l)/3;\n        if(func1(m1)<func1(m2)):\n            return find_maxima(m1,r)\n        elif(func1(m1)>func1(m2)):\n            return find_maxima(l,m2)\n        return find_maxima(m1,m2);\n\n\"\"\"\nTo find the minima of a unimodal function we have to do the following task:\n1. We choose any two points m1 and m2 such that l<=m1<=m2<=r.\n2. if func(m1)<func(m2){\n        we go for the range [l,m2]\n    }\n    else if func(m1)>func(m2){\n        we go for the range [m1,r]\n    }\n    else{\n        we reduce our space to [m1,m2]\n    }\n 3. Step 2 is repeated with same conditions until we reach our desired precision value in\n    our result. \n\"\"\"\n\ndef find_minima(l,r):\n    if(abs(l-r)<=PRECISION):\n        return func2(l);\n    else:\n        m1 = l+(r-l)/3;\n        m2 = l+2*(r-l)/3;\n        if(func2(m1)<func2(m2)):\n            return find_minima(l,m2)\n        elif(func2(m1)>func2(m2)):\n            return find_minima(m1,r)\n        return find_minima(m1,m2)\n\n\ndef main_func():\n    print(\"maxima for func1: \", end=\"\")\n    print(find_maxima(-1000000000,1000000000))\n    print(\"minima for func2: \", end =\"\")\n    print(find_minima(-1000000000,1000000000))\n\nmain_func();"
  },
  {
    "path": "Algorithms/Searching/Trie-Search/Trie Data Structure.cpp",
    "content": "#include<iostream>\n#include<unordered_map>\nusing namespace std;\nclass Node{\npublic:\n    char data;\n    unordered_map<char,Node*> children;\n    bool terminal;\n    Node(char d){\n        data = d;\n        terminal = false;\n    }\n};\nclass Trie{\n    Node *root;\n    int cnt;\n\npublic:\n    Trie(){\n        root = new Node('\\0');\n        cnt = 0;\n    }\n    void insert(char *w){\n        Node *temp = root;\n        for(int i=0;i<w[i]!='\\0';i++){\n            char ch = w[i];\n            if(temp->children.count(ch)){\n                temp = temp->children[ch];\n            }\n            else{\n                Node *n = new Node(ch);\n                temp->children[ch] = n;\n                temp = n;\n            }\n        }\n        temp->terminal = true;\n    }\n    bool find(char *w){\n        Node *temp = root;\n        for(int i=0;i<w[i]!='\\0';i++){\n            char ch = w[i];\n            if(temp->children.count(ch)){\n                temp = temp->children[ch];\n            }\n            else{\n                return false;\n            }\n        }\n        return temp->terminal;\n    }\n};\n\nint main(){\n    Trie T;\n    char words[][10] = {\"a\",\"hello\",\"not\",\"news\",\"apple\",\"no\"};\n    for(int i=0;i<6;i++){\n        T.insert(words[i]);\n    }\n    char *w;\n    w = \"no\";\n    if(T.find(w)){\n        cout<<\"Present\";\n    }\n    else{\n        cout<<\"Absent\";\n    }\n}\n"
  },
  {
    "path": "Algorithms/Searching/Trie-Search/Trie1_HashMap.java",
    "content": "import java.util.HashMap;\nimport java.util.Map;\n\npublic class Trie1_HashMap{\n\n\tpublic static void main(String[] args) {\n\t\tTrie t=new Trie();\n\t\tt.insert(\"CAT\");\n\t\tt.insert(\"CAP\");\n\t\tt.insert(\"DOG\");\n\t\tt.insert(\"DAD\");\n\t\tt.insert(\"DADDY\");\n\t\tt.insert(\"COPY\");\n\t\tSystem.out.println(t.search(\"CAP\"));\n\t\t// t.display();\n\t}\n\n}\nclass TrieNode{\n\tchar data;\n\tMap<Character,TrieNode> next;\n\tboolean terminate;\n\t\n\tpublic TrieNode(char data,boolean terminate) {\n\t\tthis.data=data;\n\t\tnext=new HashMap<>();\n\t\tthis.terminate=terminate; \n\t}\n}\n\nclass Trie{\n\tTrieNode root;\n\t\n\tpublic Trie() {\n\t\tthis.root=new TrieNode('\\0',false);\n\t}\n\t\n\tpublic boolean search(String s) {\n\t\tTrieNode x=this.root;\n\t\tfor(int i=0;i<s.length();i++) {\n\t\t\tchar c=s.charAt(i);\n\t\t\tif(i+1 == s.length() && x.next.containsKey(c) && x.next.get(c).terminate) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\tif(!x.next.containsKey(c)) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tx=x.next.get(c);\n\t\t}\n\t\treturn false;\n\t}\n\n\tpublic void display() {\n\t\tdisplay(root);\n\t}\n\n\tprivate void display(TrieNode root) {\n\t\tif(root== null) {\n\t\t\treturn;\n\t\t}\n\t\tfor(Map.Entry<Character,TrieNode> e:root.next.entrySet()) {\n\t\t\tSystem.out.print(e.getValue().data+\" \"+e.getValue().terminate+\" \");\n\t\t\tdisplay(e.getValue());\n\t\t\tSystem.out.println();\n\t\t}\t\t\n\t}\n\n\tpublic void insert(String data) {\n\t\tinsert(root,data);\n\t}\n\n\tprivate void insert(TrieNode root, String s) {\n\n\t\tTrieNode x=root;\n\t\t\n\t\tfor(int i=0;i<s.length();i++) {\n\t\t\tchar c=s.charAt(i);\n\t\t\tif(i+1== s.length()) {\n\t\t\t\tx.next.put(c,new TrieNode(c,true));\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tif(!x.next.containsKey(c)) {\n\t\t\t\tx.next.put(c,new TrieNode(c,false));\n\t\t\t}\n\t\t\tx=x.next.get(c);\n\t\t}\n\n\t}\n\t\n\t\n\t\n}\n\n\n"
  },
  {
    "path": "Algorithms/Searching/Trie-Search/TrieDataStructure.java",
    "content": "\n\nimport java.util.*;\n\npublic class TrieDataStructure { \n            \n    //trie node defination\n    static class TrieNode \n    { \n        TrieNode[] children = new TrieNode[26]; \n       \n        boolean isEndOfWord; \n          \n        TrieNode(){ \n            isEndOfWord = false; \n            for (int i = 0; i < 26; i++) \n                children[i] = null; \n        } \n    }; \n       \n     \n      \n    static void insert(String key) \n    { \n        int level; \n        int length = key.length(); \n        int index; \n       \n        TrieNode p = root; \n       \n        for (level = 0; level < length; level++) \n        { \n            index = key.charAt(level) - 'a'; \n            if (p.children[index] == null) \n                p.children[index] = new TrieNode(); \n       \n            p = p.children[index]; \n        } \n       \n        p.isEndOfWord = true; \n    } \n       \n    static boolean search(String key) \n    { \n        int level; \n        int length = key.length(); \n        int index; \n        TrieNode p = root; \n       \n        for (level = 0; level < length; level++) \n        { \n            index = key.charAt(level) - 'a'; \n       \n            if (p.children[index] == null) \n                return false; \n       \n            p = p.children[index]; \n        } \n       \n        return (p != null && p.isEndOfWord); \n    } \n       \n    static TrieNode root; \n    public static void main(String args[]) \n    {  \n        String keys[] = {\"a\",\"hello\",\"not\",\"news\",\"apple\",\"no\"}; \n\n        root = new TrieNode(); \n        \n        for (int i = 0; i < keys.length ; i++) \n            insert(keys[i]); \n        \n        if(search(\"no\") == true) \n            System.out.println(\"Present\"); \n        else System.out.println(\"Absent\"); \n          \n        if(search(\"news\") == true) \n            System.out.println(\"Present\"); \n        else System.out.println(\"Absent\");\n          \n        if(search(\"trie\") == true) \n            System.out.println(\"Present\"); \n        else System.out.println(\"Absent\"); \n           \n         \n    } \n} "
  },
  {
    "path": "Algorithms/Searching/Trie-Search/Trie_Search.cpp",
    "content": "#include <stdio.h>\n#include <stdlib.h>\n\n// define character size\n#define CHAR_SIZE 26\n\n// A Trie node\nstruct Trie\n{\n\tint isLeaf;\t// 1 when node is a leaf node\n\tstruct Trie* character[CHAR_SIZE];\n};\n\n// Function that returns a new Trie node\nstruct Trie* getNewTrieNode()\n{\n\tstruct Trie* node = (struct Trie*)malloc(sizeof(struct Trie));\n\tnode->isLeaf = 0;\n\n\tfor (int i = 0; i < CHAR_SIZE; i++)\n\t\tnode->character[i] = NULL;\n\n\treturn node;\n}\n\n// Iterative function to insert a string in Trie\nvoid insert(struct Trie *head, char* str)\n{\n\t// start from root node\n\tstruct Trie* curr = head;\n\twhile (*str)\n\t{\n\t\t// create a new node if path doesn't exists\n\t\tif (curr->character[*str - 'a'] == NULL)\n\t\t\tcurr->character[*str - 'a'] = getNewTrieNode();\n\n\t\t// go to next node\n\t\tcurr = curr->character[*str - 'a'];\n\n\t\t// move to next character\n\t\tstr++;\n\t}\n\n\t// mark current node as leaf\n\tcurr->isLeaf = 1;\n}\n\n// Iterative function to search a string in Trie. It returns 1\n// if the string is found in the Trie, else it returns 0\nint search(struct Trie* head, char* str)\n{\n\t// return 0 if Trie is empty\n\tif (head == NULL)\n\t\treturn 0;\n\n\tstruct Trie* curr = head;\n\twhile (*str)\n\t{\n\t\t// go to next node\n\t\tcurr = curr->character[*str - 'a'];\n\n\t\t// if string is invalid (reached end of path in Trie)\n\t\tif (curr == NULL)\n\t\t\treturn 0;\n\n\t\t// move to next character\n\t\tstr++;\n\t}\n\n\t// if current node is a leaf and we have reached the\n\t// end of the string, return 1\n\treturn curr->isLeaf;\n}\n\n// returns 1 if given node has any children\nint haveChildren(struct Trie* curr)\n{\n\tfor (int i = 0; i < CHAR_SIZE; i++)\n\t\tif (curr->character[i])\n\t\t\treturn 1;\t// child found\n\n\treturn 0;\n}\n\n// Recursive function to delete a string in Trie\nint deletion(struct Trie **curr, char* str)\n{\n\t// return if Trie is empty\n\tif (*curr == NULL)\n\t\treturn 0;\n\n\t// if we have not reached the end of the string\n\tif (*str)\n\t{\n\t\t// recur for the node corresponding to next character in\n\t\t// the string and if it returns 1, delete current node\n\t\t// (if it is non-leaf)\n\t\tif (*curr != NULL && (*curr)->character[*str - 'a'] != NULL &&\n\t\t\tdeletion(&((*curr)->character[*str - 'a']), str + 1) &&\n\t\t\t(*curr)->isLeaf == 0)\n\t\t{\n\t\t\tif (!haveChildren(*curr))\n\t\t\t{\n\t\t\t\tfree(*curr);\n\t\t\t\t(*curr) = NULL;\n\t\t\t\treturn 1;\n\t\t\t}\n\t\t\telse {\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t}\n\t}\n\n\t// if we have reached the end of the string\n\tif (*str == '\\0' && (*curr)->isLeaf)\n\t{\n\t\t// if current node is a leaf node and don't have any children\n\t\tif (!haveChildren(*curr))\n\t\t{\n\t\t\tfree(*curr); // delete current node\n\t\t\t(*curr) = NULL;\n\t\t\treturn 1; // delete non-leaf parent nodes\n\t\t}\n\n\t\t// if current node is a leaf node and have children\n\t\telse\n\t\t{\n\t\t\t// mark current node as non-leaf node (DON'T DELETE IT)\n\t\t\t(*curr)->isLeaf = 0;\n\t\t\treturn 0;\t\t// don't delete its parent nodes\n\t\t}\n\t}\n\n\treturn 0;\n}\n\n// Trie Implementation in C - Insertion, Searching and Deletion\nint main()\n{\n\tstruct Trie* head = getNewTrieNode();\n\n\tinsert(head, \"hello\");\n\tprintf(\"%d \", search(head, \"hello\"));\t\t// print 1\n\n\tinsert(head, \"helloworld\");\n\tprintf(\"%d \", search(head, \"helloworld\"));  // print 1\n\n\tprintf(\"%d \", search(head, \"helll\"));\t\t// print 0 (Not present)\n\n\tinsert(head, \"hell\");\n\tprintf(\"%d \", search(head, \"hell\"));\t\t// print 1\n\n\tinsert(head, \"h\");\n\tprintf(\"%d \\n\", search(head, \"h\")); \t\t// print 1 + newline\n\n\tdeletion(&head, \"hello\");\n\tprintf(\"%d \", search(head, \"hello\"));\t\t// print 0 (hello deleted)\n\tprintf(\"%d \", search(head, \"helloworld\"));  // print 1\n\tprintf(\"%d \\n\", search(head, \"hell\"));  \t// print 1 + newline\n\n\tdeletion(&head, \"h\");\n\tprintf(\"%d \", search(head, \"h\"));\t\t\t// print 0 (h deleted)\n\tprintf(\"%d \", search(head, \"hell\"));\t\t// print 1\n\tprintf(\"%d\\n\", search(head, \"helloworld\")); // print 1 + newline\n\n\tdeletion(&head, \"helloworld\");\n\tprintf(\"%d \", search(head, \"helloworld\"));  // print 0\n\tprintf(\"%d \", search(head, \"hell\"));\t\t// print 1\n\n\tdeletion(&head, \"hell\");\n\tprintf(\"%d\\n\", search(head, \"hell\"));\t\t// print 0 + newline\n\n\tif (head == NULL)\n\t\tprintf(\"Trie empty!!\\n\");\t\t\t\t// Trie is empty now\n\n\tprintf(\"%d \", search(head, \"hell\"));\t\t// print 0\n\n\treturn 0;\n}\n"
  },
  {
    "path": "Algorithms/Searching/Trie-Search/Trie_Search.go",
    "content": "package main\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n)\n\n// Trie structure\ntype Trie struct {\n\troot *trieNode\n}\n\ntype trieNode struct {\n\tchildren [26]*trieNode\n\twordEnd  bool\n}\n\n// Constructor initialize the Trie data structure\nfunc Constructor() Trie {\n\treturn Trie{\n\t\troot: &trieNode{},\n\t}\n}\n\n// Insert a word into the trie\nfunc (this *Trie) Insert(word string) {\n\tword = strings.ToLower(word)\n\tcurrent := this.root\n\tfor i := 0; i < len(word); i++ {\n\t\tindex := word[i] - 'a'\n\t\tif current.children[index] == nil {\n\t\t\tcurrent.children[index] = &trieNode{}\n\t\t}\n\t\tcurrent = current.children[index]\n\t}\n\tcurrent.wordEnd = true\n}\n\n// Search returns if the word is in the trie\nfunc (this *Trie) Search(word string) bool {\n\tword = strings.ToLower(word)\n\tcurrent := this.root\n\tfor i := 0; i < len(word); i++ {\n\t\tindex := word[i] - 'a'\n\t\tif current.children[index] == nil {\n\t\t\treturn false\n\t\t}\n\t\tcurrent = current.children[index]\n\t}\n\tif current.wordEnd {\n\t\treturn true\n\t}\n\treturn false\n}\n\nfunc main() {\n\tinsertWords := []string{\"hello\", \"world\", \"golang\", \"trie\", \"tree\"}\n\tsearchWords := []string{\n\t\t\"world\",  /* true */\n\t\t\"Golang\", /* true */\n\t\t\"word\",   /* false */\n\t}\n\n\ttrie := Constructor()\n\n\tfor _, node := range insertWords {\n\t\ttrie.Insert(node)\n\t}\n\n\tfor _, node := range searchWords {\n\t\tfound := trie.Search(node)\n\t\tif found {\n\t\t\tfmt.Println(node, \": Found in the trie\")\n\t\t} else {\n\t\t\tfmt.Println(node, \": Not found in the trie\")\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "Algorithms/Searching/Trie-Search/Trie_Search.py",
    "content": "# Program for Trie Insert and Search\n\n# Trie node\nclass TrieNode:\n\tdef __init__(self):\n\t\tself.children = [None]*26\n\t\tself.isEndOfWord = False\n\n# Trie Class\nclass Trie:\n\tdef __init__(self):\n\t\tself.root = self.getNode()\n\n\tdef getNode(self):\n\t\treturn TrieNode()\n\n\tdef toIndex(self, ch):\n\t\treturn ord(ch)-ord('a')\n\n\t# Function to Insert into Trie\n\tdef insert(self, key):\n\t\tnode = self.root\n\t\tlength = len(key)\n\n\t\tfor i in range(length):\n\t\t\tidx = self.toIndex(key[i])\n\t\t\tif not node.children[idx]:\n\t\t\t\tnode.children[idx] = self.getNode()\n\t\t\tnode = node.children[idx]\n\t\tnode.isEndOfWord = True\n\n\t# Function for Trie Search\n\tdef search(self, key):\n\t\tnode = self.root\n\t\tlength = len(key)\n\n\t\tfor i in range(length):\n\t\t\tidx = self.toIndex(key[i])\n\t\t\tif not node.children[idx]:\n\t\t\t\treturn False\n\t\t\tnode = node.children[idx]\n\t\treturn node!=None and node.isEndOfWord\n\n\n# Main function \n# To test code, please edit keys list and print statements for search\ndef main():\n\tkeys = [\"the\",\"apple\",\"there\",\"hello\",\"world\", \"by\",\"python\"]\n\toutput = [\"Not present in trie\", \"Present in trie\"]\n\n\t# Construct Trie\n\ttrie = Trie()\n\n\tfor key in keys:\n\t\ttrie.insert(key)\n\n\n\t# Search in trie\n\tprint(\"{} => {}\".format(\"the\", output[trie.search(\"the\")]))\n\tprint(\"{} => {}\".format(\"hi\", output[trie.search(\"hi\")]))\n\tprint(\"{} => {}\".format(\"apple\", output[trie.search(\"apple\")]))\n\tprint(\"{} => {}\".format(\"man\", output[trie.search(\"man\")]))\n\nif __name__ == '__main__':\n\tmain()\n\n## Sample Output ##\n# the => Present in trie\n# hi => Not present in trie\n# apple => Present in trie\n# man => Not present in trie"
  },
  {
    "path": "Algorithms/Sorting/3-Way_Quick_Sort/3-Way_Quick_Sort.cpp",
    "content": "/*\r\nAuthor: immortal-j\r\nImplementation Details\r\nQuick sort 3 works on Dutch National Flag Algorithm\r\nThe major diffrence between simple quicksort and quick sort 3 comes in the function quick_sort_partition3\r\nIn quick_sort_partition3 we divide the vector/array into 3 parts i.e\r\na[0...q_l]-->less than pivot\r\na[q_l+1...q_e-1]-->Equal to pivot\r\na[q_e...r]-->Greater than pivot\r\nquick sort 3 works faster in some cases as compared to simple quicksort.\r\n*/\r\n#include <iostream>\r\n#include <vector>\r\n#include <cstdlib>\r\n\r\n/*This function takes first element as pivot, places  \r\n  the pivot element at its correct position in sorted  \r\n  array*/\r\nstd::vector<int> quick_sort_partition3(std::vector<int> &arr, int low, int high) {\r\n    int x = arr[low];//taking first element as pivot\r\n    int q_l = low;//We initiate q_l to be the part that is less than the pivot\r\n    int count = low;\r\n    int q_e = high;// The part that is greater than the pivot\r\n    std::vector<int> m(2);//this vector is used to return positions of higher and lower\r\n    while (count <= q_e) {\r\n        if (arr[count] < x) {\r\n            std::swap(arr[q_l], arr[count]);\r\n            q_l++;\r\n            count++;//increment index\r\n        } else if (arr[count] == x) {\r\n            count++;//increment index\r\n        } else {\r\n            std::swap(arr[count], arr[q_e]);\r\n            q_e -= 1;\r\n        }\r\n        m[0] = q_l;\r\n        m[1] = q_e;\r\n    }\r\n    return m;\r\n}\r\n/*\r\narr-->vector to be sorted \r\nlow-->Starting index\r\nhigh-->Ending Index\r\n*/\r\nvoid randomized_quick_sort(std::vector<int> &arr, int low, int high) {\r\n    if (low >= high) {\r\n        return;\r\n    }\r\n    int random = low + rand() % (high - low + 1);//provides a random index;\r\n    std::swap(arr[low], arr[random]);\r\n    std::vector<int> m = quick_sort_partition3(arr, low, high);\r\n    randomized_quick_sort(arr, low, m[0] - 1);\r\n    randomized_quick_sort(arr, m[1] + 1, high);\r\n}\r\n//Driver program to test above functions \r\nint main() {\r\n    int sizeofvector;\r\n    std::cin >> sizeofvector;\r\n    std::vector<int> arr(sizeofvector);\r\n    for (size_t i = 0; i < arr.size(); ++i) {\r\n        std::cin >> arr[i];\r\n    }\r\n    randomized_quick_sort(arr, 0, arr.size() - 1);\r\n    //prints vector/array after sorting\r\n    for (size_t i = 0; i < arr.size(); ++i) {\r\n        std::cout << arr[i] << ' ';\r\n    }\r\n    return 0;\r\n}"
  },
  {
    "path": "Algorithms/Sorting/3-Way_Quick_Sort/3-Way_Quick_Sort.cs",
    "content": "\nusing System;\n\nclass Sort {\n\t\n\tstatic void swap<T>(ref T lhs, ref T rhs)\n\t{\n\t\tT temp;\n\t\ttemp = lhs;\n\t\tlhs = rhs;\n\t\trhs = temp;\n\t}\n\n\tpublic static void partition(int[] a, int l, int r, ref int i, ref int j)\n\t{\n\t\ti = l - 1;\n\t\tj = r;\n\t\tint p = l - 1, q = r;\n\t\tint v = a[r];\n\n\t\twhile (true) {\n\t\t\t\n\t\t\twhile (a[++i] < v)\n\t\t\t\t;\n\n\t\t\twhile (v < a[--j])\n\t\t\t\tif (j == l)\n\t\t\t\t\tbreak;\n\n\t\t\n\t\t\tif (i >= j)\n\t\t\t\tbreak;\n\n\t\t\n\t\t\tswap(ref a[i], ref a[j]);\n\n\t\t\t\n\t\t\tif (a[i] == v) {\n\t\t\t\tp++;\n\t\t\t\tswap(ref a[p], ref a[i]);\n\t\t\t}\n\n\t\t\t\n\t\t\tif (a[j] == v) {\n\t\t\t\tq--;\n\t\t\t\tswap(ref a[j], ref a[q]);\n\t\t\t}\n\t\t}\n\n\n\t\tswap(ref a[i], ref a[r]);\n\n\t\tj = i - 1;\n\t\tfor (int k = l; k < p; k++, j--)\n\t\t\tswap(ref a[k], ref a[j]);\n\n\t\ti = i + 1;\n\t\tfor (int k = r - 1; k > q; k--, i++)\n\t\t\tswap(ref a[i], ref a[k]);\n\t}\n\n\n\tpublic static void quicksort(int[] a, int l, int r)\n\t{\n\t\tif (r <= l)\n\t\t\treturn;\n\n\t\tint i = 0, j = 0;\n\n\n\t\tpartition(a, l, r, ref i, ref j);\n\n\t\tquicksort(a, l, j);\n\t\tquicksort(a, i, r);\n\t}\n\n\t\n\tpublic static void printarr(int[] a, int n)\n\t{\n\t\tfor (int i = 0; i < n; ++i)\n\t\t\tConsole.Write(a[i] + \" \");\n\t\tConsole.Write(\"\\n\");\n\t}\n\n\t\n\tstatic void Main()\n\t{\n\t\tint[] a = { 4, 9, 4, 4, 1, 9, 4, 4, 9, 4, 4, 1, 4 };\n\t\tint size = a.Length;\n\t\t\n\t\t\n\t\tprintarr(a, size);\n\t\tquicksort(a, 0, size - 1);\n\t\tprintarr(a, size);\n\t}\n}\n"
  },
  {
    "path": "Algorithms/Sorting/3-Way_Quick_Sort/3-Way_Quick_Sort.java",
    "content": "import java.io.BufferedReader;\nimport java.io.IOException;\nimport java.io.InputStreamReader;\n\npublic class QuickSort {\n\t\n\tprivate static void swap(Comparable[] arr, int first, int second)\n\t{\t// Swaps the two array elements with indices passed as arguments.\n\t\tComparable temp = arr[first];\n\t\tarr[first] = arr[second];\n\t\tarr[second] = temp;\n\t}\n\n\t\n\tprivate static void quickSort3Way(Comparable[] arr, int low, int high)\n\t{\t/*\n\t\t\tarr: Array to be sorted using the Three Way QuickSort Algorithm\n\t\t\tlow: The starting index of a subarray\n\t\t\thigh: The ending index of a subarray\n\t\t*/\n\t\t\n\t\t// No partitioning for subarrays of size 1 or below.\n\t\tif(high <= low) return;\n\n\t\t// Partitioning item value\n\t\tComparable v = arr[low];\n\t\t\n\t\t// Three variables lesser, i and greater are used for the corresponding partitions to be made.\n\t\t// lesser partition i.e. arr[low .. lesser - 1] denotes the partition with items of value less than the partitioning item v.\n\t\t// greater partition i.e arr[greater + 1 .. high] denotes the partition with items of value greater than the partitioning item v.\n\t\t// equals partition i.e. arr[lesser .. greater] denotes the partition with items of value equal to the partitioning item v.\n\t\t// variable i represents the current element that is to be put into one of the above three partitions.\n\t\tint lesser = low, i = low + 1, greater = high;\n\n\t\twhile(i <= greater)\n\t\t{\n\t\t\tint cmp = arr[i].compareTo(v);\n\t\t\tif(cmp < 0) swap(arr, lesser++, i++);\n\t\t\telse if(cmp > 0) swap(arr, i, greater--);\n\t\t\telse i++;\n\t\t}\n\t\tquickSort3Way(arr, low, lesser-1);\n\t\tquickSort3Way(arr, greater+1, high);\n\t}\n\t\n\tprivate static void printSortedArray(Comparable[] arr)\n\t{\t// Prints the sorted array as output.\n\t\tfor(int index=0; index<arr.length; index++)\n\t\t\tSystem.out.print(arr[index]+\" \");\n\t\tSystem.out.println();\n\t}\n\t\n\tpublic static void main(String[] args) throws IOException\n\t{\n\t\tBufferedReader reader = new BufferedReader(new InputStreamReader(System.in));\n\t\tString[] arr = reader.readLine().split(\" \"); // String[] used in this implementation. Any data type implementing the Comparable interface can be used in it's place.\n\t\tquickSort3Way(arr, 0, arr.length-1); // Sort the input array using the Three Way QuickSort Algorithm.\n\t\tprintSortedArray(arr); // Print the output as the sorted array.\n\t}\n}\n"
  },
  {
    "path": "Algorithms/Sorting/3-Way_Quick_Sort/3_Way_Quick_Sort.c",
    "content": "#include<stdio.h>\r\n#include<stdlib.h>\r\n\r\nvoid swap(int &x, int &y)\r\n{\r\n\tint temp = x;\r\n\tx = y;\r\n\ty = temp;\r\n}\r\n\r\nvoid partition(int a[], int l, int r, int& i, int& j)\r\n{\r\n\ti = l - 1, j = r;\r\n\tint p = l - 1, q = r;\r\n\tint v = a[r];\r\n\r\n\twhile (true) {\r\n\r\n\t\twhile (a[++i] < v);\r\n\r\n\t\twhile (v < a[--j])\r\n\t\t\tif (j == l)\r\n\t\t\t\tbreak;\r\n\t\tif (i >= j)\r\n\t\t\tbreak;\r\n\r\n\t\tswap(a[i], a[j]);\r\n\t\tif (a[i] == v) {\r\n\t\t\tp++;\r\n\t\t\tswap(a[p], a[i]);\r\n\t\t}\r\n\t\tif (a[j] == v) {\r\n\t\t\tq--;\r\n\t\t\tswap(a[j], a[q]);\r\n\t\t}\r\n\t}\r\n\tswap(a[i], a[r]);\r\n\tj = i - 1;\r\n\tfor (int k = l; k < p; k++, j--)\r\n\t\tswap(a[k], a[j]);\r\n\r\n\ti = i + 1;\r\n\tfor (int k = r - 1; k > q; k--, i++)\r\n\t\tswap(a[i], a[k]);\r\n}\r\n\r\nvoid quicksort(int a[], int l, int r)\r\n{\r\n\tif (r <= l)\r\n\t\treturn;\r\n\tint i, j;\r\n\tpartition(a, l, r, i, j);\r\n\tquicksort(a, l, j);\r\n\tquicksort(a, i, r);\r\n}\r\n\r\nvoid printarr(int a[], int n)\r\n{\r\n\tfor (int i = 0; i < n; ++i)\r\n\t\tprintf(\"%d \", a[i]);\r\n\tprintf(\"\\n\");\r\n}\r\n\r\nint main()\r\n{\r\n\tint n;\r\n\tscanf(\"%d\", &n);\r\n\r\n\tint ar[n];\r\n\tfor (int i = 0; i < n; i++)\r\n\t\tscanf(\"%d\", &ar[i]);\r\n\r\n\tprintf(\"Before Sorting: \");\r\n\tprintarr(ar, n);\r\n\tquicksort(ar, 0, n - 1);\r\n\tprintf(\"After Sorting: \");\r\n\tprintarr(ar, n);\r\n\treturn 0;\r\n}\r\n"
  },
  {
    "path": "Algorithms/Sorting/Bead_Sort/Bead_Sort.php",
    "content": "<?php\nfunction columns($my_array) {\n    if (count($my_array) == 0)\n        return array();\n    else if (count($my_array) == 1)\n        return array_chunk($my_array[0], 1);\n     array_unshift($my_array, NULL);\n    // array_map(NULL, $my_array[0], $my_array[1], ...)\n    $transpose = call_user_func_array('array_map', $my_array);\n    return array_map('array_filter', $transpose);\n}\nfunction bead_sort($my_array) {\n    foreach ($my_array as $e)\n        $poles []= array_fill(0, $e, 1);\n    return array_map('count', columns(columns($poles)));\n}\n$test_array = array(3, 2, 5, 4, 1, 100);\necho \"\\nOriginal Array :\\n\";\necho implode(', ',$test_array );\necho \"\\nSorted Array :\\n\";\necho implode(', ',bead_sort($test_array)). PHP_EOL;\n"
  },
  {
    "path": "Algorithms/Sorting/Bead_Sort/Bead_Sort.rb",
    "content": "class Array\n  def beadsort\n    map {|e| [1] * e}.columns.columns.map(&:length)\n  end\n \n  def columns\n    y = length\n    x = map(&:length).max\n    Array.new(x) do |row|\n      Array.new(y) { |column| self[column][row] }.compact\n    end\n  end\nend\n \np [5,3,1,7,4,1,1].beadsort\n"
  },
  {
    "path": "Algorithms/Sorting/Bead_Sort/Bead_sort.cpp",
    "content": "#include <bits/stdc++.h>\nusing namespace std;\nvoid beadSort(int *a, int len)\n{\n    int max = a[0];\n    for (int i = 1; i < len; i++)\n        if (a[i] > max)\n           max = a[i];\n\n    char beads[max*len];\n    memset(beads, 0, sizeof(beads));\n    for (int i = 0; i < len; i++)\n        for (int j = 0; j < a[i]; j++)\n            beads[i*max +j] = 1;\n\n    for (int j = 0; j < max; j++)\n    {\n        int sum = 0;\n        for (int i=0; i < len; i++)\n        {\n            sum += beads[i*max +j];\n            beads[i*max +j] = 0;\n        }\n\n        for (int i = len - sum; i < len; i++)\n            beads[i*max +j] = 1;\n    }\n\n    for (int i = 0; i < len; i++)\n    {\n        int j;\n        for (j = 0; j < max && beads[i*max +j]; j++);\n        a[i] = j;\n    }\n}\nint main()\n{\n    int n;\n    cout<<\"enter the no of element in array :\";\n    cin>>n;\n    cout<<\"enter the elements: \";\n    int a[n];\n    for(int i=0;i<n;i++) cin>>a[i];\n    beadSort(a, n);\n    for (int i = 0; i < n; i++)\n        printf(\"%d \", a[i]);\n\n    return 0;\n}\n"
  },
  {
    "path": "Algorithms/Sorting/Bead_Sort/README.md",
    "content": "## BEAD SORTING:\n\nBead Sort is also known as Gravity Sort.\n\nThis algorithm was inspired from natural phenomenons and was designed keeping in beads of abacus in mind falling under the influence of gravity.\n\n**For Example:**\n1. Imagine a abacus sorted in a pattern of 7,2,1,4,2. Now, imagine that this is the position of the beads at time t = 0 and with every passing second the beads will fall down by one level provided there is no bead already present below them. In such a case, they just rest upon the bead below them.\n\n2. Now, at time t = 1 the bottom 2 beads in the first two rods from the left stay at their positions while the second bead from the top from the second rod comes down by one level to rest upon the bead below it. The beads in the 3rd and 4th rod at level 2 come down to level 1. Simultaneously, the beads in the rods 3 to 7 come down by one level. Now, the numbers from top to bottom become: 2, 6, 2, 2, 4.\n\n3. This goes on till time t = 4 where we get the sorted sequence of numbers from top to bottom which is: 1, 2, 2, 4, 7.\n\nSo, INPUT: 7,2,1,4,2.\nOUTPUT: 2,6,2,2,4.\n"
  },
  {
    "path": "Algorithms/Sorting/Bead_Sort/bead_sort.py",
    "content": "def bead_sort(obj):\n    if all([type(x) == int and x >= 0 for x in obj]):\n        ref = [range(x) for x in obj]  #for reference\n    else:\n        raise ValueError(\"All elements must be positive integers\")\n    inter = []  #for intermediate\n    ind = 0  #for index\n    prev = sum([1 for x in ref if len(x) > ind])  #prev for previous\n    while prev:\n        inter.append(range(prev))\n        ind += 1\n        prev = sum([1 for x in ref if len(x) > ind])\n    ind = 0\n    prev = sum([1 for x in inter if len(x) > ind])\n    out = []\n    while prev:\n        out.append(prev)\n        ind += 1\n        prev = sum([1 for x in inter if len(x) > ind])\n    out = out[::-1]\n    return out\n    \n\na=[2,4,3,5,1]\nprint(bead_sort(a))\n"
  },
  {
    "path": "Algorithms/Sorting/Binary_Insertion_Sort/Binary Insertion Sort.c",
    "content": "// C program for implementation of binary insertion sort,Time Complexity : O(n^2)\n\n\n\n#include <stdio.h> \n\nint binarySearch(int a[], int item, int low, int high) \n{ \n    if (high <= low) \n        return (item > a[low])?  (low + 1): low; \n  \n    int mid = (low + high)/2; \n  \n    if(item == a[mid]) \n        return mid+1; \n  \n    if(item > a[mid]) \n        return binarySearch(a, item, mid+1, high); \n    return binarySearch(a, item, low, mid-1); \n} \n  \n// Function to sort an array a[] of size 'n' \nvoid insertionSort(int a[], int n) \n{ \n    int i, loc, j, k, selected; \n  \n    for (i = 1; i < n; ++i) \n    { \n        j = i - 1; \n        selected = a[i]; \n  \n        // find location where selected sould be inseretd \n        loc = binarySearch(a, selected, 0, j); \n  \n        // Move all elements after location to create space \n        while (j >= loc) \n        { \n            a[j+1] = a[j]; \n            j--; \n        } \n        a[j+1] = selected; \n    } \n} \n  \n\nint main() \n{ \n    int n,i;\n    scanf(\"%d\",&n);\n    int arrr[n];\n\n    for (i = 0; i < n; i++) \n        scanf(\"%d\",&a[i]);\n\n    insertionSort(a, n); \n  \n    printf(\"Sorted array: \\n\"); \n    for (i = 0; i < n; i++) \n        printf(\"%d \",a[i]); \n  \n    return 0; \n} "
  },
  {
    "path": "Algorithms/Sorting/Binary_Insertion_Sort/Binary_Insertion_Sort.cpp",
    "content": "// C program for implementation of binary insertion sort \n#include <stdio.h> \n\nint binarySearch(int a[], int item, int low, int high) \n{ \n\tif (high <= low) \n\t\treturn (item > a[low])? (low + 1): low; \n\n\tint mid = (low + high)/2; \n\n\tif(item == a[mid]) \n\t\treturn mid+1; \n\n\tif(item > a[mid]) \n\t\treturn binarySearch(a, item, mid+1, high); \n\treturn binarySearch(a, item, low, mid-1); \n} \n\n// Function to sort an array a[] of size 'n' \nvoid insertionSort(int a[], int n) \n{ \n\tint i, loc, j, k, selected; \n\n\tfor (i = 1; i < n; ++i) \n\t{ \n\t\tj = i - 1; \n\t\tselected = a[i]; \n\n\t\t// find location where selected sould be inseretd \n\t\tloc = binarySearch(a, selected, 0, j); \n\n\t\t// Move all elements after location to create space \n\t\twhile (j >= loc) \n\t\t{ \n\t\t\ta[j+1] = a[j]; \n\t\t\tj--; \n\t\t} \n\t\ta[j+1] = selected; \n\t} \n} \n\nint main() \n{ \n\tint a[] = {37, 23, 0, 17, 12, 72, 31, \n\t\t\t46, 100, 88, 54}; \n\tint n = sizeof(a)/sizeof(a[0]), i; \n\n\tinsertionSort(a, n); \n\n\tprintf(\"Sorted array: \\n\"); \n\tfor (i = 0; i < n; i++) \n\t\tprintf(\"%d \",a[i]); \n\n\treturn 0; \n} \n"
  },
  {
    "path": "Algorithms/Sorting/Binary_Insertion_Sort/Binary_Insertion_Sort.py",
    "content": "import bisect\n\ndef binsertion_sort(arr):\n    '''\n    Author: Kinshuk Dua (@kinshukdua)\n    Python program to perform binary insertion sort\n    Comparison complexity O(nlogn)\n    Sorting complexity O(n^2)\n    '''\n    for i in range(1,len(arr)):\n        bisect.insort(arr, arr.pop(i), 0, i)\n    return\n\n#testing\narr = [5,4,3,2,1]\nbinsertion_sort(arr)\nprint(arr)"
  },
  {
    "path": "Algorithms/Sorting/Binary_Insertion_Sort/Readme.md",
    "content": "# BINARY INSERTION SORTING\n\nBinary search is used to reduce the number of comparisons in Insertion sort. This modification is known as Binary Insertion Sort.\n\nBinary Insertion Sort use binary search to find the proper location to insert the selected item at each iteration. In insertion sort, it takes O(i) at ith iteration in worst case. Using binary search, it is reduced to O(log i).\n\n**For Example:**\n\nIf we know insertion sort and binary search already, then its pretty straight forward. When we insert a piece in insertion sort, we must compare to all previous pieces.Like if we want to move this [2] to the correct place, we would have to compare to 7 pieces before we find the right place.\n[1][3][3][3][4][4][5] ->[2]<- [11][0][50][47]\n\nHowever, if we start the comparison at the half way point (like a binary search), then we will only compare to 4 pieces! This can be done because we know the left pieces are already in order.\n"
  },
  {
    "path": "Algorithms/Sorting/Bitonic_Search/BitonicSort.java",
    "content": "/* Java program for Bitonic Sort. Size of input should always be a power of 2. */\npublic class BitonicSort \n{ \n\t\n\n\t/* Sorts a bitonic sequence recursively in ascending \n\torder, if arr = 1, and in descending order otherwise \n\t(means arr=0). The sequence to be sorted starts at \n\tindex position low, the parameter cnt is the number \n\tof elements to be sorted.*/\n\tvoid merge(int a[], int low, int cnt, int arr) \n\t{ \n\t\tif (cnt>1) \n\t\t{ \n\t\t\tint k = cnt/2; \n\t\t\tfor (int i=low; i<low+k; i++) \n\t\t\t\tswap(a,i, i+k, arr); \n\t\t\tmerge(a,low, k, arr); \n\t\t\tmerge(a,low+k, k, arr); \n\t\t} \n\t} \n\t\n\t/* The arr indicates the sorting direction, \n\tASCENDING or DESCENDING; if (a[i] > a[j]) agrees \n\twith the direction, then a[i] and a[j] are \n\tinterchanged. */\n\tvoid swap(int a[], int i, int j, int arr) \n\t{ \n\t\tif ( (a[i] > a[j] && arr == 1) || \n\t\t\t(a[i] < a[j] && arr == 0)) \n\t\t{ \n\t\t\t// Swap elements \n\t\t\tint temp = a[i]; \n\t\t\ta[i] = a[j]; \n\t\t\ta[j] = temp; \n\t\t} \n\t} \n\n\t/* A bitonic sequence is produced by \n\trecursively sorting its two halves in opposite sorting \n\torders, and then calls merge to make them in \n\tthe same order */\n\tvoid bitonicSort(int a[], int low, int cnt, int arr) \n\t{ \n\t\tif (cnt>1) \n\t\t{ \n\t\t\tint k = cnt/2; \n\n\t\t\t// sort in ascending order since arr here is 1 \n\t\t\tbitonicSort(a, low, k, 1); \n\n\t\t\t// sort in descending order since arr here is 0 \n\t\t\tbitonicSort(a,low+k, k, 0); \n\n\t\t\t// Will merge wole sequence in ascending order \n\t\t\t// since arr=1. \n\t\t\tmerge(a, low, cnt, arr); \n\t\t} \n\t} \n\n\t/* bitonicSort is called here for sorting the entire array \n\tof length N in ASCENDING order */\n\tvoid sort(int a[], int N, int up) \n\t{ \n\t\tbitonicSort(a, 0, N, up); \n\t} \n\n\t/* A utility function to print array of size n */\n\tstatic void printArray(int arr[]) \n\t{ \n\t\tint n = arr.length; \n\t\tfor (int i=0; i<n; ++i) \n\t\t\tSystem.out.print(arr[i] + \" \"); \n\t\tSystem.out.println(); \n\t} \n\n\t// Driver method \n\tpublic static void main(String args[]) \n\t{ \n\t\tint a[] = {5,7,2,4}; \n\t\tint up = 1; \n\t\tBitonicSort ob = new BitonicSort(); \n\t\tob.sort(a, a.length,up); \n\t\tSystem.out.println(\"\\nSorted array\"); \n\t\tprintArray(a); \n\t} \n} \n"
  },
  {
    "path": "Algorithms/Sorting/Bitonic_Search/Bitonic_sort.c",
    "content": "/* C++ Program for Bitonic Sort. Note that this program\n\t works only when size of input is a power of 2. */\n#include<bits/stdc++.h>\nusing namespace std;\n\n/*The parameter dir indicates the sorting direction, ASCENDING\nor DESCENDING; if (a[i] > a[j]) agrees with the direction,\nthen a[i] and a[j] are interchanged.*/\nvoid compAndSwap(int a[], int i, int j, int dir)\n{\n\tif (dir==(a[i]>a[j]))\n\t\tswap(a[i],a[j]);\n}\n\n/*It recursively sorts a bitonic sequence in ascending order,\nif dir = 1, and in descending order otherwise (means dir=0).\nThe sequence to be sorted starts at index position low,\nthe parameter cnt is the number of elements to be sorted.*/\nvoid bitonicMerge(int a[], int low, int cnt, int dir)\n{\n\tif (cnt>1)\n\t{\n\t\tint k = cnt/2;\n\t\tfor (int i=low; i<low+k; i++)\n\t\t\tcompAndSwap(a, i, i+k, dir);\n\t\tbitonicMerge(a, low, k, dir);\n\t\tbitonicMerge(a, low+k, k, dir);\n\t}\n}\n\n/* This function first produces a bitonic sequence by recursively\n\tsorting its two halves in opposite sorting orders, and then\n\tcalls bitonicMerge to make them in the same order */\nvoid bitonicSort(int a[],int low, int cnt, int dir)\n{\n\tif (cnt>1)\n\t{\n\t\tint k = cnt/2;\n\n\t\t// sort in ascending order since dir here is 1\n\t\tbitonicSort(a, low, k, 1);\n\n\t\t// sort in descending order since dir here is 0\n\t\tbitonicSort(a, low+k, k, 0);\n\n\t\t// Will merge wole sequence in ascending order\n\t\t// since dir=1.\n\t\tbitonicMerge(a,low, cnt, dir);\n\t}\n}\n\n/* Caller of bitonicSort for sorting the entire array of\nlength N in ASCENDING order */\nvoid sort(int a[], int N, int up)\n{\n\tbitonicSort(a,0, N, up);\n}\n\n// Driver code\nint main()\n{\n\tint a[]= {3, 7, 4, 8, 6, 2, 1, 5};\n\tint N = sizeof(a)/sizeof(a[0]);\n\n\tint up = 1; // means sort in ascending order\n\tsort(a, N, up);\n\n\tprintf(\"Sorted array: \\n\");\n\tfor (int i=0; i<N; i++)\n\t\tprintf(\"%d \", a[i]);\n\treturn 0;\n}\n"
  },
  {
    "path": "Algorithms/Sorting/Bitonic_Search/Readme.md",
    "content": "# Bitonic Sort\n\nBitonic Sort is a classic parallel algorithm for sorting which sorts in O(n Log 2n) comparisons. It must be used if number of elements to sort are 2^n. The procedure of bitonic sequence fails if the number of elements are not in aforementioned quantity precisely.\n\nA sequence is called Bitonic if it is first increasing, then decreasing. In other words, an array arr[0..n-i] is Bitonic if there exists an index i where 0<=i<=n-1 such that \n**x0 <= x1 …..<= xi  and  xi >= xi+1….. >= xn-1**\n1. A sequence, sorted in increasing order is considered Bitonic with the decreasing part as empty. Similarly, decreasing order sequence is considered Bitonic with the increasing part as empty.\n2. A rotation of Bitonic Sequence is also bitonic.\n\n**EXAMPLE:**\n\nConverting 3, 7, 4, 8, 6, 2, 1, 5 into Bitonic sequence,\n\n1. Consider each 2-consecutive elements as bitonic sequence and apply bitonic sort on each 2- pair elements. In next step, take two 4 element bitonic sequences and so on.\n2. Two 4 element bitonic sequences : A(3,7,8,4) and B(2,6,5,1) with comparator length as 2.\n3. After this step, we’ll get Bitonic sequence of length 8.\n\nOUTPUT: 1, 2, 3, 4, 5, 6, 7, 8.\n"
  },
  {
    "path": "Algorithms/Sorting/Bitonic_Search/bitonic_search.py",
    "content": "def compAndSwap(a, i, j, dire):\n    if (dire == 1 and a[i] > a[j]) or (dire == 0 and a[i] < a[j]):\n        a[i], a[j] = a[j], a[i]\n        \ndef bitonic_merge(a, low, cnt, dire):\n    if cnt > 1:\n        k = int(cnt / 2)\n        for i in range(low, low + k):\n            compAndSwap(a, i, i + k, dire)\n        bitonic_merge(a, low, k, dire)\n        bitonic_merge(a, low + k, k, dire)\n        \ndef bitonic_sort(a, low, cnt, dire):\n    if cnt > 1:\n        k = int(cnt / 2)\n        bitonic_sort(a, low, k, 1)\n        bitonic_sort(a, low + k, k, 0)\n        bitonic_merge(a, low, cnt, dire)\n \ndef sort(a, N, up):\n    bitonic_sort(a, 0, N, up)\n \n \nif __name__ == \"__main__\":\n \n    a = []\n \n    n = int(input().strip())\n    for i in range(n):\n        a.append(int(input().strip()))\n    up = 1\n \n    sort(a, n, up)\n    print(\"\\n\\nSorted array is\")\n    for i in range(n):\n        print(\"%d\" % a[i])\n"
  },
  {
    "path": "Algorithms/Sorting/Brick_Sort/BrickSort.js",
    "content": "/* A JavaScript program to perform Brick Sort */\n\n// A utility function to sort the array values\nfunction swap(arr, first_Index, second_Index) {\n  var temp = arr[first_Index];\n  arr[first_Index] = arr[second_Index];\n  arr[second_Index] = temp;\n}\n\n// A function to perform the Brick Sort\nfunction brickSort(arr) {\n  if (arr.length < 1) return 0;\n  var arrayLength = arr.length;\n  var isSorted = false;\n  while(!isSorted){\n  isSorted = true;\n  \n  // Perform Bubble sort on odd indexed element\n  for (let i=1; i<=arrayLength-2; i=i+2) \n    { \n      if (arr[i] > arr[i+1]) \n        { \n          swap(arr,i,i+1);\n          isSorted = false; \n        } \n     }\n     \n  // Perform Bubble sort on even indexed element\n  for (let i=0; i<=arrayLength-2; i=i+2) \n    { \n       if (arr[i] > arr[i+1]) \n         { \n           swap(arr,i,i+1);         \n           isSorted = false; \n         } \n     }\n   }\n   return arr;\n}\nconsole.log(brickSort([3, 0, 2, 5, -1, 4, 1]));\n"
  },
  {
    "path": "Algorithms/Sorting/Brick_Sort/Brick_Sort.c",
    "content": "// A C++ Program to implement Odd-Even  Brick Sort //\n#include<bits/stdc++.h>\nusing namespace std;\n\n// A function to sort the algorithm using Odd Even sort\nvoid oddEvenSort(int arr[], int n)\n{\n\tbool isSorted = false; // Initially array is unsorted\n\n\twhile (!isSorted)\n\t{\n\t\tisSorted = true;\n\n\t\t// Perform Bubble sort on odd indexed element\n\t\tfor (int i=1; i<=n-2; i=i+2)\n\t\t{\n\t\t\tif (arr[i] > arr[i+1])\n\t\t\t{\n\t\t\t\tswap(arr[i], arr[i+1]);\n\t\t\t\tisSorted = false;\n\t\t\t}\n\t\t}\n\n\t\t// Perform Bubble sort on even indexed element\n\t\tfor (int i=0; i<=n-2; i=i+2)\n\t\t{\n\t\t\tif (arr[i] > arr[i+1])\n\t\t\t{\n\t\t\t\tswap(arr[i], arr[i+1]);\n\t\t\t\tisSorted = false;\n\t\t\t}\n\t\t}\n\t}\n\n\treturn;\n}\n\n// A utility function ot print an array of size n\nvoid printArray(int arr[], int n)\n{\nfor (int i=0; i < n; i++)\n\tcout << arr[i] << \" \";\ncout << \"\\n\";\n}\n\n// Driver program to test above functions.\nint main()\n{\n\tint arr[] = {34, 2, 10, -9};\n\tint n = sizeof(arr)/sizeof(arr[0]);\n\n\toddEvenSort(arr, n);\n\tprintArray(arr, n);\n\n\treturn (0);\n}\n"
  },
  {
    "path": "Algorithms/Sorting/Brick_Sort/Readme.md",
    "content": "# BRICK SORT\n\nBrick Sorting is basically variation of Bubble Sorting. It is divided into two phases Odd and Even Phase.\nIn the odd phase,bubble sort is performed on odd indexed elements and in the even phase,bubble sort is performed on even indexed elements.\n\n**Example:**\n\nLet's take Unsorted Array A={3, 2, 3, 8, 5, 6, 4, 1}.\nSorting will perfromed in 8 steps:\n\n1. Pairing in even number - [3 2],[3 8],[5 6],[4 1].\n2. Now in odd number - [2],[3 3],[8 5],[6 1],[4].\n3. Similarly following step 1 and 2 - [2 3],[3 5],[8 1],[6 4].\n4. [2],[3 3],[5 1],[8 4],[6].\n5. [2 3],[3 1],[5 4],[8 6].\n6. [2],[3 1],[3 4],[5 6],[8].\n7. [2 1],[3 3],[4 5],[6 8].\n8. [1],[2 3],[3 4],[5 6],8.\n\nOUTPUT: [1 2],[3 3],[4 5],[6 8] - {1, 2, 3, 3, 4, 5, 6, 8}.\n\n"
  },
  {
    "path": "Algorithms/Sorting/Brick_Sort/brickSort.py",
    "content": "def brickSort(array, n):\n    isSorted = 0\n    while isSorted == 0:\n        isSorted = 1\n        temp = 0\n        for i in range(1, n - 1, 2):\n            if array[i] > array[i + 1]:\n                array[i], array[i + 1] = array[i + 1], array[i]\n                isSorted = 0\n\n        for i in range(0, n - 1, 2):\n            if array[i] > array[i + 1]:\n                array[i], array[i + 1] = array[i + 1], array[i]\n                isSorted = 0\n    return\n\n\narr = [23,45,67,89]\nn = len(arr)\n\nbrickSort(arr, n);\nfor i in range(0, n):\n    print(arr[i], end=' ')\n"
  },
  {
    "path": "Algorithms/Sorting/Bubble_Sort/BubbleSort.js",
    "content": "function swap(arr, first_Index, second_Index) {\r\n  var temp = arr[first_Index];\r\n  arr[first_Index] = arr[second_Index];\r\n  arr[second_Index] = temp;\r\n}\r\n\r\nfunction bubbleSort(arr) {\r\n  if (arr.length < 1) return 0;\r\n  var arrayLength = arr.length;\r\n  for (let i = 0; i < arrayLength; i++) {\r\n    for (let j = 0, end = arrayLength - i; j < end; j++) {\r\n      if (arr[j] > arr[j + 1]) {\r\n        swap(arr, j, j + 1);\r\n      }\r\n    }\r\n  }\r\n  return arr;\r\n}\r\nconsole.log(bubbleSort([3, 0, 2, 5, -1, 4, 1]));\r\n"
  },
  {
    "path": "Algorithms/Sorting/Bubble_Sort/BubbleSort.scala",
    "content": "object BubbleSortAscApp {\n\n  //main function\n  def main(args: Array[String]): Unit = {\n  \n    //Passing list to be sorted to bubble sort function\n    println(bubbleSortAsc(List(3,1,6,8,2)))\n    \n    println(bubbleSortAsc(List(\"z\", \"c\", \"a\", \"b\")))\n    \n  }\n  \n  // Bubble sort function\n  def bubbleSortAsc[T <% Ordered[T]](myData: List[T]):\n    List[T] = myData match {\n    \n      case Nil => Nil\n      case _ => {\n       \n        val (max, remainingData) = calcMax(myData)\n      \n        bubbleSortAsc(remainingData) ::: List(max)\n    \n      }\n    }\n    \n    //calculating max each iteration\n  def calcMax[T <% Ordered[T]](myData: List[T]): (T,List[T]) = myData match {\n  \n      case (Nil) => (null.asInstanceOf[T], Nil)\n      \n      case (head :: Nil) => (head, Nil)\n      \n      case (head :: tail) => {\n      \n        val (tailMax, tailRemaining) = calcMax(tail)\n        \n        if (tailMax >= head) (tailMax, head :: tailRemaining)\n        \n        else (head, tailMax :: tailRemaining)\n      }\n  }\n}\n"
  },
  {
    "path": "Algorithms/Sorting/Bubble_Sort/Bubble_Sort.c",
    "content": "#include<stdio.h>\n\nint main()\n{\n\n   int count, temp, i, j, number[30];\n\n   printf(\"How many numbers are u going to enter?:\\n \");\n   scanf(\"%d\",&count);\n\n   printf(\"Enter %d numbers: \",count);\n\n   for(i=0;i<count;i++)\n   scanf(\"%d\",&number[i]);\n\n   /* This is the main logic of bubble sort algorithm \n    */\n   for(i=count-2;i>=0;i--){\n      for(j=0;j<=i;j++){\n        if(number[j]>number[j+1]){\n           temp=number[j];\n           number[j]=number[j+1];\n           number[j+1]=temp;\n        }\n      }\n   }\n\n   printf(\"Sorted elements: \");\n   for(i=0;i<count;i++)\n      printf(\" %d\",number[i]);\n\n   return 0;\n}\n"
  },
  {
    "path": "Algorithms/Sorting/Bubble_Sort/Bubble_Sort.cs",
    "content": "using System;\nnamespace BubbleSort {\n   class MySort {\n      static void Main(string[] args) {\n      //change the array according to you input or take the user input \n         int[] arr = { 78, 55, 45, 98, 13 };\n         int temp;\n         for (int j = 0; j <= arr.Length - 2; j++) {\n            for (int i = 0; i <= arr.Length - 2; i++) {\n               if (arr[i] > arr[i + 1]) {\n                  temp= arr[i + 1];\n                  arr[i + 1] = arr[i];\n                  arr[i] = temp;\n               }\n            }\n         }\n         Console.WriteLine(\"Sorted:\");\n         foreach (int p in arr)\n            Console.Write(p + \" \");\n         Console.Read();\n      }\n   }\n}\n"
  },
  {
    "path": "Algorithms/Sorting/Bubble_Sort/Bubble_Sort.py",
    "content": "# This is the Python version of Bubble Sort\n# Code is contributed by: Harsh Udai.\n# \n# Bubble sort is an Sorting Algorithm which takes compelxity: O(n^2)\n\narray=[5,4,3,2,1,6]\n\nfor i in range(0,len(array)):\n    for j in range(0,len(array)-1):\n        if(array[j]>array[j+1]): # swaps if greater element is before the smaller one\n            temp=array[j]\n            array[j]=array[j+1]\n            array[j+1]=temp\n\n\nprint(array)"
  },
  {
    "path": "Algorithms/Sorting/Bubble_Sort/Bubble_sort_optimised.cpp",
    "content": "// Optimized implementation of Bubble sort \r\n#include <bits/stdc++.h>\r\nusing namespace std;\r\n#define IOS ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(0)\r\n\r\nvoid swap(int *xp, int *yp) \r\n{ \r\n\tint temp = *xp; \r\n\t*xp = *yp; \r\n\t*yp = temp; \r\n} \r\n\r\n// An optimized version of Bubble Sort \r\nvoid bubbleSort(int arr[], int n) \r\n{ \r\n    int i, j; \r\n    bool swapped; \r\n    for (i = 0; i < n-1; i++) \r\n    { \r\n\t    swapped = false; \r\n\t    for (j = 0; j < n-i-1; j++) \r\n\t    { \r\n\t\t    if (arr[j] > arr[j+1]) \r\n\t\t    { \r\n\t\t        swap(&arr[j], &arr[j+1]); \r\n\t\t        swapped = true; \r\n\t\t    } \r\n\t    } \r\n\r\n\t// IF no two elements were swapped by inner loop, then break \r\n\t    if (swapped == false) \r\n\t\t    break; \r\n    } \r\n} \r\n\r\n/* Function to print an array */\r\nvoid printArray(int arr[], int size) \r\n{ \r\n\tint i; \r\n\tfor (i=0; i < size; i++) \r\n\t\tcout<<arr[i]<<\" \"; \r\n\tcout<<endl; \r\n} \r\n\r\n// Driver program to test above functions \r\nint main() \r\n{ \r\n    IOS;\r\n\tint arr[] = {64, 34, 25, 12, 22, 11, 90}; \r\n\tint n = sizeof(arr)/sizeof(arr[0]); \r\n\tbubbleSort(arr, n); \r\n\tcout<<\"Sorted array: \\n\"; \r\n\tprintArray(arr, n); \r\n\treturn 0; \r\n} \r\n"
  },
  {
    "path": "Algorithms/Sorting/Bubble_Sort/bubbleSort.cpp",
    "content": "#include<bits/stdc++.h>\r\nusing namespace std;\r\n\r\nvoid bubble_sort(int arr[],int n)\r\n{\r\n    for(int i = 0;i<n;i++)\r\n    {\r\n        for(int j =0;j<n;j++)\r\n        {\r\n            if(arr[i] < arr[j])\r\n            {\r\n                swap(arr[i],arr[j]);\r\n            }\r\n        }\r\n    }\r\n}\r\nint main()\r\n{\r\n    int n;\r\n    cin>>n;\r\n    int arr[n];\r\n    for(int i =0;i<n;i++)cin>>arr[i];\r\n    bubble_sort(arr,n);\r\n    \r\n\r\n}"
  },
  {
    "path": "Algorithms/Sorting/Bubble_Sort/bubble_sort.java",
    "content": "class Bubble\n{\n    void Sort(int array[])\n    {\n        int n = array.length;\n        for (int i = 0; i < n-1; i++)\n            for (int j = 0; j < n-i-1; j++)\n                if (array[j] > array[j+1])\n                {\n                                      \n                    int temp = array[j];\n                    array[j] = array[j+1];\n                    array[j+1] = temp;// swapping temp and array\n                }\n    }\n \n   \n    void printarrayay(int array[])//to print the array\n    {\n        int n = array.length;\n        for (int i=0; i<n; ++i)\n            System.out.print(array[i] + \" \");\n        System.out.println();\n    }\n \n    public static void main(String args[])\n    {\n        BubbleSort obj = new BubbleSort();\n        int array[] = {645, 67, 56, 32, 76, 90, 83, 73, 32, 12, 34};\n        obj.bubbleSort(array);\n        System.out.println(\"Array Sorted successfully\");\n        obj.printarray(array);\n    }\n}\n"
  },
  {
    "path": "Algorithms/Sorting/Bubble_Sort/bubble_sort.sh",
    "content": "echo \"Enter the number of elements in the array: \"\nread n\n\necho \"Enter the elements: \"\nread -a arr\n\nfor (( i = 0; i < $n ; i++ ))\ndo\n        for (( j = $i; j < $n; j++ ))\n        do\n                if [ ${arr[$i]} -gt ${arr[$j]} ]; then\n                        t=${arr[$i]}\n                        arr[$i]=${arr[$j]}\n                        arr[$j]=$t\n                fi\n        done\ndone\n\necho \"After Sorting: \"\nfor (( i=0; i < $n; i++ ))\ndo\n        echo ${arr[$i]}\ndone\n"
  },
  {
    "path": "Algorithms/Sorting/Bubble_Sort/readme.md",
    "content": "## BUBBLE SORT\n\nBubble sorting is a type of sorting technique in which adjacent element is swapped with each other if they are in wrong order.\n\nFor example: (9 7 6 8) –> (9 7 8 6) -> (9 8 7 6)\n"
  },
  {
    "path": "Algorithms/Sorting/Bucket_Sort/BucketSort.c",
    "content": "// Bucket sort in C\r\n\r\n#include <stdio.h>\r\n#include <stdlib.h>\r\n\r\n#define NARRAY 10   // Array size\r\n#define NBUCKET 6  // Number of buckets\r\n#define INTERVAL 10  // Each bucket capacity\r\n\r\nstruct Node {\r\n  int data;\r\n  struct Node *next;\r\n};\r\n\r\nvoid BucketSort(int arr[]);\r\nstruct Node *InsertionSort(struct Node *list);\r\nvoid print(int arr[]);\r\nvoid printBuckets(struct Node *list);\r\nint getBucketIndex(int value);\r\n\r\n// Sorting function\r\nvoid BucketSort(int arr[]) {\r\n  int i, j;\r\n  struct Node **buckets;\r\n\r\n  // Create buckets and allocate memory size\r\n  buckets = (struct Node **)malloc(sizeof(struct Node *) * NBUCKET);\r\n\r\n  // Initialize empty buckets\r\n  for (i = 0; i < NBUCKET; ++i) {\r\n    buckets[i] = NULL;\r\n  }\r\n\r\n  // Fill the buckets with respective elements\r\n  for (i = 0; i < NARRAY; ++i) {\r\n    struct Node *current;\r\n    int pos = getBucketIndex(arr[i]);\r\n    current = (struct Node *)malloc(sizeof(struct Node));\r\n    current->data = arr[i];\r\n    current->next = buckets[pos];\r\n    buckets[pos] = current;\r\n  }\r\n\r\n  // Print the buckets along with their elements\r\n  for (i = 0; i < NBUCKET; i++) {\r\n    printf(\"Bucket[%d]: \", i);\r\n    printBuckets(buckets[i]);\r\n    printf(\"\\n\");\r\n  }\r\n\r\n  // Sort the elements of each bucket\r\n  for (i = 0; i < NBUCKET; ++i) {\r\n    buckets[i] = InsertionSort(buckets[i]);\r\n  }\r\n\r\n  printf(\"-------------\\n\");\r\n  printf(\"Bucktets after sorting\\n\");\r\n  for (i = 0; i < NBUCKET; i++) {\r\n    printf(\"Bucket[%d]: \", i);\r\n    printBuckets(buckets[i]);\r\n    printf(\"\\n\");\r\n  }\r\n\r\n  // Put sorted elements on arr\r\n  for (j = 0, i = 0; i < NBUCKET; ++i) {\r\n    struct Node *node;\r\n    node = buckets[i];\r\n    while (node) {\r\n      arr[j++] = node->data;\r\n      node = node->next;\r\n    }\r\n  }\r\n\r\n  return;\r\n}\r\n\r\n// Function to sort the elements of each bucket\r\nstruct Node *InsertionSort(struct Node *list) {\r\n  struct Node *k, *nodeList;\r\n  if (list == 0 || list->next == 0) {\r\n    return list;\r\n  }\r\n\r\n  nodeList = list;\r\n  k = list->next;\r\n  nodeList->next = 0;\r\n  while (k != 0) {\r\n    struct Node *ptr;\r\n    if (nodeList->data > k->data) {\r\n      struct Node *tmp;\r\n      tmp = k;\r\n      k = k->next;\r\n      tmp->next = nodeList;\r\n      nodeList = tmp;\r\n      continue;\r\n    }\r\n\r\n    for (ptr = nodeList; ptr->next != 0; ptr = ptr->next) {\r\n      if (ptr->next->data > k->data)\r\n        break;\r\n    }\r\n\r\n    if (ptr->next != 0) {\r\n      struct Node *tmp;\r\n      tmp = k;\r\n      k = k->next;\r\n      tmp->next = ptr->next;\r\n      ptr->next = tmp;\r\n      continue;\r\n    } else {\r\n      ptr->next = k;\r\n      k = k->next;\r\n      ptr->next->next = 0;\r\n      continue;\r\n    }\r\n  }\r\n  return nodeList;\r\n}\r\n\r\nint getBucketIndex(int value) {\r\n  return value / INTERVAL;\r\n}\r\n\r\nvoid print(int ar[]) {\r\n  int i;\r\n  for (i = 0; i < NARRAY; ++i) {\r\n    printf(\"%d \", ar[i]);\r\n  }\r\n  printf(\"\\n\");\r\n}\r\n\r\n// Print buckets\r\nvoid printBuckets(struct Node *list) {\r\n  struct Node *cur = list;\r\n  while (cur) {\r\n    printf(\"%d \", cur->data);\r\n    cur = cur->next;\r\n  }\r\n}\r\n\r\n// Driver code\r\nint main(void) {\r\n  int array[NARRAY] = {42, 32, 33, 52, 37, 47, 51, 28, 44, 39};\r\n\r\n  printf(\"Initial array: \");\r\n  print(array);\r\n  printf(\"-------------\\n\");\r\n\r\n  BucketSort(array);\r\n  printf(\"-------------\\n\");\r\n  printf(\"Sorted array: \");\r\n  print(array);\r\n  return 0;\r\n}\r\n\r\n/*Output:\r\n\r\nInitial array: 42 32 33 52 37 47 51 28 44 39\r\n-------------\r\nBucket[0]:\r\nBucket[1]:\r\nBucket[2]: 28\r\nBucket[3]: 39 37 33 32\r\nBucket[4]: 44 47 42\r\nBucket[5]: 51 52\r\n-------------\r\nBucktets after sorting\r\nBucket[0]:\r\nBucket[1]:\r\nBucket[2]: 28\r\nBucket[3]: 32 33 37 39\r\nBucket[4]: 42 44 47\r\nBucket[5]: 51 52\r\n-------------\r\nSorted array: 28 32 33 37 39 42 44 47 51 52 */\r\n"
  },
  {
    "path": "Algorithms/Sorting/Bucket_Sort/BucketSort.java",
    "content": "// Bucket sort in Java\n\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.Scanner;\n\npublic class BucketSort {\n  public void bucketSort(float[] arr, int n) {\n    if (n <= 0)\n      return;\n    @SuppressWarnings(\"unchecked\")\n    ArrayList<Float>[] bucket = new ArrayList[n];\n\n    // Create empty buckets\n    for (int i = 0; i < n; i++)\n      bucket[i] = new ArrayList<Float>();\n\n    // Add elements into the buckets\n    for (int i = 0; i < n; i++) {\n      int bucketIndex = (int) arr[i] * n;\n      bucket[bucketIndex].add(arr[i]);\n    }\n\n    // Sort the elements of each bucket\n    for (int i = 0; i < n; i++) {\n      Collections.sort((bucket[i]));\n    }\n\n    // Get the sorted array\n    int index = 0;\n    for (int i = 0; i < n; i++) {\n      for (int j = 0, size = bucket[i].size(); j < size; j++) {\n        arr[index++] = bucket[i].get(j);\n      }\n    }\n  }\n\n  // Driver code\n  public static void main(String[] args) {\n    BucketSort b = new BucketSort();\n    Scanner s = new Scanner(System.in);  // Create a Scanner object\n    System.out.println(\"Enter no of elemets\");\n    int n=s.nextInt();\n    ArrayList<Float>[] arr = new ArrayList[n];\n    for(int i=0;i<n;i++){\n      System.out.println(\"Enter a number\");\n      float num=s.nextFloat();\n      num.add(arr[]);\n    }\n    \n    b.bucketSort(arr, n);\n\n    for (float i : arr)\n      System.out.print(i + \"  \");\n  }\n}\n"
  },
  {
    "path": "Algorithms/Sorting/Bucket_Sort/BucketSort.js",
    "content": "const sortInsertion = (arr) => {\n\tfor (let i = 1; i < arr.length; i++) {\n\t\tconst value = arr[i];\n\t\tlet lastIndex = i - 1;\n\t\twhile (lastIndex >= 0 && arr[lastIndex] > value) {\n\t\t\tarr[lastIndex + 1] = arr[lastIndex];\n\t\t\tlastIndex--;\n\t\t}\n\t\tarr[lastIndex + 1] = value;\n\t};\n\treturn arr;\n};\n\nconst sortBucketPositive = (arr) => {\n\tconst length = arr.length;\n\tconst maxValue = Math.max(...arr);\n\tconst divider = Math.ceil((maxValue + 1) / length);\n\t\n\tconst buckets = [];\n\t\n\t// Place array values inside buckets\n\tfor (let i = 0; i < length; i++) {\n\t\tconst value = arr[i];\n\t\tconst bucketIndex = Math.floor(value / divider);\n\t\t\n\t\t// If bucket does not exist\n\t\t// Instantiate a new array inside the buckets array\n\t\tif (!buckets[bucketIndex]) {\n\t\t\tbuckets[bucketIndex] = [];\n\t\t};\n\t\t\n\t\tbuckets[bucketIndex].push(value);\n\t};\n\t\n\t// Iterate through buckets and perform insertion sort\n\tfor (let i = 0; i < length; i++) {\n\t\t// Ignore empty buckets\n\t\tif (!buckets[i]) {\n\t\t\tcontinue;\n\t\t}\n\t\t\n\t\tbuckets[i] = sortInsertion(buckets[i]);\n\t};\n\t\n\t// Merge and return buckets\n\treturn buckets.flat();\n};\n\n// This bucket sort implementation works with both positive and negative values\nconst sortBucket = (arr) => {\n\tconst positiveArr = [];\n\tconst absNegativeArr = [];\n\t\n\t// Split array into two arrays\n\t// An array containing the positive values\n\t// And an array containing the absolute value of all the negative values\n\tfor (let i = 0; i < arr.length; i++) {\n\t\tconst value = arr[i];\n\t\tif (value >= 0) {\n\t\t\tpositiveArr.push(value);\n\t\t}\n\t\telse {\n\t\t\tabsNegativeArr.push(Math.abs(value));\n\t\t}\n\t};\n\t\n\tconst sortedPositiveArr = sortBucketPositive(positiveArr);\n\tconst sortedNegativeArr = sortBucketPositive(absNegativeArr).reverse().map(x => -x);\n\t\n\treturn sortedNegativeArr.concat(sortedPositiveArr);\n};\n\n\n// Driver Code\n\n// Test Cases:\n// Standard shuffled array\n// Backwards array\n// Already sorted array\n// Empty array\n// Array of length 1\n// Exclusively negative elements\n// Negative and positive elements\n// Equal values\n\nconst arrays = [\n\t[3, 8, 9, 10, 2, 6, 4, 5, 7, 1],\n\t[10, 9, 8, 7, 6, 5, 4, 3, 2, 1],\n\t[1, 2, 3, 4, 5, 6, 7, 8, 9, 10],\n\t[3],\n\t[-1, -2, -5, -4, -10, -8, -3, -9, -6, -7],\n\t[10, -3, -8, 12, 6],\n\t[5, 5, 3, 2]\n];\n\nfor (let i = 0; i < arrays.length; i++) {\n\tconst arr = arrays[i];\n\tconst sortedArr = sortBucket(arr);\n\tconsole.log(`${arr} => Bucket Sorted = ${sortedArr}!`);\n};"
  },
  {
    "path": "Algorithms/Sorting/Bucket_Sort/BucketSort.py",
    "content": "def bucket_sort(input_list):\r\n    # Find maximum value in the list and use length of the list to determine which value in the list goes into which bucket \r\n    max_value = max(input_list)\r\n    size = max_value/len(input_list)\r\n\r\n    # Create n empty buckets where n is equal to the length of the input list\r\n    buckets_list= []\r\n    for x in range(len(input_list)):\r\n        buckets_list.append([]) \r\n\r\n    # Put list elements into different buckets based on the size\r\n    for i in range(len(input_list)):\r\n        j = int (input_list[i] / size)\r\n        if j != len (input_list):\r\n            buckets_list[j].append(input_list[i])\r\n        else:\r\n            buckets_list[len(input_list) - 1].append(input_list[i])\r\n\r\n    # Sort elements within the buckets using Insertion Sort\r\n    for z in range(len(input_list)):\r\n        insertion_sort(buckets_list[z])\r\n            \r\n    # Concatenate buckets with sorted elements into a single list\r\n    final_output = []\r\n    for x in range(len (input_list)):\r\n        final_output = final_output + buckets_list[x]\r\n    return final_output\r\n"
  },
  {
    "path": "Algorithms/Sorting/Bucket_Sort/README.md",
    "content": "## BUCKET SORT\n\nBucket sort is mainly useful when input is uniformly distributed over a range. In the Bucket Sorting technique, the data items are distributed in a set of buckets. Each bucket can hold a similar type of data. After distributing, each bucket is sorted using another sorting algorithm. After that, all elements are gathered on the main list to get the sorted form.\n\nThe complexity of the Bucket Sort Technique :\n1. Time Complexity: O(n + k) for best case and average case and O(n^2) for the worst case.\n2. Space Complexity: O(nk) for worst case\n\n**FOR EXAMPLE:**\nInput:\nA list of unsorted data: 0.25 0.36 0.58 0.41 0.29 0.22 0.45 0.79 0.01 0.69\nArray before Sorting: 0.25 0.36 0.58 0.41 0.29 0.22 0.45 0.79 0.01 0.69\n\nOutput:\nArray after Sorting: 0.01 0.22 0.25 0.29 0.36 0.41 0.45 0.58 0.69 0.79\n"
  },
  {
    "path": "Algorithms/Sorting/Bucket_Sort/bucket_sort.cpp",
    "content": "// C++ program to sort an array using bucket sort \n#include <algorithm> \n#include <iostream> \n#include <vector> \nusing namespace std; \n\nvoid bucketSort(float arr[], int n) \n{ \n\tvector<float> b[n]; \n\tfor (int i = 0; i < n; i++) { \n\t\tint bi = n * arr[i]; \n\t\tb[bi].push_back(arr[i]); \n\t} \n  \n\tfor (int i = 0; i < n; i++) \n\t\tsort(b[i].begin(), b[i].end()); \n\n\tint index = 0; \n\tfor (int i = 0; i < n; i++) \n\t\tfor (int j = 0; j < b[i].size(); j++) \n\t\t\tarr[index++] = b[i][j]; \n} \n\nint main() \n{ \n\tfloat arr[] = { 0.897, 0.565, 0.656, 0.1234, 0.665, 0.3434 }; \n\tint n = sizeof(arr) / sizeof(arr[0]); \n\tbucketSort(arr, n); \n\n\tcout << \"Sorted array is \\n\"; \n\tfor (int i = 0; i < n; i++) \n\t\tcout << arr[i] << \" \"; \n\treturn 0; \n}\n"
  },
  {
    "path": "Algorithms/Sorting/Bucket_Sort/bucketsort.php",
    "content": "<?php\nfunction insertion_sort(&$elements, $fn = 'comparison_function') {\n  if (!is_array($elements) || !is_callable($fn)) return;\n  for ($i = 1; $i < sizeof($elements); $i++) {\n    $key = $elements[$i]; \n    $j = $i - 1; // this will be in $b in comparison function\n    while ( $j >= 0 && $fn($key, $elements[$j]) ) {\n      $elements[$j + 1] = $elements[$j]; // shift right\n      $j = $j - 1;\n    }\n    $elements[$j + 1] = $key;\n  }\n}\n\nfunction comparison_function(&$a, &$b) {\n  return $a < $b;\n}\n\nfunction bucket_sort(&$elements) {\n  $n = sizeof($elements);\n  $buckets = array();\n  // Initialize the buckets.\n  for ($i = 0; $i < $n; $i++) {\n    $buckets[$i] = array();\n  }\n  // Put each element into matched bucket.\n  foreach ($elements as $el) {\n    array_push($buckets[ceil($el/10)], $el);\n  }\n  // Sort elements in each bucket using insertion sort.\n  $j = 0;\n  for ($i = 0; $i < $n; $i++) {\n    // sort only non-empty bucket\n    if (!empty($buckets[$i])) {\n      insertion_sort($buckets[$i]);\n      // Move sorted elements in the bucket into original array.\n      foreach ($buckets[$i] as $el) {\n        $elements[$j++] = $el;\n      }\n    }\n  }\n}\n$a = array(-1,0,10,15,-2);\nbucket_sort($a); // Sort the elements\necho \"\\nSorted Array :\\n\";\nvar_dump($a);\n?>\n"
  },
  {
    "path": "Algorithms/Sorting/Bucket_Sort/bucketsort.rb",
    "content": "\n# arr array to be sorted\n# n number of elements in array\n# buckets instance of buckets\n# m  elements in a are supposed between 0..m - 1\n#\ndef bucket_sort(arr, n, buckets, m)\n    for j in 0...m\n      buckets[j] = 0\n    end\n    for i in 0...n\n      buckets[arr[i]] += 1\n    end\n    i = 0\n    for j in 0...m\n      for k in 0...buckets[j]\n        arr[i] = j\n        i += 1\n      end\n    end\n  end"
  },
  {
    "path": "Algorithms/Sorting/Bucket_Sort/bucketsortinC.c",
    "content": "/*\n * C Program to Sort Array using Bucket Sort\n */\n#include <stdio.h>\n \n/* Function for bucket sort */\nvoid Bucket_Sort(int array[], int n)\n{  \n    int i, j;  \n    int count[n]; \n    for (i = 0; i < n; i++)\n        count[i] = 0;\n \n    for (i = 0; i < n; i++)\n        (count[array[i]])++;\n \n    for (i = 0, j = 0; i < n; i++)  \n        for(; count[i] > 0; (count[i])--)\n            array[j++] = i;\n}   \n/* End of Bucket_Sort() */\n \n/* The main() begins */\nint main()\n{\n    int array[100], i, num; \n \n    printf(\"Enter the size of array : \");   \n    scanf(\"%d\", &num);   \n    printf(\"Enter the %d elements to be sorted:\\n\",num); \n    for (i = 0; i < num; i++)\n        scanf(\"%d\", &array[i]); \n    printf(\"\\nThe array of elements before sorting : \\n\");\n    for (i = 0; i < num; i++)\n        printf(\"%d \", array[i]);  \n    printf(\"\\nThe array of elements after sorting : \\n\"); \n    Bucket_Sort(array, num); \n    for (i = 0; i < num; i++)\n        printf(\"%d \", array[i]);   \n    printf(\"\\n\");     \n    return 0;\n}\n"
  },
  {
    "path": "Algorithms/Sorting/Circle_Sort/Circle_Sort.c",
    "content": "#include <stdio.h>\n#include <stdlib.h>\n\nint circle_sort_inner(int *start, int *end)\n{\n  int *p, *q, t, swapped;\n \n  if (start == end) return 0;\n  for (swapped = 0, p = start, q = end; p<q || (p==q && ++q); p++, q--)\n    if (*p > *q)\n      t = *p, *p = *q, *q = t, swapped = 1;\n \n  return swapped | circle_sort_inner(start, q) | circle_sort_inner(p, end);\n}\n\nvoid circle_sort(int a[], int n) \n{ \n    while (circle_sort_inner(a, a + (n - 1))) \n    { \n       ; \n    } \n} \n \nint main(void)\n{\n  int N , i ,j;\n  printf(\"Enter Size of Array :- \\n\");\n  scanf(\"%d\",&N);\n  int A[N];\n  for(i = 0 ; i < N;i++)\n    scanf(\"%d\",&A[i]);\n\n  circle_sort(A, N);\n  printf(\"Sorted Array :- \\n\");\n  for(i = 0 ; i < N;i++)\n    printf(\"%d \",A[i]);\n  printf(\"\\n\");\n\n  return 0;\n}"
  },
  {
    "path": "Algorithms/Sorting/Circle_Sort/Circle_Sort.cs",
    "content": " // C# program to implement circle sort \n    using System;\n\n    class Program\n    {\n        /// <summary>\n        /// Main application function.\n        /// </summary>\n        public static void Main()\n        {\n            int[] arr = { -32, 41, 6, -2, 16, 0, 23 };\n\n            // Calling circle Sort function \n            // to sort the array \n            CircleSort(arr);\n\n            // Display the sorted array \n            for (int i = 0; i < arr.Length-1; i++)\n                Console.Write(arr[i] + \" \");\n        }\n\n        public static void CircleSort(int[] array)\n        {\n            var swapMade = false;\n            do\n            {\n                swapMade = CircleSort(array, 0, array.Length - 1);\n            } while (swapMade);\n\n        }\n\n        /// <summary>\n        /// Runs circle sort on provided array\n        /// </summary>\n        /// <param name=\"array\">array to be sorted</param>\n        /// <param name=\"lowIndex\">Index to start at</param>\n        /// <param name=\"highIndex\">Index to end at</param>\n        private static bool CircleSort(int[] array, int lowIndex, int highIndex)\n        {\n            bool swapMade = false;\n            if (lowIndex == highIndex)\n                return swapMade;\n            var subArrayLength = highIndex - lowIndex;\n            var midPoint = subArrayLength / 2;\n\n            int currentLowIndex = lowIndex;\n            int currentHighIndex = highIndex;\n            while (currentLowIndex < currentHighIndex) {\n                if (array[currentLowIndex] > array[currentHighIndex]) {\n                    var tempLowValue = array[currentLowIndex];\n                    array[currentLowIndex] = array[currentHighIndex];\n                    array[currentHighIndex] = tempLowValue;\n                    swapMade = true;\n                }\n                currentLowIndex++;\n                currentHighIndex--;\n            }\n\n            swapMade |= CircleSort(array, lowIndex, lowIndex + midPoint);\n            swapMade |= CircleSort(array,lowIndex + midPoint + 1, highIndex);\n            return swapMade;\n\n        }\n    }\n"
  },
  {
    "path": "Algorithms/Sorting/Circle_Sort/Circle_Sort.java",
    "content": "import java.util.Scanner;\nclass circleSortClass\n{\n  boolean circleSortInner(int a[], int low, int high) \n  {\n      boolean swapped = false;\n      if (low == high)\n          return false;\n      int l = low, h = high;\n      int mid = (high - low) / 2;\n      boolean left, right;\n      while (l < h)\n      {\n\t        if (a[l] > a[h])\n\t        {\n\t            swap (a,l,h);\n\t            swapped = true;\n          }\n\t        l++;\n\t        h--;\n      }\n      if (l == h)\n          if (a[l] > a[h + 1])\n\t        {\n\t            swap (a,l,h + 1);\n  \t        swapped = true;\n\t        }\n          left = circleSortInner (a, low, low + mid);\n          right = circleSortInner (a, low + mid + 1, high);\n          return swapped || left || right;\n  }\n \n\n  void circleSort (int a[], int n) \n  {\n      while (circleSortInner (a, 0, n - 1));\n  }\n\n\n  void swap(int arr[],int l,int h)\n  {\n      int temp=arr[l];\n      arr[l]=arr[h];\n      arr[h]=temp;\n  }\n\n \n\n  // Driver program \n  public static void main(String[] args)\n  {\n      int arr[];\n      Scanner sc=new Scanner(System.in);\n      System.out.println(\"Enter number of elements to be sorted:\");\n      int n=sc.nextInt();\n      arr = new int[n]; \n      System.out.println(\"Enter \"+n+\" elements\");\n      for (int i=0;i<n;i++)\n          arr[i]=sc.nextInt();\n      circleSortClass c=new circleSortClass();\n      c.circleSort (arr, n);\n      System.out.println(\"Array after sorting:\");\n      for (int i = 0; i < n; i++)\n          System.out.print(arr[i]+\" \");\n      System.out.println();\n  }\n}\n"
  },
  {
    "path": "Algorithms/Sorting/Circle_Sort/Circle_Sort.rb",
    "content": "class Array\n  def circle_sort!\n    while _circle_sort!(0, size-1) > 0\n    end\n    self\n  end\n \n  private\n\n  def _circle_sort!(lo, hi, swaps=0)\n    return swaps if lo == hi\n    low, high = lo, hi\n    mid = (lo + hi) / 2\n    while lo < hi\n      if self[lo] > self[hi]\n        self[lo], self[hi] = self[hi], self[lo]\n        swaps += 1\n      end\n      lo += 1\n      hi -= 1\n    end\n    if lo == hi && self[lo] > self[hi+1]\n      self[lo], self[hi+1] = self[hi+1], self[lo]\n      swaps += 1\n    end\n    swaps + _circle_sort!(low, mid) + _circle_sort!(mid+1, high)\n  end\nend\n \nary = [6, 7, 8, 9, 2, 5, 3, 4, 1]\nputs \"before sort: #{ary}\"\nputs \" after sort: #{ary.circle_sort!}\"\n"
  },
  {
    "path": "Algorithms/Sorting/Circle_Sort/README.md",
    "content": "## Circle Sort\n\nCircle sort algorithm can be visualized by drawing concentric circles on an array of integers. The elements of the array lying on the same circle diametrically opposite to each other are compared and if found in the wrong order they are swapped. This goes on in a recursive fashion in which the array is divided into sub-arrays on which the above process is repeated until we get pairs of sorted elements which when put together form a sorted array.\n\n**In short below two steps are repeated while there are swap operations involved in the steps.**\n\n1. Compare the first element to the last element, then the second element to the second last element, etc.\n2. Then split the array in two and recurse until there is only one single element in the array.\n\n**For Example**\n\nA = {6,5,3,1,8,7,2,4}\n\n1st element is swipped with last similarly 2nd element with second last and the divides the arrays into 2 parts :\n\nX = {4,2,3,1}      and       Y = {8,7,5,6}\n\nAgain swipping of elements takes place in similar circular manner and divides the arrays in futher 2-2 parts :\n\nP = {1,2}  Q = {3,4}   R = {6,5}   S = {7,8}\n\nAfter swipping {6,5} Final output is :\n\nA = {1,2,3,4,5,6,7,8}\n"
  },
  {
    "path": "Algorithms/Sorting/Cocktail_Sort/Cocktail_Sort.c",
    "content": "// C implementation of Cocktail Sort \n#include <stdio.h> \n\n//Swap Utility Func\nvoid swap(int *a, int *b){\n\tint temp = *a;\n\t*a = *b;\n\t*b = temp;\n}\n\n// Sorts arrar a[0..n-1] using Cocktail sort \nvoid CocktailSort(int a[], int n) \n{ \n\tint swapped = 1; \n\tint start = 0; \n\tint end = n - 1; \n\tint i;\n\n\twhile (swapped) { \n\t\tswapped = 0; \n\n\t\tfor (i = start; i < end; ++i) { \n\t\t\tif (a[i] > a[i + 1]) { \n\t\t\t\tswap(&a[i], &a[i + 1]); \n\t\t\t\tswapped = 1; \n\t\t\t} \n\t\t} \n\n\t\tif (!swapped) \n\t\t\tbreak; \n\n\t\tswapped = 0; \n\t\t--end; \n\n\t\tfor (i = end - 1; i >= start; --i) { \n\t\t\tif (a[i] > a[i + 1]) { \n\t\t\t\tswap(&a[i], &a[i + 1]); \n\t\t\t\tswapped = 1; \n\t\t\t} \n\t\t} \n\t\t++start; \n\t} \n} \n\n/* Prints the array */\nvoid printArray(int a[], int n) \n{ \n\tint i;\n\tfor (i = 0; i < n; i++) \n\t\tprintf(\"%d \", a[i]); \n\tprintf(\"\\n\"); \n} \n\n// Driver code \nint main() \n{ \n\tint n,i;\n\tint arr[10000];\n\tscanf(\"%d\", &n);\n\tfor(i=0;i<n;i++)\n\t\tscanf(\"%d\", &arr[i]);\n\tCocktailSort(arr, n); \n\tprintf(\"Sorted array :\\n\"); \n\tprintArray(arr, n); \n\treturn 0; \n} \n"
  },
  {
    "path": "Algorithms/Sorting/Cocktail_Sort/Cocktail_Sort.cpp",
    "content": "#include<iostream>\nusing namespace std;\nvoid cocktailSort(int arr[], int n){\n   bool flag = true;\n   int start = 0, end = n-1;\n   while(flag){\n      flag = false;\n      for(int i = start; i<end; i++){ //scan from left to right as bubble sort\n         if(arr[i] > arr[i+1]){\n            swap(arr[i], arr[i+1]);\n            flag = true;\n         }\n      }\n      if(!flag){ //if nothing has changed simply break the loop\n         break;\n      }\n      flag = false;\n      end--; //decrease the end pointer\n      for(int i = end - 1; i >= start; i--){ //scan from right to left\n         if(arr[i] > arr[i+1]){\n            swap(arr[i], arr[i+1]);\n            flag = true;\n         }\n      }\n      start++;\n   }\n}\nmain() {int n;\n   cin>>n;\n   int a[n];\n   for(int i=0;i<n;i++)\n   cin>>a[i];\n   cout << \"Sorted Sequence \";\n   cocktailSort(a, n);\n   for(int i = 0; i <n;i++){\n      cout << a[i] << \" \";\n   }\n}\n"
  },
  {
    "path": "Algorithms/Sorting/Cocktail_Sort/Cocktail_Sort.java",
    "content": " import java.io.*;\n // Cocktail sort function sorts the unsorted array similar to bubble sort.\n // Cocktail sort algorithm has less complexity as compared to bubble sort.\n public class Cocktailsort {\n\tvoid cocktailsort(int l[], int n) {\n\t\t /*\n\t\t ** cocktail sort function takes two arguments-\n\t\t ** l is the list of elements that is unsorted and n is the length of the array.\n\t\t */\n\t\t // k is the variable used to check if the array contains sorted elements after sorting process. \n\t    int k = 1;\n\t     // first is the variable that denotes the first index in the array.\n\t    int first = 0;\n\t     // last denotes the last index in the array.\n\t    int last = n;\n\t    do {\n\t    \t // do-while loop is used to sort the array for the first time and next check the condition.\n\t\t    k = 0;\n\t\t    for (int i = first; i < last - 1; i++) {\n\t\t     \t // for loop performs the forward sort on the array.\n\t\t\t    if (l[ i ] > l[ i + 1 ]) {\n\t\t\t    \tint temp = l[i];\n\t\t\t\t    l[i] = l[i+1];\n\t\t\t\t    l[i+1] = temp;\n\t\t\t\t    k = 1;\n\t\t\t    }\n\t\t    }\n\t\t     // To check the array status if it is sorted the k is 0 and controls moves out of loop.\n\t\t    if (k == 0) {\n\t\t\t    break;\n\t\t    } else {\n\t\t    \tk = 1;\n\t\t    \t // the last index is decreased by 1 as largets element in array is sorted in each try.\n\t\t    \tlast--;\n\t    \t}\n\t\t    for (int i = last - 1; i >= first; i--) {\n\t\t    \t // for loop performs the backward sort on the array\n\t\t\t    if (l[ i ] > l[ i + 1 ]) {\n\t\t\t\t    int temp = l[i];\n\t\t\t        l[i] = l[i+1];\n\t\t\t\t    l[i+1] = temp;\n\t\t\t\t    k = 1;\n\t\t\t    }\n\t\t    }\n\t\t     // the first index is increased by 1 after backward sort.\n\t\t    first++;\n\t    }while (k == 1);\n\t}\n\n\tvoid printArray(int a[]) { \n    \t // this funtion prints the sorted array elements.\n        int n = a.length; \n        for (int i = 0; i < n; i++) \n            System.out.print(a[i] + \" \"); \n    } \n\n    public static void main(String[] args) { \n    \tCocktailsort ob = new Cocktailsort(); \n         // a denotes the unsorted array.\n        int a[] = { 5, 1, 4, 2, 8, 0, 2 , 5, 3, 1}; \n         // n is the variable used to get the size of array.\n        int n = a.length;\n         // cocktail sort function is called to sort the array.\n        ob.cocktailsort(a,n);\n         // To print the sorted array, printarray is called with parameter a i.e. sorted array \n        ob.printArray(a); \n    } \n}\n\n"
  },
  {
    "path": "Algorithms/Sorting/Cocktail_Sort/Cocktail_Sort.py",
    "content": "# cocktailsort is the function used to sort array\n# it is just like bubble sort with less complexity comparatively\ndef cocktailsort(l):\n    # first indicates the first index of the array\n    first = 0\n    # k is the variable that counts the length of the array\n    k = len(l)\n    # last indicates the last index element of the array\n    last = k - 1\n    # t variable is used to denote if array is sorted after the sorting process.\n    # it is initialised 1 to check if array is sorted after every iteration\n    t = 1\n    # temp is used as third variable to exchange the values\n    temp = 0\n    while t != 0:\n        # t is set to 0 when loop conditions comes true\n        # both forward and backward sort runs simultaneously\n        t = 0\n        # this for loop will do the forward sort\n        # the greatest element after each pass will be at the last index\n        for i in range(first, last, 1):\n            if l[i] < l[i + 1]:\n                continue\n            else:\n                temp = l[i]\n                l[i] = l[i + 1]\n                l[i + 1] = temp\n                t = 1\n        # t is initialised to 1 to chech if the loop was sorted or not in the forward sort\n        # if value of t was not changed the control will jump off the loop\n        # else the control will move to the backward sort\n        if t == 0:\n            break\n        else:\n            t = 0\n            # value of last is decreased everytime that shows the greatest element is found after forward sort\n            last -= 1\n        # the next loop will do the backward sort in the array\n        for i in range(last, first - 1, -1):\n            if l[i] < l[i + 1]:\n                continue\n            else:\n                temp = l[i]\n                l[i] = l[i + 1]\n                l[i + 1] = temp\n                # t is set to 1 to show array has completed one backward sort pass.\n                t = 1\n        # value of first variable is increased everytime as smallest element is found after backward sort\n        first += 1\n    # when both the sorting is done the array is returned\n    return l\n\n\n# sample array is taken\na = [23, 1, 5, 32, 122, 76, 45]\nc = cocktailsort(a)\nprint(\"New Array: \")\nfor i in a:\n    print(i, end=\" \")\n# output-> New Array: 1 5 23 32 45 76 122\n"
  },
  {
    "path": "Algorithms/Sorting/Cocktail_Sort/README.md",
    "content": "## This folder is empty.\n"
  },
  {
    "path": "Algorithms/Sorting/Cocktail_Sort/cocktail_sort.js",
    "content": "var inputArray = [];\nvar size = prompt('Enetr the size: ');\n\nfor(var i=0; i<size; i++) {\n\t\n\tinputArray[i] = prompt('Enter Element ' + (i+1) + ' : ');\n}\n\n\nlet nums = inputArray;\nconsole.log(\"Original array:\");\nconsole.log(nums);\nlet is_Sorted = true;\nwhile (is_Sorted){\n\tfor (let i = 0; i< nums.length - 1; i++){\n\t  if (nums[i] > nums[i + 1])\n\t    {\n      \tlet temp = nums[i];\n        nums[i] = nums[i + 1];\n        nums[i+1] = temp;\n        is_Sorted = true;\n      }\n   }\n\n\t\tif (!is_Sorted)\n\t    break;\n\n   is_Sorted = false;\n\n   for (let j = nums.length - 1; j > 0; j--){\n\t\t if (nums[j-1] > nums[j])\n  \t   {\n  \t     let temp = nums[j];\n         nums[j] = nums[j - 1];\n         nums[j - 1] = temp;\n  \t     is_Sorted = true;\n       }\n   }\n}\nconsole.log(\"Sorted array:\")\nconsole.log(nums);\n"
  },
  {
    "path": "Algorithms/Sorting/Comb_Sort/Comb_Sort.c",
    "content": "#include<stdio.h>\n#include<stdlib.h>\n#include <stdbool.h>\n\nint newGap(int gap) {\n  gap = (gap * 10) / 13;\n  if (gap == 9 || gap == 10)\n    gap = 11;\n  if (gap < 1)\n    gap = 1;\n  return gap;\n}\nvoid combsort(int a[], int aSize) {\n  int gap = aSize;\n  for (;;) {\n    gap = newGap(gap);\n    bool swapped = false;\n    for (int i = 0; i < aSize - gap; i++) {\n      int j = i + gap;\n      if (a[i] > a[j]) {\n        int temp=a[i];\n           a[i]=a[i + gap];\n           a[i + gap]=temp;\n        swapped = true;\n      }\n    }\n    if (gap == 1 && !swapped)\n      break;\n  }\n}\nint main()\n{\n    int i , N;\n    printf(\"Enter Size of Array :-\\n\");\n    scanf(\"%d\",&N);\n    int A[N];\n    printf(\"Enter Array Elements :-\\n\");\n    for(i = 0 ;i < N;i++)\n        scanf(\"%d\",&A[i]);\n    combsort(A , N);\n    printf(\"Sorted Array :-\\n\");\n    for(i = 0 ;i < N;i++)\n        printf(\"%d \",A[i]);\n    printf(\"\\n\");\n\n    return 0;\n}\n"
  },
  {
    "path": "Algorithms/Sorting/Comb_Sort/Comb_Sort.cpp",
    "content": "include<iostream>\n#include<algorithm>\nusing namespace std;\nvoid display(int *array, int size){\n   for(int i = 0; i<size; i++)\n      cout << array[i] << \" \";\n   cout << endl;\n}\nvoid combSort(int *array, int size){\n   int gap = size; //initialize gap size with size of array\n   bool flag = true;\n   while(gap != 1 || flag == true){\n      gap = (gap*10)/13; //minimize gap by shrink factor\n      if(gap<1)\n         gap = 1;\n      flag = false;\n      for(int i = 0; i<size-gap; i++){ //compare elements with gap\n         if(array[i] > array[i+gap]){\n            swap(array[i], array[i+gap]);\n            flag = true;\n         }\n      }\n   }\n}\nint main(){\n   int n;\n   cout << \"Enter the number of elements: \";\n   cin >> n;\n   int arr[n]; //create an array with given number of elements\n   cout << \"Enter elements:\" << endl;\n   for(int i = 0; i<n; i++){\n      cin >> arr[i];\n   }\n   cout << \"Array before Sorting: \";\n   display(arr, n);\n   combSort(arr, n);\n   cout << \"Array after Sorting: \";\n   display(arr, n);\n}\n"
  },
  {
    "path": "Algorithms/Sorting/Comb_Sort/README.md",
    "content": "## This folder is empty.\n"
  },
  {
    "path": "Algorithms/Sorting/Comb_Sort/comb.py",
    "content": "def getNextGap(gap):  \n\tgap = (gap * 10)/13\n\tif gap < 1: \n\t\treturn 1\n\treturn gap \n\ndef combSort(array_to_sort): \n\tgap = n = len(array_to_sort) \n\tto_swap = 1\n\n\twhile gap !=1 or to_swap == 1: \n\t\tgap = getNextGap(gap) \n\t\tto_swap = 0\n\t\tfor i in range(0, n-gap): \n\t\t\tif array_to_sort[i] > array_to_sort[i + gap]: \n\t\t\t\tarray_to_sort[i], array_to_sort[i + gap] = array_to_sort[i + gap], array_to_sort[i] \n\t\t\t\tto_swap = 1\n\n\narray_to_sort = [2,3,24,45,2,11,5,42,24] \ncombSort(array_to_sort) \n\nprint (\"Array after applying comb sort\") \nfor i in range(len(array_to_sort)): \n\tprint (array_to_sort[i]), \n"
  },
  {
    "path": "Algorithms/Sorting/Comb_Sort/comb_sort.rb",
    "content": "# The gap starts with a large value and shrinks by a factor of 1.3 in every iteration until it reaches the value 1.\ndef comb_sort(arr)\n    gap = arr.length\n   \n    while gap > 1\n        i = 0\n        gap /= 1.3\n        gap = gap.to_i\n        while arr[i + gap]\n            if arr[i] > arr[i + gap]\n                temp = arr[i]\n                arr[i] = arr[i + gap]\n                arr[i + gap] = temp\n            end\n            i += 1\n        end\n    end\n    arr\nend\n"
  },
  {
    "path": "Algorithms/Sorting/Counting_Sort/Count_sort.py",
    "content": "\"\"\"Count Sort\nTime Complexity : O(n)\nSpace Complexity : O(n+k), k is range of input data\n\nIt can work on negative no. also\n\"\"\"\ndef count_sort(ls):\n    mx=max(ls)\n    mi=min(ls)\n    rang=(mx-mi+1)      #range of input data\n    count=[0]*rang      #count list\n    out=['Null']*len(ls)    #output list intialised with NUll values\n    \n    #calculating frequency\n    for i in ls:\n        count[i-mi]=count[i-mi]+1\n\n    #cumulative sum of Frequency\n    for i in range(1,len(count)):\n        count[i]=count[i]+count[i-1]\n\n    #output the data in out array in sorted order\n    for i in range(len(ls)-1,-1,-1):\n        out[count[ls[i]-mi]-1]=ls[i]\n        count[ls[i]-mi]=count[ls[i]-mi]-1\n\n    #copy the content of out list to original list\n    for i in range(len(out)):\n        ls[i]=out[i]\n        \n    return ls\n\nif __name__ == \"__main__\":\n    ls=list(map(int,input(\"Enter the array :: \").split()))\n    ls= count_sort(ls)\n    print(ls)\n"
  },
  {
    "path": "Algorithms/Sorting/Counting_Sort/Counting_Sort.c",
    "content": "#include <stdio.h> \n#include <stdlib.h>\n\nvoid countSort(int arr[], int len) \n{ \n    int* output = (int*) malloc(len * sizeof(int));\n\t// Create a count array to store count of inidividul numbers \n\tint count[10], i; \n\n\t// Store count of each character \n\tfor (i = 0; i < len; ++i) \n\t\t++count[arr[i]]; \n\n\t// Change count[i] so that count[i] contains cumulative count \n\tfor (i = 1; i < 10; ++i) \n\t\tcount[i] += count[i - 1]; \n\n\t// Build the sorted array \n\tfor (i = 0; i < len; ++i) \n\t{ \n\t\toutput[count[arr[i]] - 1] = arr[i]; \n\t\t--count[arr[i]]; \n\t}\n\t\n\tfor (i = 0; i < len; i++)\n\t    arr[i] = output[i];\n\n} \n\nint main() \n{ \n    //Assumption: Array only contains numbers from 0-9\n\tint arr[] = {4,3,2,1,4,2,1,5,6,4};\n\tint n = sizeof(arr)/sizeof(arr[0]);\n\n\tcountSort(arr, n); \n\n\tprintf(\"Sorted Array:\");\n\tfor(int i = 0; i < n; i++)\n\t{\n\t    printf(\"%d \",arr[i]);\n\t}\n\treturn 0; \n} \n"
  },
  {
    "path": "Algorithms/Sorting/Counting_Sort/Counting_Sort.cs",
    "content": "using System;\n\nclass Program\n{\n    /// <summary>\n    /// Sorts the integers in the given array using the Counting SOrt algorithm.\n    /// </summary>\n    public static int[] CountingSort(int[] arrayToSort)\n    {\n        int[] sortedArray = new int[arrayToSort.Length];\n        \n        int minimumValue = arrayToSort[0];\n        int maximumValue = arrayToSort[0];\n\n        for (int i = 1; i < arrayToSort.Length; i++)\n        {\n            if (arrayToSort[i] < minimumValue)\n            {\n                minimumValue = arrayToSort[i];\n            }\n            else if (arrayToSort[i] > maximumValue)\n            {\n                maximumValue = arrayToSort[i];\n            }\n        }\n\n        int[] counts = new int[((maximumValue - minimumValue) + 1)];\n\n        for (int i = 0; i < arrayToSort.Length; i++)\n        {\n            counts[(arrayToSort[i] - minimumValue)] += 1;\n        }\n\n        counts[0] -= 1;\n\n        for (int i = 1; i < counts.Length; i++)\n        {\n            counts[i] = (counts[i] + counts[(i - 1)]);\n        }\n\n        for (int i = arrayToSort.Length - 1; i > -1; i--)\n        {\n            sortedArray[(counts[(arrayToSort[i] - minimumValue)]--)] = arrayToSort[i];\n        }\n     \n        return sortedArray;\n    }\n\n    /// <summary>\n    /// Main application function.\n    /// </summary>\n    static void Main()\n    {\n        int[] arrayToSort;\n        string userInput;\n        \n        Console.WriteLine(\"Enter the integers that you want to sort as a comma delimited string:\");\n        userInput = Console.ReadLine();\n        \n        string[] splittedItems = userInput.Split(new string[] { \" \", \",\", \";\", \"|\" }, StringSplitOptions.RemoveEmptyEntries);\n\n        if (splittedItems.Length == 0) { Program.ExitAfterInvalidInput(); }\n        \n        arrayToSort = new int[splittedItems.Length];\n\n        for (int i = 0; i < splittedItems.Length; i++)\n        {\n            int parsedInteger;\n\n            if (int.TryParse(splittedItems[i], out parsedInteger) == false) { Program.ExitAfterInvalidInput(); }\n\n            arrayToSort[i] = parsedInteger;\n        }\n\n        int[] sortedArray = Program.CountingSort(arrayToSort);\n        \n        Console.WriteLine();\n        Console.WriteLine(string.Format(\"Unsorted : {0}\", string.Join(\", \", userInput)));\n        Console.WriteLine(string.Format(\"Sorted   : {0}\", string.Join(\", \", sortedArray)));\n    }\n    \n    /// <summary>\n    /// Informs the user that an invalid value has been entered and exits the program.\n    /// </summary>\n    private static void ExitAfterInvalidInput()\n    {\n        Console.WriteLine(\"You've entered an invalid value. Exiting...\");\n        Environment.Exit(1);\n    }\n}\n"
  },
  {
    "path": "Algorithms/Sorting/Counting_Sort/Counting_Sort.java",
    "content": "package algo_ds_101.Algorithms.Sorting_Algorithms.Counting_Sort;\n\nimport java.io.*;\nimport java.util.*;\n\nclass Counting_Sort\n{\n    public static void main(String[] args) {\n        int n, k = 0, i,j;  \n        int []A=new int[15];\n        int []B=new int[15];\n        int []C=new int[100];\n        System.out.println(\"Enter the number of input : \");  \n        Scanner sc = new Scanner(System.in);\n        n=sc.nextInt();\n        System.out.println(\"\\nEnter the elements to be sorted :\\n\");  \n        for (i = 1; i <= n; i++)  \n        {  \n            A[i]=sc.nextInt();  \n            if (A[i] > k) {  \n                k = A[i];  \n            }  \n        }    \n        System.out.println(\"\\n\");    \n  \n    for (i = 0; i <= k; i++)  \n        C[i] = 0;  \n    for (j = 1; j <= n; j++)  \n        C[A[j]] = C[A[j]] + 1;  \n    for (i = 1; i <= k; i++)  \n        C[i] = C[i] + C[i-1];  \n    for (j = n; j >= 1; j--)  \n    {  \n        B[C[A[j]]] = A[j];  \n        C[A[j]] = C[A[j]] - 1;  \n    }  \n    System.out.println(\"The Sorted array is : \");  \n    for (i = 1; i <= n; i++)  \n        System.out.println(B[i]);  \n  \n   \n}\n}\n"
  },
  {
    "path": "Algorithms/Sorting/Counting_Sort/Counting_sort.js",
    "content": "function counting_sort(arrin) {\n    let arrout = new Array(arrin.length) //Creates the output array\n\n    let arrcount = new Array(arrin.reduce(\n        (prev, cur) => {\n            return biggest = prev > cur ? prev : cur;\n        }\n    )).fill(0) //Creates the counting array (number = index - 1, value = quantity)\n\n    //Gets the numbers quatities in their respective index\n    arrin.forEach(val => arrcount[val - 1] += 1)\n\n    let startpos = 0 //Starting position to fill with numbers\n\n    arrcount.forEach((val, index) => {\n        if (val != 0) { //If this number exists in the input array, its quantity is different than 0\n\n            //Fill the output array with the number by its quantity beggining in the starting position\n            //and ending after the number quantity\n            arrout.fill(index + 1, startpos, startpos + val)\n\n            startpos += val //Changes the starting position to the last known position for the next number\n        }\n    })\n\n    return arrout //Return the sorted array\n}\n\n//Example of this algorithm\nlet example_input = [1, 4, 1, 2, 7, 5, 2]\nlet output = counting_sort(example_input)\nconsole.log(`${example_input} sorted is ${output}`)\n\n//Author -> GuilhermeOliveiraCasagrande"
  },
  {
    "path": "Algorithms/Sorting/Counting_Sort/README.md",
    "content": "## This folder is empty.\n"
  },
  {
    "path": "Algorithms/Sorting/Counting_Sort/counting_sort.py",
    "content": "def countingSort(array):\n    size = len(array)\n    output = [0] * size\n    count = [0] * 10\n    for i in range(0, size):\n        count[array[i]] += 1\n    for i in range(1, 10):\n        count[i] += count[i - 1]\n    i = size - 1\n    while i >= 0:\n        output[count[array[i]] - 1] = array[i]\n        count[array[i]] -= 1\n        i -= 1\n    for i in range(0, size):\n        array[i] = output[i]\n\n\ndata = [4, 2, 2, 8, 3, 3, 1]\ncountingSort(data)\nprint(\"Sorted Array in Ascending Order: \")\nprint(data)\n"
  },
  {
    "path": "Algorithms/Sorting/Counting_Sort/countingsort.py",
    "content": " def countSort(arr):  \n\toutput = [0 for i in range(256)] \n\tcount = [0 for i in range(256)]  \n\tans = [\"\" for _ in arr] \n\tfor i in arr: \n\t\tcount[ord(i)] += 1\n\n\tfor i in range(256): \n\t\tcount[i] += count[i-1] \n\tfor i in range(len(arr)): \n\t\toutput[count[ord(arr[i])]-1] = arr[i] \n\t\tcount[ord(arr[i])] -= 1\n\tfor i in range(len(arr)): \n\t\tans[i] = output[i] \n\treturn ans \n\narr = \"abfhuervbvnonvioebvoavnioscd\"\nans = countSort(arr) \nprint(\"Sorted character array is %s\" %(\"\".join(ans)) )\n"
  },
  {
    "path": "Algorithms/Sorting/Cycle_Sort/CYCLESort.cs",
    "content": "using System; \n\n  \n//MyCode\nclass GFG { \n\n      \n\n    // Function sort the array using Cycle sort \n\n    public static void cycleSort(int[] arr, int n) \n\n    { \n\n        // count number of memory writes \n\n        int writes = 0; \n\n  \n\n        // traverse array elements and  \n\n        // put it to on the right place \n\n        for (int cycle_start = 0; cycle_start <= n - 2; cycle_start++) \n\n        { \n\n            // initialize item as starting point \n\n            int item = arr[cycle_start]; \n\n  \n\n            // Find position where we put the item.  \n\n            // We basically count all smaller elements  \n\n            // on right side of item. \n\n            int pos = cycle_start; \n\n            for (int i = cycle_start + 1; i < n; i++) \n\n                if (arr[i] < item) \n\n                    pos++; \n\n  \n\n            // If item is already in correct position \n\n            if (pos == cycle_start) \n\n                continue; \n\n  \n\n            // ignore all duplicate elements \n\n            while (item == arr[pos]) \n\n                pos += 1; \n\n  \n\n            // put the item to it's right position \n\n            if (pos != cycle_start) { \n\n                int temp = item; \n\n                item = arr[pos]; \n\n                arr[pos] = temp; \n\n                writes++; \n\n            } \n\n  \n\n            // Rotate rest of the cycle \n\n            while (pos != cycle_start) { \n\n                pos = cycle_start; \n\n  \n\n                // Find position where we put the element \n\n                for (int i = cycle_start + 1; i < n; i++) \n\n                    if (arr[i] < item) \n\n                        pos += 1; \n\n  \n\n                // ignore all duplicate elements \n\n                while (item == arr[pos]) \n\n                    pos += 1; \n\n  \n\n                // put the item to it's right position \n\n                if (item != arr[pos]) { \n\n                    int temp = item; \n\n                    item = arr[pos]; \n\n                    arr[pos] = temp; \n\n                    writes++; \n\n                } \n\n            } \n\n        } \n\n    } \n\n  \n\n    // Driver program to test above function \n\n    public static void Main() \n\n    { \n\n        int[] arr = { 1, 8, 3, 9, 10, 10, 2, 4 }; \n\n        int n = arr.Length; \n\n          \n\n        // Function calling \n\n        cycleSort(arr, n); \n\n  \n\n        Console.Write(\"After sort : \"); \n\n        for (int i = 0; i < n; i++) \n\n            Console.Write(arr[i] + \" \"); \n\n    } \n} \n"
  },
  {
    "path": "Algorithms/Sorting/Cycle_Sort/Cyclesort.py",
    "content": "def cycleSort(array): \n  writes = 0\n    \n  # Loop through the array to find cycles to rotate. \n  for cycleStart in range(0, len(array) - 1): \n    item = array[cycleStart] \n      \n    # Find where to put the item. \n    pos = cycleStart \n    for i in range(cycleStart + 1, len(array)): \n      if array[i] < item: \n        pos += 1\n      \n    # If the item is already there, this is not a cycle. \n    if pos == cycleStart: \n      continue\n      \n    # Otherwise, put the item there or right after any duplicates. \n    while item == array[pos]: \n      pos += 1\n    array[pos], item = item, array[pos] \n    writes += 1\n      \n    # Rotate the rest of the cycle. \n    while pos != cycleStart: \n        \n      # Find where to put the item. \n      pos = cycleStart \n      for i in range(cycleStart + 1, len(array)): \n        if array[i] < item: \n          pos += 1\n        \n      # Put the item there or right after any duplicates. \n      while item == array[pos]: \n        pos += 1\n      array[pos], item = item, array[pos] \n      writes += 1\n    \n  return writes \n    \n#  driver code  \narr = [1, 8, 3, 9, 10, 10, 2, 4 ] \nn = len(arr)  \ncycleSort(arr) \n  \nprint(\"After sort : \") \nfor i in range(0, n) :  \n    print(arr[i], end = \\' \\') \n"
  },
  {
    "path": "Algorithms/Sorting/Cycle_Sort/README.md",
    "content": "## This folder is empty.\n"
  },
  {
    "path": "Algorithms/Sorting/Cycle_Sort/cyclesort.c",
    "content": "void cycleSort(int arr[], int n) \n{ \n    // count number of memory writes \n    int writes = 0; \n  \n    // traverse array elements and put it to on \n    // the right place \n    for (int cycle_start = 0; cycle_start <= n - 2; cycle_start++) { \n        // initialize item as starting point \n        int item = arr[cycle_start]; \n  \n        // Find position where we put the item. We basically \n        // count all smaller elements on right side of item. \n        int pos = cycle_start; \n        for (int i = cycle_start + 1; i < n; i++) \n            if (arr[i] < item) \n                pos++; \n  \n        // If item is already in correct position \n        if (pos == cycle_start) \n            continue; \n  \n        // ignore all duplicate  elements \n        while (item == arr[pos]) \n            pos += 1; \n  \n        // put the item to it's right position \n        if (pos != cycle_start) { \n            swap(item, arr[pos]); \n            writes++; \n        } \n  \n        // Rotate rest of the cycle \n        while (pos != cycle_start) { \n            pos = cycle_start; \n  \n            // Find position where we put the element \n            for (int i = cycle_start + 1; i < n; i++) \n                if (arr[i] < item) \n                    pos += 1; \n  \n            // ignore all duplicate  elements \n            while (item == arr[pos]) \n                pos += 1; \n  \n            // put the item to it's right position \n            if (item != arr[pos]) { \n                swap(item, arr[pos]); \n                writes++; \n            } \n        } \n    } \n  \n    // Number of memory writes or swaps \n    // cout << writes << endl ; \n} \n  \n// Driver program to test above function \nint main() \n{ \n    int arr[] = { 1, 8, 3, 9, 10, 10, 2, 4 }; \n    int n = sizeof(arr) / sizeof(arr[0]); \n    cycleSort(arr, n); \n  \n    cout << \"After sort : \" << endl; \n    for (int i = 0; i < n; i++) \n        cout << arr[i] << \" \"; \n    return 0; \n} "
  },
  {
    "path": "Algorithms/Sorting/Cycle_Sort/stoogesort.java",
    "content": "import java.io.*; \n  \npublic class stooge { \n    // Function to implement stooge sort \n    static void stoogesort(int arr[], int l, int h) \n    { \n        if (l >= h) \n            return; \n  \n        if (arr[l] > arr[h]) { \n            int t = arr[l]; \n            arr[l] = arr[h]; \n            arr[h] = t; \n        } \n  \n        \n        if (h - l + 1 > 2) { \n            int t = (h - l + 1) / 3; \n  \n           \n            stoogesort(arr, l, h - t); \n  \n            \n            stoogesort(arr, l + t, h); \n            stoogesort(arr, l, h - t); \n        } \n    } \n  \n    public static void main(String args[]) \n    { \n        int arr[] = { 2, 4, 5, 3, 1 }; \n        int n = arr.length; \n  \n        stoogesort(arr, 0, n - 1); \n  \n        for (int i = 0; i < n; i++) \n            System.out.print(arr[i] + \" \"); \n    } \n} \n"
  },
  {
    "path": "Algorithms/Sorting/Gnome_Sort/Gnome_Sort.cs",
    "content": "// C# Program to implement Gnome Sort \nusing System; \n  \nclass GFG { \n      \n    static void gnomeSort(int[] arr, int n) \n    { \n        int index = 0; \n  \n        while (index < n)  \n        { \n            if (index == 0) \n                index++; \n            if (arr[index] >= arr[index - 1]) \n                index++; \n            else { \n                int temp = 0; \n                temp = arr[index]; \n                arr[index] = arr[index - 1]; \n                arr[index - 1] = temp; \n                index--; \n            } \n        } \n        return; \n    } \n  \n    // Driver program to test above functions. \n    public static void Main() \n    { \n        int[] arr = { 34, 2, 10, -9 }; \n          \n        // Function calling \n        gnomeSort(arr, arr.Length); \n  \n        Console.Write(\"Sorted sequence after applying Gnome sort: \"); \n  \n        for (int i = 0; i < arr.Length; i++) \n            Console.Write(arr[i] + \" \"); \n    } \n} \n  \n// This code is contributed by Sam007 \n"
  },
  {
    "path": "Algorithms/Sorting/Gnome_Sort/Gnome_Sort.java",
    "content": "// Java Program to implement Gnome Sort \n  \nimport java.util.Arrays; \npublic class GFG { \n    static void gnomeSort(int arr[], int n) \n    { \n        int index = 0; \n  \n        while (index < n) { \n            if (index == 0) \n                index++; \n            if (arr[index] >= arr[index - 1]) \n                index++; \n            else { \n                int temp = 0; \n                temp = arr[index]; \n                arr[index] = arr[index - 1]; \n                arr[index - 1] = temp; \n                index--; \n            } \n        } \n        return; \n    } \n  \n    // Driver program to test above functions. \n    public static void main(String[] args) \n    { \n        int arr[] = { 34, 2, 10, -9 }; \n  \n        gnomeSort(arr, arr.length); \n  \n        System.out.print(\"Sorted sequence after applying Gnome sort: \"); \n        System.out.println(Arrays.toString(arr)); \n    } \n} \n  \n// Code Contributed by Mohit Gupta_OMG \n"
  },
  {
    "path": "Algorithms/Sorting/Gnome_Sort/Gnome_Sort.php",
    "content": "<?php \n// PHP Program to implement \n// Gnome Sort \n  \n// A function to sort the  \n// algorithm using gnome sort \nfunction gnomeSort($arr, $n) \n{ \n    $index = 0; \n  \n    while ($index < $n)  \n    { \n        if ($index == 0) \n            $index++; \n        if ($arr[$index] >= $arr[$index - 1]) \n            $index++; \n        else \n        { \n            $temp = 0; \n            $temp = $arr[$index]; \n            $arr[$index] = $arr[$index - 1]; \n            $arr[$index - 1] = $temp; \n            $index--; \n        } \n    } \n    echo \"Sorted sequence \",  \n         \"after Gnome sort: \"; \n    for ($i = 0; $i < $n; $i++) \n        echo $arr[$i] . \" \"; \n    echo \"\\n\";  \n} \n  \n// Driver Code \n$arr = array(34, 2, 10, -9); \n$n = count($arr); \n  \ngnomeSort($arr, $n); \n  \n// This code is contributed \n// by Sam007 \n?> \n"
  },
  {
    "path": "Algorithms/Sorting/Gnome_Sort/Gnome_Sort.py",
    "content": "# Python program to implement Gnome Sort \n  \n# A function to sort the given list using Gnome sort \ndef gnomeSort( arr, n): \n    index = 0\n    while index < n: \n        if index == 0: \n            index = index + 1\n        if arr[index] >= arr[index - 1]: \n            index = index + 1\n        else: \n            arr[index], arr[index-1] = arr[index-1], arr[index] \n            index = index - 1\n  \n    return arr \n  \n# Driver Code \narr = [ 34, 2, 10, -9] \nn = len(arr) \n  \narr = gnomeSort(arr, n) \nprint \"Sorted seqquence after applying Gnome Sort :\", \nfor i in arr: \n    print i, \n  \n# Contributed By Harshit Agrawal \n"
  },
  {
    "path": "Algorithms/Sorting/Gnome_Sort/gnomeSort.java",
    "content": "//Implementation of gnome sort in java\nimport java.util.Arrays;\nclass gnomeSort {\n void gnomeSort(int[] nums)\n  {\n  int i=1;\n  int j=2;\n \n  while(i < nums.length) {\n    if ( nums[i-1] <= nums[i] ) \n\t{\n      i = j; j++;\n    } else {\n      int tmp = nums[i-1];\n      nums[i-1] = nums[i];\n      nums[i--] = tmp;\n      i = (i==0) ? j++ : i;\n    }\n  }\n}\n  \n    // Method to test above\n    public static void main(String args[])\n    {\n        gnomeSort ob = new gnomeSort();\n        int nums[] = {7, -5, 3, 2, 1, 0, 45};\n        System.out.println(\"Original Array:\");\n        System.out.println(Arrays.toString(nums));\n        ob.gnomeSort(nums);\n        System.out.println(\"Sorted Array\");\n        System.out.println(Arrays.toString(nums));\n    }\n}\n"
  },
  {
    "path": "Algorithms/Sorting/Heap_Sort/Heap_Sort.js",
    "content": "var heapSort = function(array) {\n  var swap = function(array, firstIndex, secondIndex) {\n    var temp = array[firstIndex];\n    array[firstIndex] = array[secondIndex];\n    array[secondIndex] = temp;\n  };\n\n  var maxHeap = function(array, i) {\n    var l = 2 * i;\n    var r = l + 1;\n    var largest;\n    if (l < array.heapSize && array[l] > array[i]) {\n      largest = l;\n    } else {\n      largest = i;\n    }\n    if (r < array.heapSize && array[r] > array[largest]) {\n      largest = r;\n    }\n    if (largest != i) {\n      swap(array, i, largest);\n      maxHeap(array, largest);\n    }\n  };\n  var buildHeap = function(array) {\n    array.heapSize = array.length;\n    for (var i = Math.floor(array.length / 2); i >= 0; i--) {\n      maxHeap(array, i);\n    }\n  };\n  buildHeap(array);\n  for (var i = array.length-1; i >= 1; i--) {\n    swap(array, 0, i);\n    array.heapSize--;\n    maxHeap(array, 0);\n\n    console.log(a + \" \");\n  }\n};\nvar a = [6, 5, 3, 1, 8, 7, 2, 4];\nheapSort(a);"
  },
  {
    "path": "Algorithms/Sorting/Heap_Sort/Heap_Sort.swift",
    "content": "private extension Int {\n  var parent: Int {\n    return (self - 1) / 2\n  }\n  \n  var leftChild: Int {\n    return (self * 2) + 1\n  }\n  \n  var rightChild: Int {\n    return (self * 2) + 2\n  }\n}\n\nclass SortingAlgorithms {\n  private init() {}\n  \n  public static func heapSort<DataType: Comparable>(_ array: inout [DataType]) {\n    if array.count < 2 { return }\n    buildHeap(&array)\n    shrinkHeap(&array)\n  }\n  \n  private static func buildHeap<DataType: Comparable>(_ array: inout [DataType]) {\n    for index in 1..<array.count {\n      var child = index\n      var parent = child.parent\n      while child > 0 && array[child] > array[parent] {\n        swap(child, with: parent, in: &array)\n        child = parent\n        parent = child.parent\n      }\n    }\n  }\n  \n  private static func shrinkHeap<DataType: Comparable>(_ array: inout [DataType]) {\n    for index in stride(from: array.count - 1, to: 0, by: -1) {\n      swap(0, with: index, in: &array)\n      var parent = 0\n      var leftChild = parent.leftChild\n      var rightChild = parent.rightChild\n      while parent < index {\n        var maxChild = -1\n        if leftChild < index {\n          maxChild = leftChild\n        } else {\n          break\n        }\n        if rightChild < index && array[rightChild] > array[maxChild] {\n          maxChild = rightChild\n        }\n        guard array[maxChild] > array[parent] else { break }\n        \n        swap(parent, with: maxChild, in: &array)\n        parent = maxChild\n        leftChild = parent.leftChild\n        rightChild = parent.rightChild\n      }\n    }\n  }\n  \n  private static func swap<DataType: Comparable>(_ firstIndex: Int, with secondIndex: Int, in array: inout [DataType]) {\n    let temp = array[firstIndex]\n    array[firstIndex] = array[secondIndex]\n    array[secondIndex] = temp\n  }\n}\n\nvar myArray = [3,4,1,2]\nSortingAlgorithms.heapSort(&myArray)\nprint(myArray)\n"
  },
  {
    "path": "Algorithms/Sorting/Heap_Sort/Max_heap_sort.cpp",
    "content": "/*\r\n\tAuthor : codewithrathi\r\n*/\r\n\r\n/*Problem Statement : \r\nImplement Heap sort to sort given set of values using max heap.*/\r\n\r\n#include <bits/stdc++.h> \r\nusing namespace std; \r\n\r\n\r\nvoid downadj(int heap[],int i,int n) //down adjust \r\n{ \r\n   int l=2*i,r=2*i+1; \r\n   int max=i; \r\n   if(l<n && heap[l]>heap[max]) \r\n   { \r\n       max=l; \r\n   } \r\n   if(r<n && heap[r]>heap[max]) \r\n   { \r\n       max=r; \r\n   } \r\n   if(max!=i) \r\n   { \r\n       swap(heap[i],heap[max]); \r\n       downadj(heap,max,n); \r\n   } \r\n}\r\n \r\nvoid show(int arr[],int n,int x) //print array \r\n{ \r\n   if(x==1) \r\n   { \r\n       cout<<\"ELEMENTS IN MAX HEAP IS AS :\\n\\n\"; \r\n   } \r\n   else \r\n   { \r\n       cout<<\"SORTED ARRAY IS :\\n\\n\"; \r\n   } \r\n\r\n   for(int i=1;i<=n;i++) \r\n   { \r\n       cout<<\"At position : \"<<i<<\" \\t------> \\t\"; \r\n       cout<<arr[i]<<\"\\n\"; \r\n   } \r\n\r\n   cout<<endl; \r\n} \r\n\r\nvoid upadj(int heap[],int i) //up adjust \r\n{ \r\n   while(i>1 && heap[i]>heap[i/2]) \r\n   { \r\n       swap(heap[i],heap[i/2]); \r\n       i=i/2; \r\n   } \r\n} \r\n\r\nvoid insert(int a[],int x) //construct max heap (Step 1) \r\n{ \r\n   int heap[x+1],n,i; \r\n   heap[0]=0,i=1; \r\n   while(i<(x+1)) \r\n   { \r\n       n=heap[0]; \r\n       heap[n+1]=a[i]; \r\n       heap[0]=n+1; \r\n       upadj(heap,n+1); \r\n       i++; \r\n   } \r\n   show(heap,heap[0],1); \r\n   n=heap[0]; \r\n   while(n>1) \r\n   { \r\n swap(heap[1],heap[n]); //(step 2) \r\n n--; //(step 3) \r\n downadj(heap,1,n); //(step 4) \r\n} \r\nshow(heap,heap[0],2); \r\n} \r\n\r\nint main() \r\n{ \r\n   int n; \r\n   cout<<\"****************************************************\\n\"; \r\n   cout<<\"IMPLEMENTATION OF HEAP SORT TO SORT USING MAX HEAP \\n\"; \r\n   cout<<\"****************************************************\\n\"; \r\n   cout<<\"\\nEnter the Number of elements in Array ?\\n\"; \r\n   cin>>n; \r\n   int a[n+1]; \r\n   a[0]=n; \r\n   for(int i=1;i<n+1;i++) \r\n   { \r\n       cout<<\"Enter the element \"<<i<<endl; \r\n       cin>>a[i]; \r\n   } \r\n   insert(a,n); \r\n   cout<<\"\\nOPERATION COMPLETED!! THANK YOU\"; \r\n   return 0; \r\n} \r\n\r\n/*\r\n-----------------------------------------------------------------------------------------------------------------------------\r\nOUTPUT :\r\n\r\n****************************************************\r\nIMPLEMENTATION OF HEAP SORT TO SORT USING MAX HEAP \r\n****************************************************\r\n\r\nEnter the Number of elements in Array ?\r\n11\r\nEnter the element 1\r\n1\r\nEnter the element 2\r\n3\r\nEnter the element 3\r\n5\r\nEnter the element 4\r\n4\r\nEnter the element 5\r\n6\r\nEnter the element 6\r\n13\r\nEnter the element 7\r\n10\r\nEnter the element 8\r\n9\r\nEnter the element 9\r\n8\r\nEnter the element 10\r\n15\r\nEnter the element 11\r\n17\r\nELEMENTS IN MAX HEAP IS AS :\r\n\r\nAt position : 1         ------>         17\r\nAt position : 2         ------>         15\r\nAt position : 3         ------>         10\r\nAt position : 4         ------>         8\r\nAt position : 5         ------>         13\r\nAt position : 6         ------>         3\r\nAt position : 7         ------>         6\r\nAt position : 8         ------>         1\r\nAt position : 9         ------>         5\r\nAt position : 10        ------>         4\r\nAt position : 11        ------>         9\r\n\r\nSORTED ARRAY IS :\r\n\r\nAt position : 1         ------>         1\r\nAt position : 2         ------>         3\r\nAt position : 3         ------>         4\r\nAt position : 4         ------>         5\r\nAt position : 5         ------>         6\r\nAt position : 6         ------>         8\r\nAt position : 7         ------>         9\r\nAt position : 8         ------>         10\r\nAt position : 9         ------>         13\r\nAt position : 10        ------>         15\r\nAt position : 11        ------>         17\r\n\r\n\r\nOPERATION COMPLETED!! THANK YOU\r\n\r\n...Program finished with exit code 0\r\nPress ENTER to exit console.\r\n*/"
  },
  {
    "path": "Algorithms/Sorting/Heap_Sort/README.md",
    "content": "## Heap Sort Implementations\n\n- [Python Implementation](heap-sort.py)\n"
  },
  {
    "path": "Algorithms/Sorting/Heap_Sort/heap-sort.c",
    "content": "#include <stdio.h>\n\nvoid swap(int *a, int *b)\n{\n    int t=*a;\n    *a=*b;\n    *b=t;\n}\n\n// heapify\nvoid heapify(int arr[], int n, int i) \n{ \n    int largest = i;  \n    int l = 2*i + 1; \n    int r = 2*i + 2;  \n   \n    if (l < n && arr[l] > arr[largest]) \n        largest = l; \n  \n    if (r < n && arr[r] > arr[largest]) \n        largest = r; \n  \n    if (largest != i) \n    { \n        swap(&arr[i], &arr[largest]); \n        heapify(arr, n, largest); \n    } \n} \n  \n// heap sort \nvoid heapSort(int arr[], int n) \n{ \n    for (int i = n / 2 - 1; i >= 0; i--) \n        heapify(arr, n, i); \n \n    for (int i=n-1; i>0; i--) \n    { \n        swap(&arr[0], &arr[i]); \n        heapify(arr, i, 0); \n    } \n} \n  \n/* A utility function to print array of size n */\nvoid printArray(int arr[], int n) \n{ \n    for (int i=0; i<n; ++i) \n        printf(\"%d \", arr[i]); \n    printf(\"\\n\"); \n} \n  \n// Main Function \nint main() \n{\n    int n;\n    int arr[100];\n    scanf(\"%d\", &n);\n    for(int i=0;i<n;i++)\n        scanf(\"%d\", &arr[i]);\n  \n    heapSort(arr, n); \n  \n    printf(\"Sorted array is \\n\"); \n    printArray(arr, n); \n} \n"
  },
  {
    "path": "Algorithms/Sorting/Heap_Sort/heap-sort.php",
    "content": "<?php\n function build_heap(&$array, $i, $t){\n  $tmp_var = $array[$i];    \n  $j = $i * 2 + 1;\n\n  while ($j <= $t)  {\n   if($j < $t)\n    if($array[$j] < $array[$j + 1]) {\n     $j = $j + 1; \n    }\n   if($tmp_var < $array[$j]) {\n    $array[$i] = $array[$j];\n    $i = $j;\n    $j = 2 * $i + 1;\n   } else {\n    $j = $t + 1;\n   }\n  }\n  $array[$i] = $tmp_var;\n }\n\n function heap_sort(&$array) {\n  //This will heapify the array\n  $init = (int)floor((count($array) - 1) / 2);\n  for($i=$init; $i >= 0; $i--){\n   $count = count($array) - 1;\n   build_heap($array, $i, $count);\n  }\n\n  //swaping of nodes\n  for ($i = (count($array) - 1); $i >= 1; $i--)  {\n   $tmp_var = $array[0];\n   $array [0] = $array [$i];\n   $array [$i] = $tmp_var;\n   build_heap($array, 0, $i - 1);\n  }\n }\n\n$array = array(9,8,7,6,5,4,3,2,1,0,10,1000,0);\nheap_sort($array);\nprint_r($array);\n?>"
  },
  {
    "path": "Algorithms/Sorting/Heap_Sort/heap-sort.py",
    "content": "'''\nInput format: contents of the array\nOutput format: Sorted Array\nTime Complexity: O(NlogN)\nSpace Complexity: O(N)\n\n**Sample Input Output**\n\nEnter the elements of the array: 2 3 1 4 5 6 8 9\nSorted array is:  1 2 3 4 5 6 8 9\n\n'''\n\n# Python program for implementation of Heap Sort \n\n# Maintaining max heap\ndef heapify(arr, n, index): \n\tlargest = index # Initialize largest as root \n\tleft = 2 * index + 1\t # left = 2 * index + 1 \n\tright = 2 * index + 2\t # right = 2 * index + 2 \n\n\t# See if left child of root exists and is \n\t# greater than root \n\tif left < n and arr[index] < arr[left]: \n\t\tlargest = left \n\n\t# See if right child of root exists and is \n\t# greater than root \n\tif right < n and arr[largest] < arr[right]: \n\t\tlargest = right \n\n\t# Change root, if needed \n\tif largest != index: \n\t\tarr[index],arr[largest] = arr[largest],arr[index] # swap \n\n\t\t# recursively build max heap\n\t\theapify(arr, n, largest) \n\n# The main function to sort an array of given size \ndef heapSort(arr): \n\tn = len(arr) \n\n\t# Build a maxheap. \n\t# Since last parent will be at ((n//2)-1) we can start at that location. \n\tfor i in range(n // 2 - 1, -1, -1): \n\t\theapify(arr, n, i) \n\n\t# One by one extract elements \n\tfor i in range(n-1, 0, -1): \n\t\tarr[i], arr[0] = arr[0], arr[i] # swap \n\t\theapify(arr, i, 0) \n\n# Driver code to test above \narr = list(map(int,input(\"Enter the elements of the array: \").split()))\nheapSort(arr) \nn = len(arr) \nprint (\"Sorted array is: \",end=\" \") \nprint(*arr)\n\n"
  },
  {
    "path": "Algorithms/Sorting/Heap_Sort/heap-sort.rb",
    "content": "def heap_sort(array)  \n    size = array.length\n    #Adding an empty element at beginning of array to be the root\n    root_array = [nil] + array            \n    \n    i = size / 2 \n    while i > 0 do\n      heapify(root_array, i, size) \n      i -= 1 \n    end  \n\n    while size > 1  do\n      root_array[1], root_array[size] = root_array[size], root_array[1]  \n      size -= 1  \n      heapify(root_array, 1, size)  \n    end  \n    root_array.shift #getting rid of the initial nil\n    root_array                  \n  end  \n    \n  def heapify(a, parent, limit)  \n    root = a[parent]  \n\n    while (child_node = 2 * parent) <= limit  do\n        if child_node < limit and a[child_node] < a[child_node + 1]  \n            child_node += 1 \n        end \n        break  if root >= a[child_node]  \n        a[parent] = a[child_node]  \n        parent = child_node  \n    end  \n    a[parent] = root \n  end  \n"
  },
  {
    "path": "Algorithms/Sorting/Heap_Sort/heap_sort.cpp",
    "content": "// C++ program for implementation of Heap Sort \n#include <iostream>\n\nusing namespace std;\n\nvoid heapify(int arr[], int n, int i) {\n\tint largest = i;\n\tint l = 2*i +1;\n\tint r = 2*i +2;\n\n\tif(l < n && arr[l] > arr[largest])\n\t\tlargest = l;\n\tif(r < n && arr[r] > arr[largest])\n\t\tlargest = r;\n\n\tif(largest != i) {\n\t\tswap(arr[i], arr[largest]);\n\t\theapify(arr, n, largest);\n\t}\n}\n\nvoid heapSort(int arr[], int n) {\n\tfor (int i = n/2 - 1; i>=0; i--)\n\t\theapify(arr, n, i);\n\tfor (int i=n-1; i>=0; i--) {\n\t\tswap(arr[0], arr[i]);\n\t\theapify(arr, i, 0);\n\t}\n}\n\nvoid printArray(int arr[], int n) {\n\tfor (int i=0; i<n; ++i)\n\t\tcout << arr[i] << \" \";\n\tcout<< \"\\n\";\n}\n\nint main() {\n\tint arr[] = {12, 11, 13, 5, 6, 7};\n\tint n = sizeof(arr)/sizeof(arr[0]);\n\theapSort(arr, n);\n\tcout << \"Sorted array is: \";\n\tprintArray(arr, n);\n}\n"
  },
  {
    "path": "Algorithms/Sorting/Heap_Sort/heap_sort.go",
    "content": "package main\n\nimport \"fmt\"\n\nfunc heapify(array []int, n, i int) {\n\tmax := i\n\tl := 2*i + 1\n\tr := 2*i + 2\n\n\tif l < n && array[l] > array[max] {\n\t\tmax = l\n\t}\n\tif r < n && array[r] > array[max] {\n\t\tmax = r\n\t}\n\n\tif max != i {\n\t\tarray[i], array[max] = array[max], array[i]\n\t\theapify(array, n, max)\n\t}\n}\n\n// HeapSort will modify/sorted the original array\nfunc HeapSort(array []int, n int) {\n\tfor i := n/2 - 1; i >= 0; i-- {\n\t\theapify(array, n, i)\n\t}\n\tfor i := n - 1; i >= 0; i-- {\n\t\tarray[0], array[i] = array[i], array[0]\n\t\theapify(array, i, 0)\n\t}\n}\n\nfunc main() {\n\tarray := []int{1, 4, 3, 8, 12, 1, 9, 10, 3, 11, 0, 3}\n\tHeapSort(array, len(array))\n\n\tfor _, values := range array {\n\t\tfmt.Printf(\"%d \", values)\n\t}\n\tfmt.Println()\n}\n"
  },
  {
    "path": "Algorithms/Sorting/Heap_Sort/heap_sort.java",
    "content": "// Java program for implementation of Heap Sort \npublic class HeapSort \n{ \n\tpublic void sort(int arr[]) \n\t{ \n\t\tint n = arr.length; \n\n\t\tfor (int i = n / 2 - 1; i >= 0; i--) \n\t\t\theapify(arr, n, i); \n\n\t\tfor (int i=n-1; i>0; i--) \n\t\t{ \n\t\t\tint temp = arr[0]; \n\t\t\tarr[0] = arr[i]; \n\t\t\tarr[i] = temp; \n\n\t\t\theapify(arr, i, 0); \n\t\t} \n\t} \n \n\tvoid heapify(int arr[], int n, int i) \n\t{ \n\t\tint largest = i;\n\t\tint l = 2*i + 1;\n\t\tint r = 2*i + 2;\n\n\t\tif (l < n && arr[l] > arr[largest]) \n\t\t\tlargest = l; \n\n\t\tif (r < n && arr[r] > arr[largest]) \n\t\t\tlargest = r; \n\n\t\tif (largest != i) \n\t\t{ \n\t\t\tint swap = arr[i]; \n\t\t\tarr[i] = arr[largest]; \n\t\t\tarr[largest] = swap; \n\n      heapify(arr, n, largest); \n\t\t} \n\t} \n\n\tstatic void printArray(int arr[]) \n\t{ \n\t\tint n = arr.length; \n\t\tfor (int i=0; i<n; ++i) \n\t\t\tSystem.out.print(arr[i]+\" \"); \n\t\tSystem.out.println(); \n\t} \n\n\tpublic static void main(String args[]) \n\t{ \n\t\tint arr[] = {12, 11, 13, 5, 6, 7}; \n\t\tint n = arr.length; \n\n\t\tHeapSort ob = new HeapSort(); \n\t\tob.sort(arr); \n\n\t\tSystem.out.println(\"Sorted array is\"); \n\t\tprintArray(arr); \n\t} \n} \n"
  },
  {
    "path": "Algorithms/Sorting/Heap_Sort/heapsorting.py",
    "content": "def heapify(arr, n, i):\n      # Find largest among root and children\n      largest = i\n      l = 2 * i + 1\n      r = 2 * i + 2\n  \n      if l < n and arr[i] < arr[l]:\n          largest = l\n  \n      if r < n and arr[largest] < arr[r]:\n          largest = r\n  \n      # If root is not largest, swap with largest and continue heapifying\n      if largest != i:\n          arr[i], arr[largest] = arr[largest], arr[i]\n          heapify(arr, n, largest)\n  \n  \n  def heapSort(arr):\n      n = len(arr)\n  \n      # Build max heap\n      for i in range(n//2, -1, -1):\n          heapify(arr, n, i)\n  \n      for i in range(n-1, 0, -1):\n          # Swap\n          arr[i], arr[0] = arr[0], arr[i]\n  \n          # Heapify root element\n          heapify(arr, i, 0)\n  \n  \n  arr = [1, 12, 9, 5, 6, 10]\n  heapSort(arr)\n  n = len(arr)\n  print(\"Sorted array is\")\n  for i in range(n):\n      print(\"%d \" % arr[i], end='')\n  \n"
  },
  {
    "path": "Algorithms/Sorting/Insertion_Sort/InsertSort.py",
    "content": "def insertion_sort(InputList):\n   for i in range(1, len(InputList)):\n      j = i-1\n      nxt_element = InputList[i]\n# Compare the current element with next one\n   while (InputList[j] > nxt_element) and (j >= 0):\n      InputList[j+1] = InputList[j]\n      j=j-1\n   InputList[j+1] = nxt_element\nlist = [19,2,31,45,30,11,121,27]\ninsertion_sort(list)\nprint(list)\n"
  },
  {
    "path": "Algorithms/Sorting/Insertion_Sort/Insertion Sort.cpp",
    "content": "// C++ program for insertion sort  \n#include <bits/stdc++.h> \nusing namespace std; \n  \n/* Function to sort an array using insertion sort*/\nvoid insertionSort(int arr[], int n)  \n{  \n    int i, key, j;  \n    for (i = 1; i < n; i++) \n    {  \n        key = arr[i];  \n        j = i - 1;  \n  \n        /* Move elements of arr[0..i-1], that are  \n        greater than key, to one position ahead  \n        of their current position */\n        while (j >= 0 && arr[j] > key) \n        {  \n            arr[j + 1] = arr[j];  \n            j = j - 1;  \n        }  \n        arr[j + 1] = key;  \n    }  \n}  \n  \n// A utility function to print an array of size n  \nvoid printArray(int arr[], int n)  \n{  \n    int i;  \n    for (i = 0; i < n; i++)  \n        cout << arr[i] << \" \";  \n    cout << endl; \n}  \n  \n/* Driver code */\nint main()  \n{  \n    int arr[] = { 5, 13, 11, 15, 16 };  \n    int n = sizeof(arr) / sizeof(arr[0]);  \n  \n    insertionSort(arr, n);  \n    printArray(arr, n);  \n  \n    return 0;  \n}  \n"
  },
  {
    "path": "Algorithms/Sorting/Insertion_Sort/InsertionSort.java",
    "content": "// Java program for implementation of Insertion Sort \n\nclass InsertionSort { \n    //  Function to sort the array\n\tvoid sort(int arr[]) \n\t{ \n\t\tint n = arr.length; \n\t\tfor (int i = 1; i < n; ++i) { \n\t\t\tint key = arr[i]; \n\t\t\tint j = i - 1; \n\n\t\t\twhile (j >= 0 && arr[j] > key) { \n\t\t\t\tarr[j + 1] = arr[j]; \n\t\t\t\tj = j - 1; \n\t\t\t} \n\t\t\tarr[j + 1] = key; \n\t\t} \n\t} \n\n\t//  Function to print array of size n.\n\tstatic void printArray(int arr[]) \n\t{ \n\t\tint n = arr.length; \n\t\tfor (int i = 0; i < n; ++i) \n\t\t\tSystem.out.print(arr[i] + \" \"); \n\n\t\tSystem.out.println(); \n\t} \n\n\t// Driver method \n\tpublic static void main(String args[]) \n\t{ \n\t\tint arr[] = { 5, 4, 3, 2, 1 }; \n\n\t\tInsertionSort obj = new InsertionSort();  //Creating object of the class\n\t\tobj.sort(arr);  // Calling sort function\n\n\t\tprintArray(arr); // Call function that print array\n\t} \n}\n"
  },
  {
    "path": "Algorithms/Sorting/Insertion_Sort/InsertionSort.py",
    "content": "def insertionSort(arr):\r\n   for i in range(1, len(arr)):\r\n      key = arr[i]\r\n      # Move elements of arr[0..i-1], that are greater\r\n      than key,\r\n      # to one position ahead of their current position\r\n      j = i-1\r\n      while j >=0 and key < arr[j] :\r\n         arr[j+1] = arr[j]\r\n         j -= 1\r\n      arr[j+1] = key\r\n# main\r\narr = ['t','u','t','o','r','i','a','l']\r\ninsertionSort(arr)\r\nprint (\"The sorted array is:\")\r\nfor i in range(len(arr)):\r\n   print (arr[i])\r\n"
  },
  {
    "path": "Algorithms/Sorting/Insertion_Sort/InsertionSort.scala",
    "content": "package com.dsa.scala\n\nobject InsertionSort {\n  def main (args: Array[String]): Unit = {\n\n    val intArray = Array(20, 35, -15, 7, 55, 1, -22)\n    println(\"**********InsertionSort Scala**********\")\n    println(\"Unsorted array\")\n\n    var i = 0\n\n    for (firstUnsortedIndex <- 1 until intArray.length by 1) {\n      var newElement = intArray(firstUnsortedIndex)\n\n      i = firstUnsortedIndex\n      for (i <- firstUnsortedIndex until 0 by 1 if intArray(i - 1) > newElement) {\n        intArray(i) = intArray(i - 1)\n      }\n      intArray(i) = newElement\n    }\n    println(\"Sorted array - By Insertion sort\")\n    insertionSort(intArray.toList).foreach(println)\n  }\n\n  def insertionSort[A] (la: List[A])(implicit ord: Ordering[A]): List[A] = {\n    println(\"inside insertionSort method\")\n\n    def insert (la: List[A], a: A) = {\n      val (h, t) = la.span(ord.lt(_, a))\n      h ::: (a :: t)\n    }\n\n    la./:(List[A]()) { (acc, a) => insert(acc, a) }\n  }\n\n}\n"
  },
  {
    "path": "Algorithms/Sorting/Insertion_Sort/Insertion_Sort.cpp",
    "content": "//Insertoion sort presumes the the array till curr index is sorted and places the curr element in the sort part at its correct place\n#include<iostream>\nusing namespace std;\nvoid insertionsort(int arr[],int len){\n    for(int curr=1;curr<len;curr++){            //starting curr from 1 because we assumes that 0th element is already sorted\n        int key=arr[curr];\n        int pos=curr-1;                         //last element of sorted part of the array \n        while(pos>=0 and arr[pos]>key){         //while end if array finishes or we encounter element smaller than curr\n            arr[pos+1]=arr[pos];                //shifting element at pos by 1 if its bigger than element at curr\n            pos--;\n        }\n        arr[pos+1]=key;                         //pos is the index of element smaller than curr therefore we place key at pos+1\n    }\n}\nint main(){\n    int len;\n    cout<<\"Enter the number of elements to sort: \";\n    cin>>len;\n    int arr[len]={0};\n    cout<<\"Enter the elements to sort: \\n\";\n    for(int idx=0;idx<len;idx++){\n        cin>>arr[idx];\n    }\n    insertionsort(arr,len);\n    cout<<\"Sorted array: \";\n    for(int idx=0;idx<len;idx++){\n        cout<<arr[idx]<<\" \";\n    }\n    return 0;\n}"
  },
  {
    "path": "Algorithms/Sorting/Insertion_Sort/Insertion_Sort.swift",
    "content": "/*Swift Implementation for Insertion Sort Algorithm*/\n\n//Binary Search to find location of where selected value should be inserted\nfunc binarySearch(numbers: [Int], value: Int, max: Int, min: Int) -> Int\n{\n    var left = min\n    var right = max\n    \n    while left <= right {\n        \n        let middle = left + (right-left)/2\n\n        if (value == numbers[middle]){\n            return middle\n        }\n        \n        if (value < numbers[middle]) {\n            right = middle - 1\n        } else {\n            left = middle+1\n        }\n        \n    }\n\n    return left\n}\n\n//Insertion Sort Function\nfunc insertionSort(input_array: [Int]) -> [Int] {\n    var sorted_array = input_array\n    for i in 0..<sorted_array.count {\n        let temp = sorted_array[i]\n        let location = binarySearch(numbers: sorted_array, value: temp, max: i-1, min: 0)\n\n        for j in stride(from: i-1, through: location, by: -1){\n            sorted_array[j+1] = sorted_array[j]\n\n        }\n        sorted_array[location] = temp\n    }\n    \n    return sorted_array\n}\n"
  },
  {
    "path": "Algorithms/Sorting/Insertion_Sort/Insertion_sort_2.cpp",
    "content": "#include<iostream>\nusing namespace std;\n\nvoid Insertion_sort(int a[],int n){\n\n  for(int i = 1; i <= n - 1; i++){\n        int e = a[i];\n        int j = i -1;\n    while(j >= 0 and a[j]> e){\n        a[j+1] = a[j];\n        j = j - 1;\n    }\n    a[j+1] = e;\n\n  }\n}\nint main(){\n    int n;\n    cin>>n;\n\n    int arr[1000];\n    for(int i = 0; i < n; i++){\n        cin>>arr[i];\n    }\n    Insertion_sort(arr,n);\n    for(int i = 0; i < n; i++){\n        cout<<arr[i];\n    }\n}\n"
  },
  {
    "path": "Algorithms/Sorting/Insertion_Sort/README.md",
    "content": "## INSERTING SORT\n\nInserting sort is simple sorting process for example like we sort the cards. We assume that the first card is already sorted then, we select an unsorted card. If the unsorted card is greater than the card in hand, it is placed on the right otherwise, to the left. In the same way, other unsorted cards are taken and put at their right place. A similar approach is used by insertion sort. Insertion sort is a sorting algorithm that places an unsorted element at its suitable place in each iteration.\n"
  },
  {
    "path": "Algorithms/Sorting/Insertion_Sort/insertion_sort.py",
    "content": "try:\n    # a = array\n    def insertion_sort(a):\n        for i in range(1, len(a)):\n            k = a[i]  # k = key\n            j = i - 1\n            while j >= 0 and k < a[j]:\n                a[j + 1] = a[j]\n                j -= 1\n            a[j + 1] = k\n    if __name__ == \"__main__\":\n        n = int(input(\"Enter the number of elements in the array: \"))\n        lst = list(map(int, input(\"\\nEnter the numbers : \").strip().split()))[:n]\n        print(\"Before sorted: \", end=\"\\n\")\n        print(lst)\n        insertion_sort(lst)\n        print(\"After sorting: \", end=\"\\n\")\n        print(lst)\nexcept EOFError as e:\n    print(end=\"\")\n\n# end code\n# contributer -> souvick roy"
  },
  {
    "path": "Algorithms/Sorting/Insertion_Sort/insertion_sort.ts",
    "content": "/**\n*This class contians information to sort a number array using insertion sort.\n*\n*@class InsertionSort\n*@constructor\n**/\nexport class InsertionSort{\n\n\n    constructor(){\n    \n    }\n    \n    /**\n    *This method contains logic to sort a partially sorted array in O(n) time.\n    *@method sort\n    *@param {Array} arr The array to be sorted.\n    *@return {Array} arr THe sorted array.\n    **/\n    public sort(arr:number[]):number[]{\n    \n      if(arr!==undefined){\n       for(let i:number = 0; i< arr.length; i++){\n    \n        let j = i-1;\n        let key = arr[i];\n    \n        while(j>-1 && arr[j]>key){\n          arr[j+1] = arr[j];\n          j--; \n        }\n    \n        arr[j+1] = key;\n    \n       }\n       return arr;\n      }\n    \n    }\n    \n    }"
  },
  {
    "path": "Algorithms/Sorting/Merge_Sort/Application of Merge Sort/Count_Inversions.c",
    "content": "#include<stdio.h>\n#include<stdlib.h>\n\nlong long int  merge(long long int a[], long long int start, long long int mid, long long int end)\n{\n\tlong long int i=start,j=mid,k=0;\n\tlong long int temp[end-start+1];\n\tlong long int count=0,len=mid;\n \n\twhile(i<mid&&j<=end)\n\t{\n\t\tif(a[i]<=a[j])\n\t\t{\n\t\t\ttemp[k]=a[i];\n\t\t\tk++;\n\t\t\ti++;\n\t\t}\n\t\telse\n\t\t{\n\t\t\ttemp[k]=a[j];\n\t\t\tcount+=len-i;\n\t\t\tk++;\n\t\t\tj++;\n\t\t}\n\t}\n \n\twhile(i<mid)\n\t{\n\t\ttemp[k]=a[i];\n\t\tk++;\n\t\ti++;\n\t}\n \n\twhile(j<=end)\n\t{\n\t\ttemp[k]=a[j];\n\t\tk++;\n\t\tj++;\n\t}\n \n\tfor(long long int i=start,k=0; i<=end; i++,k++)\n\t{\n\t\ta[i]=temp[k];\n\t}\n \n\treturn count;\n}\n \nlong long int merge_sort(long long int a[],long long int start,long long int end)\n{\n\t//Base Case: num of elements=0 or 1;\n\t//long long int count=0;\n \n\tif(start<end)\n\t{\n \n\t   long long int mid=(start+end)/2;\n \n\t   long long int countLeft=merge_sort(a,start,mid);\n\t   long long int countRight=merge_sort(a,mid+1,end);\n\t   long long int count_during_Merge=merge(a,start,mid+1,end);\n \n\t   long long int ans=countLeft+countRight+count_during_Merge;\n \n\t   return ans;\n    }\n \n    return 0;\n \n}\n\n\nint main()\n{\n\tlong long int n;\n\tscanf(\"%lld\",&n);\n \n\tlong long int a[n];\n\tfor(int i=0; i<n; i++)\n        scanf(\"%lld\",&a[i]);\n \n\tlong long int ans=merge_sort(a,0,n-1);\n\tprintf(\"%lld\\n\",ans);\n\n    return 0;\n} "
  },
  {
    "path": "Algorithms/Sorting/Merge_Sort/Application of Merge Sort/Count_Inversions.cpp",
    "content": "#include<bits/stdc++.h>\nusing namespace std;\n\nlong long merge(long long a[], long long start, long long mid, long long end)\n{\n\tlong long i=start,j=mid,k=0;\n\tlong long temp[end-start+1];\n\tlong long count=0,len=mid;\n \n\twhile(i<mid&&j<=end)\n\t{\n\t\tif(a[i]<=a[j])\n\t\t{\n\t\t\ttemp[k]=a[i];\n\t\t\tk++;\n\t\t\ti++;\n\t\t}\n\t\telse\n\t\t{\n\t\t\ttemp[k]=a[j];\n\t\t\tcount+=len-i;\n\t\t\tk++;\n\t\t\tj++;\n\t\t}\n\t}\n \n\twhile(i<mid)\n\t{\n\t\ttemp[k]=a[i];\n\t\tk++;\n\t\ti++;\n\t}\n \n\twhile(j<=end)\n\t{\n\t\ttemp[k]=a[j];\n\t\tk++;\n\t\tj++;\n\t}\n \n\tfor(long long i=start,k=0; i<=end; i++,k++)\n\t{\n\t\ta[i]=temp[k];\n\t}\n \n\treturn count;\n}\n \nlong long merge_sort(long long a[],long long start,long long end)\n{\n\t//Base Case: num of elements=0 or 1;\n\t//long long count=0;\n \n\tif(start<end)\n\t{\n \n\t   long long mid=(start+end)/2;\n \n\t   long long countLeft=merge_sort(a,start,mid);\n\t   long long countRight=merge_sort(a,mid+1,end);\n\t   long long count_during_Merge=merge(a,start,mid+1,end);\n \n\t   long long ans=countLeft+countRight+count_during_Merge;\n \n\t   return ans;\n    }\n \n    return 0;\n \n}\n\n\nint main()\n{\n\tlong long n;\n\tcin>>n;\n \n\tlong long a[n];\n\tfor(int i=0; i<n; i++)\n        cin>>a[i];\n \n\tlong long ans=merge_sort(a,0,n-1);\n\tcout<<ans<<endl;\n\n    return 0;\n} "
  },
  {
    "path": "Algorithms/Sorting/Merge_Sort/MERGE_SORT.c",
    "content": "#include <stdio.h>\n\n#define max 10\n\nint a[11] = { 23, 34, 17, 24, 29, 31, 33, 35, 42, 54, 0 };\nint b[10];\n\n//merging function\nvoid merging(int low, int mid, int high) {\n   int l1, l2, i;\n\n   for(l1 = low, l2 = mid + 1, i = low; l1 <= mid && l2 <= high; i++) {\n      if(a[l1] <= a[l2])\n         b[i] = a[l1++];\n      else\n         b[i] = a[l2++];\n   }\n   \n   while(l1 <= mid)    \n      b[i++] = a[l1++];\n\n   while(l2 <= high)   \n      b[i++] = a[l2++];\n\n   for(i = low; i <= high; i++)\n      a[i] = b[i];\n}\n\n//sorting part\nvoid sort(int low, int high) {\n   int mid;\n   \n   if(low < high) {\n      mid = (low + high) / 2;\n      sort(low, mid);\n      sort(mid+1, high);\n      merging(low, mid, high);\n   } else { \n      return;\n   }   \n}\n\nint main() { \n   int i;\n\n   printf(\" Before sorting\\n\");\n   \n   for(i = 0; i <= max; i++)\n      printf(\"%d \", a[i]);\n\n   sort(0, max);\n\n   printf(\"\\nAfter sorting\\n\");\n   \n   for(i = 0; i <= max; i++)\n      printf(\"%d \", a[i]);\n}\n"
  },
  {
    "path": "Algorithms/Sorting/Merge_Sort/MERGE_SORT.cpp",
    "content": "#include <iostream>\nusing namespace std;\n\n// Merge two subarrays L and M into arr\nvoid merge(int arr[], int p, int q, int r) \n{\n  \n  // Create L ← A[p..q] and M ← A[q+1..r]\n  int n1 = q - p + 1;\n  int n2 = r - q;\n\n  int L[n1], M[n2];\n\n  for (int i = 0; i < n1; i++)\n    L[i] = arr[p + i];\n  for (int j = 0; j < n2; j++)\n    M[j] = arr[q + 1 + j];\n\n  // Maintain current index of sub-arrays and main array\n  int i, j, k;\n  i = 0;\n  j = 0;\n  k = p;\n\n  // Until we reach either end of either L or M, pick larger among\n  // elements L and M and place them in the correct position at A[p..r]\n  while (i < n1 && j < n2) \n  {\n    if (L[i] <= M[j]) \n    {\n      arr[k] = L[i];\n      i++;\n    } \n    else \n    {\n      arr[k] = M[j];\n      j++;\n    }\n    k++;\n  }\n\n  // When we run out of elements in either L or M,\n  // pick up the remaining elements and put in A[p..r]\n  while (i < n1) \n  {\n    arr[k] = L[i];\n    i++;\n    k++;\n  }\n\n  while (j < n2) \n  {\n    arr[k] = M[j];\n    j++;\n    k++;\n  }\n}\n\n// Divide the array into two subarrays, sort them and merge them\nvoid mergeSort(int arr[], int l, int r) {\n  if (l < r) {\n    // m is the point where the array is divided into two subarrays\n    int m = l + (r - l) / 2;\n\n    mergeSort(arr, l, m);\n    mergeSort(arr, m + 1, r);\n\n    // Merge the sorted subarrays\n    merge(arr, l, m, r);\n  }\n}\n\n// Print the array\nvoid printArray(int arr[], int size) {\n  for (int i = 0; i < size; i++)\n    cout << arr[i] << \" \";\n  cout << endl;\n}\n\n// Driver program\nint main() {\n  int arr[] = {6, 5, 12, 10, 9, 1};\n  int size = sizeof(arr) / sizeof(arr[0]);\n\n  mergeSort(arr, 0, size - 1);\n\n  cout << \"Sorted array: \\n\";\n  printArray(arr, size);\n  return 0;\n}\n"
  },
  {
    "path": "Algorithms/Sorting/Merge_Sort/MERGE_SORT.java",
    "content": "/* Java program for Merge Sort */\nclass MergeSort { \n    // Merges two subarrays of arr[]. \n    // First subarray is arr[l..m] \n    // Second subarray is arr[m+1..r] \n    void merge(int arr[], int l, int m, int r) \n    { \n        // Find sizes of two subarrays to be merged \n        int n1 = m - l + 1; \n        int n2 = r - m; \n  \n        /* Create temp arrays */\n        int L[] = new int[n1]; \n        int R[] = new int[n2]; \n  \n        /*Copy data to temp arrays*/\n        for (int i = 0; i < n1; ++i) \n            L[i] = arr[l + i]; \n        for (int j = 0; j < n2; ++j) \n            R[j] = arr[m + 1 + j]; \n  \n        /* Merge the temp arrays */\n  \n        // Initial indexes of first and second subarrays \n        int i = 0, j = 0; \n  \n        // Initial index of merged subarry array \n        int k = l; \n        while (i < n1 && j < n2) { \n            if (L[i] <= R[j]) { \n                arr[k] = L[i]; \n                i++; \n            } \n            else { \n                arr[k] = R[j]; \n                j++; \n            } \n            k++; \n        } \n  \n        /* Copy remaining elements of L[] if any */\n        while (i < n1) { \n            arr[k] = L[i]; \n            i++; \n            k++; \n        } \n  \n        /* Copy remaining elements of R[] if any */\n        while (j < n2) { \n            arr[k] = R[j]; \n            j++; \n            k++; \n        } \n    } \n  \n    // Main function that sorts arr[l..r] using \n    // merge() \n    void sort(int arr[], int l, int r) \n    { \n        if (l < r) { \n            // Find the middle point \n            int m = (l + r) / 2; \n  \n            // Sort first and second halves \n            sort(arr, l, m); \n            sort(arr, m + 1, r); \n  \n            // Merge the sorted halves \n            merge(arr, l, m, r); \n        } \n    } \n  \n    /* A utility function to print array of size n */\n    static void printArray(int arr[]) \n    { \n        int n = arr.length; \n        for (int i = 0; i < n; ++i) \n            System.out.print(arr[i] + \" \"); \n        System.out.println(); \n    } \n  \n    // Driver method \n    public static void main(String args[]) \n    { \n        int arr[] = { 12, 11, 13, 5, 6, 7 }; \n  \n        System.out.println(\"Given Array\"); \n        printArray(arr); \n  \n        MergeSort ob = new MergeSort(); \n        ob.sort(arr, 0, arr.length - 1); \n  \n        System.out.println(\"\\nSorted array\"); \n        printArray(arr); \n    } \n} \n/* This code is contributed by Abhay Bhatt */"
  },
  {
    "path": "Algorithms/Sorting/Merge_Sort/MERGE_SORT.js",
    "content": "function mergeSort(array,half = array.length/2){\n\n  if(array.length < 2){\n    return array\n  }\n\n  const left = array.splice(0,half); //left part of array\n\n  return merger(mergeSort(left),mergeSort(array))\n}\n\nfunction merger(left,right){\n\n  const arr = [];\n\n  while(left.length && right.length){\n    if(left[0] < right [0]){\n      arr.push(left.shift())\n    }else{\n      arr.push(right.shift())\n    }\n  }\n\n  return [...arr,...left,...right];\n}\n\nconsole.log(mergeSort([3,6,7,3,4,5,7,8,1]));"
  },
  {
    "path": "Algorithms/Sorting/Merge_Sort/MergeSort.scala",
    "content": "package com.dsa.scala.functionalDataStructuresAndAlgorithms\n\nobject MergeSortGeneric {\n  def main (args: Array[String]): Unit = {\n    val inputList = List(1, 9, 2, 7, 3, 6, 8, 5)\n\n    val mergetSort_ASC_int = mergeSort((x: Int, y: Int) => x < y) _\n    val mergetSort_DESC_int = mergeSort((x: Int, y: Int) => x > y) _\n    val mergetSort_ASC_Double = mergeSort((x: Double, y: Double) => x < y) _\n    val mergetSort_DESC_Double = mergeSort((x: Double, y: Double) => x > y) _\n\n    val sortedList_ASC = mergetSort_ASC_int(inputList)\n    val sortedList_DESC = mergetSort_DESC_int(inputList)\n\n    println(sortedList_ASC)  // List(1, 2, 3, 5, 6, 7, 8, 9)\n    println(sortedList_DESC) // List(9, 8, 7, 6, 5, 3, 2, 1)\n\n    val inputListDouble = inputList.map(_.toDouble)\n\n    val sortedList_ASC_Double = mergetSort_ASC_Double(inputListDouble)\n    val sortedList_DESC_Double = mergetSort_DESC_Double(inputListDouble)\n\n    println(sortedList_ASC_Double)   // List(1.0, 2.0, 3.0, 5.0, 6.0, 7.0, 8.0, 9.0)\n    println(sortedList_DESC_Double)  // List(9.0, 8.0, 7.0, 6.0, 5.0, 3.0, 2.0, 1.0)\n\n  }\n\n\n  def mergeSort[T] (min: (T, T) => Boolean)(ls: List[T]): List[T] = {\n    def merge (xs: List[T], ys: List[T]): List[T] = {\n      (xs, ys) match {\n        case (_, Nil) => xs\n        case (Nil, _) => ys\n        case (x :: xs1, y :: ys1) =>\n          if (min(x, y)) x :: merge(xs1, ys) else y :: merge(xs, ys1)\n      }\n    }\n\n    val n = ls.length / 2\n    if (n == 0) ls\n    else {\n      val (ys, zs) = ls.splitAt(n)\n      merge(mergeSort(min)(ys), mergeSort(min)(zs))\n    }\n  }\n}\n"
  },
  {
    "path": "Algorithms/Sorting/Merge_Sort/Non_recursive_merge_sort.cpp",
    "content": "#include <iostream>\n#include <fstream>\n#include <string>\n#include <ctime>\n\nvoid merge(int *a, int size, int low, int high, int mid)\n{\n\tint i, j, k;\n\tint *c = new int[size];\n\ti = low;\n\tk = low;\n\tj = mid + 1;\n\twhile (i <= mid && j <= high)\n\t{\n\t\tif (a[i] < a[j])\n\t\t{\n\t\t\tc[k] = a[i];\n\t\t\tk++;\n\t\t\ti++;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tc[k] = a[j];\n\t\t\tk++;\n\t\t\tj++;\n\t\t}\n\t}\n\twhile (i <= mid)\n\t{\n\t\tc[k] = a[i];\n\t\tk++;\n\t\ti++;\n\t}\n\twhile (j <= high)\n\t{\n\t\tc[k] = a[j];\n\t\tk++;\n\t\tj++;\n\t}\n\tfor (i = low; i < k; i++)\n\t{\n\t\ta[i] = c[i];\n\t}\n}\n\nvoid mergeSortIterative(int* arr, int size, int low, int high)\n{\n\tint mid;\n\n\tfor (int i = 2; i <= size; i *= 2) {\n\t\tfor (int x = 0; x < size; x += i)\n\t\t{\n\t\t\tint newHigh;\n\t\t\tif (x + i - 1 < size - 1)\n\t\t\t{\n\t\t\t\tnewHigh = x + i - 1;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tnewHigh = size - 1;\n\t\t\t}\n\t\t\tmid = (newHigh - low) / 2;\n\n\t\t\tmerge(arr, size, x, newHigh, mid);\n\t\t}\n\t}\n\treturn ;\n}\n\nint main()\n{\n\tstd::ifstream inFile;\n\tstd::string inFileName;\n\tint count = 0;\n\tint *myIterative;\n\tint index;\n\tint nums = 0;\n\n\t// Get filename from user\n\tstd::cout << \"Enter the input filename: \" << std::endl;\n\tstd::cin >> inFileName;\n\n\t// Open input file\n\tinFile.open(inFileName.c_str(), std::ios::app);\n\n\t// process input file\n\twhile (!inFile)\n\t{\n\t\t// the file could not be found and opened\n\t\t//display error message\n\t\tstd::cout << \"Could not access file\" << std::endl;\n\t\tstd::cin >> inFileName;\n\t}\n\n\twhile (inFile >> index) {\n\t\tcount++;\n\t}\n\tmyIterative = new int[count];\n\n\tinFile.clear();\n\tinFile.seekg(0, inFile.beg);\n\n\twhile (inFile >> index) {\n\t\tmyIterative[nums] = index;\n\t\tnums++;\n\t}\n\n\n\tfor (int x = 0; x < nums; x++) {\n\t\tstd::cout << \"Given integers Iterative: \" << myIterative[x] << std::endl;\n\t\tstd::cout << x << std::endl;\n\t}\n\n\tmergeSortIterative(myIterative, nums, 0, nums - 1);\n\tfor (int x = 0; x < nums; x++) {\n\t\tstd::cout << \"Sorted Iterative Array: \" << myIterative[x] << std::endl;\n\t\tstd::cout << x << std::endl;\n\t}\n\nreturn 0;\n}\n"
  },
  {
    "path": "Algorithms/Sorting/Merge_Sort/README.md",
    "content": "## Merge Sort\n\nMerge sorting is a type of sorting technique in which an array is divided in two halves till its size become one and then it merges the two sorted halves.\nFor example: [5 8 4 6 2] -> [5 8 4] [6 2] -> [5 8] [4] [6] [2] -> \n[5] [8] [4] [6] [2] -> [4 5 6 8] [2] -> [2 4 5 6 8]\n\n"
  },
  {
    "path": "Algorithms/Sorting/Merge_Sort/mergeSort.py",
    "content": "# Python program for implementation of MergeSort \ndef mergeSort(arr): \n    if len(arr) >1: \n        mid = len(arr)//2 # Finding the mid of the array \n        L = arr[:mid] # Dividing the array elements  \n        R = arr[mid:] # into 2 halves \n  \n        mergeSort(L) # Sorting the first half \n        mergeSort(R) # Sorting the second half \n  \n        i = j = k = 0\n          \n        # Copy data to temp arrays L[] and R[] \n        while i < len(L) and j < len(R): \n            if L[i] < R[j]: \n                arr[k] = L[i] \n                i+= 1\n            else: \n                arr[k] = R[j] \n                j+= 1\n            k+= 1\n          \n        # Checking if any element was left \n        while i < len(L): \n            arr[k] = L[i] \n            i+= 1\n            k+= 1\n          \n        while j < len(R): \n            arr[k] = R[j] \n            j+= 1\n            k+= 1\n  \n# Code to print the list \ndef printList(arr): \n    for i in range(len(arr)):         \n        print(arr[i], end =\" \") \n    print() \n  \n# driver code to test the above code \nif __name__ == '__main__': \n    arr = [5, 11, 53, 15, 67, 7]  \n    print (\"Input array is:\", end =\"\\n\")  \n    printList(arr) \n    mergeSort(arr) \n    print(\"Sorted array is: \", end =\"\\n\") \n    printList(arr)\n"
  },
  {
    "path": "Algorithms/Sorting/Merge_Sort/merge_Sort.rb",
    "content": "\ndef merge_sort(unsorted_array) \n    # if array only has one element or fewer there is nothing to do\n    if unsorted_array.length <=1 \n        return unsorted_array\n    else \n        # dividing and then merge-sorting the halves\n        mid = unsorted_array.length/2\n        first_half = merge_sort(unsorted_array.slice(0...mid))\n        second_half = merge_sort(unsorted_array.slice(mid...unsorted_array.length))\n        merge(first_half, second_half)\n    end \nend\n\ndef merge(left_array, right_array)\n    sorted_array = []\n    # If either array is empty we don't need to compare them\n    while !left_array.empty? && !right_array.empty? do\n        # we are shifting out the compared/used values so we don't repeat\n        if left_array[0] < right_array[0]\n            sorted_array.push(left_array.shift)\n        else   \n            sorted_array.push(right_array.shift)\n        end\n    end \n    #concat appends elements of another array to an array\n    return sorted_array.concat(left_array).concat(right_array)\nend\n"
  },
  {
    "path": "Algorithms/Sorting/Merge_Sort/mergesort.sh",
    "content": "#!/bin/bash\n\nMergeSort (){\n  local a=(\"$@\")\n  if [ ${#a[@]} -eq \"1\" ]\n  then\n    r=(\"${a[@]}\")\n    echo \"${r[@]}\"\n  elif [[ \"${#a[@]}\" -eq \"2\" ]]\n  then\n    if [[ \"${a[0]}\" -gt \"${a[1]}\" ]]\n    then\n      local t=(\"${a[1]}\" \"${a[0]}\")\n      echo \"${t[@]}\"\n    else\n      r=(\"${a[@]}\")\n      echo \"${r[@]}\"\n    fi\n  else\n\n    local p=$(( ${#a[@]} / 2 ))\n    local m1=()\n    m1=($(MergeSort \"${a[@]::p}\"))\n    local m2=()\n    m2=($(MergeSort \"${a[@]:p}\"))\n    local ret=()\n\n    while true\n    do\n      if [ ${#m1[@]} -gt 0 ] && [ ${#m2[@]} -gt 0 ]\n      then\n        if [ \"${m1[0]}\" -le \"${m2[0]}\" ]\n        then\n          ret=(\"${ret[@]}\" \"${m1[0]}\")\n          m1=(\"${m1[@]:1}\")\n        else\n          ret=(\"${ret[@]}\" \"${m2[0]}\")\n          m2=(\"${m2[@]:1}\")\n        fi\n      elif [ \"${#m1[@]}\" -gt 0 ]\n      then\n        ret=(\"${ret[@]}\" \"${m1[@]}\")\n        unset m1\n      elif [ \"${#m2[@]}\" -gt 0 ]\n      then\n        ret=(\"${ret[@]}\" \"${m2[@]}\")\n        unset m2\n      else\n        break\n      fi\n    done\n    echo \"${ret[@]}\"\n  fi\n}\n\na=(5 9 1 3 4 6 6 3 2)\nMergeSort \"${a[@]}\"\n"
  },
  {
    "path": "Algorithms/Sorting/Merge_Sort/non_recursive_merge_sort.c",
    "content": "#include <stdio.h>\n#include <string.h>\n#include <math.h>\n#include <stdlib.h>\n\nstruct Element{                    // this is the structure of element to be stored in stack\n    int left;                       //left index of array\n    int right;                      //right index of array\n    int state;                      //state = 0 represents the array needs to be split and 1 represents that to merge\n};\n\nstruct Stack{                           //Structure for Stack\n    int top;\n    struct Element array[10000];       //array of Element\n};\n\nint IsEmpty(struct Stack *stack){\n    if(stack->top == -1){\n        return 1;\n    }\n    return 0;\n}\n\nint Push(struct Stack *stack, struct Element val){      // val is of type struct Element\n    stack->top += 1;\n    stack->array[stack->top] = val;\n    return 0;    \n}\n\nstruct Element Top(struct Stack *stack){\n    if(IsEmpty(stack)){\n        struct Element empty={0,0,0};                // to return an empty element\n        return empty;                                // this if condition will never come true because only for\n    }                                                // non empty stacks, we will call Top and Pop.\n    else{\n        return stack->array[stack->top];\n    }\n}\nstruct Element Pop(struct Stack *stack){\n    if(stack->top == -1){\n        struct Element empty= {0,0,0};\n        return empty;\n    }\n    else{\n        struct Element item = stack->array[stack->top] ;\n        stack->top -= 1;\n        return item;\n    }\n}\n\n\n\nvoid merge(int* A,int* B, int n, int left, int mid, int right){         //This is the basic merge function, no change\n    int p = left, q=mid+1 ,r =left;\n    while(r<=right){\n        if(p<=mid && q<=right){\n            if(A[p]<=A[q]){\n                B[r]=A[p];\n                r=r+1, p=p+1;\n                continue;\n            }\n            else{\n                B[r] =A[q];\n                r=r+1, q=q+1;\n                continue;\n            }\n        }\n        else if(p<=mid && q>right){\n            B[r]= A[p];\n            r=r+1, p=p+1;\n            continue;\n        }\n        else if(p>mid && q<=right){\n            B[r]=A[q];\n            r=r+1, q=q+1;\n            continue;\n        }\n    }\n    \n    for(int i=left; i<=right;i++){\n        A[i]=B[i];\n    }\n}\n\nvoid merge_sort(int* A,int* B, int n){              //we will call this function only once for an array\n    struct Stack stack;                            //therefore new stack is defined once for every array \n    stack.top = -1;\n    struct Element parent_array = {0,n-1,0};           //parent_array represents the array with left = 0, right = n-1\n    Push(&stack, parent_array);\n    \n    while(!IsEmpty(&stack)){\n        struct Element current_array = Pop(&stack);       //current_array is the one we are working with\n        if(current_array.state == 0){                     //the array needs to be split\n            current_array.state =1;                       //the state is changed to 1 meaning we have consdered state=0\n            int mid = (current_array.left +current_array.right)/2;\n            if(current_array.right <= current_array.left){                //for singleton do nothing\n                continue;                                                                       \n            }\n            struct Element lchild_array = {current_array.left, mid, 0};//lchild_array and rchild_array are two subarrays\n            struct Element rchild_array = {mid+1, current_array.right, 0};   // of current_array\n        \n            Push(&stack, current_array);\n            Push(&stack, rchild_array);\n            Push(&stack, lchild_array);\n        }\n        else{                                                            //if state = 1, we need to merge the subarray\n            int mid = (current_array.left +current_array.right)/2;\n            merge(A,B,n, current_array.left, mid, current_array.right);\n        }\n    }\n}\n\nint main() {\n    \n    int t;\n    scanf(\"%d\",&t);\n    for(int i=0; i<t; i++){\n        int n;\n        scanf(\"%d\",&n);\n        int A[n];\n        int B[n];\n        for(int j=0 ; j<n; j++){\n            scanf(\"%d\",&A[j]);\n            B[j]= A[j];\n        }\n        merge_sort(A,B,n);\n        for(int k=0; k<n; k++){\n            printf(\"%d \",A[k]);\n            \n        }\n        printf(\"\\n\");\n    }\n\n    return 0;\n\n}\n"
  },
  {
    "path": "Algorithms/Sorting/Merge_Sort/non_recursive_merge_sort.cs",
    "content": "using System; \r\n  \r\nclass MS { \r\n    static void mergeSort(int[] arr, \r\n                           int l, int r) \r\n    { \r\n        if (l < r) \r\n        { \r\n            int m = l + (r - l) / 2;  \r\n            mergeSort(arr, l, m); \r\n            mergeSort(arr, m+1, r); \r\n            merge(arr, l, m, r); \r\n       } \r\n    } \r\n  \r\n    static void merge(int[] arr, int l, \r\n                           int m, int r) \r\n    { \r\n        int i, j, k; \r\n        int n1 = m - l + 1; \r\n        int n2 = r - m; \r\n      \r\n        int []L = new int[n1]; \r\n        int []R = new int[n2]; \r\n      \r\n\r\n        for (i = 0; i < n1; i++) \r\n            L[i] = arr[l + i]; \r\n        for (j = 0; j < n2; j++) \r\n            R[j] = arr[m + 1+ j]; \r\n      \r\n        i = 0; \r\n        j = 0; \r\n        k = l; \r\n        while (i < n1 && j < n2) \r\n        { \r\n            if (L[i] <= R[j]) \r\n            { \r\n                arr[k] = L[i]; \r\n                i++; \r\n            } \r\n            else\r\n            { \r\n                arr[k] = R[j]; \r\n                j++; \r\n            } \r\n            k++; \r\n        } \r\n      \r\n        while (i < n1) \r\n        { \r\n            arr[k] = L[i]; \r\n            i++; \r\n            k++; \r\n        } \r\n\r\n        while (j < n2) \r\n        { \r\n            arr[k] = R[j]; \r\n            j++; \r\n            k++; \r\n        } \r\n    } \r\n      \r\n    static void printArray(int []A, int size) \r\n    { \r\n        int i; \r\n        for (i=0; i < size; i++) \r\n            Console.Write(A[i]+\" \"); \r\n        Console.Write(\"\\n\"); \r\n    } \r\n      \r\n    public static void Main() \r\n    { \r\n        int []arr = {12, 11, 13, 5, 6, 7}; \r\n        int arr_size = arr.Length; \r\n      \r\n        Console.Write(\"Given array is \\n\"); \r\n        printArray(arr, arr_size); \r\n      \r\n        mergeSort(arr, 0, arr_size - 1); \r\n      \r\n        Console.Write(\"\\nSorted array is \\n\"); \r\n        printArray(arr, arr_size); \r\n    } \r\n} "
  },
  {
    "path": "Algorithms/Sorting/Merge_Sort/non_recursive_merge_sort.py",
    "content": "def mergeSort(a):  \n      \n    current_size = 1\n      \n    while current_size < len(a) - 1:  \n          \n        left = 0\n        while left < len(a)-1:  \n              \n            mid = min((left + current_size - 1),(len(a)-1)) \n              \n            right = ((2 * current_size + left - 1,  \n                    len(a) - 1)[2 * current_size  \n                        + left - 1 > len(a)-1])  \n                              \n            merge(a, left, mid, right)  \n            left = left + current_size*2\n              \n        current_size = 2 * current_size  \n  \ndef merge(a, l, m, r):  \n    n1 = m - l + 1\n    n2 = r - m  \n    L = [0] * n1  \n    R = [0] * n2  \n    for i in range(0, n1):  \n        L[i] = a[l + i]  \n    for i in range(0, n2):  \n        R[i] = a[m + i + 1]  \n  \n    i, j, k = 0, 0, l  \n    while i < n1 and j < n2:  \n        if L[i] > R[j]:  \n            a[k] = R[j]  \n            j += 1\n        else:  \n            a[k] = L[i]  \n            i += 1\n        k += 1\n  \n    while i < n1:  \n        a[k] = L[i]  \n        i += 1\n        k += 1\n  \n    while j < n2:  \n        a[k] = R[j]  \n        j += 1\n        k += 1\n  \n  \n\na = list(map(int, input(\"Enter the numbers: \").split()))\nprint(\"Given list is \")  \nprint(a)  \n  \nmergeSort(a)  \n  \nprint(\"Sorted list is \")  \nprint(a)  \n"
  },
  {
    "path": "Algorithms/Sorting/Merge_Sort_on_Doubly_Linked_List/Mergesort_doubly.c",
    "content": "#include<stdio.h> \r\n#include<stdlib.h> \r\nstruct Node \r\n{ \r\n    int data; \r\n    struct Node *next, *prev; \r\n}; \r\n  \r\nstruct Node *split(struct Node *head); \r\n  \r\n// Function to merge two linked lists \r\nstruct Node *merge(struct Node *first, struct Node *second) \r\n{ \r\n    // If first linked list is empty \r\n    if (!first) \r\n        return second; \r\n  \r\n    // If second linked list is empty \r\n    if (!second) \r\n        return first; \r\n  \r\n    // Pick the smaller value \r\n    if (first->data < second->data) \r\n    { \r\n        first->next = merge(first->next,second); \r\n        first->next->prev = first; \r\n        first->prev = NULL; \r\n        return first; \r\n    } \r\n    else\r\n    { \r\n        second->next = merge(first,second->next); \r\n        second->next->prev = second; \r\n        second->prev = NULL; \r\n        return second; \r\n    } \r\n} \r\n  \r\n// Function to do merge sort \r\nstruct Node *mergeSort(struct Node *head) \r\n{ \r\n    if (!head || !head->next) \r\n        return head; \r\n    struct Node *second = split(head); \r\n  \r\n    // Recur for left and right halves \r\n    head = mergeSort(head); \r\n    second = mergeSort(second); \r\n  \r\n    // Merge the two sorted halves \r\n    return merge(head,second); \r\n} \r\n  \r\n// A utility function to insert a new node at the \r\n// beginning of doubly linked list \r\nvoid insert(struct Node **head, int data) \r\n{ \r\n    struct Node *temp = \r\n        (struct Node *)malloc(sizeof(struct Node)); \r\n    temp->data = data; \r\n    temp->next = temp->prev = NULL; \r\n    if (!(*head)) \r\n        (*head) = temp; \r\n    else\r\n    { \r\n        temp->next = *head; \r\n        (*head)->prev = temp; \r\n        (*head) = temp; \r\n    } \r\n} \r\n  \r\n// A utility function to print a doubly linked list in \r\n// both forward and backward directions \r\nvoid print(struct Node *head) \r\n{ \r\n    struct Node *temp = head; \r\n    printf(\"Forward Traversal using next poitner\\n\"); \r\n    while (head) \r\n    { \r\n        printf(\"%d \",head->data); \r\n        temp = head; \r\n        head = head->next; \r\n    } \r\n    printf(\"\\nBackward Traversal using prev pointer\\n\"); \r\n    while (temp) \r\n    { \r\n        printf(\"%d \", temp->data); \r\n        temp = temp->prev; \r\n    } \r\n} \r\n  \r\n// Utility function to swap two integers \r\nvoid swap(int *A, int *B) \r\n{ \r\n    int temp = *A; \r\n    *A = *B; \r\n    *B = temp; \r\n} \r\n  \r\n// Split a doubly linked list (DLL) into 2 DLLs of \r\n// half sizes \r\nstruct Node *split(struct Node *head) \r\n{ \r\n    struct Node *fast = head,*slow = head; \r\n    while (fast->next && fast->next->next) \r\n    { \r\n        fast = fast->next->next; \r\n        slow = slow->next; \r\n    } \r\n    struct Node *temp = slow->next; \r\n    slow->next = NULL; \r\n    return temp; \r\n} \r\n  \r\n// Driver program \r\nint main(void) \r\n{ \r\n    struct Node *head = NULL; \r\n    insert(&head,5); \r\n    insert(&head,20); \r\n    insert(&head,4); \r\n    insert(&head,3); \r\n    insert(&head,30); \r\n    insert(&head,10); \r\n    head = mergeSort(head); \r\n    printf(\"\\n\\nLinked List after sorting\\n\"); \r\n    print(head); \r\n    return 0; \r\n}"
  },
  {
    "path": "Algorithms/Sorting/Merge_Sort_on_Doubly_Linked_List/Mergesort_doubly.cpp",
    "content": "#include <bits/stdc++.h> \r\nusing namespace std; \r\nclass Node  \r\n{  \r\n    public: \r\n    int data;  \r\n    Node *next, *prev;  \r\n};  \r\n  \r\nNode *split(Node *head); \r\nNode *merge(Node *first, Node *second)  \r\n{   \r\n    if (!first)  \r\n        return second;  \r\n    if (!second)  \r\n        return first;  \r\n    if (first->data < second->data)  \r\n    {  \r\n        first->next = merge(first->next,second);  \r\n        first->next->prev = first;  \r\n        first->prev = NULL;  \r\n        return first;  \r\n    }  \r\n    else\r\n    {  \r\n        second->next = merge(first,second->next);  \r\n        second->next->prev = second;  \r\n        second->prev = NULL;  \r\n        return second;  \r\n    }  \r\n}  \r\n   \r\nNode *mergeSort(Node *head)  \r\n{  \r\n    if (!head || !head->next)  \r\n        return head;  \r\n    Node *second = split(head);  \r\n    head = mergeSort(head);  \r\n    second = mergeSort(second);\r\n    return merge(head,second);  \r\n}  \r\n    \r\nvoid insert(Node **head, int data)  \r\n{  \r\n    Node *temp = new Node(); \r\n    temp->data = data;  \r\n    temp->next = temp->prev = NULL;  \r\n    if (!(*head))  \r\n        (*head) = temp;  \r\n    else\r\n    {  \r\n        temp->next = *head;  \r\n        (*head)->prev = temp;  \r\n        (*head) = temp;  \r\n    }  \r\n}  \r\n  \r\nvoid print(Node *head)  \r\n{  \r\n    Node *temp = head;  \r\n    cout<<\"Forward Traversal using next poitner\\n\";  \r\n    while (head)  \r\n    {  \r\n        cout << head->data << \" \";  \r\n        temp = head;  \r\n        head = head->next;  \r\n    }  \r\n    cout  << \"\\nBackward Traversal using prev pointer\\n\";  \r\n    while (temp)  \r\n    {  \r\n        cout << temp->data << \" \";  \r\n        temp = temp->prev;  \r\n    }  \r\n}  \r\nvoid swap(int *A, int *B)  \r\n{  \r\n    int temp = *A;  \r\n    *A = *B;  \r\n    *B = temp;  \r\n}  \r\nNode *split(Node *head)  \r\n{  \r\n    Node *fast = head,*slow = head;  \r\n    while (fast->next && fast->next->next)  \r\n    {  \r\n        fast = fast->next->next;  \r\n        slow = slow->next;  \r\n    }  \r\n    Node *temp = slow->next;  \r\n    slow->next = NULL;  \r\n    return temp;  \r\n}  \r\n  \r\nint main(void)  \r\n{  \r\n    Node *head = NULL;  \r\n    insert(&head, 5);  \r\n    insert(&head, 20);  \r\n    insert(&head, 4);  \r\n    insert(&head, 3);  \r\n    insert(&head, 30);  \r\n    insert(&head, 10);  \r\n    head = mergeSort(head);  \r\n    cout << \"Linked List after sorting\\n\";  \r\n    print(head);  \r\n    return 0;  \r\n} "
  },
  {
    "path": "Algorithms/Sorting/Merge_Sort_on_Doubly_Linked_List/Mergesort_doubly.java",
    "content": "class LinkedList { \r\n  \r\n    static Node head; \r\n    static class Node { \r\n  \r\n        int data; \r\n        Node next, prev; \r\n  \r\n        Node(int d) { \r\n            data = d; \r\n            next = prev = null; \r\n        } \r\n    } \r\n  \r\n    void print(Node node) { \r\n        Node temp = node; \r\n        System.out.println(\"Forward Traversal using next pointer\"); \r\n        while (node != null) { \r\n            System.out.print(node.data + \" \"); \r\n            temp = node; \r\n            node = node.next; \r\n        } \r\n        System.out.println(\"\\nBackward Traversal using prev pointer\"); \r\n        while (temp != null) { \r\n            System.out.print(temp.data + \" \"); \r\n            temp = temp.prev; \r\n        } \r\n    } \r\n  \r\n    Node split(Node head) { \r\n        Node fast = head, slow = head; \r\n        while (fast.next != null && fast.next.next != null) { \r\n            fast = fast.next.next; \r\n            slow = slow.next; \r\n        } \r\n        Node temp = slow.next; \r\n        slow.next = null; \r\n        return temp; \r\n    } \r\n  \r\n    Node mergeSort(Node node) { \r\n        if (node == null || node.next == null) { \r\n            return node; \r\n        } \r\n        Node second = split(node); \r\n  \r\n        node = mergeSort(node); \r\n        second = mergeSort(second); \r\n  \r\n        return merge(node, second); \r\n    } \r\n  \r\n    Node merge(Node first, Node second) { \r\n        if (first == null) { \r\n            return second; \r\n        } \r\n        if (second == null) { \r\n            return first; \r\n        } \r\n        if (first.data < second.data) { \r\n            first.next = merge(first.next, second); \r\n            first.next.prev = first; \r\n            first.prev = null; \r\n            return first; \r\n        } else { \r\n            second.next = merge(first, second.next); \r\n            second.next.prev = second; \r\n            second.prev = null; \r\n            return second; \r\n        } \r\n    } \r\n    public static void main(String[] args) { \r\n  \r\n        LinkedList list = new LinkedList(); \r\n        list.head = new Node(10); \r\n        list.head.next = new Node(30); \r\n        list.head.next.next = new Node(3); \r\n        list.head.next.next.next = new Node(4); \r\n        list.head.next.next.next.next = new Node(20); \r\n        list.head.next.next.next.next.next = new Node(5); \r\n          \r\n          \r\n        Node node = null; \r\n        node = list.mergeSort(head); \r\n        System.out.println(\"Linked list after sorting :\"); \r\n        list.print(node); \r\n  \r\n    } \r\n} "
  },
  {
    "path": "Algorithms/Sorting/Merge_Sort_on_Doubly_Linked_List/Mergesort_doubly.py",
    "content": "class Node: \r\n  def __init__(self,data): \r\n    self.data=data; \r\n    self.next=None;\r\n    self.previous=None;\r\n\r\nclass DoubleLinkedList:\r\n  def __init__(self): \r\n    self.start=None;\r\n    \r\n  def merge(self,a,b): \r\n    if (a==None): \r\n      return b; \r\n    if (b==None): \r\n      return a;\r\n    if (a.data < b.data): \r\n      a.next=self.merge(a.next,b); \r\n      a.next.previous=a; \r\n      a.previous=None;\r\n      return a; \r\n    else: \r\n      b.next=self.merge(a,b.next); \r\n      (b.next).previous=b;\r\n      b.previous=None;\r\n      return b;\r\n  def mergesort(self,head): \r\n    if (head==None): \r\n      return head; \r\n    if (head.next==None): \r\n      return head; \r\n    b = self.div(head); \r\n    head = self.mergesort(head); \r\n    b = self.mergesort(b);\r\n    return self.merge(head,b); \r\n \r\n  def div(self,head): \r\n    first=last=head; \r\n    while(True): \r\n      if (first.next==None): \r\n        break;\r\n      if ((first.next).next==None): \r\n        break;\r\n      first=(first.next).next;\r\n      last=last.next;\r\n      \r\n    t=last.next;\r\n    last.next=None;\r\n    return t; \r\n     \r\n  def insert(self,d):  \r\n    n=Node(d); \r\n    n.next=self.start; \r\n \r\n    if (self.start!=None): \r\n      self.start.previous=n; \r\n    self.start=n; \r\n  \r\n  def display(self,node):  \r\n    t=node;\r\n    while(node!=None): \r\n      print (node.data); \r\n      t=node; \r\n      node=node.next;\r\n\r\nob=DoubleLinkedList();\r\ninp=int(input(\"Enter the number of nodes you want to enter:\"));\r\nfor i in range(inp):\r\n        j=int(input(\"Enter the data of the node:\"));\r\n        ob.insert(j);\r\nob.start=ob.mergesort(ob.start) \r\nprint (\"\\nDisplaying the double linked list after merge sort (in ascending order):\");\r\nob.display(ob.start);"
  },
  {
    "path": "Algorithms/Sorting/Pancake_Sort/PancakeSort.java",
    "content": "import java.util.Arrays;\n\n/**\n * @author Alessandro Arosio - 05/10/2020 17:28\n */\npublic class PancakeSort {\n\n    public static void main(String[] args) {\n        int[] result = pancakeSort(new int[]{-32, 41, 6, -2, 16, 0, 23});\n        Arrays.stream(result).forEach(System.out::println);\n    }\n\n    static int[] pancakeSort(int[] arr) {\n        int i = arr.length;\n        int len = arr.length;\n        while (i >= 0) {\n            int pos = findGreatestElement(arr, 0, len);\n            flip(arr, pos);\n            flip(arr, len - 1);\n            len--;\n            i--;\n        }\n        return arr;\n    }\n\n    public static void flip(int[] arr, int k) {\n        int i = 0;\n        int j = k;\n        while (i < k) {\n            int tempArray = arr[j];\n            arr[j] = arr[i];\n            arr[i] = tempArray;\n            i++;\n            j--;\n        }\n    }\n\n    public static int findGreatestElement(int[] arr, int start, int end) {\n        int maxValue = Integer.MIN_VALUE;\n        int maxPosition = 0;\n        for (int i = start; i < end; i++) {\n            if (arr[i] >= maxValue) {\n                maxValue = arr[i];\n                maxPosition = i;\n            }\n        }\n        return maxPosition;\n    }\n}\n"
  },
  {
    "path": "Algorithms/Sorting/Pancake_Sort/Pancake_Sort.c",
    "content": "#include <stdlib.h>\r\n#include <stdio.h>\r\n\r\n//functio to reverse the array.\r\nvoid flip(int arr[], int i)\r\n{\r\n\tint temp, start = 0;\r\n\twhile (start < i)\r\n\t{\r\n\t\ttemp = arr[start];\r\n\t\tarr[start] = arr[i];\r\n\t\tarr[i] = temp;\r\n\t\tstart++;\r\n\t\ti--;\r\n\t}\r\n}\r\n\r\n//function to find maximum in the array\r\nint findMax(int arr[], int n)\r\n{\r\n\tint mi, i;\r\n\tfor (mi = 0, i = 0; i < n; ++i)\r\n\t\tif (arr[i] > arr[mi])\r\n\t\t\tmi = i;\r\n\treturn mi;\r\n}\r\n\r\n//function to perform PancakeSort\r\nint pancakeSort(int *ar, int n)\r\n{\r\n\t//the main idea behind the algo is\r\n\t//take the greatest element to the first position\r\n\t//then flip the aray from the end\r\n\t//so that greatest element becomes last element\r\n\t//and then reduce the curr_size\r\n\t//perfrom these operations till the array get sorted.\r\n\r\n\tfor (int curr_size = n; curr_size > 1; curr_size--)\r\n\t{\r\n\t\tint mi = findMax(ar, curr_size);\r\n\t\tif (mi != curr_size - 1)\r\n\t\t{\r\n\t\t\t//this calls for flipping the array elements.\r\n\t\t\tflip(ar, mi);\r\n\t\t\tflip(ar, curr_size - 1);\r\n\t\t}\r\n\t}\r\n\treturn 0;\r\n}\r\n\r\nint main()\r\n{\r\n\t//input no. of elements required in array ar\r\n\tint n;\r\n\tscanf(\"%d\", &n);\r\n\r\n\tint ar[n];\r\n\r\n\t//input elements in the array\r\n\tfor (int i = 0; i < n; i++)\r\n\t\tscanf(\"%d\", &ar[i]);\r\n\r\n\t//Pancake Sort Algorithm\r\n\t//The idea behind this algorithm is similar to that of selection sort.\r\n\r\n\t//the only thing we must perform is flipping the array elements from (0,i)\r\n\t//our aim is to sort the array and not focus on time complexity\r\n\t//thus total time complexity of this code : O(n^2);\r\n\t//total O(n) flips will be performed.\r\n\r\n\tpancakeSort(ar, n);\r\n\r\n\tfor (int i = 0; i < n; i++)\r\n\t\tprintf(\"%d \", ar[i]);\r\n\tprintf(\"\\n\");\r\n\r\n\treturn 0;\r\n}"
  },
  {
    "path": "Algorithms/Sorting/Pancake_Sort/Pancake_Sort.c++",
    "content": "#include<bits/stdc++.h>  \nusing namespace std;  \n  \n\nvoid flip(int arr[], int i)  \n{  \n    int temp, start = 0;  \n    while (start < i)  \n    {  \n        temp = arr[start];  \n        arr[start] = arr[i];  \n        arr[i] = temp;  \n        start++;  \n        i--;  \n    }  \n}  \n  \nint findMax(int arr[], int n)  \n{  \n    int mi, i;  \n    for (mi = 0, i = 0; i < n; ++i)  \n    {\n        if (arr[i] > arr[mi])  \n                mi = i;  \n    }\n    return mi;  \n}  \n  \nvoid pancakeSort(int *arr, int n)  \n{  \n    for (int curr_size = n; curr_size > 1; --curr_size)  \n    {  \n        int mi = findMax(arr, curr_size);  \n  \n        if (mi != curr_size-1)  \n        {  \n            flip(arr, mi);  \n            flip(arr, curr_size-1);  \n        }  \n    }  \n}  \nvoid printArray(int arr[], int n)  \n{  \n    for (int i = 0; i < n; ++i)  \n        cout<< arr[i]<<\" \";  \n    cout << \"\\n\";   \n}  \n  \n\nint main()  \n{  \n    int N,i,j;\n    cout << \"Enter Size of Array :- \" << \"\\n\";\n    cin >> N;\n    int A[N];\n    cout << \"Enter Array Elements:- \" << \"\\n\";\n    for(i = 0 ; i < N;i++)\n        cin >> A[i];\n    \n    pancakeSort(A, N);  \n    cout<<\"Sorted Array \"<<\"\\n\";  \n    printArray(A, N);  \n  \n    return 0;  \n}  "
  },
  {
    "path": "Algorithms/Sorting/Pancake_Sort/Pancake_Sort.cs",
    "content": "// C# program to implement stooge sort \n    using System;\n\n    class Program\n    {\n        /// <summary>\n        /// Main application function.\n        /// </summary>\n        public static void Main()\n        {\n            int[] arr = { -32, 41, 6, -2, 16, 0, 23 };\n\n            // Calling pancake Sort function \n            // to sort the array \n            PancakeSort(arr);\n\n            // Display the sorted array \n            for (int i = 0; i < arr.Length-1; i++)\n                Console.Write(arr[i] + \" \");\n        }\n\n        /// <summary>\n        /// Runs pancake sort on provided array\n        /// </summary>\n        /// <param name=\"array\">array to be sorted</param>\n        public static int[] PancakeSort(int[] array)\n        {\n            for (var subArrayLength = array.Length - 1; subArrayLength >= 0; subArrayLength--)\n            {\n                // get the position of the maximum element of the subarray\n                var indexOfMax = IndexOfMax(array, subArrayLength);\n                if (indexOfMax != subArrayLength)\n                {\n                    // flip the array to the maximum element index\n                    // the maximum element of the subarray will be located at the beginning\n                    Flip(array, indexOfMax);\n                    // flip the entire subarray\n                    Flip(array, subArrayLength);\n                }\n            }\n\n            return array;\n\n        }\n        /// <summary>\n        /// method to get the index of the maximum subarray element\n        /// </summary>\n        /// <param name=\"array\">array to be searched</param>\n        /// <param name=\"n\">Max index</param>\n        /// <returns>Index of max element</returns>\n        private static int IndexOfMax(int[] array, int n)\n        {\n            int result = 0;\n            for (var i = 1; i <= n; ++i)\n            {\n                if (array[i] > array[result])\n                {\n                    result = i;\n                }\n            }\n\n            return result;\n        }\n\n        /// <summary>\n        /// method for flipping the array\n        /// </summary>\n        /// <param name=\"array\">Array to be modified</param>\n        /// <param name=\"end\">Index of last item to be flipped</param>\n        private static void Flip(int[] array, int end)\n        {\n            for (var start = 0; start < end; start++, end--)\n            {\n                var temp = array[start];\n                array[start] = array[end];\n                array[end] = temp;\n            }\n        }\n    }\n"
  },
  {
    "path": "Algorithms/Sorting/Pancake_Sort/Pancake_Sort.js",
    "content": "function pancakeSort(arr){\n  findMaxIndex = (arr2, k) => {\n    let max = -Infinity \n    let maxIndex = 0\n    \n    for(let i = 0; i < k; i++){\n        if(arr2[i] >= max){\n          max = arr2[i]\n          maxIndex = i\n        }       \n    }\n    return maxIndex\n  }\n  flip = (arr3, k2) => {\n    let i = 0\n       \n    while (i < k2) {\n      let temp = arr3[k2]\n      arr3[k2] = arr3[i]\n      arr3[i] = temp\n      i++\n      k2--\n    }\n    return arr3\n  }\n  let i = arr.length\n  while(i > 1){\n  \tlet maxIndex = findMaxIndex(arr, i)\n  \tif(maxIndex !== i - 1){\n  \t\tflip(arr, maxIndex)\n  \t\tflip(arr, i - 1)\n  \t}\n  i--\n  }\n  return arr\n}\n\npancakeSort([4,3,1,2,5,6]);//[1,2,3,4,5,6]\n"
  },
  {
    "path": "Algorithms/Sorting/Pancake_Sort/Pancake_Sort.py",
    "content": "input_vector = [3,6,8,3,1,4,8,9,5,3,2,5,8,9,1]\n\ndef pancake_sort(nums):\n    arr_len = len(nums)\n    while arr_len > 1:\n        mi = nums.index(max(nums[0:arr_len]))\n        nums = nums[mi::-1] + nums[mi+1:len(nums)]\n        nums = nums[arr_len-1::-1] + nums[arr_len:len(nums)]\n        arr_len -= 1\n    return nums\n\nprint(pancake_sort(input_vector))"
  },
  {
    "path": "Algorithms/Sorting/Pancake_Sort/Pancake_Sort.rb",
    "content": "class Array\n  def pancake_sort!\n    num_flips = 0\n    (self.size-1).downto(1) do |end_idx|\n      max     = self[0..end_idx].max\n      max_idx = self[0..end_idx].index(max)\n      next if max_idx == end_idx\n \n      if max_idx > 0\n        self[0..max_idx] = self[0..max_idx].reverse \n      end\n \n      self[0..end_idx] = self[0..end_idx].reverse \n    end\n    self\n  end\nend\n \np a = (1..9).to_a.shuffle\np a.pancake_sort!\n"
  },
  {
    "path": "Algorithms/Sorting/Pancake_Sort/README.md",
    "content": "## This folder is empty.\n"
  },
  {
    "path": "Algorithms/Sorting/Patience_Sort/PatienceSort.cs",
    "content": "﻿using System;\r\nusing System.Collections.Generic;\r\n\r\n// To compile: csc PatienceSort.cs\r\nnamespace PatienceSort\r\n{    \r\n    class Program\r\n    {\r\n        //Example:\r\n        static void Main(string[] args)\r\n        {\r\n            // Expected input:\r\n            // One line, n: ammount of integer numbers to sort\r\n            // next n lines: A new number\r\n            // Example:\r\n            // 4\r\n            // 3\r\n            // 1\r\n            // 2\r\n            // 4\r\n            // Prints the following output:\r\n            // 1 2 3 4 \r\n\r\n            int n = Convert.ToInt32(Console.ReadLine());\r\n            int[] numbers = new int[n];\r\n\r\n            for(var i = 0; i < n; i++)\r\n                numbers[i] = Convert.ToInt32(Console.ReadLine());\r\n\r\n            // We pass the array numbers. At the end of the function, it should be sorted\r\n            PatienceSort(ref numbers);\r\n\r\n            // Print output array\r\n            foreach (var i in numbers)\r\n                Console.Write(i.ToString() + ' ');\r\n            Console.WriteLine();\r\n\r\n        }\r\n\r\n        /*\r\n            Patience sort works the same way as the \"Patience\" card game.\r\n            We start with a deck of cards (a number array in this case) and,\r\n            for each card, we search the left-most pile such that the card at the top\r\n            of the pile is higher or equal to out current card. If we can't find such\r\n            pile, we start a new one after the rightmost pile with only the current card,\r\n            and so on until we run out of cards\r\n\r\n            When there's no more cards, we take the smallest visible card (aka the smallest \r\n            card at the top of some pile) and take it, and we repeat until there's no more \r\n            piles.\r\n\r\n            The resulting sequence of cards turns out to be sorted :)\r\n\r\n            The following is a simulation of a 'Patience' game. \r\n        */        \r\n        static void PatienceSort(ref int[] numbers) \r\n        {\r\n            // The list of piles, the maximum number of piles we could have is\r\n            // n (the number of elements in the array), when all elements\r\n            // are sorted in increasing order. (Note that C# could increase the \r\n            // size of the list, but we prefer to allocate space only once)\r\n            List<Stack<int>> piles = new List<Stack<int>>(numbers.Length);\r\n\r\n\r\n            // For each number, find the pile such that\r\n            // its top is greater or equal, and put \r\n            // this number as its top\r\n            foreach(var i in numbers) \r\n            {\r\n                // 'pushed' checks if there's a stack that can hold our\r\n                // current number, if it does not exist, push a new one\r\n                var pushed = false; \r\n                foreach(var pile in piles)\r\n                    if (pile.Peek() >= i)\r\n                    {\r\n                        pile.Push(i);\r\n                        pushed = true;\r\n                        break; // We only care about the left-most\r\n                    }\r\n\r\n                if (!pushed) \r\n                { \r\n                    // Since we couldn't add this number to any pile, we create a new one\r\n                    // with just this number\r\n                    var newStack = new Stack<int>();\r\n                    newStack.Push(i);\r\n                    piles.Add(newStack);\r\n                }\r\n            }\r\n\r\n            var nextNum = 0; // next array position\r\n            int minPile = 0;     // the index of the pile with the smallest top \r\n            var empty = false;\r\n            while(!empty) // We stop when every pile is empty\r\n            {\r\n                var min = int.MaxValue;\r\n                empty = true;\r\n                // We search linearly the minimum until there's no more numbers  \r\n                for(var i = 0; i < piles.Count; i++){\r\n                    var pile = piles[i];\r\n\r\n                    empty = empty && pile.Count == 0;\r\n\r\n                    if(pile.Count == 0)\r\n                        continue; // If the pile is empty, we skip it\r\n\r\n                    if(pile.Peek() <= min)\r\n                    {\r\n                        min = pile.Peek();\r\n                        minPile = i;\r\n                    }\r\n                }\r\n\r\n                // If we found a new number, add it in its corresponding position\r\n                if(!empty)\r\n                {\r\n                    numbers[nextNum] = piles[minPile].Pop();\r\n                    nextNum++;\r\n                }\r\n            }\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "Algorithms/Sorting/Patience_Sort/Patience_sort.cpp",
    "content": "//The code is in C\n#include<stdlib.h>\n#include<stdio.h>\n\n//sorting function\nint* patienceSort(int* arr, int size)\n{\n    //variables and array declaration\n\tint decks[size][size], min, pickedRow;\n\n    //Dynamic memory allocation\n\tint *count = (int*)calloc(sizeof(int),size);\n    int *sortedArr = (int*)malloc(size*sizeof(int));\n    //creating a pile just like in the game of solitaire \n\tfor(int i = 0; i < size; i++)\n    {\n\t\tfor(int j = 0; j < size; j++)\n        {\n\t\t\tif(count[j] == 0 || (count[j] > 0 && decks[j][count[j] - 1] >= arr[i]))\n            {\n\t\t\t\tdecks[j][count[j]] = arr[i];\n\t\t\t\tcount[j]++;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n    //setting up initial stage\n\tmin = decks[0][count[0] - 1];\n\tpickedRow = 0;\n    //check for the minimum value number from the top-most elements in each pile\n    //and popping that least element in sorted array list\n\tfor(int i = 0; i < size; i++)\n    {\n\t\tfor(int j = 0; j < size; j++)\n        {\n\t\t\tif(count[j] > 0 && decks[j][count[j] - 1] < min){\n\t\t\t\tmin = decks[j][count[j] - 1];\n\t\t\t\tpickedRow = j;\n\t\t\t}\n\t\t}\n\t\tsortedArr[i] = min;\n\t\tcount[pickedRow]--;\n \n\t\tfor(int j = 0; j < size; j++)\n\t\t\tif(count[j] > 0)\n            {\n\t\t\t\tmin = decks[j][count[j] - 1];\n\t\t\t\tpickedRow = j;\n\t\t\t\tbreak;\n\t\t\t}\n\t}\n    //freeing up the allocated memory\n\tfree(count);\n\tfree(decks);\n \n\treturn sortedArr;\n}\n \nint main (void) //(int argC,char* argV[])\n{\n\tint *arr, *sortedArr;\n    int sizeOfarray;\n    \n    printf(\"Enter the size of array: \");\n    scanf(\"%d\", &sizeOfarray);\n    //dynamic mermory allocation to array\n    arr = (int*)malloc((sizeOfarray) * sizeof(int));\n    //array input\n    printf(\"Enter %d elements of array (each seperated by a space): \", sizeOfarray);\n    for(int i = 0; i < sizeOfarray; i++)\n    {\n        scanf(\"%d\", &arr[i]);\n    }\n\n    //function call\n\tsortedArr = patienceSort(arr, sizeOfarray);\n    printf(\"The sorted array is: \");\n    //printing the sorted array\n\tfor(int i = 0; i < sizeOfarray; i++)\n    {\n\t\tprintf(\"%d \", sortedArr[i]);\n    }\n    free(arr);\n}"
  },
  {
    "path": "Algorithms/Sorting/Patience_Sort/README.md",
    "content": "<h1 align = center>Patience Sort</h1>\n\n## Problem statement\n\nWrite a program for *Patience sort* \n</br> </br>\n\n### About\n\nIn computer science, *Patience sorting* is a sorting algorithm inspired by and named after, the card game patience. </br>\n\nThis game begins with a shuffled deck of cards. These cards are dealt one by one into a sequence of piles on the table, according to the following rules: </br>\n\n- Initially, there are no piles. \n- The first card dealt forms a new pile consisting of the single card.\n- Each subsequent card is placed on the leftmost existing pile whose top card has a value greater than or equal the new card's value, or to the right of all of the existing piles, thus forming a new pile.\n- When there are no more cards remaining to deal, the game ends. </br>\n\nThis card game is turned into a two-phase sorting algorithm, as follows:\n- Given an array of n elements from some totally ordered domain, consider this array as a collection of cards.\n- Simulate the patience sorting game. \n- When the game is over, recover the sorted sequence by repeatedly picking off the minimum visible card.\n- In other words, perform a k-way merge of the p piles, each of which is internally sorted. \n\n</br>\n\n### *Note*: A variant of the algorithm efficiently computes the length of a longest increasing subsequence in a given array. </br> Checkout the code for better understanding.\n\n</br> </br>\n\n### Sample Input-1\n```\n4\n-21 22 1 0\n```\n\n### Sample Ouput\n```\nThe sorted array is: -21 0 1 22\n```\n</br>\n\n### Sample Input-2\n```\n10\n4 3 5 1 4 7 9 8 0 -1\n```\n\n### Sample Ouput\n```\nThe sorted array is: -1 0 1 3 4 4 5 7 8 9\n```\n</br>\n\n### Contributed by\n[*Sarthak Luthra*](https://github.com/sarthak-21)"
  },
  {
    "path": "Algorithms/Sorting/Patience_sort.py",
    "content": "#Patience sort algorithm to sort given list in python\n\n\ndef new_stack(val):             #create new stack \n    newl=[]\n    newl.append(val)\n    return newl\n\ndef patience_sort(t,n):         #gives sorted list\n    ans=[]\n\n    for j in range(n):\n        mn=100000\n        flag=0\n        for i in range(len(t)):\n            if len(t[i])>0:\n                x=t[i].pop()\n                if x<mn:\n                    mn=x\n                    l=i\n                t[i].append(x)\n        t[l].pop()\n        if t[l]==0:\n            t.pop(l)\n        ans.append(mn)\n        #print(f'level {j+1} has minimum value {mn}')\n    for i in range(len(ans)):\n        print(ans[i],end=\" \")\n\n\nif __name__=='__main__':\n    n=int(input('Enter number of element you want: '))\n    print('Enter space seperated values:  ')\n    l=list(map(int,input().split()))\n    fir=new_stack(l[0])\n    t=[]\n    t.append(fir)\n   # print(len(t))\n    for i in range(1,n):\n\n        flag=0\n        for j in range(len(t)):\n            y=t[j].pop()\n            if y>=l[i]:\n                flag=1\n                t[j].append(y)\n                t[j].append(l[i])\n                break\n            else:\n                t[j].append(y)\n        if flag!=1:\n            fir=new_stack(l[i])\n            t.append(fir)\n    print('Sorted list using patience sorting algorithm: ')\n    patience_sort(t,n)\n"
  },
  {
    "path": "Algorithms/Sorting/Pigeonhole_Sort/PigeonholeSort.cpp",
    "content": "/* C program to implement Pigeonhole Sort */\n#include <bits/stdc++.h> \nusing namespace std; \n  \n/* Sorts the array using pigeonhole algorithm */\nvoid pigeonholeSort(int arr[], int n) \n{ \n    // Find minimum and maximum values in arr[] \n    int min = arr[0], max = arr[0]; \n    for (int i = 1; i < n; i++) \n    { \n        if (arr[i] < min) \n            min = arr[i]; \n        if (arr[i] > max) \n            max = arr[i]; \n    } \n    int range = max - min + 1; // Find range \n  \n    // Create an array of vectors. Size of array \n    // range. Each vector represents a hole that \n    // is going to contain matching elements. \n    vector<int> holes[range]; \n  \n    // Traverse through input array and put every \n    // element in its respective hole \n    for (int i = 0; i < n; i++) \n        holes[arr[i]-min].push_back(arr[i]); \n  \n    // Traverse through all holes one by one. For \n    // every hole, take its elements and put in \n    // array. \n    int index = 0;  // index in sorted array \n    for (int i = 0; i < range; i++) \n    { \n       vector<int>::iterator it; \n       for (it = holes[i].begin(); it != holes[i].end(); ++it) \n            arr[index++]  = *it; \n    } \n} \n  \n// Driver program to test the above function \nint main() \n{ \n    int arr[] = {8, 3, 2, 7, 4, 6, 8}; \n    int n = sizeof(arr)/sizeof(arr[0]); \n  \n    pigeonholeSort(arr, n); \n  \n    printf(\"Sorted order is : \"); \n    for (int i = 0; i < n; i++) \n        printf(\"%d \", arr[i]); \n  \n    return 0; \n} "
  },
  {
    "path": "Algorithms/Sorting/Pigeonhole_Sort/PigeonholeSort.ts",
    "content": "/* PigeonholeSort Implementation in Typescript\nIt is suitable for sorting elements where number of \nelements is approximately the same as the number of\npossible values\n*/\nconst pigeonholeSort = (array: number[]): number[] => {\n  const max = Math.max(...array);\n  const min = Math.min(...array);\n  const range = max - min + 1;\n  let phole = new Array(range).fill(0);\n\n  for (let i = 0; i < array.length; i++) {\n    phole[array[i] - min]++;\n  }\n\n  let index = 0;\n\n  for (let j = 0; j < range; j++) {\n    while (phole[j]-- > 0) {\n      array[index++] = j + min;\n    }\n  }\n\n  return array;\n};\n\nconst array = [9, 4, 2, 5, 1, 7, 8, 6];\nconsole.log(pigeonholeSort(array));\n"
  },
  {
    "path": "Algorithms/Sorting/Pigeonhole_Sort/Pigeonhole_Sort.c",
    "content": "#include<stdio.h>\n\n#include<stdlib.h>\n\nvoid pigeonhole_sort(int arr[], int num, int min, int max)\n{\n  int size,i,j,k,count;\n  size = max - min + 1;\n  int holes[size];\n  for(i=0;i<size;i++)\n    holes[i]=0;\n  for (j=0; j < num ;j++)\n    holes[arr[j] - min]++;\n  k=0;\n  for (count = 0; count < size; count++)\n\n  while (holes[count]-- > 0)\n  {\n    arr[k] = count + min;\n    k=k+1;\n  }\n}\nint main()\n{\n    int i,n, c, d, t;\n    printf(\"Enter the number of Elements : \");\n    scanf(\"%d\",&n);\n    int array[n];\n    printf(\"Enter the elements to be sorted :\\n\");\n    \n    for (i = 0; i < n; i++)\n        scanf(\"%d\",&array[i]);\n        \n    int min = array[0] , max = array[0];\n\n    for (i = 1; i < n; i++)\n    {\n        if(min > array[i])\n          min = array[i];\n        if(max < array[i])\n          max = array[i];\n    }\n    pigeonhole_sort(array, n,min,max);\n    printf(\"Sorted Array :\\n\");\n    for(i = 0; i < n; i++)\n      printf(\"%d \",array[i]);\n    printf(\"\\n\");\n\nreturn 0;\n\n}"
  },
  {
    "path": "Algorithms/Sorting/Pigeonhole_Sort/Pigeonhole_Sort.java",
    "content": "import java.lang.*; \nimport java.util.*; \n  \npublic class Pigeonhole_Sort\n{ \n    public static void pigeonhole_sort(int arr[], \n                                           int n) \n    { \n        int min = arr[0]; \n        int max = arr[0]; \n        int range, i, j, index;  \n  \n        for(int a=0; a<n; a++) \n        { \n            if(arr[a] > max) \n                max = arr[a]; \n            if(arr[a] < min) \n                min = arr[a]; \n        } \n  \n        range = max - min + 1; \n        int[] phole = new int[range]; \n        Arrays.fill(phole, 0); \n  \n        for(i = 0; i<n; i++) \n            phole[arr[i] - min]++; \n  \n          \n        index = 0; \n  \n        for(j = 0; j<range; j++) \n            while(phole[j]-->0) \n                arr[index++]=j+min; \n  \n    } \n  \n    public static void main(String[] args) \n    { \n        Pigeonhole_Sort sort = new Pigeonhole_Sort(); \n        Scanner obj = new Scanner(System.in);\n\n        int N , i;\n        System.out.print(\"Enter Size of Array :- \");\n        N = obj.nextInt();\n        int A[] = new int[N];\n        System.out.print(\"Enter Array Elements :- \");\n        for(i = 0;i < N;i++)\n            A[i] = obj.nextInt();\n        System.out.print(\"Sorted order is : \"); \n        sort.pigeonhole_sort(A,A.length); \n          \n        for(i=0 ; i<A.length ; i++) \n            System.out.print(A[i] + \" \"); \n        System.out.println();\n    } \n  \n} "
  },
  {
    "path": "Algorithms/Sorting/Pigeonhole_Sort/pigeonhole.py",
    "content": " def pigeonhole_sort(a): \n\tmy_min = min(a) \n\tmy_max = max(a) \n\tsize = my_max - my_min + 1\n\tholes = [0] * size  \n\tfor x in a: \n\t\tassert type(x) is int, \"integers only please\"\n\t\tholes[x - my_min] += 1\n\ti = 0\n\tfor count in range(size): \n\t\twhile holes[count] > 0: \n\t\t\tholes[count] -= 1\n\t\t\ta[i] = count + my_min \n\t\t\ti += 1\n\t\t\t\n\na = [8, 3,1,2,3,4,5,4, 6, 8] \nprint(\"Sorted order is : \", end =\" \") \n\npigeonhole_sort(a) \n\t\t\nfor i in range(0, len(a)): \n\tprint(a[i], end =\" \") \n\t\n"
  },
  {
    "path": "Algorithms/Sorting/Quick_Select/QuickSelect.cpp",
    "content": "/**\n* Finding Kth largest element in an array using QuickSelect algorithm\n*/\n\nclass Solution {\npublic:\n    int findKthLargest(vector<int>& nums, int k) {\n       return findKthLargest(nums, 0, nums.size()-1, nums.size()-k);\n    }\n\n    int findKthLargest(vector<int>& nums, int left, int right ,int k) {\n        int pivot = nums[right];\n        int leftMark = left;\n        for (int i = left; i<right; i++) {\n            if(nums[i] <= pivot)\n                swap(nums, leftMark++, i);\n        }\n        swap(nums, leftMark, right);\n\n    if (leftMark == k)// Found kth smallest number\n\t\treturn nums[leftMark];\n\telse if (leftMark < k)// Check right part\n\t\treturn findKthLargest(nums, leftMark + 1, right, k);\n\telse // Check left part\n\t\treturn findKthLargest(nums, left, leftMark - 1, k);\n}\n\nvoid swap( vector<int>& A, int i, int j) {\n\tint tmp = A[i];\n\tA[i] = A[j];\n\tA[j] = tmp;\n}\n};"
  },
  {
    "path": "Algorithms/Sorting/Quick_Select/Quick_Select.js",
    "content": "function partition(array3, l, r){ \r\n    var x = array3[r], i = l,temp;\r\n    for (var j = l; j <= r - 1; j++) { \r\n        if (array3[j] <= x) { \r\n            temp = array3[i];\r\n            array3[i] = array3[j];\r\n            array3[j] = temp; \r\n            i++; \r\n        } \r\n    } \r\n    temp = array3[i];\r\n    array3[i] = array3[j];\r\n    array3[j] = temp; \r\n    return i; \r\n}\r\nfunction termFinder(array1, l, r, k){ \r\n    if (k > 0 && k <= r - l + 1) { \r\n        var index = partition(array1, l, r); \r\n        if (index - l == k - 1){\r\n            return array1[index]; \r\n        }\r\n        if (index - l > k - 1){\r\n            return termFinder(array1, l, index - 1, k);\r\n        }\r\n        return termFinder(array1, index + 1, r,k - index + l - 1); \r\n    }\r\n    return \"error\"; \r\n}\r\nvar array1 = [];\r\nvar length1 = parseInt(prompt(\"Enter length of array -> \"));\r\nfor(var i=0;i<length1;i++){\r\n    array1[i] = parseInt(prompt(\"Enter \" + (i+1) + \" th element of the array -> \"));\r\n}\r\nvar num1 = parseInt(prompt(\"Enter value of k for 'k th' smallest element -> \"));\r\n\r\nalert(\"K-th smallest element is \" + termFinder(array1,0, length1-1,num1)); "
  },
  {
    "path": "Algorithms/Sorting/Quick_Select/Quick_Select.php",
    "content": "<?php\n\n/**\n * Select kth smallest element\n * \n * @param array $list Elements\n * @param int $kthPosition Kth position\n * @return mixed\n */\nfunction kthSmallest(array $list, int $kthPosition) {\n    $high = count($list) - 1;\n    $kthIndex = $kthPosition -1;\n    \n    if($high < $kthIndex) {\n        throw \"Index out of bound\";\n    }\n\n    return quickSelect($list, 0, $high, $kthIndex);  \n}\n\n/**\n * Quick selection of element\n * \n * @param array $list Elements\n * @param int $low Lowest index\n * @param int $high Higest index\n * @param int $kthPosition Kth index\n * @return mixed\n */\nfunction quickSelect(array $list, int $low, int $high, int $kthIndex) {\n    $partition = partition($list, $low, $high);\n\n    if($partition == $kthIndex) {\n\n        return $list[$partition];\n\n    } elseif($partition < $kthIndex) {\n\n        return quickSelect($list, $partition + 1, $high, $kthIndex);\n\n    } else {\n\n        return quickSelect($list, $low, $partition - 1, $kthIndex); \n    }\n}\n\n/**\n * Partition of the elements\n * \n * @param array $list elements\n * @param int $low Lowest index\n * @param int $high Highest index\n * @return int $pivotLoc Pivot location\n */\nfunction partition(array &$list, int $low, int $high) { \n    $pivot = $list[$high];\n    $pivotLoc = $low;\n\n    for ($i = $low; $i <= $high; $i++) {\n\n        if($list[$i] < $pivot) {\n\n            $temp = $list[$i]; \n            $list[$i] = $list[$pivotLoc]; \n            $list[$pivotLoc] = $temp; \n            $pivotLoc++; \n        }\n    }\n    \n    $temp = $list[$high]; \n    $list[$high] = $list[$pivotLoc]; \n    $list[$pivotLoc] = $temp;\n    return $pivotLoc; \n}\n\n\n//Test\n$elements = [7, 4, 5, 8 , 9, 0, 10, 16];\n$kthPosition = 5;\n\necho \"The kth smallest element for {$kthPosition} is: \" . kthSmallest($elements, $kthPosition);\n\n//Output: The kth smallest element for 5 is: 8"
  },
  {
    "path": "Algorithms/Sorting/Quick_Select/Quick_select.py",
    "content": "import heapq\n \nclass Solution:\n    def findKthLargest(self, nums: 'List[int]', k: 'int') -> 'int':\n \n        # Time complexity : O(N*logK)\n        # Space complexity : O(K)\n \n        heap = []\n        \n        for i in nums :\n            heapq.heappush(heap, i)\n            \n            if len(heap) > k :\n                heapq.heappop(heap)\n        \n        return heapq.heappop(heap)\n \n        \n    def findKthLargest(self, nums: 'List[int]', k: 'int') -> 'int':\n \n        # Time complexity : O(N)\n        # Space complexity : O(1)\n        \n        def partition(l, r, i):\n            \n            start = l\n            pivot = nums[i]\n            nums[i], nums[start] = nums[start], nums[i]\n            \n            l += 1\n            \n            while l <= r :\n                \n                while l<=r and nums[l] <= pivot :\n                    l += 1\n                while l<=r and nums[r] > pivot :\n                    r -= 1\n                    \n                if l < r :\n                    nums[l], nums[r] = nums[r], nums[l]\n                    l += 1\n                    r -= 1\n            \n            nums[r], nums[start] = nums[start], nums[r]\n            return r\n        \n        def select(l, r, k_smallest):\n            \n            if l == r :\n                return nums[l]\n            \n            i = random.randint(l, r)\n            i = partition(l, r, i)\n            \n            if k_smallest == i :\n                return nums[i]\n            elif k_smallest > i :\n                return select(i+1, r, k_smallest)\n            else :\n                return select(l, i-1, k_smallest)\n        \n        return select(0, len(nums)-1, len(nums)-k)\n"
  },
  {
    "path": "Algorithms/Sorting/Quick_Select/README.md",
    "content": "## This folder is empty.\n"
  },
  {
    "path": "Algorithms/Sorting/Quick_Select/quick_select.java",
    "content": "class quick_select {\n  public int kthLargest(int[] arr, int k) {\n    int n = arr.length;\n    int left = 0;\n    int right = n - 1;\n    Random rand = new Random(0);\n    while (left <= right) {\n      int choosenPivotIndex = rand.nextInt(right - left + 1) + left;\n      int finalIndexOfChoosenPivot = partition(arr, left, right, choosenPivotIndex);\n      if (finalIndexOfChoosenPivot == n - k) {\n        return arr[finalIndexOfChoosenPivot];\n      } else if (finalIndexOfChoosenPivot > n - k) {\n       \n        right = finalIndexOfChoosenPivot - 1;\n      } else {\n        left = finalIndexOfChoosenPivot + 1;\n      }\n    }\n    return -1;\n  }\n  private int partition(int[] arr, int left, int right, int pivotIndex) {\n    int pivotValue = arr[pivotIndex];\n    int lesserItemsTailIndex = left;\n\n    swap(arr, pivotIndex, right);\n\n    for (int i = left; i < right; i++) {\n      if (arr[i] < pivotValue) {\n        swap(arr, i, lesserItemsTailIndex);\n        lesserItemsTailIndex++;\n      }\n    }\n    swap(arr, right, lesserItemsTailIndex);\n\n    return lesserItemsTailIndex;\n  }\n\n  private void swap(int[] arr, int first, int second) {\n    int temp = arr[first];\n    arr[first] = arr[second];\n    arr[second] = temp;\n  }\n"
  },
  {
    "path": "Algorithms/Sorting/Quick_Select/quick_select.rb",
    "content": "# @param {Integer[]} nums\n# @param {Integer} k\n# @return {Integer}\ndef find_kth_largest(nums, k)\n    n = nums.size\n    quick_select(nums, 0, n - 1, n - k) # Kth largest is at n - 1 - (k - 1) = (n - k)th index\nend\n\ndef quick_select(a, p, r, k)            # Note the k here refers to (n - k) from the question stand-point\n    return a[p] if p == r               # Base case of recursion\n    q = rand_partition(a, p, r)         # Pick the pivot using random partition\n\n    if k < q\n        quick_select(a, p, q - 1, k)    # kth smallest is in the lower partition\n    elsif k > q\n        quick_select(a, q + 1, r, k)    # kth smallest is in the higher partition\n    else\n        a[q]                            # if q == k return Pivot as the kth smallest\n    end\nend\n\ndef partition(a, p, r)\n    i = p - 1                           # Choose the index before the pth index\n    pivot = a[r]                        # Choose the last element as pivot\n\n    p.upto(r - 1) do |j|                # Loop from p to r-1 moving elements to either side of pivot\n      next if a[j] > pivot              # Move to next element if element is already > than pivot element\n      i += 1                            # Increment index i for current placement index\n      a[i], a[j] = a[j], a[i]           # Swap elements at pivot placement index with the current index j\n    end\n  \n    a[i + 1], a[r] = a[r], a[i + 1]     # Move the pivot to its final place: index before which all elements < pivot\n    i + 1                               # return pivot index\nend\n\ndef rand_partition(a, p, r)\n    i = rand(p..r)                      # Pick a random index between p and r\n    a[i], a[r] = a[r], a[i]             # Swap the last element with the one at i\n\n    partition(a, p, r)                  # Return result of partition()\nend\n"
  },
  {
    "path": "Algorithms/Sorting/Quick_Sort/QuickSort.java",
    "content": "// Java program for implementation of QuickSort \n\nclass QuickSort \n{ \n\t// This function takes last element as pivot.\n\n\tint partition(int arr[], int low, int high) \n\t{ \n\t\tint pivot = arr[high]; \n\t\tint i = (low-1); // index of smaller element \n\t\tfor (int j=low; j<high; j++) \n\t\t{ \n\t\t\t// If current element is smaller than the pivot \n\t\t\tif (arr[j] < pivot) \n\t\t\t{ \n\t\t\t\ti++; \n\n\t\t\t\t// swap arr[i] and arr[j] \n\t\t\t\tint temp = arr[i]; \n\t\t\t\tarr[i] = arr[j]; \n\t\t\t\tarr[j] = temp; \n\t\t\t} \n\t\t} \n\n\t\t// swap arr[i+1] and arr[high] (or pivot) \n\t\tint temp = arr[i+1]; \n\t\tarr[i+1] = arr[high]; \n\t\tarr[high] = temp; \n\n\t\treturn i+1; \n\t} \n\n\n\tvoid sort(int arr[], int low, int high) \n\t{ \n\t\tif (low < high) \n\t\t{ \n\t\t\t// pi is partitioning index, arr[pi] is now at right place.\n            \n\t\t\tint pi = partition(arr, low, high); \n\n\t\t\t// Recursively sort elements before \n\t\t\t// partition and after partition \n\t\t\tsort(arr, low, pi-1); \n\t\t\tsort(arr, pi+1, high); \n\t\t} \n\t} \n\n\t// Function to print array.\n\tstatic void printArray(int arr[]) \n\t{ \n\t\tint n = arr.length; \n\t\tfor (int i=0; i<n; ++i) \n\t\t\tSystem.out.print(arr[i]+\" \"); \n\t\tSystem.out.println(); \n\t} \n\n\t// Driver Code\n\tpublic static void main(String args[]) \n\t{ \n\t\tint arr[] = {5, 4, 3, 2, 1}; // Default Array \n\t\tint n = arr.length; \n\n\t\tQuickSort obj = new QuickSort(); \n\t\tobj.sort(arr, 0, n-1);  // Calling sort function\n\n\t\tprintArray(arr);  // Call function that print array\n\t} \n} \n\n"
  },
  {
    "path": "Algorithms/Sorting/Quick_Sort/QuickSort.js",
    "content": "function quickSort(array) { // assumes an array of ints\n    if (array.length <= 1) {\n       return array;\n       } else {\n            var left = [], right = [], nextArray = [], length = array.length;\n            var pivot = array.splice(Math.floor(Math.random()*array.length),1); // get random pivot\n            length--;\n             for (var i = 0; i < length; i++) {\n                if (array[i] <= pivot) {    // compare left/right of pivot\n                   left.push(array[i]);      \n             } else {\n                     right.push(array[i]);\n           }\n         }\n       return nextArray.concat(quickSort(left), pivot, quickSort(right));                                                                          //returned untill sorting occurs\n    }\n }\n\n// use node to run, uncomment below to test\n//  var array = [9, 0, 2, 7, -2, 6, 1 ];\n//  console.log(\"Given array --> \" + array);\n//  var arrayAfterQuickSort = quickSort(array);\n//  console.log(\"Array after QuickSort: \" + arrayAfterQuickSort);"
  },
  {
    "path": "Algorithms/Sorting/Quick_Sort/QuickSort.py",
    "content": "# This is the Python version of Quick Sort\n# Code is contributed by: Italo Vinicius.\n# \n# Quick sort is an Sorting Algorithm which takes compelxity: O(n log n)\n\n# This function takes last element as pivot, places \n# the pivot element at its correct position in sorted \n# array, and places all smaller (smaller than pivot) \n# to left of pivot and all greater elements to right \n# of pivot \n\ndef partition(arr,low,high): \n    i = ( low-1 )         # index of smaller element \n    pivot = arr[high]     # pivot \n\n    for j in range(low , high): \n\n        # If current element is smaller than the pivot \n        if   arr[j] < pivot: \n\n            # increment index of smaller element \n            i = i+1 \n            arr[i],arr[j] = arr[j],arr[i] \n\n    arr[i+1],arr[high] = arr[high],arr[i+1] \n    return ( i+1 ) \n\n# Function to do Quick sort \ndef quickSort(arr,low,high): \n    if low < high: \n\n        # pi is partitioning index, arr[p] is now \n        # at right place \n        pi = partition(arr,low,high) \n\n        # Separately sort elements before \n        # partition and after partition \n        quickSort(arr, low, pi-1) \n        quickSort(arr, pi+1, high) \n\nif __name__ == \"__main__\":\n    arr = list(map(int,input().split()))\n    quickSort(arr,0,len(arr)-1)\n"
  },
  {
    "path": "Algorithms/Sorting/Quick_Sort/Quick_Sort.cpp",
    "content": "/* C++ implementation of QuickSort */\n#include <bits/stdc++.h> \nusing namespace std; \n\n// A utility function to swap two elements \nvoid swap(int* a, int* b) \n{ \n\tint t = *a; \n\t*a = *b; \n\t*b = t; \n} \n\nint partition (int arr[], int low, int high) \n{ \n\tint pivot = arr[high]; // pivot \n\tint i = (low - 1); // Index of smaller element \n\n\tfor (int j = low; j <= high - 1; j++) \n\t{ \n\t\t// If current element is smaller than the pivot \n\t\tif (arr[j] < pivot) \n\t\t{ \n\t\t\ti++; // increment index of smaller element \n\t\t\tswap(&arr[i], &arr[j]); \n\t\t} \n\t} \n\tswap(&arr[i + 1], &arr[high]); \n\treturn (i + 1); \n} \n\nvoid quickSort(int arr[], int low, int high) \n{ \n\tif (low < high) \n\t{ \n\t\t\n\t\tint pi = partition(arr, low, high); \n\n\t\tquickSort(arr, low, pi - 1); \n\t\tquickSort(arr, pi + 1, high); \n\t} \n} \n\n/* Function to print an array */\nvoid printArray(int arr[], int size) \n{ \n\tint i; \n\tfor (i = 0; i < size; i++) \n\t\tcout << arr[i] << \" \"; \n\tcout << endl; \n} \n\n// Driver Code \nint main() \n{ \n\tint arr[] = {10, 7, 8, 9, 1, 5}; \n\tint n = sizeof(arr) / sizeof(arr[0]); \n\tquickSort(arr, 0, n - 1); \n\tcout << \"Sorted array: \\n\"; \n\tprintArray(arr, n); \n\treturn 0; \n} \n\n"
  },
  {
    "path": "Algorithms/Sorting/Quick_Sort/Quick_Sort.go",
    "content": "package main\n\nimport \"fmt\"\n\nfunc swap(num1 *int, num2 *int) {\n\tvar val int\n\tval = *num1\n\t*num1 = *num2\n\t*num2 = val\n}\n\nfunc partition(elements []int, low int, high int) int {\n\tvar pivot int\n\tpivot = elements[high]\n\tvar i int\n\ti = low\n\tvar j int\n\tfor j = low; j < high; j++ {\n\t\tif elements[j] <= pivot {\n\t\t\tswap(&elements[i], &elements[j])\n\t\t\ti++\n\t\t}\n\t}\n\tswap(&elements[i], &elements[high])\n\treturn i\n}\n\nfunc quickSort(elements []int, low int, high int) {\n\tif low < high {\n\t\tvar part int\n\t\tpart = partition(elements, low, high)\n\t\tquickSort(elements, low, part-1)\n\t\tquickSort(elements, part+1, high)\n\t}\n}\n\nfunc main() {\n\tvar num int\n\n\tfmt.Print(\"Enter Number of Elements: \")\n\tfmt.Scan(&num)\n\tvar array = make([]int, num)\n\tvar i int\n\n\tfor i = 0; i < num; i++ {\n\t\tfmt.Scan(&array[i])\n\t}\n\n\tfmt.Print(\"Elements: \", array, \"\\n\")\n\tquickSort(array, 0, num-1)\n\tfmt.Print(\"Sorted Elements: \", array, \"\\n\")\n}\n"
  },
  {
    "path": "Algorithms/Sorting/Quick_Sort/Quick_Sort.sh",
    "content": "#!/bin/bash\n# Bubble Sort Array sorting algortihm in O(n^2) complexity\n# E.g. Array Size = 6\n# Elements:\n# 1\n# 7\n# 8\n# 14\n# 12\n# 21\n# Sorted Array:\n# 1\n# 7\n# 8\n# 12\n# 14\n# 21\n\necho \"Enter Array Size\"\nread len\n\n# taking input from user\necho \"Provide Number for an Array:\"\nfor (( i = 0; i < $len; i++ ))\ndo\n    read arr[$i]\ndone\n\n# Bubble Sort Logic\nfor (( i = 0; i < $len ; i++ ))\ndo\n    for (( j = $i; j < $len; j++ ))\n    do\n        if [ ${arr[$i]} -gt ${arr[$j]}  ]; then\n            temp=${arr[$i]}\n            arr[$i]=${arr[$j]}\n            arr[$j]=$temp\n        fi\n    done\ndone\n\n# Printing the sorted number\necho \"Sorted Array: \"\nfor (( i=0; i < $len; i++ ))\ndo\n    echo ${arr[$i]}\ndone"
  },
  {
    "path": "Algorithms/Sorting/Quick_Sort/README.md",
    "content": "## QUICK SORT\n\nQuick sorting is almost similar like merge sorting but in quick sorting the element named pivot is chose which can be any element of the array. There are many different versions of quicksort that pick pivot in different ways. After choosing pivot all the elements are compared with the pivot element and if it satisfies the condition the two adjacent get swapped otherwise it remain as it is.\n\n\ta. Always pick first element as pivot.\n\tb. Always pick last element as pivot (implemented below)\n\tc. Pick a random element as pivot.\n\td. Pick median as pivot.\n       \n**For example:**\n[3 5 9 7] in this lets 7 be the pivot. Condition is (pivot < number) then swap.\n7 is greater than 3: No change [3 5 9 7].\n7 > 5: No change [3 5 9 7].\n9 > 7: Swap [3 5 7 9]\nOutput: [3 5 7 9]\n\n"
  },
  {
    "path": "Algorithms/Sorting/Quick_Sort/quicksort.C",
    "content": "#include <stdio.h>\nint partition(int a[], int beg, int end);  \nvoid quickSort(int a[], int beg, int end);  \nvoid main()  \n{  \n    int i;  \n    int arr[10]={90,23,101,45,65,28,67,89,34,29};  \n    quickSort(arr, 0, 9);  \n    printf(\"\\n The sorted array is: \\n\");  \n    for(i=0;i<10;i++)  \n    printf(\" %d\\t\", arr[i]);  \n}  \nint partition(int a[], int beg, int end)  \n{  \n    int left, right, temp, loc, flag;     \n    loc = left = beg;  \n    right = end;  \n    flag = 0;  \n    while(flag != 1)  \n    {  \n        while((a[loc] <= a[right]) && (loc!=right))  \n        right--;  \n        if(loc==right)  \n        flag =1;  \n        else if(a[loc]>a[right])  \n        {  \n            temp = a[loc];  \n            a[loc] = a[right];  \n            a[right] = temp;  \n            loc = right;  \n        }  \n        if(flag!=1)  \n        {  \n            while((a[loc] >= a[left]) && (loc!=left))  \n            left++;  \n            if(loc==left)  \n            flag =1;  \n            else if(a[loc] < a[left])  \n            {  \n                temp = a[loc];  \n                a[loc] = a[left];  \n                a[left] = temp;  \n                loc = left;  \n            }  \n        }  \n    }  \n    return loc;  \n}  \nvoid quickSort(int a[], int beg, int end)  \n{  \n    int loc;  \n    if(beg<end)  \n    {  \n        loc = partition(a, beg, end);  \n        quickSort(a, beg, loc-1);  \n        quickSort(a, loc+1, end);  \n    }  \n}  \n"
  },
  {
    "path": "Algorithms/Sorting/Quick_Sort/quicksort.c",
    "content": "#include <stdio.h>\nint partition(int a[], int beg, int end);  \nvoid quickSort(int a[], int beg, int end);  \nvoid main()  \n{  \n    int i;  \n    int arr[10]={90,23,101,45,65,28,67,89,34,29};  \n    quickSort(arr, 0, 9);  \n    printf(\"\\n The sorted array is: \\n\");  \n    for(i=0;i<10;i++)  \n    printf(\" %d\\t\", arr[i]);  \n}  \nint partition(int a[], int beg, int end)  \n{  \n    int left, right, temp, loc, flag;     \n    loc = left = beg;  \n    right = end;  \n    flag = 0;  \n    while(flag != 1)  \n    {  \n        while((a[loc] <= a[right]) && (loc!=right))  \n        right--;  \n        if(loc==right)  \n        flag =1;  \n        else if(a[loc]>a[right])  \n        {  \n            temp = a[loc];  \n            a[loc] = a[right];  \n            a[right] = temp;  \n            loc = right;  \n        }  \n        if(flag!=1)  \n        {  \n            while((a[loc] >= a[left]) && (loc!=left))  \n            left++;  \n            if(loc==left)  \n            flag =1;  \n            else if(a[loc] < a[left])  \n            {  \n                temp = a[loc];  \n                a[loc] = a[left];  \n                a[left] = temp;  \n                loc = left;  \n            }  \n        }  \n    }  \n    return loc;  \n}  \nvoid quickSort(int a[], int beg, int end)  \n{  \n    int loc;  \n    if(beg<end)  \n    {  \n        loc = partition(a, beg, end);  \n        quickSort(a, beg, loc-1);  \n        quickSort(a, loc+1, end);  \n    }  \n}  \n"
  },
  {
    "path": "Algorithms/Sorting/README.md",
    "content": "## Sorting Algorithms\n\nA Sorting Algorithm is used to rearrange a given array or list elements according to a comparison operator on the elements. The comparison operator is used to decide the new order of element in the respective data structure.\n\n**Types of Sorting Algorithms:**\n\n1. Selection Sort\n2. Bubble Sort\n3. Recursive Bubble Sort\n4. Insertion Sort\n5. Recursive Insertion Sort\n6. Merge Sort\n7. Iterative Merge Sort\n8. Quick Sort\n9. Iterative Quick Sort\n10. Heap Sort\n11. Counting Sort\n12. Radix Sort\n13. Bucket Sort\n14. ShellSort\n15. TimSort\n16. Comb Sort\n17. Pigeonhole Sort\n18. Cycle Sort\n19. Cocktail Sort\n20. Strand Sort\n21. Bitonic Sort\n22. Pancake sorting\n23. Binary Insertion Sort\n24. BogoSort or Permutation Sort\n25. Gnome Sort\n26. Sleep Sort\n27. Structure Sorting in C++\n28. Stooge Sort\n29. Tag Sort\n30. Tree Sort\n31. Cartesian Tree Sorting\n32. Odd-Even Sort / Brick Sort\n33. QuickSort on Singly Linked List\n34. QuickSort on Doubly Linked List\n35. 3-Way QuickSort (Dutch National Flag)\n36. Merge Sort for Linked Lists\n37. Merge Sort for Doubly Linked List\n38. 3-way Merge Sort\n\n"
  },
  {
    "path": "Algorithms/Sorting/Radix_Sort/README.md",
    "content": "## This folder is empty.\n"
  },
  {
    "path": "Algorithms/Sorting/Radix_Sort/Radix Sort With C (Mayukh Mitra)/Radix_sort.c",
    "content": "#include <stdio.h>\n\n//Function to get maximum value in the array... \nint max(int arr[], int n)\n{\n\tint max = arr[0];\n\tfor (int i = 1; i < n; i++)\n\t\tif (arr[i] > max)\n\t\t\tmax = arr[i];\n\treturn max;\n}\n\n//Counting Sort...\nvoid counting_sort(int arr[], int n, int j)\n{\n\tint output[n]; \n\tint i, count[10] = { 0 };\n\n\tfor (i = 0; i < n; i++)\n\t\tcount[(arr[i] / j) % 10]++;\n\n\tfor (i = 1; i < 10; i++)\n\t\tcount[i] += count[i - 1];\n\n\tfor (i = n - 1; i >= 0; i--) {\n\t\toutput[count[(arr[i] / j) % 10] - 1] = arr[i];\n\t\tcount[(arr[i] /j) % 10]--;\n\t}\n\n\tfor (i = 0; i < n; i++)\n\t\tarr[i] = output[i];\n}\n\n// Radix Sort...\nvoid radix_sort(int arr[], int n)\n{\n\t// Finding the number of digits...\n\tint m = max(arr, n);\n\n\t// Performing counting sort for every digit...\n\tfor (int j = 1; m / j > 0; j *= 10)\n\t\tcounting_sort(arr, n, j);\n}\n\nint main()\n{\n    int n = 10; // Size of the array...\n\n    // The elements of the array...\n\tint arr[] = { 12, 89, 45, 4, 11, 67, 32, 100, 3, 33 };\n\t\n\tradix_sort(arr, n);\n\n    // Printing the array after performing radix sort on it...\n\tfor (int i = 0; i < n; i++)\n\t\tprintf(\"%d \",arr[i]);\n\treturn 0;\n}\n\n/* This code is contributed by Mayukh Mitra */\n"
  },
  {
    "path": "Algorithms/Sorting/Radix_Sort/RadixSort.java",
    "content": "public class Radix_Sort {  \n    public static void main(String[] args) {  \n            int i;  \n            Scanner sc = new Scanner(System.in);  \n            int[] a = {90,23,101,45,65,23,67,89,34,23};  \n            radix_sort(a);    \n            System.out.println(\"\\n The sorted array is: \\n\");  \n            for(i=0;i<10;i++)  \n                System.out.println(a[i]);  \n        }  \n      \n        static int largest(inta[])  \n        {     \n            int larger=a[0], i;   \n            for(i=1;i<10;i++)  \n            {  \n                if(a[i]>larger)  \n                larger = a[i];  \n            }  \n            returnlarger;  \n        }  \n        static void radix_sort(inta[])  \n        {  \n            int bucket[][]=newint[10][10];  \n            int bucket_count[]=newint[10];  \n            int i, j, k, remainder, NOP=0, divisor=1, larger, pass;  \n            larger = largest(a);  \n            while(larger>0)  \n            {  \n                NOP++;  \n                larger/=10;  \n            }  \n            for(pass=0;pass<NOP;pass++) // Initialize the buckets  \n            {  \n                for(i=0;i<10;i++)  \n                bucket_count[i]=0;  \n                for(i=0;i<10;i++)  \n                {  \n                    // sort the numbers according to the digit at passth place            \n                    remainder = (a[i]/divisor)%10;  \n                    bucket[remainder][bucket_count[remainder]] = a[i];  \n                    bucket_count[remainder] += 1;  \n                }  \n                // collect the numbers after PASS pass  \n                i=0;  \n                for(k=0;k<10;k++)  \n                {  \n                    for(j=0;j<bucket_count[k];j++)  \n                    {  \n                        a[i] = bucket[k][j];  \n                        i++;  \n                    }  \n                }  \n                divisor *= 10;  \n            }  \n        }  \n    }  "
  },
  {
    "path": "Algorithms/Sorting/Radix_Sort/RadixSort.py",
    "content": "# This is the Python version of Radix Sort\n# Code is contributed by: Italo Vinicius.\n# Radix Sort is an Sorting Algorithm which takes compelxity: O((n+b) * logb(k))\n\ndef countingSort(arr, exp1):\n \n    n = len(arr)\n \n    # The output array elements that will have sorted arr\n    output = [0] * (n)\n \n    # initialize count array as 0\n    count = [0] * (10)\n \n    # Store count of occurrences in count[]\n    for i in range(0, n):\n        index = (arr[i] / exp1)\n        count[int(index % 10)] += 1\n \n    # Change count[i] so that count[i] now contains actual\n    # position of this digit in output array\n    for i in range(1, 10):\n        count[i] += count[i - 1]\n \n    # Build the output array\n    i = n - 1\n    while i >= 0:\n        index = (arr[i] / exp1)\n        output[count[int(index % 10)] - 1] = arr[i]\n        count[int(index % 10)] -= 1\n        i -= 1\n \n    # Copying the output array to arr[],\n    # so that arr now contains sorted numbers\n    i = 0\n    for i in range(0, len(arr)):\n        arr[i] = output[i]\n \n# Method to do Radix Sort\ndef radixSort(arr):\n \n    # Find the maximum number to know number of digits\n    max1 = max(arr)\n \n    # Do counting sort for every digit. Note that instead\n    # of passing digit number, exp is passed. exp is 10^i\n    # where i is current digit number\n    exp = 1\n    while max1 / exp > 0:\n        countingSort(arr, exp)\n        exp *= 10\n\nif __name__ == \"__main__\":\n    arr = list(map(int,input().split()))\n    radixSort(arr)\n    \n    print(' '.join(str(x) for x in arr))"
  },
  {
    "path": "Algorithms/Sorting/Radix_Sort/Radix_Sort.js",
    "content": "// helper function to get the last nth digit of a number\nvar getDigit = function (num, nth) {\n    // get last nth digit of a number\n    var remainder = 0;\n    while (nth--) {\n        remainder = num % 10\n        num = Math.floor((num - remainder) / 10)\n    }\n    return remainder\n}\n\n// radixSort\nfunction radixSort(list) {\n    var max = Math.floor(Math.log10(Math.max.apply(Math, list))),\n        //get the length of digits of the max value in this array\n        digitBuckets = [],\n        index = 0;\n\n    for (var i = 0; i < max + 1; i++) {\n\n        // rebuild the digit buckets according to this digit\n        digitBuckets = []\n        for (var j = 0; j < list.length; j++) {\n            var digit = getDigit(list[j], i + 1);\n            digitBuckets[digit] = digitBuckets[digit] || [];\n            digitBuckets[digit].push(list[j]);\n        }\n\n        // rebuild the list according to this digit\n        index = 0\n        for (var t = 0; t < digitBuckets.length; t++) {\n            if (digitBuckets[t] && digitBuckets[t].length > 0) {\n                for (j = 0; j < digitBuckets[t].length; j++) {\n                    list[index++] = digitBuckets[t][j];\n                }\n            }\n        }\n    }\n    return list\n}\n\nvar array = [76, 45, 89, 23, 9];\nradixSort(array);\n\n//OUTPUT\n//[ 9, 23, 45, 76, 89 ]\n\n//O(kn) where k is the number of bits required to represent the largest element in the array and n is the number of element\n"
  },
  {
    "path": "Algorithms/Sorting/Radix_Sort/Radix_Sort.rb",
    "content": "def counting_sort(input_arr, exp)\n  count_arr = Array.new(10, 0)\n  result = Array.new(input_arr.size)\n\n  m = 10 ** (exp+1)\n  n = 10 ** exp\n\n  input_arr.each do |item|\n    count_arr[(item % m) / n] += 1\n  end\n\n  for i in 1...10\n    count_arr[i] = count_arr[i-1] + count_arr[i]\n  end\n\n  i = input_arr.size - 1\n  until i < 0 do\n    item = input_arr[i]\n    count_arr[(item % m) / n] -= 1\n    result[count_arr[(item % m) / n]] = item\n    i -= 1\n  end\n\n  result\nend\n\ndef radix_sort(arr)\n  maximum = arr.max\n  exp = 0\n\n  until maximum == 0 do\n    exp += 1\n    maximum = maximum / 10\n  end\n\n  for i in 0...exp do\n    arr = counting_sort(arr, i)\n  end\n\n  arr\nend\n\narray = [170, 45, 75, 90, 802, 24, 2, 66]\narray = radix_sort(array)\n\nprint array\nputs\n\n# Output\n# [2, 24, 45, 66, 75, 90, 170, 802]\n"
  },
  {
    "path": "Algorithms/Sorting/Radix_Sort/Radix_sort.cs",
    "content": "using System;\n namespace Radix_Sort\n{\n    class Program\n    {\n        static void Sort(int[] arr)\n        {\n            int i, j;\n            int[] tmp = new int[arr.Length];\n            for (int shift = 31; shift > -1; --shift)\n            {\n                j = 0;\n                for (i = 0; i < arr.Length; ++i)\n                {\n                    bool move = (arr[i] << shift) >= 0;\n                    if (shift == 0 ? !move : move)   \n                        arr[i-j] = arr[i];\n                    else                             \n                        tmp[j++] = arr[i];\n                }\n                Array.Copy(tmp, 0, arr, arr.Length-j, j);\n            }\n        }\n        static void Main(string[] args)\n        {\n            \n\t\t\tint[] arr = new int[] { 2, 5, -4, 11, 0, 18, 22, 67, 51, 6  };\n\t\t\tConsole.WriteLine(\"\\nOriginal array : \");\n\t\t\tforeach (var item in arr)\n            {\n                Console.Write(\" \" + item);    \n            }\n\n            Sort(arr);\n\t\t\tConsole.WriteLine(\"\\nSorted array : \");\n\t\t\tforeach (var item in arr)\n            {\n                Console.Write(\" \" + item);    \n            }\n           Console.WriteLine(\"\\n\");\n        }\n    }\n}\n"
  },
  {
    "path": "Algorithms/Sorting/Radix_Sort/radixSort.php",
    "content": "\r\n<?php\r\n//Radix Sort algorithm\r\n// Description: The idea of Radix Sort is to divide the array in digit by digit starting from least significant digit to most significant digit. Radix sort uses counting sort as a subroutine to sort.\r\n// Time Complexity: O((n+b) * logb(k))\r\n\r\n// A function to do counting sort of arr[] \r\n// according to the digit represented by exp. \r\nfunction countSort(&$arr, $size, $exp) \r\n{ \r\n\t$output = array_fill(0, $size, 0);  \r\n\t$count = array_fill(0, 10, 0); \r\n\r\n\t// Store count of occurrences in count[] \r\n\tfor ($i = 0; $i < $size; $i++) \r\n\t\t$count[ ($arr[$i] / $exp) % 10 ]++; \r\n\r\n\t// Change count[i] so that count[i] \r\n\t// now contains actual position of \r\n\t// this digit in output[] \r\n\tfor ($i = 1; $i < 10; $i++) \r\n\t\t$count[$i] += $count[$i - 1]; \r\n\r\n\t// Build the output array \r\n\tfor ($i = $size - 1; $i >= 0; $i--) \r\n\t{ \r\n\t\t$output[$count[ ($arr[$i] / \r\n\t\t\t\t\t\t$exp) % 10 ] - 1] = $arr[$i]; \r\n\t\t$count[ ($arr[$i] / $exp) % 10 ]--; \r\n\t} \r\n\r\n\t// Copy the output array to arr[], so \r\n\t// that arr[] now contains sorted numbers\r\n\t// according to current digit \r\n\tfor ($i = 0; $i < $size; $i++) \r\n\t\t$arr[$i] = $output[$i]; \r\n} \r\n\r\n// The main function to that sorts arr[] \r\n// of size n using Radix Sort \r\nfunction radixsort(&$arr, $size) \r\n{ \r\n\t\r\n\t// Find the maximum number to know\r\n\t// number of digits \r\n\t$m = max($arr); \r\n\r\n\t// Do counting sort for every digit. Note \r\n\t// that instead of passing digit number, \r\n\t// exp is passed. exp is 10^i where i is \r\n\t// current digit number \r\n\tfor ($exp = 1; $m / $exp > 0; $exp *= 10) \r\n\t\tcountSort($arr, $size, $exp); \r\n} \r\n\r\n// Function to print an array \r\nfunction printArray(&$arr,$size) \r\n{ \r\n\tfor ($i = 0; $i < $size; $i++) \r\n\t\techo $arr[$i] . \" \"; \r\n} \r\n\r\n// Input is given here \r\n\r\n$arr = array(170, 43, 77, 90, 21, 820, 2, 65); \r\n$size = count($arr); \r\n\r\n// Function Call\r\nradixsort($arr, $size); \r\nprintArray($arr, $size); \r\n\r\n?>"
  },
  {
    "path": "Algorithms/Sorting/Radix_Sort/radixsort.cpp",
    "content": "#include<iostream>\nusing namespace std;\n\nint max(int arr[], int n)\n{\n\tint max = arr[0];\n\tfor (int i = 1; i < n; i++)\n\t\tif (arr[i] > max)\n\t\t\tmax = arr[i];\n\treturn max;\n}\n\n\nvoid counting_sort(int arr[], int n, int j)\n{\n\tint output[n]; \n\tint i, count[10] = { 0 };\n\n\tfor (i = 0; i < n; i++)\n\t\tcount[(arr[i] / j) % 10]++;\n\n\tfor (i = 1; i < 10; i++)\n\t\tcount[i] += count[i - 1];\n\n\tfor (i = n - 1; i >= 0; i--) {\n\t\toutput[count[(arr[i] / j) % 10] - 1] = arr[i];\n\t\tcount[(arr[i] /j) % 10]--;\n\t}\n\n\tfor (i = 0; i < n; i++)\n\t\tarr[i] = output[i];\n}\n\n\nvoid radix_sort(int arr[], int n)\n{\n\t\n\tint m = max(arr, n);\n\tfor (int j = 1; m / j > 0; j *= 10)\n\t\tcounting_sort(arr, n, j);\n}\n\nint main()\n{\n    int n = 10; \n\tint arr[] = { 12, 89, 45, 4, 11, 67, 32, 100, 3, 33 };\n\tradix_sort(arr, n);\n\tfor (int i = 0; i < n; i++)\n\t\tcout<<\"\\t \"<<arr[i];\n\treturn 0;\n}\n"
  },
  {
    "path": "Algorithms/Sorting/Selection_Algorithms.cpp",
    "content": "#include<iostream>\nusing namespace std;\nvoid swapping(int &a, int &b) {         //swap the content of a and b\n   int temp;\n   temp = a;\n   a = b;\n   b = temp;\n}\nvoid display(int *array, int size) {\n   for(int i = 0; i<size; i++)\n      cout << array[i] << \" \";\n   cout << endl;\n}\nvoid selectionSort(int *array, int size) {\n   int i, j, imin;\n   for(i = 0; i<size-1; i++) {\n      imin = i;   //get index of minimum data\n      for(j = i+1; j<size; j++)\n         if(array[j] < array[imin])\n            imin = j;\n         //placing in correct position\n         swap(array[i], array[imin]);\n   }\n}\nint main() {\n   int n;\n   cout << \"Enter the number of elements: \";\n   cin >> n;\n   int arr[n];           //create an array with given number of elements\n   cout << \"Enter elements:\" << endl;\n   for(int i = 0; i<n; i++) {\n      cin >> arr[i];\n   }\n   cout << \"Array before Sorting: \";\n   display(arr, n);\n   selectionSort(arr, n);\n   cout << \"Array after Sorting: \";\n   display(arr, n);\n}\n"
  },
  {
    "path": "Algorithms/Sorting/Selection_Sort/README.md",
    "content": "## Selection Sort\n\nIn selection sort array is first divided into two part sorted and unsorted part. Then in unsorted part the minimum number is checked and shifted to first position similarly this process is carried till the array is sorted.\n\nFor example: [8 3 6 2] -> |[8 3 6 2] -> [2]|[8 3 6] -> [2 3]|[8 6] -> [2 3 6]|[8]     -> [2 3 6 8].\n\n"
  },
  {
    "path": "Algorithms/Sorting/Selection_Sort/Selection Sort.py",
    "content": "A = [2,3,80,45,6,111]\n\nfor i in range(len(A)):\n    min = i\n    for j in range(i+1, len(A)):\n        if A[min] > A[j]:\n            min = j\n    A[i], A[min] = A[min],A[i]\nfor i in range(len(A)):\n    print(A[i],end = \" \")"
  },
  {
    "path": "Algorithms/Sorting/Selection_Sort/SelectionSort.java",
    "content": "// Java program for implementation of Selection Sort \n\nclass SelectionSort \n{ \n\tvoid sort(int arr[]) \n\t{ \n\t\tint n = arr.length; \n\n\t\tfor (int i = 0; i < n-1; i++) \n\t\t{ \n\t\t\t// Find the minimum element in unsorted array \n\t\t\tint min_idx = i; \n\t\t\tfor (int j = i+1; j < n; j++) \n\t\t\t\tif (arr[j] < arr[min_idx]) \n\t\t\t\t\tmin_idx = j; \n\n\t\t\t// Swap the found minimum element with the first \n\t\t\t// element \n\t\t\tint temp = arr[min_idx]; \n\t\t\tarr[min_idx] = arr[i]; \n\t\t\tarr[i] = temp; \n\t\t} \n\t} \n\n\t// Prints the array \n\tvoid printArray(int arr[]) \n\t{ \n\t\tint n = arr.length; \n\t\tfor (int i=0; i<n; ++i) \n\t\t\tSystem.out.print(arr[i]+\" \"); \n\t\tSystem.out.println(); \n\t} \n\n\t// Driver code \n\tpublic static void main(String args[]) \n\t{ \n\t\tSelectionSort obj = new SelectionSort(); \n\t\tint arr[] = {50, 40, 30, 20, 10}; // Default Array\n\t\tobj.sort(arr);  // Calling sorting funtion\n\t\tobj.printArray(arr); //Printing Array\n\t} \n} \n\n"
  },
  {
    "path": "Algorithms/Sorting/Selection_Sort/SelectionSort.py",
    "content": "def selection_sort(lst):\r\n    for i in range(len(lst) - 1):\r\n        k = min(range(i, len(lst)), key=lst.__getitem__)\r\n        lst[i], lst[k] = lst[k], lst[i]\r\n    return lst\r\n         \r\nlst = [8,3,6,2]\r\nprint(selection_sort(lst))\r\n"
  },
  {
    "path": "Algorithms/Sorting/Selection_Sort/SelectionSort.scala",
    "content": "//Selection sort in scala\nobject SelectionSortAscApp {\n\n  //main function\n  def main(args: Array[String]): Unit = {\n  \n    //list to be sorted using selection sort\n    println(selectionSortAsc(List(5,3,2,8,7)))\n    \n    println(selectionSortAsc(List(\"k\",\"d\",\"c\",\"a\",\"q\")))\n    \n  }\n  \n  //Selection sort algorithm\n  /*1. Find the smallest element, or largest element if doing descending order, in the list and swap with the first element.\n    2. In the second pass, find the smallest element in the remaining list, which is a sublist of the given list that doesn’t have the global smallest element.\n    3. Swap the smallest element with the lowest index in the sublist if the lowest index element is greater than this smallest element.\n    4. Continue the above steps until two elements are left in the list, which is the final pass, requiring only one comparison. Swap if the element at the lower index is greater than the element at the higher index. This completes selection sort.\n  */\n  \n  def selectionSortAsc[T <% Ordered[T]](myData: List[T]):\n  List[T] = myData match {\n  \n    case Nil => Nil\n    \n    case head :: Nil => List(head)\n    \n    case head :: tail => {\n    \n      val minElem = tail.min\n      \n      val indexOfMinElem = tail.indexOf(minElem)\n      \n      if(head <= minElem) {\n      \n        head :: selectionSortAsc(tail)\n        } else {\n          val (tailHalf1, tailHalf2) =  tail.splitAt(indexOfMinElem)\n          \n          tailHalf2.head :: selectionSortAsc(tailHalf1 ::: head :: tailHalf2.tail)\n          \n          }\n       }\n  }\n}\n"
  },
  {
    "path": "Algorithms/Sorting/Selection_Sort/Selection_Sort.cpp",
    "content": "//Selection sort, sort the array by swapping the curr element with the smallest element from indexes curr+1 to len-1\n#include<iostream>\nusing namespace std;\nvoid selection_sort(int a[],int n){\n    for(int i=0;i<n-1;i++){\n        int min_index=i;\n        for(int j=i+1;j<=n-1;j++){\n            if(a[j]<a[min_index]){\n                min_index=j;\n            }\n        }\n      swap(a[i],a[min_index]);\n    }\n}\nint main(){\n    int n;\n    cin>>n;\n    int a[1000];\n    for(int i=0;i<n;i++){\n        cin>>a[i];\n    }\n    selection_sort(a,n);\n    for(int i=0;i<n;i++){\n        cout<<a[i]<<\",\";\n    }\n    return 0;\n}\n"
  },
  {
    "path": "Algorithms/Sorting/Selection_Sort/Selection_Sort.go",
    "content": "package main\r\n\r\nimport (\r\n\t\"fmt\"\r\n\t\"strconv\"\r\n)\r\n\r\nfunc selectionSort(arr [100]int, n int) {\r\n\tfor i := 0; i < n-1; i++ {\r\n\t\tvar minIndex = i\r\n\t\tfor j := i + 1; j < n; j++ {\r\n\t\t\tif arr[minIndex] > arr[j] {\r\n\t\t\t\tminIndex = j\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tvar temp = arr[minIndex]\r\n\t\tarr[minIndex] = arr[i]\r\n\t\tarr[i] = temp\r\n\t}\r\n\tfmt.Print(\"After Sorting: \")\r\n\tprintArray(arr, n)\r\n}\r\n\r\nfunc printArray(arrs [100]int, n int) {\r\n\tfor i := 0; i < n; i++ {\r\n\t\tfmt.Print(strconv.Itoa(arrs[i]) + \" \")\r\n\t}\r\n\tfmt.Println(\"\")\r\n}\r\n\r\nfunc main() {\r\n\tfmt.Print(\"How many number : \")\r\n\tvar no = 0\r\n\tfmt.Scanln(&no)\r\n\tvar arr [100]int\r\n\tfmt.Print(\"Enter array values : \")\r\n\tfor i := 0; i < no; i++ {\r\n\t\tfmt.Scanf(\"%d\", &arr[i])\r\n\t}\r\n\tfmt.Print(\"Before Sorting: \")\r\n\tprintArray(arr, no)\r\n\tselectionSort(arr, no)\r\n}\r\n"
  },
  {
    "path": "Algorithms/Sorting/Selection_Sort/selection sort.cs",
    "content": "// C# program for implementation  \n// of Selection Sort \nusing System; \n  \nclass GFG \n{  \n    static void sort(int []arr) \n    { \n        int n = arr.Length; \n  \n        // One by one move boundary of unsorted subarray \n        for (int i = 0; i < n - 1; i++) \n        { \n            // Find the minimum element in unsorted array \n            int min_idx = i; \n            for (int j = i + 1; j < n; j++) \n                if (arr[j] < arr[min_idx]) \n                    min_idx = j; \n  \n            // Swap the found minimum element with the first \n            // element \n            int temp = arr[min_idx]; \n            arr[min_idx] = arr[i]; \n            arr[i] = temp; \n        } \n    } \n  \n    // Prints the array \n    static void printArray(int []arr) \n    { \n        int n = arr.Length; \n        for (int i=0; i<n; ++i) \n            Console.Write(arr[i]+\" \"); \n        Console.WriteLine(); \n    } \n  \n    // Driver code  \n    public static void Main() \n    { \n        int []arr = {64,25,12,22,11}; \n        sort(arr); \n        Console.WriteLine(\"Sorted array\"); \n        printArray(arr); \n    } \n  \n} \n"
  },
  {
    "path": "Algorithms/Sorting/Selection_Sort/selection_sort.c",
    "content": "#include<stdio.h>\nint main(){\n   /* Here i & j for loop counters, temp for swapping,\n    * count for total number of elements, number[] to\n    * store the input numbers in array. You can increase\n    * or decrease the size of number array as per requirement\n    */\n   int i, j, count, temp, number[25];\n\n   printf(\"How many numbers u are going to enter?: \");\n   scanf(\"%d\",&count);\n\n   printf(\"Enter %d elements: \", count);\n   // Loop to get the elements stored in array\n   for(i=0;i<count;i++)\n      scanf(\"%d\",&number[i]);\n \n   // Logic of selection sort algorithm\n   for(i=0;i<count;i++){\n      for(j=i+1;j<count;j++){\n         if(number[i]>number[j]){\n            temp=number[i];\n            number[i]=number[j];\n            number[j]=temp;\n         }\n      }\n   }\n\n   printf(\"Sorted elements: \");\n   for(i=0;i<count;i++)\n      printf(\" %d\",number[i]);\n\n   return 0;\n}\n"
  },
  {
    "path": "Algorithms/Sorting/Selection_Sort/selection_sort.rb",
    "content": "array = Array[4,456,45,657,34,8,987,1,78,50]\n\nsize = array.size\n\nmin = 0\n\nfor i in 0..size\n    for j in (i+1)..size\n        if array[j-1] < array[i-1]\n            min = array[j-1]\n            array[j-1] = array[i-1]\n            array[i-1] = min\n        end\n    end\nend\n\nputs array\n"
  },
  {
    "path": "Algorithms/Sorting/Shell_Sort/README.md",
    "content": "## This folder is empty.\n"
  },
  {
    "path": "Algorithms/Sorting/Shell_Sort/Shell_Sort.c",
    "content": "#include <stdio.h>\r\n#include <stdlib.h>\r\n\r\nint main()\r\n{\r\n\t//input size of the array ar\r\n\tint n;\r\n\tscanf(\"%d\", &n);\r\n\tint ar[n];\r\n\r\n\t//input elements in ar[n]\r\n\tfor (int i = 0; i < n; i++)\r\n\t\tscanf(\"%d\", &ar[i]);\r\n\r\n\t//shell sort algorithm\r\n\t//shell sort is a variation of insertion sort.\r\n\r\n\t//gap = [n/2], floor value.\r\n\t//we try to sort elements with this gap\r\n\t//we continue reducing the gap until it reaches 1.\r\n\r\n\t//complexity becomes O(n*logn)\r\n\r\n\tint gap, i, j, temp;\r\n\r\n\tfor (gap = n / 2; gap >= 1; gap /= 2)\r\n\t{\r\n\t\tfor (i = gap; i < n; i++)\r\n\t\t{\r\n\t\t\ttemp = ar[i];\r\n\t\t\tj = i - gap;\r\n\t\t\twhile (j >= 0 && ar[j] > temp)\r\n\t\t\t{\r\n\t\t\t\tar[j + gap] = ar[j];\r\n\t\t\t\tj = j - gap;\r\n\t\t\t}\r\n\t\t\tar[j + gap] = temp;\r\n\t\t}\r\n\t}\r\n\r\n\tfor (int i = 0; i < n; i++)\r\n\t\tprintf(\"%d \", ar[i]);\r\n\tprintf(\"\\n\");\r\n\r\n\treturn 0;\r\n}\r\n"
  },
  {
    "path": "Algorithms/Sorting/Shell_Sort/Shell_Sort.cpp",
    "content": "// The Shell Sort Algorithm in C++\n\nusing namespace std;\n#include <iostream> \n\n// Shell Sort Algorithm in a Function\nvoid ShellSort(int sortArray[], int size) {\n    for (int gap = size / 2; gap > 0; gap /= 2)\n    {\n        for (int i = gap; i < size; i++)\n        {\n            int temp = sortArray[i];\n            int j;\n            for (j = i; j >= gap && sortArray[j - gap] > temp; j -= gap)\n            {\n                sortArray[j] = sortArray[j - gap];\n            }\n            sortArray[j] = temp;\n        }        \n    }        \n}\n\n\nint main() {\n    cout << \"\\n\";\n    // Requesting Array Size to the User\n    int size;\n    cout << \"Enter the size of the array: \";\n    cin >> size;\n\n    // Requesting Array Elements to the User\n    int sortArray[size];\n    cout << \"Enter the array elements: \\n\";    \n    for (int i = 0; i < size; i++)\n    {\n        cin >> sortArray[i];\n    }\n\n    cout << \"\\n\";\n\n    // OUTPUT Array before Shell Sort\n    cout << \"Array BEFORE the Shell Sort: \";\n    cout << \"[\";\n    for (int i = 0; i < size; i++)\n    {\n        cout << sortArray[i] << \", \";\n    }\n    cout << \"\\b\\b\";\n    cout << \"]\";\n\n    cout << \"\\n\\n\";\n\n    // Applying the Shell Sort Algorithm\n    cout << \"Applying the Shell Sort Algorithm...\\n\";\n    ShellSort(sortArray, size);\n\n    cout << \"\\n\";\n\n    // OUTPUT Array after Shell Sort\n    cout << \"Array AFTER the Shell Sort: \";\n    cout << \"[\";\n    for (int i = 0; i < size; i++)\n    {\n        cout << sortArray[i] << \", \";\n    }\n    cout << \"\\b\\b\";\n    cout << \"]\";\n    cout << endl;\n\n    cout << \"\\n\\n\";\n\n    return 0;    \n}"
  },
  {
    "path": "Algorithms/Sorting/Shell_Sort/Shell_Sort.cs",
    "content": "class ShellSort \r\n{ \r\n    static void printArray(int []arr) \r\n    { \r\n        int n = arr.Length; \r\n        for (int i=0; i<n; ++i) \r\n        Console.Write(arr[i] + \" \"); \r\n        Console.WriteLine(); \r\n    } \r\n  \r\n    int sort(int []arr) \r\n    { \r\n        int n = arr.Length; \r\n  \r\n        for (int gap = n/2; gap > 0; gap /= 2) \r\n        { \r\n            for (int i = gap; i < n; i += 1) \r\n            { \r\n                int temp = arr[i]; \r\n  \r\n\r\n                int j; \r\n                for (j = i; j >= gap && arr[j - gap] > temp; j -= gap) \r\n                    arr[j] = arr[j - gap]; \r\n  \r\n                arr[j] = temp; \r\n            } \r\n        } \r\n        return 0; \r\n    } \r\n\r\n    public static void Main() \r\n    { \r\n        int []arr = {12, 34, 54, 2, 3}; \r\n        Console.Write(\"Array before sorting :\\n\"); \r\n        printArray(arr); \r\n  \r\n        ShellSort ob = new ShellSort(); \r\n        ob.sort(arr); \r\n  \r\n        Console.Write(\"Array after sorting :\\n\"); \r\n        printArray(arr); \r\n    } \r\n}  "
  },
  {
    "path": "Algorithms/Sorting/Shell_Sort/Shell_Sort.java",
    "content": "import java.io.BufferedReader;\nimport java.io.IOException;\nimport java.io.InputStreamReader;\n\npublic class ShellSort {\n\t\n\tprivate static void shellSort(Comparable[] arr)\n\t{\t//Sort arr[] into increasing order\n\t\tint N = arr.length;\n\t\tint h = 1;\n\t\twhile(h < N/3)\n\t\t\th = 3*h+1; // 1, 4, 13, 40, 121, 364, 1093, ... \n\t\twhile(h >= 1)\n\t\t{\t//h-sort the array\n\t\t\tfor(int i=h; i<N; i++)\n\t\t\t{\t//Insert arr[i] among arr[i-h], arr[i-2*h], arr[i-3*h]...\n\t\t\t\tfor(int j=i; j>=h && lessThan(arr[j], arr[j-h]); j-=h)\n\t\t\t\t\tswap(arr, j, j-h);\n\t\t\t}\n\t\t\th = h/3;\n\t\t}\n\t}\n\t\n\tprivate static boolean lessThan(Comparable first, Comparable second)\n\t{\n\t\treturn first.compareTo(second) < 0; \n\t}\n\t\n\tprivate static void swap(Comparable[] arr, int first, int second)\n\t{\t// Swaps two elements in the array.\n\t\tComparable temp = arr[first];\n\t\tarr[first] = arr[second];\n\t\tarr[second] = temp;\n\t}\n\t\n\tprivate static void printSortedArray(Comparable[] arr)\n\t{\t// Print the sorted array as output, on a single line.\n\t\tfor(int i=0; i<arr.length; i++)\n\t\t\tSystem.out.print(arr[i]+\" \");\n\t\tSystem.out.println();\n\t}\n\t\n\tpublic static void main(String[] args) throws IOException\n\t{\n\t\tBufferedReader reader = new BufferedReader(new InputStreamReader(System.in));\n\t\tString[] arr = reader.readLine().split(\" \"); // String[] used in this implementation. Any data type implementing the Comaprable interface can be used in it's place.\n\t\tshellSort(arr); // Sort the array using ShellSort\n\t\tprintSortedArray(arr); // Print the sorted output\n\t}\n}\n"
  },
  {
    "path": "Algorithms/Sorting/Shell_Sort/Shell_Sort.js",
    "content": "/* A JavaScript program to perform Shell Sort */\r\n\r\nshellSort = (array) => {\r\n  for (var h = array.length; h > 0; h = parseInt(h / 2)) {\r\n    for (var i = h; i < array.length; i++) {\r\n      var k = array[i];\r\n      for (var j = i; j >= h && k < array[j - h]; j -= h)\r\n        array[j] = array[j - h];\r\n      array[j] = k;\r\n    }\r\n  }\r\n  return array;\r\n};\r\n\r\nvar array = [8, 3, 5, 9, 1, 5, 9, 2, 3, 8, 4];\r\nconsole.log(shellSort(array));\r\n"
  },
  {
    "path": "Algorithms/Sorting/Shell_Sort/Shell_Sort.swift",
    "content": "func ShellSort(_ items: [Int]) -> [Int] {\n        var result = items\n        \n        let length = result.count\n        var h = 1\n        \n        while h < length / 3 {\n            h = 3 * h + 1\n        }\n        \n        while h >= 1 {\n            for i in h..<length {\n                for j in stride(from: i, to: h - 1, by: -h) {\n                    if result[j] < result[j - h] {\n                        result.swapAt(j,j-h)\n                    } else {\n                        break\n                    }\n                }\n            }\n            h /= 3\n        }\n        \n        return result\n    }\n\nvar data:[Int] = [22, 7, 2, -5, 8, 4]\nprint(ShellSort(data)) // [-5, 2, 4, 7, 8, 22]\n\n"
  },
  {
    "path": "Algorithms/Sorting/Shell_Sort/shell_sort.py",
    "content": "def shell(a):\n  n=len(a)\n  gap=n//2\n  while gap>0:\n    for j in range(gap,n):\n      key=a[j]\n      i=j\n      while i>0 and a[i-gap]>key:\n        a[i]=a[i-gap]\n        i=i-gap\n      a[i]=key\n    gap=gap//2\n  return a\n\na=[2,7,4,6,1,8,5]\nprint(shell(a))\n"
  },
  {
    "path": "Algorithms/Sorting/Shell_Sort/shell_sort.sh",
    "content": "shellsort()\n{\n    arr=(\"$@\")\n    len=${#arr[@]}\n    gap=$(( $n / 2 ))\n    while [ $gap -gt 0 ]; do\n        for((ind=$gap;$ind<$n;ind++)); do\n            temp=${arr[$ind]}\n            j=$ind\n            while [[ $j -ge $gap && ${arr[$(( $j - $gap ))]} -gt $temp ]]; do\n                arr[$j]=${arr[$(( $j - $gap ))]}\n                j=$(( $j - $gap ))\n            done\n            arr[$j]=$temp\n        done\n        gap=$(( $gap / 2 ))\n    done\n    echo ${arr[@]}\n}\n\n\necho -n \"Enter the total numbers: \"\nread n\necho \"Enter numbers: \"\ni=0\n\nwhile [ $i -lt $n ]\ndo\n    read a[$i]\n\n    i=`expr $i + 1`\ndone\n\nshellsort ${a[@]}\n"
  },
  {
    "path": "Algorithms/Sorting/Stooge_Sort/README.md",
    "content": "## This folder is empty.\n"
  },
  {
    "path": "Algorithms/Sorting/Stooge_Sort/Stooge_Sort.cs",
    "content": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Threading.Tasks;\n\nnamespace ConsoleApp1\n{\n    // C# program to implement stooge sort \n    using System;\n\n    class Program\n    {\n        /// <summary>\n        /// Main application function.\n        /// </summary>\n        public static void Main()\n        {\n            int[] arr = { 2, 4, 5, 3, 1 };\n            int n = arr.Length;\n\n            // Calling Stooge Sort function \n            // to sort the array \n            StoogeSort(ref arr);\n\n            // Display the sorted array \n            for (int i = 0; i < n; i++)\n                Console.Write(arr[i] + \" \");\n        }\n\n        /// <summary>\n        /// Runs stooge sort on provided array\n        /// </summary>\n        /// <param name=\"arr\">array to be sorted</param>\n        /// <param name=\"lowIndex\">Low index of current sort</param>\n        /// <param name=\"highIndex\">High index of current sort</param>\n        public static void StoogeSort(ref int[] arr)\n        {\n            StoogeSort(ref arr,0,arr.Length-1);\n        }\n        /// <summary>\n        /// Runs stooge sort on provided array\n        /// </summary>\n        /// <param name=\"arr\">array to be sorted</param>\n        /// <param name=\"lowIndex\">Low index of current sort</param>\n        /// <param name=\"highIndex\">High index of current sort</param>\n        public static void StoogeSort(ref int[] arr, int lowIndex, int highIndex, int? depth = 0)\n        {\n            int arrayLength = (highIndex - lowIndex + 1);\n            //if there are not 2 items here, we are done\n            if (arrayLength <= 1)\n                return;\n\n\n            // If first element is smaller \n            // than last, swap them \n            if (arr[lowIndex] > arr[highIndex])\n            {\n                int tempLowIndexValue = arr[lowIndex];\n                arr[lowIndex] = arr[highIndex];\n                arr[highIndex] = tempLowIndexValue;\n            }\n            \n            //if only 2 values, we know we are done. start to end recursion\n            if (arrayLength == 2)\n                return;\n            \n            int thirdOfArrayLength = (highIndex - lowIndex + 1) / 3;\n\n            // Recursively sort first  \n            // 2/3 elements \n            \n           StoogeSort(ref arr, lowIndex, highIndex - thirdOfArrayLength, depth +1);\n            // Recursively sort last \n            // 2/3 elements \n            StoogeSort(ref arr, lowIndex +thirdOfArrayLength, highIndex, depth + 1);\n\n            // Recursively sort first  \n            // 2/3 elements again to  \n            // confirm \n            StoogeSort(ref arr, lowIndex, highIndex - thirdOfArrayLength, depth + 1);\n            \n        }\n\n    }\n}\n"
  },
  {
    "path": "Algorithms/Sorting/Stooge_Sort/Stooge_Sort.go",
    "content": "package main\n\nimport \"fmt\"\n\nvar arr = []int{1, 44, 37, 6, 54, 81, 21, 66}\n\nfunc main() {\n\tfmt.Println(\"Before Sorting:\", arr)\n\tstoogesort(arr)\n\tfmt.Println(\"After Stooge Sort: \", arr)\n}\n\nfunc stoogesort(arr []int) {\n\tend := len(arr) - 1\n\tif arr[end] < arr[0] {\n\t\tarr[0], arr[end] = arr[end], arr[0]\n\t}\n\tif end > 1 {\n\t\tt := len(arr) / 3\n\t\tstoogesort(arr[:len(arr)-t])\n\t\tstoogesort(arr[t:])\n\t\tstoogesort(arr[:len(arr)-t])\n\t}\n}\n"
  },
  {
    "path": "Algorithms/Sorting/Stooge_Sort/Stooge_Sort.py",
    "content": "\"\"\"\nStooge Sort in Python\n\nThe stooge function takes three parameters:\n- number_list: list to order\n- first: Index of the first item to be ordered on the list. Default is zero.\n- last: Index of the last item to be ordered on the list.\n\nThe stooge function returns the ordered list\n\"\"\"\nfrom typing import List\nfrom math import ceil\n\ndef stooge(number_list: List[int], last: int, first: int = 0):\n    length = last - first + 1\n\n    # Swap first value with last value if first > last\n    if number_list[first] > number_list[last]:\n        n = number_list[first]\n        number_list[first] = number_list[last]\n        number_list[last] = n\n\n    # If the length of the section of the list that's being ordered is > 3\n    # perform stooge on the first 2/3 of the list, then the last 2/3 of the list \n    # and finally the first 2/3 of the list again \n    if last - first + 1 > 2:\n        third = ceil((last - first + 1) / 3)\n        \n        stooge(number_list, last - third)\n        stooge(number_list, last, first + third)\n        stooge(number_list, last - third)\n    \n    return number_list\n\n\n"
  },
  {
    "path": "Algorithms/Sorting/Strand_Sort/README.md",
    "content": "## Strand Sort\n\nFirst, begin a sublist by moving the first item from the original list to the sublist. For each subsequent item in the original list, if it is greater than the last item of the sublist, remove it from the original list and append it to the sublist. Merge the sublist into a final, sorted list. Repeatedly extract and merge sublists until all items are sorted. Handle two or fewer items as special cases.\n\nFor Example :\nInput : ip[] = {10, 5, 30, 40, 2, 4, 9}\nOutput : op[] = {2, 4, 5, 9, 10, 30, 40}\n"
  },
  {
    "path": "Algorithms/Sorting/Strand_Sort/Strand_Sort.cpp",
    "content": "'''\nStrand Sort is a sorting algorithm that works in O(n) time if list is already sorted and works in O(n*n) in worst case.\n'''\n\n#include <bits/stdc++.h> \nusing namespace std; \n\n//Templates start here\n#define pb push_back\n#define mp make_pair\n#define F first\n#define S second\n#define ll long long\n#define fo(i, j, k, in) for (int i = j; i < k; i += in)\n#define refo(i, j, k, in) for (int i = j; i >= k; i -= in)\n#define rep(i, j) fo(i, 0, j, 1)\n#define rerep(i, j) fo(i, j, 0, 1)\n#define all(cont) cont.begin(), cont.end()\n#define reall(cont) cont.end(), cont.begin()\n#define foreach(it, l) for (auto it = l.begin() l it != l.end(); it++)\n#define in(A, B, C) assert(B <= A && A <= C)\n#define MOD (int)1e9\n#define MOD7 1000000007\n#define PI 3.1415926535897932384626433832795\ntypedef pair<int, int> PII;\ntypedef pair<long long, long long> PLL;\ntypedef vector<int> VI;\ntypedef vector<long long> VL;\ntypedef vector<string> VS;\ntypedef vector<PII> VII;\ntypedef vector<PLL> VLL;\ntypedef vector<VI> VVI;\ntypedef vector<VL> VVL;\ntypedef map<int, int> MPII;\ntypedef map<long long, long long> MPLL;\ntypedef set<int> SETI;\ntypedef multiset<int> MSETI;\n//Templates end here\n\n//I'm not using my templates for better understanding, else above templates can be easily used, you can alse benefit yourself just copy above templates and use them\n\nvoid strandSort(list<int> &ip, list<int> &op) \n{ \n    if (ip.empty()) \n        return; \n    list<int> sublist; \n    sublist.push_back(ip.front()); \n    ip.pop_front(); \n    for (auto it = ip.begin(); it != ip.end(); ) \n    { \n        if (*it > sublist.back()) { \n            sublist.push_back(*it); \n            it = ip.erase(it); \n        } \n        else\n            it++; \n    } \n    op.merge(sublist); \n    strandSort(ip, op); \n} \nint main(void) \n{ \n    list<int> ip{10, 5, 30, 40, 2, 4, 9}; \n    list<int> op; \n    strandSort(ip, op); \n    for (auto x : op) \n        cout << x << \" \"; \n    return 0; \n} "
  },
  {
    "path": "Algorithms/Sorting/Strand_Sort/Strand_sort.java",
    "content": "import java.util.*;\r\npublic class Strand_sort {\r\n    public static void main(String args[])\r\n    {\r\n        Scanner sc= new Scanner(System.in);\r\n        List<Integer> given_array = new ArrayList<Integer>();\r\n        List<Integer> temp = new ArrayList<Integer>();\r\n        List<Integer> temp2 = new ArrayList<Integer>();\r\n        List<Integer> output = new ArrayList<Integer>();\r\n\r\n        System.out.println(\"How many number do you want to enter :\");\r\n        int i,j,max,no=sc.nextInt();\r\n        System.out.println(\"Enter your values :\");\r\n        for(i=0;i<no;i++)\r\n        {\r\n            given_array.add(sc.nextInt());\r\n        }\r\n        System.out.println(\"Input: \"+given_array);\r\n        while(given_array.size()!=0)\r\n        {\r\n            for(i=0,max=0;i<given_array.size();i++)\r\n            {\r\n                if(given_array.get(i)>=max)\r\n                {\r\n                    temp.add(given_array.get(i));\r\n                    max=given_array.get(i);\r\n                    given_array.remove(i);\r\n                    i--;\r\n                }\r\n            }\r\n            for(i=0,j=0;i<temp.size()&&j<output.size();)\r\n            {\r\n                if(temp.get(i)>output.get(i))\r\n                {\r\n                    temp2.add(output.get(i));\r\n                    output.remove(i);\r\n                }\r\n                else\r\n                {\r\n                    temp2.add(temp.get(i));\r\n                    temp.remove(i);\r\n                }\r\n            }\r\n            if(temp.size()!=0)\r\n            {\r\n                temp2.addAll(temp);\r\n                temp.clear();\r\n            }\r\n            else if(output.size()!=0)\r\n            {\r\n                temp2.addAll(output);\r\n                output.clear();\r\n            }\r\n            output.addAll(temp2);\r\n            temp2.clear();\r\n        }\r\n        System.out.println(\"Output: \"+output);\r\n    }\r\n}\r\n"
  },
  {
    "path": "Algorithms/Sorting/Strand_Sort/strand_sort.c",
    "content": "#include <stdio.h>\n \ntypedef struct node_t *node, node_t;\nstruct node_t { int v; node next; };\ntypedef struct { node head, tail; } slist;\n \nvoid push(slist *l, node e) {\n\tif (!l->head) l->head = e;\n\tif (l->tail)  l->tail->next = e;\n\tl->tail = e;\n}\n \nnode removehead(slist *l) {\n\tnode e = l->head;\n\tif (e) {\n\t\tl->head = e->next;\n\t\te->next = 0;\n\t}\n\treturn e;\n}\n \nvoid join(slist *a, slist *b) {\n\tpush(a, b->head);\n\ta->tail = b->tail;\n}\n \nvoid merge(slist *a, slist *b) {\n\tslist r = {0};\n\twhile (a->head && b->head)\n\t\tpush(&r, removehead(a->head->v <= b->head->v ? a : b));\n \n\tjoin(&r, a->head ? a : b);\n\t*a = r;\n\tb->head = b->tail = 0;\n}\n \nvoid sort(int *ar, int len)\n{\n\tnode_t all[len];\n \n\t\n\tfor (int i = 0; i < len; i++)\n\t\tall[i].v = ar[i], all[i].next = i < len - 1 ? all + i + 1 : 0;\n \n\tslist list = {all, all + len - 1}, rem, strand = {0},  res = {0};\n \n\tfor (node e = 0; list.head; list = rem) {\n\t\trem.head = rem.tail = 0;\n\t\twhile ((e = removehead(&list)))\n\t\t\tpush((!strand.head || e->v >= strand.tail->v) ? &strand : &rem, e);\n \n\t\tmerge(&res, &strand);\n\t}\n \n\t\n\tfor (int i = 0; res.head; i++, res.head = res.head->next)\n\t\tar[i] = res.head->v;\n}\n \nvoid show(const char *title, int *x, int len)\n{\n\tprintf(\"%s \", title);\n\tfor (int i = 0; i < len; i++)\n\t\tprintf(\"%3d \", x[i]);\n\tputchar('\\n');\n}\n \nint main(void)\n{       int n;\n        printf(\"Enter size of array \");\n        scanf(\"%d\", &n);\n        int x[n];\n        for(int i = 0; i < n; ++i) {\n     scanf(\"%d\", &x[i]);\n  }\n\n#\tdefine SIZE sizeof(x)/sizeof(int)\n \n\tshow(\"before sort:\", x, SIZE);\n\tsort(x, sizeof(x)/sizeof(int));\n\tshow(\"after sort: \", x, SIZE);\n \n\treturn 0;\n}\n"
  },
  {
    "path": "Algorithms/Sorting/Strand_Sort/strand_sort.ts",
    "content": "function strandSort(arrin: number[]): number[] {\n\n  /* if the array has no elements, then it dosent need to be sorted */\n  if (arrin.length == 0) return\n\n  let arrout: number[] = []\n  /* \n  is the same as\n  let subarr: number[], arrout: number[] = [] \n  but to run the JS compiled code without undefined error, I did this\n  */\n\n  while (arrin.length != 0) {\n    let subarr: number[] = [] /* Start the new iteration with a new subarray */\n\n    subarr.push(arrin.shift()) /* Get the first element into subarray */\n\n    arrin.forEach((num) => {\n      if (num > subarr[0]) {\n        subarr.push(num) /* Add every element bigger than the first element to the subarray*/\n      }\n    })\n\n    /* Remove from input array elements that where added to the subarray*/\n    arrin = arrin.filter(num => subarr.indexOf(num) == -1)\n\n    /* Find out if we concat the subarray before or after the output array */\n    if (arrout.length == 0 || arrout[arrout.length - 1] > subarr[0]) {\n      arrout = subarr.concat(arrout)\n    } else {\n      arrout = arrout.concat(subarr)\n    }\n  }\n\n  return arrout /* Retun the output array */\n}\nconsole.log(strandSort([10, 5, 30, 40, 2, 4, 9]))\n\n/*\n Example input\n strandSort([10, 5, 30, 40, 2, 4, 9])\n*/\n\n\n/*\n Example output\n {2, 4, 5, 9, 10, 30, 40}\n */"
  },
  {
    "path": "Algorithms/Sorting/Tim_Sort/README.md",
    "content": "##Tim Sorting Algorithm\n\nTimSort algorithm is a sorting technique widely used in programming. Java and python use this algorithm in their built-in sort() methods. It is a combined hybrid of two other sorting techniques – Insertion-Sort and Merge-Sort\n\nWhile TimSort is a complex algorithm in itself, where it looks for an ideal minimum size called “minrun”, performs “galloping” in merge-sort to avoid iterations for pre-sorted elements, etc., this post deals with a simple and basic implementation.\n\nIt is, however, noteworthy that merge sort is most efficient when the size of the array is a power of 2. Take for instance an array of size 16, which is 2^4. Hence, in each recursion or iteration (depends on the implementation of merge-sort), the array splits into 2 equal subarrays. This happens until we are left with 16 single elements. These are then reconstructed to get the sorted array.\n\nAlso, note that insertion sort works best when the size of the array is less. Hence in TimSort, minrun is usually set between 32 and 64. In this implementation, since we are not finding minrun, we are taking 32 as minrun. And from the previous point, we understand that the algorithm is more efficient when (size_of_arr/32) is a power of 2.\n"
  },
  {
    "path": "Algorithms/Sorting/Tim_Sort/Tim_Sort.c",
    "content": "//C Program for Tim Sort\n#include<stdio.h>\n\nconst int run = 32;\n//Function to find minimum of two numbers\nint min (int a, int b)\n{\n  if (a < b)\n    return a;\n  else\n    return b;\n}\n//function implementing insertion sort \nvoid insertionSort (int a[], int low, int high)\n{\n  int i, j, temp;\n  for (i = low + 1; i <= high; i++)\n    {\n      temp = a[i];\n      j = i - 1;\n      while (a[j] > temp && j >= low)\n        a[j + 1] = a[j--];\n      a[j + 1] = temp;\n    }\n}\n//function implementing merge sort\nvoid merge (int a[], int left, int mid, int right)\n{\n  int len1 = mid - left + 1;\n  int len2 = right - mid;\n  int low[len1], high[len2];\n  int i, j, k;\n  for (i = 0; i < len1; i++)\n    low[i] = a[left + i];\n  for (i = 0; i < len2; i++)\n    high[i] = a[mid + 1 + i];\n\n  i = 0; j = 0;\n  k = left;\n\n  while (i < len1 && j < len2)\n    {\n      if (low[i] <= high[j])\n\t   a[k] = low[i++];\n      else\n\t   a[k] = high[j++];\n      k++;\n    }\n    while (i < len1)\n      a[k++] = low[i++];\n\n    while (j < len2)\n      a[k++] = high[j++];\n}\n\nvoid timSort (int a[], int n)\n{\n  int i, size, low, mid, high;\n  for (i = 0; i < n; i += run)\n    insertionSort (a, i, min ((i + 31), (n - 1)));\n  for (size = run; size < n; size = 2 * size)\n  {\n    for (low = 0; low < n; low += 2 * size)\n\t{\n\t  mid = low + size - 1;\n\t  high = min ((low + 2 * size - 1), (n - 1));\n      merge (a, low, mid, high);\n\t}\n  }\n}\n\nvoid main ()\n{\n  int a[50] , n, i;\n  //Get number of elements from user\n  printf(\"Enter number of elements to be sorted:\");\n  scanf(\"%d\",&n);\n  //Get elements from user into array\n  printf(\"Enter the elements:\");\n  for(i=0;i<n;i++)\n    scanf(\"%d\",&a[i]);\n  //Apply timsort to the array\n  timSort (a, n);\n  //Print the sorted array\n  printf (\"Printing sorted array elements \\n\");\n  for (i = 0; i < n; i++)\n    printf (\"%d  \", a[i]);\n  printf (\"\\n\");\n}\n"
  },
  {
    "path": "Algorithms/Sorting/Tim_Sort/Tim_Sort.java",
    "content": "class Timsort{ \n  \n    static int RUN = 32; \n  \n    public static void insertionSort(int[] arr, int left, int right)  \n    { \n        for (int i = left + 1; i <= right; i++)  \n        { \n            int temp = arr[i]; \n            int j = i - 1; \n            while (j >= left && arr[j] > temp) \n            { \n                arr[j + 1] = arr[j]; \n                j--; \n            } \n            arr[j + 1] = temp; \n        } \n    } \n  \n    public static void merge(int[] arr, int l,int m, int r) \n    { \n        int len1 = m - l + 1, len2 = r - m; \n        int[] left = new int[len1]; \n        int[] right = new int[len2]; \n        for (int x = 0; x < len1; x++)  \n        { \n            left[x] = arr[l + x]; \n        } \n        for (int x = 0; x < len2; x++)  \n        { \n            right[x] = arr[m + 1 + x]; \n        } \n  \n        int i = 0; \n        int j = 0; \n        int k = l; \n   \n        while (i < len1 && j < len2)  \n        { \n            if (left[i] <= right[j])  \n            { \n                arr[k] = left[i]; \n                i++; \n            } \n            else \n            { \n                arr[k] = right[j]; \n                j++; \n            } \n            k++; \n        } \n  \n        while (i < len1) \n        { \n            arr[k] = left[i]; \n            k++; \n            i++; \n        } \n  \n        while (j < len2)  \n        { \n            arr[k] = right[j]; \n            k++; \n            j++; \n        } \n    } \n  \n    public static void timSort(int[] arr, int n)  \n    { \n        for (int i = 0; i < n; i += RUN)  \n        { \n            insertionSort(arr, i, Math.min((i + 31), (n - 1))); \n        } \n          for (int size = RUN; size < n; size = 2 * size)  \n        { \n              \n            for (int left = 0; left < n; left += 2 * size)  \n            { \n                int mid = left + size - 1; \n                int right = Math.min((left + 2 * size - 1), (n - 1)); \n                merge(arr, left, mid, right); \n            } \n        } \n    } \n  \n    public static void printArray(int[] arr, int n) \n    { \n        for (int i = 0; i < n; i++) \n        { \n            System.out.print(arr[i] + \" \"); \n        } \n        System.out.print(\"\\n\"); \n    } \n  \n    public static void main(String[] args)  \n    { \n        int n;  \n        Scanner sc=new Scanner(System.in);  \n        System.out.print(\"Enter the number of elements : \");  \n        n=sc.nextInt();  \n        int[] arr = new int[n];  \n        System.out.println(\"Enter the elements of the array: \");  \n        for(int i=0; i<n; i++)  \n        {  \n        arr[i]=sc.nextInt();  \n        }  \n        System.out.print(\"Array is\\n\"); \n        printArray(arr, n); \n        timSort(arr, n); \n        System.out.print(\"After Sorting Array is\\n\"); \n        printArray(arr, n); \n    } \n} "
  },
  {
    "path": "Algorithms/Sorting/Tim_Sort/Tim_Sort.py",
    "content": "minrun = 32\n\ndef InsSort(arr,start,end):    \n    for i in range(start+1,end+1):\n        elem = arr[i]\n        j = i-1\n        while j>=start and elem<arr[j]:\n            arr[j+1] = arr[j]\n            j -= 1\n        arr[j+1] = elem\n    return arr\n\ndef merge(arr,start,mid,end):\n    if mid==end:\n        return arr\n    first = arr[start:mid+1]\n    last = arr[mid+1:end+1]\n    len1 = mid-start+1\n    len2 = end-mid\n    ind1 = 0\n    ind2 = 0\n    ind  = start\n     \n    while ind1<len1 and ind2<len2:\n        if first[ind1]<last[ind2]:\n            arr[ind] = first[ind1]\n            ind1 += 1\n        else:\n            arr[ind] = last[ind2]\n            ind2 += 1\n        ind += 1\n     \n    while ind1<len1:\n        arr[ind] = first[ind1]\n        ind1 += 1\n        ind += 1\n              \n    while ind2<len2:\n        arr[ind] = last[ind2]\n        ind2 += 1\n        ind += 1   \n              \n    return arr\n            \n\ndef TimSort(arr):\n    n = len(arr)\n    \n    for start in range(0,n,minrun):\n        end = min(start+minrun-1,n-1)\n        arr = InsSort(arr,start,end)\n        \n    curr_size = minrun\n    while curr_size<n:    \n        for start in range(0,n,curr_size*2):\n            mid = min(n-1,start+curr_size-1)\n            end = min(n-1,mid+curr_size)\n            arr = merge(arr,start,mid,end)\n        curr_size *= 2\n    return arr"
  },
  {
    "path": "Algorithms/Sorting/Topological_Sort/README.md",
    "content": "## Toplogical Sort\n\nTopological sorting for Directed Acyclic Graph (DAG) is a linear ordering of vertices such that for every directed edge u v, vertex u comes before v in the ordering. Topological Sorting for a graph is not possible if the graph is not a DAG.\n"
  },
  {
    "path": "Algorithms/Sorting/Topological_Sort/Topological_Sort.cpp",
    "content": "// A C++ program to print topological \n// sorting of a DAG \n#include <iostream> \n#include <list> \n#include <stack> \nusing namespace std; \n  \n// Class to represent a graph \nclass Graph { \n    // No. of vertices' \n    int V; \n  \n    // Pointer to an array containing adjacency listsList \n    list<int>* adj; \n  \n    // A function used by topologicalSort \n    void topologicalSortUtil(int v, bool visited[], \n                             stack<int>& Stack); \n  \npublic: \n    // Constructor \n    Graph(int V); \n  \n    // function to add an edge to graph \n    void addEdge(int v, int w); \n  \n    // prints a Topological Sort of \n    // the complete graph \n    void topologicalSort(); \n}; \n  \nGraph::Graph(int V) \n{ \n    this->V = V; \n    adj = new list<int>[V]; \n} \n  \nvoid Graph::addEdge(int v, int w) \n{ \n    // Add w to v’s list. \n    adj[v].push_back(w); \n} \n  \n// A recursive function used by topologicalSort \nvoid Graph::topologicalSortUtil(int v, bool visited[], \n                                stack<int>& Stack) \n{ \n    // Mark the current node as visited. \n    visited[v] = true; \n  \n    // Recur for all the vertices \n    // adjacent to this vertex \n    list<int>::iterator i; \n    for (i = adj[v].begin(); i != adj[v].end(); ++i) \n        if (!visited[*i]) \n            topologicalSortUtil(*i, visited, Stack); \n  \n    // Push current vertex to stack \n    // which stores result \n    Stack.push(v); \n} \n  \n// The function to do Topological Sort. \n// It uses recursive topologicalSortUtil() \nvoid Graph::topologicalSort() \n{ \n    stack<int> Stack; \n  \n    // Mark all the vertices as not visited \n    bool* visited = new bool[V]; \n    for (int i = 0; i < V; i++) \n        visited[i] = false; \n  \n    // Call the recursive helper function \n    // to store Topological \n    // Sort starting from all \n    // vertices one by one \n    for (int i = 0; i < V; i++) \n        if (visited[i] == false) \n            topologicalSortUtil(i, visited, Stack); \n  \n    // Print contents of stack \n    while (Stack.empty() == false) { \n        cout << Stack.top() << \" \"; \n        Stack.pop(); \n    } \n} \n  \n// Driver Code \nint main() \n{ \n    // Create a graph given in the above diagram \n    Graph g(6); \n    g.addEdge(5, 2); \n    g.addEdge(5, 0); \n    g.addEdge(4, 0); \n    g.addEdge(4, 1); \n    g.addEdge(2, 3); \n    g.addEdge(3, 1); \n  \n    cout << \"Following is a Topological Sort of the given \"\n            \"graph \\n\"; \n    \n    // Function Call \n    g.topologicalSort(); \n  \n    return 0; \n}\n"
  },
  {
    "path": "Algorithms/Sorting/Topological_Sort/Topological_sort.cs",
    "content": "//  Topological_sort algorithm.\nusing System; \nusing System.Collections.Generic; \n  \n// Class represents a directed graph \n// using adjacency list representation \nclass Graph { \n  \n    // for vertices \n    private int V; \n  \n    // Adjacency List as ArrayList \n    // of ArrayList's \n    private List<List<int> > adj; \n  \n    Graph(int v) \n    { \n        V = v; \n        adj = new List<List<int> >(v); \n        for (int i = 0; i < v; i++) \n            adj.Add(new List<int>()); \n    } \n  \n    // Function to add an edge into the graph \n    public void AddEdge(int v, int w) { adj[v].Add(w); } \n  \n    // A recursive function used by topologicalSort \n    void TopologicalSortUtil(int v, bool[] visited, \n                             Stack<int> stack) \n    { \n  \n        visited[v] = true; \n        foreach(var vertex in adj[v]) \n        { \n            if (!visited[vertex]) \n                TopologicalSortUtil(vertex, visited, stack); \n        } \n  \n        // Push current vertex to \n        // stack which stores result \n        stack.Push(v); \n    } \n  \n   \n    void TopologicalSort() \n    { \n        Stack<int> stack = new Stack<int>(); \n  \n        // Mark all the vertices as not visited \n        var visited = new bool[V]; \n   \n        for (int i = 0; i < V; i++) { \n            if (visited[i] == false) \n                TopologicalSortUtil(i, visited, stack); \n        } \n  \n        // Print contents of stack \n        foreach(var vertex in stack) \n        { \n            Console.Write(vertex + \" \"); \n        } \n    } \n  \n    public static void Main(string[] args) \n    { \n  \n        // Create a graph given \n        // in the above diagram \n        Graph g = new Graph(6); \n        g.AddEdge(5, 2); \n        g.AddEdge(5, 0); \n        g.AddEdge(4, 0); \n        g.AddEdge(4, 1); \n        g.AddEdge(2, 3); \n        g.AddEdge(3, 1); \n          \n          // Function Call \n        g.TopologicalSort(); \n    } \n} \n  \n  /* output is: 5 4 3 2 1 0\n   * time complexity : O(V+E)\n   * auxiliary space: O(V)\n   */"
  },
  {
    "path": "Algorithms/Sorting/Topological_Sort/Topological_sort.py",
    "content": "from collections import defaultdict \n  \n#Class to represent a graph \nclass Graph: \n    def __init__(self,vertices): \n        self.graph = defaultdict(list) #dictionary containing adjacency List \n        self.V = vertices #No. of vertices \n  \n    # function to add an edge to graph \n    def addEdge(self,u,v): \n        self.graph[u].append(v) \n  \n    # A recursive function used by topologicalSort \n    def topologicalSortUtil(self,v,visited,stack): \n  \n        # Mark the current node as visited. \n        visited[v] = True\n  \n        # Recur for all the vertices adjacent to this vertex \n        for i in self.graph[v]: \n            if visited[i] == False: \n                self.topologicalSortUtil(i,visited,stack) \n  \n        # Push current vertex to stack which stores result \n        stack.insert(0,v) \n  \n    # The function to do Topological Sort. It uses recursive  \n    # topologicalSortUtil() \n    def topologicalSort(self): \n        # Mark all the vertices as not visited \n        visited = [False]*self.V \n        stack =[] \n  \n        # Call the recursive helper function to store Topological \n        # Sort starting from all vertices one by one \n        for i in range(self.V): \n            if visited[i] == False: \n                self.topologicalSortUtil(i,visited,stack) \n  \n        # Print contents of stack \n        print stack \n  \ng= Graph(6) \ng.addEdge(5, 2); \ng.addEdge(5, 0); \ng.addEdge(4, 0); \ng.addEdge(4, 1); \ng.addEdge(2, 3); \ng.addEdge(3, 1); \n  \nprint \"Following is a Topological Sort of the given graph\"\ng.topologicalSort()\n"
  },
  {
    "path": "Algorithms/Sorting/Tree_Sort/README.md",
    "content": "## This folder is empty.\n"
  },
  {
    "path": "Algorithms/Sorting/Tree_Sort/Tree_Sort.c",
    "content": "// C++ program to implement Tree Sort \n#include<bits/stdc++.h> \n\nusing namespace std; \n\nstruct Node \n{ \n\tint key; \n\tstruct Node *left, *right; \n}; \n\n// A utility function to create a new BST Node \nstruct Node *newNode(int item) \n{ \n\tstruct Node *temp = new Node; \n\ttemp->key = item; \n\ttemp->left = temp->right = NULL; \n\treturn temp; \n} \n\n// Stores inoder traversal of the BST \n// in arr[] \nvoid storeSorted(Node *root, int arr[], int &i) \n{ \n\tif (root != NULL) \n\t{ \n\t\tstoreSorted(root->left, arr, i); \n\t\tarr[i++] = root->key; \n\t\tstoreSorted(root->right, arr, i); \n\t} \n} \n\n/* A utility function to insert a new \nNode with given key in BST */\nNode* insert(Node* node, int key) \n{ \n\t/* If the tree is empty, return a new Node */\n\tif (node == NULL) return newNode(key); \n\n\t/* Otherwise, recur down the tree */\n\tif (key < node->key) \n\t\tnode->left = insert(node->left, key); \n\telse if (key > node->key) \n\t\tnode->right = insert(node->right, key); \n\n\t/* return the (unchanged) Node pointer */\n\treturn node; \n} \n\n// This function sorts arr[0..n-1] using Tree Sort \nvoid treeSort(int arr[], int n) \n{ \n\tstruct Node *root = NULL; \n\n\t// Construct the BST \n\troot = insert(root, arr[0]); \n\tfor (int i=1; i<n; i++) \n\t\troot = insert(root, arr[i]); \n\n\t// Store inoder traversal of the BST \n\t// in arr[] \n\tint i = 0; \n\tstoreSorted(root, arr, i); \n} \n\n// Driver Program to test above functions \nint main() \n{ \n\t//create input array \n\tint arr[] = {5, 4, 7, 2, 11}; \n\tint n = sizeof(arr)/sizeof(arr[0]); \n\n\ttreeSort(arr, n); \n\n\t\tfor (int i=0; i<n; i++) \n\tcout << arr[i] << \" \"; \n\n\treturn 0; \n} \n"
  },
  {
    "path": "Algorithms/Sorting/Tree_Sort/tree sort.cpp",
    "content": "#include<iostream>\nusing namespace std;\nstruct tree{\n    int info;\n    tree *Left, *Right;\n};\ntree *root;\nclass TreeSort{\n    public:\n        int no_of_elements;\n        int elements[10];\n    public:\n        void getarray();\n        void sortit();\n        void insert1(int);\n        tree *insert2(tree *, tree *);\n        void display(tree *);\n};\nvoid TreeSort::getarray(){\n    cout<<\"How many elements? \";\n    cin>>no_of_elements;\n    cout<<\"Insert array of element to sort: \";\n    for(int i=0;i<no_of_elements;i++){\n        cin>>elements[i];\n    }\n}\nvoid TreeSort::sortit(){\n    for(int i = 0; i  < no_of_elements; i++){\n        insert1(elements[i]);\n    }\n}\ntree* TreeSort::insert2(tree *temp,tree *newnode){\n    if(temp==NULL){\n        temp=newnode;\n    }\n    else if(temp->info < newnode->info){\n        insert2(temp->Right,newnode);\n        if(temp->Right==NULL)\n            temp->Right=newnode;\n    }\n    else{\n        insert2(temp->Left,newnode);\n        if(temp->Left==NULL)\n            temp->Left=newnode;\n    }\n    return temp;\n}\nvoid TreeSort::insert1(int n){\n    tree *temp=root,*newnode;\n    newnode=new tree;\n    newnode->Left=NULL;\n    newnode->Right=NULL;\n    newnode->info=n;\n    root=insert2(temp,newnode);\n}\n/* Inorder traversal */\nvoid TreeSort::display(tree *t = root){\n    if(root==NULL){\n        cout<<\"Nothing to display\";\n    }else\n    if(t!=NULL){\n        display(t->Left);\n        cout<<t->info<<\" \";\n        display(t->Right);\n    }\n}\nint main(){\n    TreeSort TS;\n    TS.getarray();\n    TS.sortit();\n    TS.display();\n    return 0;\n}"
  },
  {
    "path": "Algorithms/Sorting/Tree_Sort/treesort.java",
    "content": "class Node{\n  int value;\n  Node left;\n  Node right;\n  Node(int value){\n    this.value = value;\n    left = null;\n    right = null;        \n  }\n}\n// Class for Binary Search Tree\nclass BST{\n  Node node;\n  BST(int value){\n    node = new Node(value);\n  }\n  public Node insert(Node node, int value){\n    if(node == null){\n      return new Node(value);\n    }\n    // Move to left for value less than parent node\n    if(value < node.value){\n      node.left = insert(node.left, value);\n    }\n    // Move to right for value greater than parent node\n    else if(value > node.value){\n      node.right = insert(node.right, value);\n    }\n    return node;\n  }\n    \n  // For traversing in order\n  public void inOrder(Node node){\n    if(node != null){\n      // recursively traverse left subtree\n      inOrder(node.left);\n      System.out.print(node.value + \" \");\n      // recursively traverse right subtree\n      inOrder(node.right);\n    }\n  }\n}\n\npublic class TreeSort {\n  public static void main(String[] args) {\n    int[] arr = {65, 68, 82, 42, 10, 75, 25, 47, 32, 72};\n    System.out.println(\"Original array- \" + Arrays.toString(arr));\n    // start creating tree with element at index 0 as root node\n    BST bst = new BST(arr[0]);\n    for(int num : arr){\n      bst.insert(bst.node, num);\n    }\n    System.out.print(\"Sorted Array after Tree sort- \");\n    bst.inOrder(bst.node);\n    System.out.println();\n  }\n}\n"
  },
  {
    "path": "Algorithms/Sorting/Wave_Sort/Wave_Sort.py",
    "content": "def sortInWave(arr_demo, n):\n    arr_demo.sort()\n    for i in range(0,n-1,2):\n        arr_demo[i], arr_demo[i+1] = arr_demo[i+1], arr_demo[i]\n\n    return arr_demo\n\narr = []\nprint(\"Please Enter no of elements in array\")\nn = int(input())\nprint(\"Please Enter elements of the array\")\nfor i in range(n):\n    sample = int(input())\n    arr.append(sample)\n\nsortInWave(arr, len(arr)) \n"
  },
  {
    "path": "Algorithms/Sorting/Wave_Sort/wave_sort.c",
    "content": "//wave sort in c\r\n#include<stdio.h>\r\n#include<stdlib.h>\r\n\r\n//C function to SWAP two reference pointers/values\r\nvoid swap(int *x, int *y)\r\n{\r\n\tint temp = *x;\r\n\t*x = *y;\r\n\t*y = temp;\r\n}\r\n\r\n//C function to implement WAVE SORT\r\nvoid sortInWave(int arr[], int n)\r\n{\r\n\r\n\t//elements are arranged in the order\r\n\t//sequence a1 >= a2 <= a3 >= a4 <= a5 >= a6 and so on.\r\n\tfor (int i = 0; i < n; i += 2)\r\n\t{\r\n\t\tif (i > 0 && arr[i - 1] > arr[i] )\r\n\t\t\tswap(&arr[i], &arr[i - 1]);\r\n\r\n\t\tif (i < n - 1 && arr[i] < arr[i + 1] )\r\n\t\t\tswap(&arr[i], &arr[i + 1]);\r\n\t}\r\n}\r\n\r\nint main()\r\n{\r\n\tint n;\r\n\tscanf(\"%d\", &n);\r\n\r\n\tint ar[n];\r\n\r\n\tfor (int i = 0; i < n; i++)\r\n\t\tscanf(\"%d\", &ar[i]);\r\n\r\n\tsortInWave(ar, n);\r\n\t//Time complexity of this algorithm :\r\n\t// O(n) time by doing a \"single traversal\".\r\n\r\n\tfor (int i = 0; i < n; i++)\r\n\t\tprintf(\"%d \", ar[i]);\r\n\tprintf(\"\\n\");\r\n\r\n\treturn 0;\r\n}\r\n"
  },
  {
    "path": "Algorithms/Sorting/Wave_Sort/wave_sort.cpp",
    "content": "using namespace std;\n#include <iostream>\n\n//UTILITY FUNCS\n\nvoid printArray(int arr[], int size)\n{\n\n    cout << \"The array = [ \";\n    for (int i = 0; i < size; i++)\n    {\n        cout << arr[i] << \" \";\n    }\n    cout << \"]\" << endl;\n    return;\n}\n\n//UTILITY FUNCS==============\n\nvoid swap(int *x, int *y)\n{\n    int temp = *x;\n    *x = *y;\n    *y = temp;\n    return;\n}\n\n// SORT==========================\n\nvoid waveSort(int arr[], int size)\n{\n    for (int i = 0; i < size; i += 2)\n    {\n\n        if (i >= 1)\n        {\n            if (arr[i - 1] >= arr[i])\n            {\n                swap(&arr[i - 1], &arr[i]);\n            }\n        }\n\n        if (i <= size - 1)\n        {\n            if (arr[i] < arr[i + 1])\n            {\n                swap(&arr[i], &arr[i + 1]);\n            }\n        }\n    }\n    return;\n}\n\n//MAIN FUNCTION=====================\n\nint main()\n{\n\n    int size;\n    cout << \"Enter size of array: \";\n    cin >> size;\n    int arr[size];\n    cout << \"Enter \" << size << \" elements of array:\" << endl;\n    for (int i = 0; i < size; i++)\n    {\n        cin >> arr[i];\n    }\n\n    cout << \"Before sort: \";\n    printArray(arr, size);\n\n    waveSort(arr, size);\n\n    cout << \"After sort: \";\n    printArray(arr, size);\n\n    return 0;\n}"
  },
  {
    "path": "Algorithms/Stack-Algorithm/Next_Greater_Element.cpp",
    "content": "// Aviral Gupta\n#include<bits/stdc++.h>\nusing namespace std;\nconst double PI = 3.14159265358979323846;\n#define LM 1e18\n#define ll  long long int\n#define ld long double\n#define ms(dp,val) memset(dp,val,sizeof(dp))\n#define all(t) t.begin(), t.end()\n#define inrange(i, a, b) ((i >= min(a, b)) && (i <= max(a, b)))\n#define pb push_back\n#define mp make_pair\n#define fi first\n#define se second \n#define f(i,n) for(int i=0;i<n;i++)\n#define fast ios_base::sync_with_stdio(false);cin.tie(NULL);\nconst ll mod=998244353;\ninline ll mul(ll a, ll b){ return (a * 1ll * b) % mod; }\ninline ll sub(ll a, ll b){ ll c = a - b; if(c < 0) c += mod; return c; }\ninline ll add(ll a, ll b){ ll c = a + b; if(c >= mod) c -= mod; return c; }\n\ntypedef pair<int, int> pii;\ntypedef pair<ll, ll> pll;\ntypedef vector<int> vi;\ntypedef vector< pll > vpi;\ntypedef vector<ll> vl;\ntypedef vector<bool> vb;\ntypedef vector<string> vs;\n\nvoid next_greater(vector<int> &A)\n{\n    stack<int> s; int n=A.size();\n    int ng[n];\n    s.push(0);\n    for(int i=1;i<n;i++)\n    {\n        while(!s.empty()&&A[i]>A[s.top()])\n        {\n            ng[s.top()]=i;  s.pop();\n        }\n        s.push(i);\n    }\n    while(!s.empty())\n    {\n        ng[s.top()]=-1;\n        s.pop();\n    }\n\n    for(int i=0;i<n;i++) if(ng[i]!=-1) cout<<A[i]<<\"-->\"<<A[ng[i]]<<endl;\n}\n\nint main()\n{\n    int n; cin>>n;\n    vector<int> a(n);\n    for (int i = 0; i < n; i++)\n    {\n        cin>>a[i];  \n    }\n\n    next_greater(a);\n\n} \n"
  },
  {
    "path": "Algorithms/Stack-Algorithm/RemoveKDigitsToGetSmallestPossibleInteger.java",
    "content": "import java.util.Scanner;\nimport java.util.Stack;\npublic class RemoveKDigitsToGetSmallestPossibleInteger{\n  public static void main(String[]args){\n    //create scanner\n    Scanner kb=new Scanner(System.in);\n    \n    //prompt user\n    System.out.println(\"Provide an integer to make smallest possible with k removals\");\n    \n    //read in input integer\n    String input=kb.next();\n    \n    System.out.println(\"Please provide an integer k representing how many digits to remove from your integer\");\n    int k=kb.nextInt();\n    \n    System.out.println(removeKdigits(input, k));\n  }\n  public static String removeKdigits(String num, int k) {\n        //make a stack of characters\n        Stack<Character>s=new Stack<Character>();\n        //set the number of elements removed so far to be 0\n        int count=0;\n        //create our string to return\n        String str=\"\";\n        //loop over the length of our string\n        for(int i=0; i<num.length(); i++){\n            /*first condition ensures we don't go out of bounds\n              \n              also, if the stack is empty or the next element is > than what is already on \n              the stack we push the stack and move forward an element.  \n              \n              We do this because we want to ensure we get the largest element\n              we can to remove.  \n              \n              For example, if we had 089, 1 as our input, we would want to return 8 \n              rather than 9.  So, we have to keep adding the next element as long as it \n              is larger than the current one to our stack so we remove it from our string\n              before the current element.  This is of course always true, since\n              if we end up with a fixed length num-k, if we will always wind up with the\n              same length, so if we remove anything before this largest element, we will\n              move the largest element left 1 position in the string, so we would have simply\n              been better off ommitting this largest element instead since the preceding element\n              was smaller.  (Example: 089, we are better off removing 9 as opposed to 8, because\n              otherwise, 9 gets shifted into 8's position, but 9 is larger than 8, so we are better\n              off simply removing the 9 to begin with).\n              \n              Also, note that we go left to right over our string since the digits on the left of an\n              integer hold greater value than those on the right, so we favor choosing those to remove\n              first if possible\n            */\n            while(i!=num.length() && (s.isEmpty() || s.peek()<num.charAt(i))){\n                s.push(num.charAt(i));\n                i++;\n            }\n            \n            /*conversely, as long as we keep seeing smaller elements than our current one, we\n            keep popping the stack since as we will prefer the smaller digits to 'bubble' towards\n            the left of our integer, removing the larger digits in its way.  \n            Example: 980, 1 => after pushing 9, we want to move something smaller than 9 to the left,\n            since it would make our integer smaller, so we do so by popping 9, which in effect would give\n            us 80 for this example.  \n            */\n            while(count!=k && i!=num.length()&&!s.isEmpty() && s.peek()>num.charAt(i)){\n                s.pop();\n                count++;\n            }\n            /*after the previous loop finishes, we can push the next character onto our stack, \n            since if we aren't out of bounds, we know our next element must no longer be smaller\n            than the current one.  \n            */\n            if (i!= num.length())\n                s.push(num.charAt(i));\n        }\n        \n        /*if we didn't remove k elements, then the final k of them must exist at the end. and thus,\n        must exist at the top of our stack, so we can pop all the remaining elements until we get to k\n        off the stack.  \n        */\n        while(count<k){\n            s.pop();\n            count++;\n        }\n        /*we remove elements from our stack and add them in reverse order to our string \n        (since using a stack inverts the order of the characters in our string). \n        */\n        while(!s.isEmpty()){\n            str=s.peek()+str;\n            s.pop();\n        }\n        //count the # of leading 0s\n        int i=0;\n        while(i!=str.length() && str.charAt(i)=='0')\n            i++;\n        //remove all leading 0s\n        str= str.substring(i);\n        \n        //if our string is empty, return 0\n        if(str.length()==0)\n            return \"0\";\n        \n        //otherwise, just return the string\n        return str;\n        \n        \n        \n/*this takes O(n) time, since we do an O(1) push operation to each element of n elements maximum 1 time and\ndo an O(1) pop operation on each of n elements 1 maximum 1 time.  We also count maximum n leading 0s \n(if every digit is a leading 0), so we count each of maximum n 0s maximum 1 time each.  \nThus, since each of the finite list of operations above was O(n) time, our algorithm is worst case O(n) time. \n\nAnd it is worst case O(n) space as well since we create a stack which at most holds n characters, where \nn=#of characters in our string, and our output string similarly contains at most n characters, for a total\nof O(n) space for each of the 2 data structures, hence worst case O(n) space.  \n*/\n  }\n }\n"
  },
  {
    "path": "Algorithms/Stack-Algorithm/Simplify-Path/QUESTION.md",
    "content": "### Simplify Path\n\nGiven an absolute path for a file (Unix-style), simplify it. Or in other words, convert it to the canonical path.\n\nIn a UNIX-style file system, a period . refers to the current directory. Furthermore, a double period .. moves the directory up a level.\n\nNote that the returned canonical path must always begin with a slash /, and there must be only a single slash / between two directory names. The last directory name (if it exists) must not end with a trailing /. Also, the canonical path must be the shortest string representing the absolute path.\n\n \n\nExample 1:\n\nInput: \"/home/\"\nOutput: \"/home\"\nExplanation: Note that there is no trailing slash after the last directory name.\nExample 2:\n\nInput: \"/../\"\nOutput: \"/\"\nExplanation: Going one level up from the root directory is a no-op, as the root level is the highest level you can go.\nExample 3:\n\nInput: \"/home//foo/\"\nOutput: \"/home/foo\"\nExplanation: In the canonical path, multiple consecutive slashes are replaced by a single one.\nExample 4:\n\nInput: \"/a/./b/../../c/\"\nOutput: \"/c\"\nExample 5:\n\nInput: \"/a/../../b/../c//.//\"\nOutput: \"/c\"\nExample 6:\n\nInput: \"/a//b////c/d//././/..\"\nOutput: \"/a/b/c\""
  },
  {
    "path": "Algorithms/Stack-Algorithm/Simplify-Path/Simplify_Path.cpp",
    "content": "#include <iostream>\n#include <bits/stdc++.h>\n\nusing namespace std;\nstring simplifyPath(string path)\n{\n    stack<string> stk;\n    string tmp;\n    stringstream ss(path);\n    while (getline(ss, tmp, '/'))\n    {\n        if (tmp == \"\" || tmp == \".\")\n            continue;\n        if (tmp == \"..\" && !stk.empty())\n            stk.pop();\n        else if (tmp != \"..\")\n            stk.push(tmp);\n    }\n    string res;\n    while (!stk.empty())\n    {\n        res = \"/\" + stk.top() + res;\n        stk.pop();\n    }\n    return res == \"\" ? \"/\" : res;\n}\n\nint main()\n{\n    string path;\n    cout << \"Enter a valid path for file: \";\n    cin >> path;\n    string res = simplifyPath(path);\n    cout << res;\n    return 0;\n}"
  },
  {
    "path": "Algorithms/Stack-Algorithm/balanced_brackets_stack.cpp",
    "content": "#include<bits/stdc++.h>\nusing namespace std;\n\nbool isBalanced(string str)\n{\n    stack<char> s;\n    for(int i = 0; i < str.length(); i++)\n    {\n        if(str[i] == '(' ) //push if opeening bracket is encountered\n            s.push(str[i]);\n        else\n        {\n            if(s.empty()) //if stack is empty return 0\n                return 0;\n            s.pop();// pop the last element in stack\n        }\n    }\n    if(!s.empty()) // if still stack has some brackets remaining return 0\n        return 0;\n    return 1;\n}\n\n\nint main()\n{\n    string bracSeq = \"(()\";\n    cout << isBalanced(bracSeq);\n    return 0;\n}\n"
  },
  {
    "path": "Algorithms/Stack-Algorithm/immediate_smaller_element.cpp",
    "content": "/*Given an integer array of size N. For each element in the array, check whether the right adjacent element (on the next immediate position) of the array is smaller. If next element is smaller, print that element. If not, then print -1.\nInput:\nThe first line of input contains an integer T denoting the number of test cases. T testcases follow. Each testcase contains 2 lines of input:\nThe first line contains an integer N, where N is the size of array.\nThe second line contains N integers(elements of the array) sperated with spaces.\nOutput:\nFor each test case, print the next immediate smaller elements for each element in the array.\nConstraints:\n1 ≤ T ≤ 200\n1 ≤ N ≤ 107\n1 ≤ arr[i] ≤ 1000\nExample:\nInput\n2\n5\n4 2 1 5 3\n6\n5 6 2 3 1 7\nOutput\n2 1 -1 3 -1\n-1 2 -1 1 -1 -1\n*/\n#include<bits/stdc++.h>\nusing namespace std;\nint main(){\n    int t;\n    cin>>t;\n    while(t--){\n        int n;\n        cin>>n;\n        int a[n];\n        for(int i=0;i<n;i++)\n            cin>>a[i];\n        for(int i=0;i<n-1;i++){\n            if(a[i]>a[i+1])\n                cout<<a[i+1]<<\" \";\n            else\n                cout<<\"-1\"<<\" \";\n        }\n        cout<<\"-1\"<<endl;\n    }\n    return 0;\n}\n"
  },
  {
    "path": "Algorithms/Stack-Algorithm/longest_valid_substring.cpp",
    "content": "/*Given a string S consisting only of opening and closing parenthesis 'ie '('  and ')', find out the length of the longest valid substring.\nNOTE: Length of smallest the valid substring ( ) is 2.\nInput\nThe first line of input contains an integer T denoting the number of test cases. Then T test cases follow.\nThe first line of each test case contains a string S consisting only of ( and ).\nOutput\nPrint out the length of the longest valid substring.\nConstraints\n1 <= T <= 100\n0 <   S  <= 110\nExamples\nInput\n4\n(()(\n()()((\n((()()())))\n()(())(\nOutput\n2\n4\n10\n6\n*/\n#include<bits/stdc++.h>\nusing namespace std;\nint main(){\n    int t;\n    cin>>t;\n    while(t--){\n        string str;\n        cin>>str;\n        stack<int> s;\n        s.push(-1);\n        int result=0;\n        for(int i=0;i<str.length();i++){\n            if(str[i]=='(')\n                s.push(i);\n            else{\n                s.pop();\n                if(!s.empty())\n                    result=max(result,(i-s.top()));\n                else\n                    s.push(i);\n            }\n        }\n        cout<<result<<endl;\n    }\n    return 0;\n}\n"
  },
  {
    "path": "Algorithms/String/Anagram/AnagramChecker.c",
    "content": "int check_anagram(char[] , char[]);\nint main()\n{\n  char a[100] , b[100];\n  printf(\"Enter 2 strings\\n\");\n  gets(a);\n  gets(b);\n  if(check_anagram(a,b))\n  {\n    printf(\"Strings Are Anagram\");\n  }\n  else\n  {\n    printf(\"Strings Are Not Anagram\");\n  }\n  return 0;\n  }\n\nint check_anagram(char a[] , char b[])\n{\n  int first[26]={0} , second[26]={0} , c=0;\n  while(a[c] != '\\0')\n  {\n    first[a[c]-'a']++;\n    c++;\n  }\n  c=0;\n  while(b[c] != '\\0')\n  {\n    second[b[c]-'a']++;\n    c++;\n  }\n  for(c=0;c<26;c++)\n  {\n    if(first[c] != second[c])\n    {\n      return 0;\n    }\n    return 1;\n  }\n"
  },
  {
    "path": "Algorithms/String/Anagram/anagram c#.cs",
    "content": "\nusing System;\nclass Anagrams {\n    \n    static bool isAnagram(string a, string b){\n    \n        if (a.Length != b.Length) return false;\n        \n        a = a.ToLower();\n        b = b.ToLower();\n        \n        char[] firstWordArr = a.ToCharArray();\n        foreach(char c in b){\n            for(int i = 0; i < firstWordArr.Length; i++){\n                if (c == firstWordArr[i]){\n                    firstWordArr[i] = ' ';\n                    break;\n                }\n            }\n        }\n        foreach(char c in firstWordArr){\n            if (c != ' ') return false;\n        }\n        \n        return true;\n    }\n        \n    static void Main()\n    {\n        string firstWord = Console.ReadLine();\n        string secondWord = Console.ReadLine();\n            \n        bool answer = isAnagram(firstWord, secondWord);\n        Console.WriteLine( (answer) ? \"Anagrams\" : \"Not Anagrams\" );\n    }\n\n}\n"
  },
  {
    "path": "Algorithms/String/Anagram/anagram.c",
    "content": "#include <stdio.h>\n#include <ctype.h>\nint check_anagram(char [], char []);\n\nint main()\n{\n  char a[1000], b[1000];\n\n  printf(\"Enter two strings\\n\");\n  gets(a);\n  gets(b);\n\n  if (check_anagram(a, b))\n   {\n    printf(\"The strings are anagrams.\\n\");\n    getch();\n   }\n  else\n    {\n    printf(\"The strings aren't anagrams.\\n\");\n    getch();\n    }\n\n  return 0;\n}\n\nint check_anagram(char a[], char b[])\n{\n  int first[26] = {0}, second[26] = {0}, c=0;\n\n  // Calculating frequency of characters of the first string\n\n  while (a[c] != '\\0')\n  {\n\n    if(isupper(a[c]))\n    {\n      a[c]=tolower(a[c]);\n    }\n\n    first[a[c]-'a']++;\n\n    c++;\n  }\n\n  c = 0;\n\n  while (b[c] != '\\0')\n  {\n    if(isupper(b[c]))\n    {\n      b[c]=tolower(b[c]);\n    }\n\n    second[b[c]-'a']++;\n\n    c++;\n  }\n\n  // Comparing the frequency of characters\n\n  for (c = 0; c < 26; c++)\n  {\n\n    if (first[c] != second[c])\n     {\n      return 0;\n     }\n  }\n  return 1;\n}"
  },
  {
    "path": "Algorithms/String/Anagram/anagram.java",
    "content": "import java.util.Arrays;\n\npublic class AnagramProgram {\n    static void isAnagram(String s1, String s2) {\n\n        // Removing all white spaces from s1 and s2\n        String copyOfs1 = s1.replaceAll(\"s\", \"\");\n        String copyOfs2 = s2.replaceAll(\"s\", \"\");\n        // Initially setting status as true\n\n        boolean status = true;\n        if (copyOfs1.length() != copyOfs2.length()) {\n            // Setting status as false if copyOfs1 and copyOfs2 doesn't have same length\n            status = false;\n        } else {\n            // Changing the case of characters of both copyOfs1 and copyOfs2 and converting them to char array\n            char[] s1Array = copyOfs1.toLowerCase().toCharArray();\n            char[] s2Array = copyOfs2.toLowerCase().toCharArray();\n\n            // Sorting both s1Array and s2Array\n            Arrays.sort(s1Array);\n            Arrays.sort(s2Array);\n\n            // Checking whether s1Array and s2Array are equal\n            status = Arrays.equals(s1Array, s2Array);\n        }\n\n        // Output\n        if (status) {\n            System.out.println(s1 + \" and \" + s2 + \" are anagrams\");\n        } else {\n            System.out.println(s1 + \" and \" + s2 + \" are not anagrams\");\n        }\n    }\n\n    public static void main(String[] args) {\n        isAnagram(\"Mother In Law\", \"Hitler Woman\");\n    }\n}"
  },
  {
    "path": "Algorithms/String/Anagram/anagram.py",
    "content": "#This is a function to check anagrams using sorted() which is an inbuilt function in python\r\ndef check(s1, s2): \r\n    if(sorted(s1)== sorted(s2)): \r\n        print(\"The strings are anagrams.\")  \r\n    else: \r\n        print(\"The strings are not anagrams.\")          \r\n             \r\ns1 =\"listen\"\r\ns2 =\"silent\" \r\ncheck(s1, s2)\r\n"
  },
  {
    "path": "Algorithms/String/Anagram/anagram.swift",
    "content": "import Foundation\n\nfunc isAnagram(_ firstWord: String, _ secondWord: String) -> Bool {\n    // check length of both words, if length is not the same, they cannot be anagrams\n    let firstWordCopy = NSString(string: firstWord).replacingOccurrences(of: \" \", with: \"\").lowercased()\n    let secondWordCopy = NSString(string: secondWord).replacingOccurrences(of: \" \", with: \"\").lowercased()\n    if firstWordCopy.count != secondWordCopy.count {\n        return false;\n    }\n    return firstWordCopy.sorted().elementsEqual(secondWordCopy.sorted())\n\n}\n\nprint(\"Enter the first word: \")\nlet firstWord = readLine(strippingNewline: true) ?? \"\"\n\nprint(\"Enter the second word: \")\nlet secondWord = readLine(strippingNewline: true) ?? \"\"\n\nprint(isAnagram(firstWord, secondWord))\n"
  },
  {
    "path": "Algorithms/String/Anagram/anagrams.sh",
    "content": "# Follwing function does:\n# Removal of all alphanumerics, Convert all lowercase to uppercase, Sort the string\npreprocessing() {\n   fold -w1 <<< \"${1//[^[:alnum:]]/}\" | tr '[:upper:]' '[:lower:]' | sort | tr -d '\\n'\n}\n\n# function to check if given 2 arguments are anagrams\nisAnagram() {\n   a=$(preprocessing \"$1\")\n   b=$(preprocessing \"$2\")\n   [[ $a = $b ]] && echo \"Strings $1 and $2 are Anagrams to each other\" || echo \"String $1 and $2 are not Anagrams\";\n}\n\necho \"Enter two Strings: \"\nread a\nread b\nisAnagram $a $b\n"
  },
  {
    "path": "Algorithms/String/Isomorphic/Isomorphic-String.java",
    "content": "import java.util.*;\n \nclass Main\n{\n    // Find if strings 'X' and 'Y' are Isomorphic or not\n    public static boolean isIsomorphic(String X, String Y)\n    {\n        // base case\n        if (X == null || Y == null) {\n            return false;\n        }\n \n        // if 'X' and 'Y' have different lengths, they cannot be isomorphic\n        if (X.length() != Y.length()) {\n            return false;\n        }\n \n        // use a map to store a mapping from characters of string 'X' to string 'Y'\n        Map<Character, Character> map = new HashMap<>();\n \n        // use set to store a pool of already mapped characters\n        Set<Character> set = new HashSet<>();\n \n        for (int i = 0; i < X.length(); i++)\n        {\n            char x = X.charAt(i), y = Y.charAt(i);\n \n            // if `x` is seen before\n            if (map.containsKey(x))\n            {\n                // return false if the first occurrence of `x` is mapped to a\n                // different character\n                if (map.get(x) != y) {\n                    return false;\n                }\n            }\n \n            // if `x` is seen for the first time (i.e., it isn't mapped yet)\n            else {\n                // return false if `y` is already mapped to some other char in 'X'\n                if (set.contains(y)) {\n                    return false;\n                }\n \n                // map `y` to `x` and mark it as mapped\n                map.put(x, y);\n                set.add(y);\n            }\n        }\n \n        return true;\n    }\n \n    public static void main(String[] args)\n    {\n        Scanner sc= new Scanner(System.in); \n        System.out.println(\"Enter string x\");\n        String X = sc.nextLine(); \n        sc.nextLine();\n        System.out.println(\"Enter string y\");\n        String Y = sc.nextLine(); \n \n        if (isIsomorphic(X, Y)) {\n            System.out.print(X + \" and \" + Y + \" are Isomorphic\");\n        }\n        else {\n            System.out.print(X + \" and \" + Y + \" are not Isomorphic\");\n        }\n    }\n}\n\n\n\n\n\n"
  },
  {
    "path": "Algorithms/String/Isomorphic/isomorphic.cpp",
    "content": "#include <iostream>\n#include <string>\n#include <unordered_map>\n#include <unordered_set>\nusing namespace std;\n \n// Find if strings 'X' and 'Y' are Isomorphic or not\nbool isIsomorphic(string X, string Y)\n{\n    // if 'X' and 'Y' have different lengths, they cannot be isomorphic\n    if (X.length() != Y.length()) {\n        return false;\n    }\n \n    // use a map to store a mapping from characters of string 'X' to string 'Y'\n    unordered_map<char, char> map;\n \n    // use set to store a pool of already mapped characters\n    unordered_set<char> set;\n \n    for (int i = 0; i < X.length(); i++)\n    {\n        char x = X[i], y = Y[i];\n \n        // if `x` is seen before\n        if (map.find(x) != map.end())\n        {\n            // return false if the first occurrence of `x` is mapped to a\n            // different character\n            if (map[x] != y) {\n                return false;\n            }\n        }\n \n        // if `x` is seen for the first time (i.e., it isn't mapped yet)\n        else {\n            // return false if `y` is already mapped to some other char in 'X'\n            if (set.find(y) != set.end()) {\n                return false;\n            }\n \n            // map `y` to `x` and mark it as mapped\n            map[x] = y;\n            set.insert(y);\n        }\n    }\n \n    return true;\n}\n \nint main()\n{\n    cout<<\"Enter String X:\";\n    string X;\n    cin>>X;\n    cout<<\"Enter String Y:\";\n    string Y;\n    cin>>Y;\n \n    if (isIsomorphic(X, Y)) {\n        cout << X << \" and \" << Y << \" are Isomorphic\";\n    }\n    else {\n        cout << X << \" and \" << Y << \" are not Isomorphic\";\n    }\n \n    return 0;\n}\n\n\n\n\n"
  },
  {
    "path": "Algorithms/String/KMP/KMP_Algorithm.php",
    "content": "<?php \r\n\r\nfunction KMPSearch($pat, $txt) \r\n{ \r\n\t$M = strlen($pat); \r\n\t$N = strlen($txt); \r\n\r\n\t$lps=array_fill(0,$M,0); \r\n\r\n\tcomputeLPSArray($pat, $M, $lps); \r\n\r\n\t$i = 0; // index for txt[] \r\n\t$j = 0; // index for pat[] \r\n\twhile ($i < $N) { \r\n\t\tif ($pat[$j] == $txt[$i]) { \r\n\t\t\t$j++; \r\n\t\t\t$i++; \r\n\t\t} \r\n\r\n\t\tif ($j == $M) { \r\n\t\t\tprintf(\"Pattern Found at index \".($i - $j).\"\\n\"); \r\n\t\t\t$j = $lps[$j - 1]; \r\n\t\t} \r\n\r\n\t\telse if ($i < $N && $pat[$j] != $txt[$i]) { \r\n\t\t\tif ($j != 0) \r\n\t\t\t\t$j = $lps[$j - 1]; \r\n\t\t\telse\r\n\t\t\t\t$i = $i + 1; \r\n\t\t} \r\n\t} \r\n} \r\n\r\nfunction computeLPSArray($pat, $M, &$lps) \r\n{ \r\n\t$len = 0; \r\n\r\n\t$lps[0] = 0; // lps[0] is always 0 \r\n\r\n\t$i = 1; \r\n\twhile ($i < $M) { \r\n\t\tif ($pat[$i] == $pat[$len]) { \r\n\t\t\t$len++; \r\n\t\t\t$lps[$i] = $len; \r\n\t\t\t$i++; \r\n\t\t} \r\n\t\telse // (pat[i] != pat[len]) \r\n\t\t{ \r\n\t\t\tif ($len != 0) { \r\n\t\t\t\t$len = $lps[$len - 1]; \r\n\r\n\t\t\t} \r\n\t\t\telse // if (len == 0) \r\n\t\t\t{ \r\n\t\t\t\t$lps[$i] = 0; \r\n\t\t\t\t$i++; \r\n\t\t\t} \r\n\t\t} \r\n\t} \r\n} \r\n\r\n\t$txt = readline(\"Enter text : \"); \r\n\t$pat = readline(\"Enter pattern : \"); \r\n\tKMPSearch($pat, $txt); \r\n\t\r\n?> \r\n"
  },
  {
    "path": "Algorithms/String/KMP/kmp.cpp",
    "content": "// C++ program for implementation of KMP pattern searching\n// algorithm\n#include <bits/stdc++.h>\n\nvoid computeLPSArray(string pat, int M, string lps);\n\n// Prints occurrences of txt[] in pat[]\nvoid KMPSearch(string pat, string txt)\n{\n\tint M = pat.size();\n\tint N = txt.size();\n\n\t// create lps[] that will hold the longest prefix suffix\n\t// values for pattern\n\tint lps[M];\n\n\t// Preprocess the pattern (calculate lps[] array)\n\tcomputeLPSArray(pat, M, lps);\n\n\tint i = 0; // index for txt[]\n\tint j = 0; // index for pat[]\n\twhile (i < N) {\n\t\tif (pat[j] == txt[i]) {\n\t\t\tj++;\n\t\t\ti++;\n\t\t}\n\n\t\tif (j == M) {\n\t\t\tprintf(\"Found pattern at index %d \", i - j);\n\t\t\tj = lps[j - 1];\n\t\t}\n\n\t\t// mismatch after j matches\n\t\telse if (i < N && pat[j] != txt[i]) {\n\t\t\t// Do not match lps[0..lps[j-1]] characters,\n\t\t\t// they will match anyway\n\t\t\tif (j != 0)\n\t\t\t\tj = lps[j - 1];\n\t\t\telse\n\t\t\t\ti = i + 1;\n\t\t}\n\t}\n}\n\n// Fills lps[] for given patttern pat[0..M-1]\nvoid computeLPSArray(string pat, int M, string lps)\n{\n\t// length of the previous longest prefix suffix\n\tint len = 0;\n\n\tlps[0] = 0; // lps[0] is always 0\n\n\t// the loop calculates lps[i] for i = 1 to M-1\n\tint i = 1;\n\twhile (i < M) {\n\t\tif (pat[i] == pat[len]) {\n\t\t\tlen++;\n\t\t\tlps[i] = len;\n\t\t\ti++;\n\t\t}\n\t\telse // (pat[i] != pat[len])\n\t\t{\n\t\t\t// This is tricky. Consider the example.\n\t\t\t// AAACAAAA and i = 7. The idea is similar\n\t\t\t// to search step.\n\t\t\tif (len != 0) {\n\t\t\t\tlen = lps[len - 1];\n\n\t\t\t\t// Also, note that we do not increment\n\t\t\t\t// i here\n\t\t\t}\n\t\t\telse // if (len == 0)\n\t\t\t{\n\t\t\t\tlps[i] = 0;\n\t\t\t\ti++;\n\t\t\t}\n\t\t}\n\t}\n}\n\n// Driver program to test above function\nint main()\n{\n\tstring txt,pat;\n\tcin>>txt>>pat;\n\tKMPSearch(pat, txt);\n\treturn 0;\n}\n"
  },
  {
    "path": "Algorithms/String/KMP/kmp.js",
    "content": "'use strict'\n\ntest();\n\n// Fills lps[] for given patttern pattern[0..M-1]\nfunction buildLPSArray(pattern, M) {\n  let lps = [0]; // First element is always 0\n  let prefixIndex = 0;\n  let suffixIndex = 1;\n\n  while(suffixIndex < M) {\n    if(pattern[prefixIndex] === pattern[suffixIndex]){\n      prefixIndex++;\n      lps[suffixIndex] = prefixIndex;\n      suffixIndex++;\n    } else if (prefixIndex === 0){\n      lps[suffixIndex] = 0;\n      suffixIndex++;\n    } else {\n      prefixIndex = lps[prefixIndex - 1];\n    }\n  }\n\n  return lps;\n}\n\n// Mathc the pattern in a given text\nfunction KMPSearch(text, pattern) {\n  const M = pattern.length;\n  const N = text.length;\n\n  // Create lps[] (longest proper prefix which is also suffix) that will hold the longest prefix suffix\n  // and preprocess it\n  const lps = buildLPSArray(pattern, M);\n\n  let textIndex = 0;\n  let patterndIndex = 0;\n\n  while(textIndex < N){\n    if(text[textIndex] === pattern[patterndIndex]) {\n      if(patterndIndex === M - 1) {\n        return true;\n      }\n      textIndex++;\n      patterndIndex++;\n    } else if(patterndIndex > 0) {\n      patterndIndex = lps[patterndIndex - 1];\n    } else {\n      patterndIndex = 0;\n      textIndex++;\n    }\n  }\n  return false;\n}\n\n// Test\nfunction test() {\n  let text = prompt(\"Write the text:\").split(\"\");\n  let pattern = prompt(\"Write the pattern:\").split(\"\");\n  console.log(KMPSearch(text, pattern));\n}"
  },
  {
    "path": "Algorithms/String/LCS/LCS.py",
    "content": "A = input(\"Sequence 1: \")\nB = input(\"Sequence 2: \")\n\nc = []\n\ndef LCS(A,B,m,n):\n    if m==0 or n==0:\n        return 0\n    elif A[m-1] == B[n-1]:\n        return 1 + LCS(A,B,m-1,n-1)\n    else:\n        return max(LCS(A,B,m,n-1),LCS(A,B,m-1,n))\n\n\nprint(LCS(A,B,len(A),len(B)))"
  },
  {
    "path": "Algorithms/String/LCS/lcs.cpp",
    "content": "#include<bits/stdc++.h>\r\n\r\nusing namespace std; \r\n\r\n\r\nvoid lcs( char *X, char *Y, int m, int n ) \r\n{ int count=0;\r\nint L[m+1][n+1]; \r\nfor (int i=0; i<=m; i++) \r\n{    \r\n\tfor (int j=0; j<=n; j++) \r\n\t{ //count++;\r\n\tif (i == 0 || j == 0) \r\n\t\tL[i][j] = 0; \r\n\telse if (X[i-1] == Y[j-1]) \r\n\t{   count++;\r\n\t\r\n\t\tL[i][j] = L[i-1][j-1] + 1; }\r\n\telse\r\n\t\tL[i][j] = max(L[i-1][j], L[i][j-1]); \r\n\t} \r\n} \r\n\r\nint index = L[m][n]; \r\n\r\nchar lcs[index+1]; \r\nlcs[index] = '\\0';\r\nint i = m, j = n; \r\nwhile (i > 0 && j > 0) \r\n{ \r\n\tif (X[i-1] == Y[j-1]) \r\n\t{ \r\n\t\tlcs[index-1] = X[i-1];  \r\n\t\ti--; j--; index--;\t \r\n\t} \r\n\r\n\telse if (L[i-1][j] > L[i][j-1]) \r\n\t\ti--; \r\n\telse\r\n\t\tj--; \r\n} \r\n\r\ncout << \"\\nLCS of \" << X << \" and \" << Y << \" is \" << lcs<<endl; \r\ncout<<count;\r\n} \r\n\r\nint main() \r\n{ \r\nchar X[] = \"1 1 0 1 0 1 \"; \r\nchar Y[] = \"0 1 0 0 1 1 0\"; \r\n\r\nint m = strlen(X); \r\nint n = strlen(Y); \r\ncout<<\"Inputs to be used are- \"<<endl;\r\ncout<<\"First sequence - \";\r\nputs(X);\r\ncout<<\"Second sequence - \";\r\nputs(Y);\r\nlcs(X, Y, m, n); \r\nreturn 0; \r\n} \r\n\r\n"
  },
  {
    "path": "Algorithms/String/LPS/longest_palindromic_substring.c",
    "content": "#include <stdio.h> \n#include <string.h> \nvoid print(char* str, int low, int high) \n{ \n    for (int i = low; i <= high; ++i) \n        printf(\"%c\", str[i]); \n} \n  \n\nvoid longestSubstr(char* str) \n{ \n    int maxLength = 1; \n    int start = 0; \n    int len = strlen(str); \n    int low, high;\n    for (int i = 1; i < len; ++i) { \n        low = i - 1; \n        high = i; \n        while (low >= 0 && high < len \n               && str[low] == str[high]) { \n            if (high - low + 1 > maxLength) { \n                start = low; \n                maxLength = high - low + 1; \n            } \n            --low; \n            ++high; \n        } \n        low = i - 1; \n        high = i + 1; \n        while (low >= 0 && high < len \n               && str[low] == str[high]) { \n            if (high - low + 1 > maxLength) { \n                start = low; \n                maxLength = high - low + 1; \n            } \n            --low; \n            ++high; \n        } \n    } \n    printf(\"Longest palindrome substring is: \"); \n    print(str, start, start + maxLength - 1); \n} \n  \n// Driver program to test above functions \nint main() \n{ \n    char s[1000], i;\n    int n;\n    printf(\"enter the length of string \\n\");\n    scanf(\"%d\", &n);\n    printf(\"Please enter your string \\n\");\n    for(i = 0; i < n; i++){\n        scanf(\"%c\", &s[i]);\n    }\n    longestSubstr(s); \n    return 0; \n} "
  },
  {
    "path": "Algorithms/String/LPS/longest_palindromic_substring.cpp",
    "content": "#include<iostream>\n#include <string> \nusing namespace std;\n\nstring expandAroundCenter(string s, int c1, int c2) {\n        int l = c1, r = c2;\n        int n = s.length();\n        while (l >= 0 && r <= n-1 && s[l] == s[r]) {\n            l--;\n            r++;\n        }\n        return s.substr(l+1, r-l-1);\n}\n        \nstring LPS(string A) {\n    int n = A.length();\n    if (n == 0) \n       return \"\";\n    string longest = A.substr(0, 1);    // a single char itself is a palindrome\n    for (int i = 0; i < n-1; i++) {\n        //for possible odd length palindrome-\n        string p1 = expandAroundCenter(A, i, i);\n        if (p1.length() > longest.length())\n            longest = p1;\n        //for possible even length palindrome-\n        string p2 = expandAroundCenter(A, i, i+1);\n        if (p2.length() > longest.length())\n            longest = p2;\n    }\n    return longest;\n}\n\nint main() {\n   string s;\n   getline(cin, s);\n   string answer = LPS(s);\n   cout << answer;\n   return 0;\n}\n"
  },
  {
    "path": "Algorithms/String/LPS/longest_palindromic_substring.java",
    "content": "//using dynamic programming approach to solve\nimport java.util.Scanner;\nclass Solution {\n    public static String longestPalindrome(String s) {\n        int n=s.length();\n        \n        //2-d array to store the palindrome status of each substring -> memory[i][j]=1 iff substring s(i,j) is palindrome otheriwise memory[i][j]=0\n        int[][] memory = new int[n][n]; \n        int maxLen=1; //maxLen stores current maximum length of palindrome substring\n        int start=0; //start stores the start index of the current longest palindrome string\n\n        for(int i=n-1;i>=0;i--)\n        {\n            for(int j=i;j<n;j++)\n            {\n\n                if(i==j)\n                {\n                    memory[i][j]=1; //updating memory for substrings of length 1. \n                    continue;\n                }\n                if(j==i+1)\n                {\n                    memory[i][i+1]=s.charAt(j)==s.charAt(i)?1:0; //updating memory with substrings of length 2\n                    if (memory[i][i+1]==1 && maxLen<=2)\n                    {\n                        maxLen=2;\n                        start=i;\n                    } \n                    continue;\n                }   \n\n                //for each substring s(i,j) of lenght>2, it is a palindrome if substring s(i+1,j-1) is a palindrome and s(i)==s(j)\n                if(memory[i+1][j-1]==1 && s.charAt(j)==s.charAt(i)) \n                {\n                    memory[i][j]=1;\n                    int len = j-i+1;\n                    if(len>=maxLen)\n                    {\n                        maxLen=len;\n                        start=i;\n                    }\n                }\n\n\n            }\n        }\n        return s.substring(start,start+maxLen); //returning longest palindrome substring\n    }\n    public static void main(String[] args)\n    {\n            System.out.print(\"\\nEnter a String : \");\n\t    Scanner scan = new Scanner(System.in);\n\t    str = scan.next();\n            System.out.println(longestPalindrome(str)); \n    }\n}\n    \n"
  },
  {
    "path": "Algorithms/String/LPS/longest_palindromic_substring.js",
    "content": "const readline = require('readline');\n\nconst rl = readline.createInterface({\n  input: process.stdin,\n  output: process.stdout,\n});\n\nrl.question(\n  'Input a string to find the longest palindromic substring: ',\n  (str) => {\n    console.log(\n      `The longest palindromic substring is: ${longestPalSubstr(str)}`\n    );\n    rl.close();\n  }\n);\n\n// Examples\n// HeyrailataLiarLiveonoevilBye  ==>  railataliar\n// Ratsliveonnoevilstar  ==>  ratsliveonnoevilstar\n// abraCadabra ==>  aca\n\nfunction longestPalSubstr(str) {\n  const n = str.length; // length of input string\n\n  const s = str.toLowerCase(); // the new string in lowercase to work with\n\n  // Set a matrix to check substrings (default values to false)\n  // - matrix[i][j] will be false if substring str[i..j] is not palindrome\n  // - otherwise, matrix[i][j] will be true\n  const matrix = new Array(n);\n  for (let i = 0; i < n; i++) {\n    matrix[i] = Array(n).fill(false);\n  }\n\n  // All substrings of length 1 are palindromes\n  let maxLength = 1;\n  for (let i = 0; i < n; i++) {\n    matrix[i][i] = true;\n  }\n\n  // Check for substring of length 2.\n  let start = 0;\n  for (let i = 0; i < n - 1; i++) {\n    if (s[i] === s[i + 1]) {\n      matrix[i][i + 1] = true;\n      start = i;\n      maxLength = 2;\n    }\n  }\n\n  // Check for lengths greater than 2.\n  // k is length of substring\n  for (let k = 3; k <= n; k++) {\n    // Starting index\n    for (let i = 0; i < n - k + 1; i++) {\n      // Ending index of substring from starting index i and length k\n      const j = i + k - 1;\n\n      // Checking for substring from ith index to jth index\n      // if str.charAt(i+1) to str.charAt(j-1) is a palindrome\n      if (matrix[i + 1][j - 1] && s[i] === s[j]) {\n        matrix[i][j] = true;\n        if (k > maxLength) {\n          start = i;\n          maxLength = k;\n        }\n      }\n    }\n  }\n  return s.slice(start, start + maxLength);\n}\n"
  },
  {
    "path": "Algorithms/String/LPS/longest_palindromic_substring.py",
    "content": "def longestPalSubstr(string): \n    \"\"\"\n    This function prints the longest palindrome substring (LPS) \n    of string. It also returns the length of the longest palindrome \n    :param string: The string to check for palindrome\n    \"\"\"\n\n    maximumLength = 1\n\n    start = 0\n    length = len(string) \n\n    low = 0\n    high = 0\n\n    # One by one consider every character as center point of \n    # even and length palindromes \n    for i in range(1, length): \n        # Find the longest even length palindrome with center \n        # points as i-1 and i. \n        low = i - 1\n        high = i \n        while((low >= 0) and (high < length) and (string[low] == string[high])): \n            if (high - low + 1 > maximumLength): \n                start = low \n                maximumLength = high - low + 1\n            low -= 1\n            high += 1\n\n        # Find the longest odd length palindrome with center \n        # point as i \n        low = i - 1\n        high = i + 1\n        while ((low >= 0) and (high < length) and (string[low] == string[high])): \n            if high - low + 1 > maximumLength: \n                start = low \n                maximumLength = high - low + 1\n            low -= 1\n            high += 1\n\n    print(\"Longest palindrome substring is: {}\".format(string[start:start + maximumLength]))\n\n# Driver program to test above functions \nstring = \"anaqwertyuioppoiuytrewqksl\"\nlongestPalSubstr(string)"
  },
  {
    "path": "Algorithms/String/LPS/longest_palindromic_substring.rb",
    "content": "\nputs \"Enter the String:\"\ninput = gets.chomp\nputs \"Entered String is: '#{input}'.\"\n\nn = input.length\n\ntable = Array.new(n) { Array.new(n, false) }\n\nmax_len = 1\ni = 0\nwhile (i < n)\n  table[i][i] = true\n  i = i + 1\nend\n\nstart = 0\ni = 0\nwhile i < n - 1\n  if (input[i] == input[i + 1])\n    table[i][i + 1] = true\n    start = i \n    max_len = 2\n  end\n  i = i + 1\nend\n\nk = 3\nwhile k <= n\n  i = 0\n  while i < (n - k + 1)\n    j = i + k - 1\n    if (table[i + 1][j - 1] and input[i] == input[j])\n      table[i][j] = true\n\n      if k > max_len\n        start = i \n        max_len = k\n      end\n    end\n    i = i + 1\n  end\n  k = k + 1\nend\n\nputs \"Longest palindromic substring is #{input[start..start+max_len-1]}\"\n"
  },
  {
    "path": "Algorithms/String/Palindrome/Palindrome.c",
    "content": "/** \n * @author  Ytalo Ramon\n */\n\n#include \"stdio.h\"\n#include \"stdlib.h\"\n#include \"string.h\"\n\n#define STRINGSIZE 11\n\nint is_palindrome(char *word);\n\nint main(int argc, char const *argv[]){\n    \n    char inputs[STRINGSIZE][STRINGSIZE] = {\n        \"ana\",\n        \"carl\",\n        \"anaa\",\n        \"level\",\n        \"levell\",\n        \"a\",\n        \"deified\",\n        \"deiffied\",\n        \"civicc\",\n        \"tesett\",\n        \"vuc\"\n    };\n\n    for(int i = 0; i < STRINGSIZE; i++)\n        printf(\"\\\"%s\\\" is palindrome ? %s\\n\", inputs[i],\n                is_palindrome(inputs[i]) ? \"Yes\" : \"NO\");\n    \n    return 0;\n}\n\nint is_palindrome(char *word){\n    int i = -1, j = strlen(word);\n    while (i < j && word[++i] == word[--j]);\n    \n    return j <= i;\n}"
  },
  {
    "path": "Algorithms/String/Palindrome/Palindrome.cs",
    "content": "using System;\n\nnamespace palindrome\n{\n    public class Test\n    {\n\t    public static void Main()\n\t    {\n\t\t    string inp, rev=\"\";\n\t\t    inp = Console.ReadLine();\n\t\t    \n\t\t    for(int i=inp.Length-1 ; i>=0;i--)\n\t\t        rev = rev + inp[i].ToString();\n\t\t    \n\t\t    if(rev.ToLower() == inp.ToLower())\n\t\t        Console.WriteLine(\"True\");\n\t\t    else\n\t\t        Console.WriteLine(\"False\");\n\t\t        \n\t    }\n    }\n}\n"
  },
  {
    "path": "Algorithms/String/Palindrome/Palindrome.java",
    "content": "public class palindrome {\n  static boolean isPalindrome(String word) {\n    int length = word.length();\n\n    for(int i = 0; i < length/2; i++)\n    {\n        if(word.charAt(i) != word.charAt(length - 1 - i))\n        {\n            return false;\n        }\n    }\n\n    return true;\n  }\n\n  public static void main(String[] args) {\n    System.out.println(isPalindrome(\"Hello\"));\n    System.out.println(isPalindrome(\"Kayak\"));\n  }\n}"
  },
  {
    "path": "Algorithms/String/Palindrome/isPalindrome.cpp",
    "content": "#include<bits/stdc++.h>\n\nusing namespace std;\n\n// Check whether the string is palindrome or not considering\n// only Alpha-Numeric Characters ignoring cases\n\nint main() {\n    string s;\n    cin>>s;\n\n    int l=0,r=s.size()-1;\n    while(l<r) {\n        while(!isalpha(s[l]) and !isdigit(s[l])) l++;\n        while(!isalpha(s[r]) and !isdigit(s[r])) r--;\n\n        if(l>=r) break;\n\n        if(isupper(s[l])) s[l] = tolower(s[l]);\n        if(isupper(s[r])) s[r] = tolower(s[r]);\n\n        if(s[l]==s[r]) l++,r--;\n        else break;\n    }\n    if(l<r) cout<<\"It is not a Palindrome string\\n\";\n    else cout<<\"It is a Palindrome String\\n\";\n    return 0;\n}\n"
  },
  {
    "path": "Algorithms/String/Palindrome/isPalindrome.py",
    "content": "# Check whether the string is palindrome or not considering\n# only Alpha-Numeric Characters ignoring cases\n\n\ns = input();\n\nt = ''.join([i.lower() if i.isalnum() else '' for i in s])\n\nif t==''.join(reversed(t)): print(\"It is a Palindrome String\")\nelse: print(\"It is not a Palindrome String\")\n\n"
  },
  {
    "path": "Algorithms/String/Palindrome/palindrome.go",
    "content": "package main\n\nimport (\n\t\"bufio\"\n\t\"fmt\"\n\t\"os\"\n\t\"strings\"\n)\n\nfunc reverse(s string) string {\n\tchars := []rune(s)\n\tfor i, j := 0, len(chars)-1; i < j; i, j = i+1, j-1 {\n\t\tchars[i], chars[j] = chars[j], chars[i]\n\t}\n\treturn string(chars)\n}\n\nfunc main() {\n\n\treader := bufio.NewReader(os.Stdin)\n\tfmt.Println(\"Enter Text to check for Palindrome. Press Ctrl-C to Quit.\")\n\tfmt.Println(\"---------------------\")\n\n\tfor {\n\t\tfmt.Print(\"-> \")\n\t\ttext, _ := reader.ReadString('\\n')\n\t\t// convert CRLF to LF\n\t\ttext = strings.Replace(text, \"\\n\", \"\", -1)\n\n\t\tif strings.Compare(text, reverse(text)) == 0 {\n\t\t\tfmt.Println(\"Palindome!\")\n\t\t} else {\n\t\t\tfmt.Println(\"Nope.\")\n\t\t}\n\t}\n\n}\n"
  },
  {
    "path": "Algorithms/String/Palindrome/palindrome.java",
    "content": "public class palindrome {\n  static boolean isPalindrome(String word) {\n    int length = word.length();\n\n    for(int i = 0; i < length/2; i++)\n    {\n        if(word.charAt(i) != word.charAt(length - 1 - i))\n        {\n            return false;\n        }\n    }\n\n    return true;\n  }\n\n  public static void main(String[] args) {\n    System.out.println(isPalindrome(\"Hello\"));\n    System.out.println(isPalindrome(\"Kayak\"));\n  }\n}"
  },
  {
    "path": "Algorithms/String/Palindrome/palindrome.js",
    "content": "const readline = require('readline');\n\nconst r1 = readline.createInterface({\n  input: process.stdin,\n  output: process.stdout\n});\n\nr1.question('Input a word to check if it is a palindrome: ', (word) => {\n  const isPalindrome = palindromeCheck(word);\n\n  if (!isPalindrome) {\n    console.log('It is NOT a palindrome!')\n  } else {\n    console.log('It is a palindrome!');\n  }\n\n  process.exit(1);\n});\n\nfunction palindromeCheck(word) {\n  return word.split('').reverse().join('') === word;\n}\n"
  },
  {
    "path": "Algorithms/String/Palindrome/palindrome.php",
    "content": "<?php\n\nfunction isPalindrome($str) {\n    if (strtolower($str) === strtolower(strrev($str))) {\n        return $str .\": is a palindrome \\n\";\n    }\n    return $str .\": is not a palindrome \\n\";\n}\n\necho isPalindrome('data');\necho isPalindrome('madaM');\necho isPalindrome('owo');\n"
  },
  {
    "path": "Algorithms/String/Palindrome/palindrome.py",
    "content": "# Palindrome\n# Python\n\ndef palindrome(rawString):\n    return rawString[::-1] == rawString\n\nif __name__ == \"__main__\":\n    rawString = input(\"Enter a string: \")\n    if palindrome(rawString.lower()) == True:\n        print(\"It is a Palindrome!\")\n    else:\n        print(\"It is not a Palindrome!\")\n"
  },
  {
    "path": "Algorithms/String/Palindrome/palindrome.swift",
    "content": "import Foundation\n\nfunc palindrome(string: String)-> Bool{\n    let char = Array(string)\n    for i in 0..<char.count / 2 {\n        if char[i] != char[char.count - 1 - i] {\n            return false\n        }\n    }\n    return true\n}\n\nprint(\"Program for checking if a string is palindrome or not\")\nprint(\"Please enter the string\")\nlet value = readLine()\nif let value = value {\n  let isPalindrome = palindrome(string: value)\n  isPalindrome ? print(\"\\(value) is a palindrome\") : print(\"\\(value) is not a palindrome\")\n}\n"
  },
  {
    "path": "Algorithms/String/Palindrome/palindrome.ts",
    "content": "import { ReadLine, createInterface } from 'readline';\n\nconst r1: ReadLine = createInterface({\n    input: process.stdin,\n    output: process.stdout\n});\n\nfunction palindromeCheck(str: string): boolean {\n    return str.split('').reverse().join('') === str;\n};\n\nr1.question('Input a word to check if it is a palindrome: ', (answer: string) => {\n    const isPalindrome: boolean = palindromeCheck(answer);\n\n    if (!isPalindrome) {\n        console.log('It is NOT a palindrome!')\n    } else {\n        console.log('It is a palindrome!');\n    }\n\n    process.exit(1);\n});\n"
  },
  {
    "path": "Algorithms/String/Palindrome/palindromecheck.go",
    "content": "package main\n\nimport (\n   \"fmt\"\n   \"strings\"\n)\n\nfunc Reverse(s string) (result string) {\n   for _, v := range s {\n      result = string(v) + result\n   }\n   return\n}\n\nfunc isPalindrome(str string) interface{} {\n   if str == Reverse(str) {\n      return true\n   }\n   return false\n}\n\nfunc main() {\n   var str string\n   fmt.Print(\"Enter a string: \")\n   fmt.Scan(&str)\n   if isPalindrome(strings.ToUpper(str)) == true {\n      fmt.Print(str, \" is a palindrome.\")\n   } else {\n      fmt.Print(str, \" is not a palindrome.\")\n   }\n}\n"
  },
  {
    "path": "Algorithms/String/README.md",
    "content": "## This folder is empty.\n"
  },
  {
    "path": "Algorithms/String/Rabin-Karp/RabinKarpAlgo.java",
    "content": "public class RabinKarb {\n    // d is the number of characters in the input alphabet\n    public final static int d = 256;\n     \n    //pat -> pattern\n    static void search(String pat, String txt, int primeNum) {\n        \n        int M = pat.length();\n        int N = txt.length();\n        int i, j;\n        int p = 0; \n        int t = 0; \n        int h = 1;\n     \n        //assigning the value to the h,t,p\n        for (i = 0; i < M-1; i++)\n            h = (h*d)%primeNum;\n     \n        for (i = 0; i < M; i++) {\n            p = (d*p + pat.charAt(i))%primeNum;\n            t = (d*t + txt.charAt(i))%primeNum;\n        }\n     \n        // Triversing the pattern 1 by 1\n        for (i = 0; i <= N - M; i++) {\n            if ( p == t ) {\n                /* Check for characters one by one */\n                for (j = 0; j < M; j++) {\n                    if (txt.charAt(i+j) != pat.charAt(j))\n                        break;\n                }\n                if (j == M)\n                    System.out.println(\"Pattern found at index \" + i);\n            }\n     \n            // Calculate hash value for next window of text: Remove\n            if ( i < N-M ) {\n                t = (d*(t - txt.charAt(i)*h) + txt.charAt(i+M))%primeNum;\n     \n                // We might get negative value of t, converting it\n                // to positive\n                if (t < 0)\n                t = (t + primeNum);\n            }\n        }\n    }\n     \n    /* Main Method */\n    public static void main(String[] args) {\n        String txt = \"enjoy the life as well as coding :)\";\n        String pattern = \"as\"; \n           \n          // A prime number\n        int primeNum = 101;\n       \n          // Function Call\n        search(pattern, txt, primeNum);\n    }\n}\n"
  },
  {
    "path": "Algorithms/String/Rabin-Karp/Rabin_Karp.cpp",
    "content": "/* Following program is a C++ implementation of Rabin Karp \nAlgorithm given in the CLRS book */\n#include <bits/stdc++.h>\nusing namespace std;\n\n// d is the number of characters in the input alphabet \n#define d 256 \n\n/* pat -> pattern \n\ttxt -> text \n\tq -> A prime number \n*/\nvoid search(char pat[], char txt[], int q) \n{ \n\tint M = strlen(pat); \n\tint N = strlen(txt); \n\tint i, j; \n\tint p = 0; // hash value for pattern \n\tint t = 0; // hash value for txt \n\tint h = 1; \n\n\t// The value of h would be \"pow(d, M-1)%q\" \n\tfor (i = 0; i < M - 1; i++) \n\t\th = (h * d) % q; \n\n\t// Calculate the hash value of pattern and first \n\t// window of text \n\tfor (i = 0; i < M; i++) \n\t{ \n\t\tp = (d * p + pat[i]) % q; \n\t\tt = (d * t + txt[i]) % q; \n\t} \n\n\t// Slide the pattern over text one by one \n\tfor (i = 0; i <= N - M; i++) \n\t{ \n\n\t\t// Check the hash values of current window of text \n\t\t// and pattern. If the hash values match then only \n\t\t// check for characters on by one \n\t\tif ( p == t ) \n\t\t{ \n\t\t\t/* Check for characters one by one */\n\t\t\tfor (j = 0; j < M; j++) \n\t\t\t{ \n\t\t\t\tif (txt[i+j] != pat[j]) \n\t\t\t\t\tbreak; \n\t\t\t} \n\n\t\t\t// if p == t and pat[0...M-1] = txt[i, i+1, ...i+M-1] \n\t\t\tif (j == M) \n\t\t\t\tcout<<\"Pattern found at index \"<< i<<endl; \n\t\t} \n\n\t\t// Calculate hash value for next window of text: Remove \n\t\t// leading digit, add trailing digit \n\t\tif ( i < N-M ) \n\t\t{ \n\t\t\tt = (d*(t - txt[i]*h) + txt[i+M])%q; \n\n\t\t\t// We might get negative value of t, converting it \n\t\t\t// to positive \n\t\t\tif (t < 0) \n\t\t\tt = (t + q); \n\t\t} \n\t} \n} \n\n/* Driver code */\nint main() \n{ \n\tchar txt[] = \"GEEKS FOR GEEKS\"; \n\tchar pat[] = \"GEEK\";\n\t\n\t// A prime number \n\tint q = 101; \n\t\n\t// Function Call\n\tsearch(pat, txt, q); \n\treturn 0; \n} \n\n"
  },
  {
    "path": "Algorithms/String/Rabin-Karp/Rabin_Karp.ts",
    "content": "function strStr(text: string, pattern: string): number {\n    if (pattern === '')\n        return 0;\n    \n    const prime = 101;\n    const n = text.length;\n    const m = pattern.length;\n    const base = 26;\n    let h = 0;\n    let wh = 0; // word window hash, m in length\n    \n    if (m > n)\n        return -1;\n    \n    const hash = (charCode: number, exp: number) => {\n        return charCode * Math.pow(base, exp) % prime;\n    };\n    \n    // hash the pattern and first window\n    for (let i = 0; i < m; i++) {\n        h += hash(pattern.charCodeAt(i), m - i - 1);\n        wh += hash(text.charCodeAt(i), m - i - 1);\n    }\n    \n    h %= prime;\n    wh %= prime;\n    \n    // traverse word\n    for (let i = 0; i <= (n - m); i++) {\n        if (h === wh && pattern === text.substring(i, i + m)) {\n            return i;\n        } else {\n            wh -= hash(text.charCodeAt(i), m - 1);\n            wh *= base;\n            wh %= prime;\n            wh += text.charCodeAt(i + m);\n            wh %= prime;\n        }\n    }\n    return -1;\n};\n"
  },
  {
    "path": "Algorithms/String/Rabin-Karp/Rabin_karp.c",
    "content": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#define MOD 1000000007 // selected prime number\n\nint main(){\n    char pattern[10000], text[1000];\n    printf(\"Enter Text:-\\n\");\n    scanf(\"%[^\\n]%*c\",text);\n    printf(\"Enter Pattern to be searched :- \\n\");\n    scanf(\"%[^\\n]%*c\",pattern);\n\n    int l1 = strlen(pattern), l2 = strlen(text);\n    long long hp = 0, ht = 0, val = 1;\n\n    long long random = rand()%(MOD-1) + 1; // generating random value x\n\n    for(int i=0; i<l1 ;i++){\n        hp = (random*hp)%MOD; // calculating hash of pattern\n        ht = (random*ht)%MOD; // calculating hash of first sub-string\n                              // of text\n        hp += pattern[i];\n        ht += text[i];\n\n        hp %= MOD;\n        ht %= MOD;\n        val = (val*random)%MOD;\n    }\n    \n    for(int i = 0; l2-l1-i >= 0 ;i++){\n        if(i != 0){\n            long long new_ht = (random*ht-val*text[i-1]+text[l1+i-1])%MOD;\n            new_ht = (new_ht + MOD)%MOD;\n            ht = new_ht;\n        }\n\n        if(hp == ht){\n            int j;\n            \n            for (j = 0; j < l1 ; j++){ \n                if (text[i+j] != pattern[j]) \n                    break; \n            }\n            \n            if(j == l1)\n                printf(\"Pattern found at index :- %d\\n\",i);//output all indices where pattern was\n                                                           //found in text\n        }\n    }\n\n    return 0;\n}"
  },
  {
    "path": "Algorithms/String/Rabin-Karp/rabin_karp.py",
    "content": "d=256\ndef search(pat, txt, q): \n    M = len(pat) \n    N = len(txt) \n    i = 0\n    j = 0\n    p = 0   \n    t = 0    \n    h = 1\n    for i in range(M-1): \n        h = (h * d)% q\n    for i in range(M): \n        p = (d * p + ord(pat[i]))% q \n        t = (d * t + ord(txt[i]))% q \n        \n    for i in range(N-M + 1): \n        if p == t: \n            for j in range(M): \n                if txt[i + j] != pat[j]: \n                    break\n  \n            j+= 1\n            if j == M: \n                print(\"Pattern found at index \" + str(i))\n   \n        if i < N-M: \n            t = (d*(t-ord(txt[i])*h) + ord(txt[i + M]))% q \n \n            if t < 0: \n                t = t + q \n   \ntxt = \"ABCDEGHABC\"\npat = \"ABC\"\nq = 101  \nsearch(pat, txt, q) \n"
  },
  {
    "path": "Algorithms/String/SCS/SCS.cpp",
    "content": "\n\n//DP - LCS\n  // Tabulation\n\n#include<iostream>\n#include<string>\n#include<algorithm>\n#include<bits/stdc++.h>\nusing namespace std;\n\nint static t[1001][1001];\nint LCS(string X,string Y,int n,int m)\n{  \n    for(int i=0;i<n+1;i++)\n    {\n      for(int j=0;j<m+1;j++)\n      {\n         if(i==0 || j==0)\n            t[i][j]=0;\n    \n         else if(X[i-1]==Y[j-1])\n             t[i][j]=1+t[i-1][j-1];\n             \n         else\n         t[i][j] = max(t[i-1][j],t[i][j-1]);\n      }\n    }\n  return t[n][m];\n}\nint SCS(string X,string Y,int n,int m)\n{\n\treturn m+n-LCS(X,Y,X.length(),Y.length());\n}\nint main()\n{\n    string X,Y;\n    cout<<\"Enter first and second string : \"<<endl;\n    cin>>X>>Y;\n   // memset(t,-1,sizeof(t));\n    cout<<\"Shortest common subsequence between two string is \"<<SCS(X,Y,X.length(),Y.length())<<endl;\n    return 0;\n}\n"
  },
  {
    "path": "Algorithms/String/ScrambleString.java",
    "content": "// Problem - Check if one string is scrambled from another\n\nimport java.io.*;\nimport java.util.*; \n\npublic class Sample\n{ \n\tstatic boolean isScramble(String S1, String S2) \n\t{ \n\t\tif (S1.length() != S2.length()) \n\t\t{ \n\t\t\treturn false; \n\t\t} \n\t\tint n = S1.length(); \n\t\n\t\tif (n == 0) \n\t\t{ \n\t\t\treturn true; \n\t\t} \n\t\t\n\t\tif (S1.equals(S2)) \n\t\t{ \n\t\t\treturn true; \n\t\t} \n\t\t\n\t\tchar[] tempArray1 = S1.toCharArray(); \n\t\tchar[] tempArray2 = S2.toCharArray(); \n\t\t\n\t\tArrays.sort(tempArray1); \n\t\tArrays.sort(tempArray2); \n\t\t\n\t\tString copy_S1 = new String(tempArray1); \n\t\tString copy_S2 = new String(tempArray2); \n\t\t\n\t\tif (!copy_S1.equals(copy_S2)) \n\t\t{ \n\t\t\treturn false; \n\t\t} \n\t\t\t\n\t\tfor(int i = 1; i < n; i++) \n\t\t{ \n\t\t\tif (isScramble(S1.substring(0, i), S2.substring(0, i)) && isScramble(S1.substring(i, n), S2.substring(i, n))) \n\t\t\t{ \n\t\t\t\treturn true; \n\t\t\t} \n\t\n\t\t\tif (isScramble(S1.substring(n - i, n), S2.substring(0, i)) && isScramble(S1.substring(0, n - i), S2.substring(i, n))) \n\t\t\t{ \n\t\t\t\treturn true; \n\t\t\t} \n\t\t} \n\t\treturn false; \n\t} \n\t\n\tpublic static void main(String[] args) throws IOException\n\t{ \n\t\tBufferedReader br=new BufferedReader(new InputStreamReader(System.in));\n\t\tSystem.out.println(\"Enter the first string to be checked\");\n\t\tString str1=br.readLine();\n\t\tSystem.out.println(\"Enter the second string to be checked\");\n\t\tString str2=br.readLine();\n\t\t\n\t\tif (isScramble(str1, str2)) \n\t\t{ \n\t\t\tSystem.out.println(\"Yes\"); \n\t\t} \n\t\telse\n\t\t{ \n\t\t\tSystem.out.println(\"No\"); \n\t\t} \n\t} \n} \n\n\n"
  },
  {
    "path": "Algorithms/String/suffix_array.cpp",
    "content": "#include <bits/stdc++.h>\r\nusing namespace std;\r\ntypedef long long ll;\r\n\r\nvoid count_sort(vector<ll>&p,vector<ll>&c)\r\n{\r\n    ll n=p.size();\r\n    vector<ll>cnt(n);\r\n    for(auto x:c)\r\n    cnt[x]++;\r\n    vector<ll>pos(n),p_new(n);\r\n    pos[0]=0;\r\n    for(ll i=1;i<n;i++)\r\n    pos[i]=pos[i-1]+cnt[i-1];\r\n    for(auto x:p)\r\n    {\r\n        ll i=c[x];\r\n        p_new[pos[i]]=x;\r\n        pos[i]++;\r\n    }\r\n    p=p_new;\r\n}\r\n\r\nint main() {\r\n\tstring s;\r\n\tcin>>s;\r\n\ts=s+\"$\";\r\n\tll n=s.size();\r\n\tvector<ll> p(n),c(n);\r\n\t//k=0\r\n\t{\r\n\t    std::vector<pair<char,ll>>a(n) ;\r\n\t    for(ll i=0;i<n;i++)a[i]={s[i],i};\r\n\t    sort(a.begin(),a.end());\r\n\t    for(ll i=0;i<n;i++)p[i]=a[i].second;\r\n\t    c[p[0]]=0;\r\n\t    for(ll i=1;i<n;i++)\r\n\t    {\r\n\t        if(a[i].first==a[i-1].first)\r\n\t        c[p[i]]=c[p[i-1]];\r\n\t        else\r\n\t        c[p[i]]=c[p[i-1]]+1;\r\n\t    }\r\n\t}\r\n\tll k=0;\r\n\twhile((1<<k)<n)\r\n\t{\r\n\t    for(ll i=0;i<n;i++)\r\n\t    {\r\n\t        p[i]=(p[i]-(1<<k)+n)%n;\r\n\t    }\r\n\t    count_sort(p,c);\r\n\t    vector<ll>c_new(n);\r\n\t    c_new[p[0]]=0;\r\n\t    for(ll i=1;i<n;i++)\r\n\t    {\r\n\t        pair<ll,ll>prev={c[p[i-1]],c[(p[i-1]+(1<<k))%n]};\r\n\t        pair<ll,ll>now={c[p[i]],c[(p[i]+(1<<k))%n]};\r\n\t        if(now==prev)\r\n\t        c_new[p[i]]=c_new[p[i-1]];\r\n\t        else\r\n\t        c_new[p[i]]=c_new[p[i-1]]+1;\r\n\t    }\r\n\t    c=c_new;\r\n\t    k++;\r\n\t}\r\n\tfor(ll i=0;i<n;i++)\r\n\tcout<<p[i]<<' ';\r\n\treturn 0;\r\n}\r\n"
  },
  {
    "path": "Algorithms/Tree/Binary_Lifting/Binary Lifting.py",
    "content": "import math\n \n# Pre-processing to calculate values of memo[][]\ndef dfs(u, p, memo, lev, log, g):\n\n    memo[u][0] = p\n    for i in range(1, log + 1):\n        memo[u][i] = memo[memo[u][i - 1]][i - 1]\n         \n    for v in g[u]:\n        if v != p:\n            lev[v] = lev[u] + 1\n            dfs(v, u, memo, lev, log, g)\n \n# Function to return the LCA of nodes u and v\ndef lca(u, v, log, lev, memo):\n\n    if lev[u] < lev[v]:\n        swap(u, v)\n\n    for i in range(log, -1, -1):\n        if (lev[u] - pow(2, i)) >= lev[v]:\n            u = memo[u][i]\n             \n    if u == v:\n        return v\n\n    for i in range(log, -1, -1):\n        if memo[u][i] != memo[v][i]:\n            u = memo[u][i]\n            v = memo[v][i]\n    \n    return memo[u][0]\n \n\nprint(\"Enter Number of Nodes\") \nn = input()\n\nlog = math.ceil(math.log(n, 2))\ng = [[] for i in range(n + 1)]\n \nmemo = [[-1 for i in range(log + 1)]\n            for j in range(n + 1)]\n \nlev = [0 for i in range(n + 1)]\n\nprint(\"Enter The Edges\")  \nfor i in range (1, (2*n-1)):\n    m = input()\n    n = input()\n    g[m].append(n)\n\n \ndfs(1, 1, memo, lev, log, g)\n\nprint(\"Enter The Edges to find LCA\") \ne1 = input()\ne2 = input()\nprint(\"The LCA is\", lca(e1, e2, log, lev, memo))"
  },
  {
    "path": "Algorithms/Tree/Binary_Lifting/Binary-Lifting.cpp",
    "content": "/*\nBinary Lifting is an algorithm to compute the LCA of two nodes in a tree in O(logn) time complexity.\nFor each node we precompute some of its ancestors above it.\nSpecifically, let's store those ancestor in the array anc, therefore anc[i][j] represents the 2^j th\nancestor of the ith node. After pre-calculation of this array, we can determine the LCA of any two \nnodes in O(logn) time.\nTime :- For each query, O(logn), n is number of nodes\nSpace :- O(n.logn)\n*/\n\n#include<bits/stdc++.h>\nusing namespace std;\n\n/* \ntimer variabel keeps the track of the order of visit of nodes in our DFS traversal\nthe incoming of dfs and outgoing of a function from the function stack is stored in vin & vout\n*/\nint n, u, v, m, tim, cnt;\nvector<int> vin, vout;\nvector<vector<int>> adj, anc;\n\nvoid dfs(int ver, int par) {\n    // time at which this particular instance is pushed into function-call stack\n    vin[ver] = ++tim;\n\n    // 2^0 = 1-st ancestore, or direct parent of the ver vertex\n    anc[ver][0] = par;\n\n    // the 2^i-th ancestor of ver is the 2^(i-1)-th ancestor of the 2^(i-1)th ancestor of ver\n    // which is already calculated during the dfs traversal\n    for(int i = 1; i <= cnt; ++i)\n        anc[ver][i] = anc[anc[ver][i - 1]][i - 1];\n    \n    for(int &edge : adj[ver]) {\n        if(edge == par) continue;\n        dfs(edge, ver);\n    }\n\n    // time at which this particular instance is popped out of function-call stack\n    vout[ver] = ++tim;\n}\n\n// intialising the ancestors of all nodes as the root\nvoid precompute(int root) {\n    tim = 0;\n    cnt = floor(log2(n)) + 1;\n    vin.assign(n + 1, 0);\n    vout.assign(n + 1, 0);\n    anc.assign(n + 1, vector<int>(cnt + 1, root));\n    dfs(root, root);\n}\n\nbool is_Ancestor(int v1, int v2) {\n    return (vin[v1] <= vin[v2] && vout[v1] >= vout[v2]);\n}\n\nint LCA(int v1, int v2) {\n    // check if these are ancestors of each other\n    if(is_Ancestor(v1, v2)) return v1;\n    if(is_Ancestor(v2, v1)) return v2;\n\n    /*\n    Iterate through all the ancestors of one of the node, then two cases arise\n    - If they have same ancestor, this is one of the possiblities of the answer\n    - If they don't, bring the pointer of first node to this node, and start searching the ancestor \n      of this node for the lowest common one\n    */\n    for(int i = cnt; i >= 0; --i) {\n        if(!is_Ancestor(anc[v1][i], v2))\n            v1 = anc[v1][i];\n    }\n    return anc[v1][0];\n}\n\n/*\nPOINTS TO NOTE :- \n# I'll be assuming 1 based indexing of nodes\n# This implementation is by assuming the tree is rooted at node 1\n# adj is the adjacency list of the tree-graph\n# anc is the array of ancestors of any node\n*/\nint main() {\n    cout << \"Enter the number of nodes : \";\n    cin >> n;\n    adj.assign(n + 1, vector<int>());\n    cout << \"Enter the edges :- \";\n    for(int i = 1; i < n; ++i) {\n        cin >> u >> v;\n        adj[u].push_back(v);\n        adj[v].push_back(u);\n    }\n    precompute(1);\n\n    cout << \"Enter number of queries : \";\n    cin >> m;\n    while(m--) {\n        cout << \"Enter the two vertexes : \";\n        cin >> u >> v;\n        cout << \"The LCA of \" << u << \" and \" << v << \" is \" << LCA(u, v) << endl;\n    }\n\n\n    return 0;\n}"
  },
  {
    "path": "Algorithms/Tree/GenericTreeImplementation/GenericTree.c",
    "content": "#include<stdio.h>\n#include<stdlib.h>\n#include<limits.h>\n#include<string.h>\n\ntypedef int element;\ntypedef struct node\n{\n    element data;\n    struct node *firstchild;\n    struct node *nextsibling;\n}*GenericTree;\n\nGenericTree create()\n{\n    return NULL;\n}\n\nint isEmpty(GenericTree gt)\n{\n    return (gt==NULL);\n}\n\nGenericTree build(element e, GenericTree firstchild, GenericTree nextsibling)\n{\n    GenericTree tree;\n    tree=(GenericTree)malloc(sizeof(struct node));\n    if(!tree)\n        return NULL;\n    tree->data=e;\n    tree->firstchild=firstchild;\n    tree->nextsibling=nextsibling;\n    return tree;\n}\n\nint nodeCount(GenericTree tree)\n{\n    if(!tree)\n        return 0;\n    return 1+nodeCount(tree->firstchild)+nodeCount(tree->nextsibling);\n\n}\n\nint nodeSum(GenericTree tree)\n{\n    if(!tree)\n        return 0;\n    return tree->data+nodeSum(tree->firstchild)+nodeSum(tree->nextsibling);\n}\n\nint nbS(GenericTree tree)\n{\n    int count=0;\n    while(tree)\n    {\n        tree=tree->nextsibling;\n        count++;\n    }\n    return count;\n}\n\nint nbC(GenericTree tree)\n{\n    int count=0;\n    if(tree)\n        tree=tree->firstchild;\n    while(tree)\n    {\n        count++;\n        tree=tree->nextsibling;\n    }\n    return count;\n}\n\nint main()\n{\n    GenericTree sample=build(1,build(2,NULL,build(3,build(4,NULL,NULL),\n                    build(5,build(6,NULL,build(7,build(8,NULL,\n                    build(9,NULL,NULL)),NULL)),build(10,build(11,NULL,\n                    build(12,NULL,build(13,NULL,NULL))),NULL)))),NULL);\n    printf(\"Number of nodes: %d\\n\",nodeCount(sample));\n    printf(\"Sum of nodes: %d\\n\",nodeSum(sample));\n    printf(\"Neighbour Siblings: %d\\n\",nbS(sample));\n    printf(\"Neighbour Children: %d\\n\",nbC(sample));\n    return 0;\n}"
  },
  {
    "path": "Algorithms/Tree/GenericTreeImplementation/GenericTree.cpp",
    "content": "#include<iostream>\n#include<queue>\n#include<vector>\nusing namespace std;\n\nclass treenode{\n    public:\n    int data;\n    vector<treenode *> children;\n\n    treenode(int data){\n        this->data = data;\n    }\n    ~treenode(){\n        for (int i = 0; i < children.size(); i++)\n        {\n            delete children[i];\n        }\n    }\n};\n\ntreenode* takeinput(){\n    queue<treenode*> pendingnodes;\n    cout<<\"enter root data\"<<endl;\n    int rootdata;\n    cin>>rootdata;\n\n    treenode* root = new treenode(rootdata);\n    pendingnodes.push(root);\n\n    while (!pendingnodes.empty())\n    {\n        treenode* currentnode = pendingnodes.front();\n        pendingnodes.pop();\n        cout<<\"enter no of child of \"<<currentnode->data<<endl;\n        int n;\n        cin>>n;\n\n        for (int i = 0; i < n; i++)\n        {\n            int currentchilddata;\n            cout<<\"enter \"<<i<<\"th child data of \"<<currentnode->data<<endl;\n            cin>>currentchilddata;\n            treenode* childnode = new treenode(currentchilddata);\n            currentnode->children.push_back(childnode);\n            pendingnodes.push(childnode);\n        }\n    }\n    return root;\n}\n\nvoid printtree(treenode* root){\n    queue<treenode *> pendingnodes;\n    pendingnodes.push(root);\n\n    while (!pendingnodes.empty())\n    {\n        treenode* currentnode = pendingnodes.front();\n        pendingnodes.pop();\n        string tobeprinted = to_string(currentnode->data)+\":\";\n        \n        for (int i = 0; i < currentnode->children.size(); i++)\n        {\n            tobeprinted += to_string(currentnode->children[i]->data)+\",\";\n            pendingnodes.push(currentnode->children.at(i));\n        }\n        cout<<tobeprinted<<endl;\n    }\n}\n\nint main(){\n    treenode* root = takeinput();\n    printtree(root);\n}"
  },
  {
    "path": "Algorithms/Tree/GenericTreeImplementation/GenericTree.java",
    "content": "import java.util.*;\n\npublic class Main {\n    public static void main(String[] args) {\nGenericTreeImplementation tree= new GenericTreeImplementation();\n    }\n}\nclass GenericTreeImplementation {\n    class Node {\n        int d;\n        ArrayList<Node> child;\n\n        Node(int d) {\n            this.d = d;\n            child = new ArrayList<>();\n        }\n    }\n\n    private Node r;\n\n    GenericTreeImplementation() {\n        Scanner s = new Scanner(System.in);\n        this.r = good(s, null, 0);\n    }\n\n    private Node good(Scanner s, Node parent, int i) {\n        if (parent == null) {\n            System.out.println(\"Enter info for root node\");\n        } else {\n            System.out.println(\"Enter info for \" + i + \"th child of \" + parent.d);\n        }\n        int d = s.nextInt();\n        Node node = new Node(d);\n        System.out.println(\"Enter the number of child for\" + node.d);\n        int n = s.nextInt();\n\n        for (int k = 0; k < n; k++) {\n            Node children = good(s, node, k);\n            node.child.add(children);\n        }\n        return node;\n    }\n}\n"
  },
  {
    "path": "Algorithms/Tree/LCA/LCA.cpp",
    "content": "/*\n Leetcode Problem Link:\n https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/\n*/\n\n/**\n * Definition for a binary tree node.\n * struct TreeNode {\n *     int val;\n *     TreeNode *left;\n *     TreeNode *right;\n *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}\n * };\n */\nclass Solution\n{\npublic:\n    TreeNode *lowestCommonAncestor(TreeNode *root, TreeNode *p, TreeNode *q)\n    {\n        if (root == NULL || root == p || root == q)\n            return root;\n        TreeNode *left = lowestCommonAncestor(root->left, p, q);\n        TreeNode *right = lowestCommonAncestor(root->right, p, q);\n        if (left == NULL)\n            return right;\n        if (right == NULL)\n            return left;\n        return root;\n    }\n};"
  },
  {
    "path": "Algorithms/Tree/LCA/LCA.cs",
    "content": "using System; \n\n// A binary tree node \npublic class Node \n{ \n\tpublic int data; \n\tpublic Node left, right; \n\n\tpublic Node(int item) \n\t{ \n\t\tdata = item; \n\t\tleft = right = null; \n\t} \n} \n\npublic class BinaryTree \n{ \n\tpublic Node root; \n\n\t/* Function to find LCA of n1 and n2. The function assumes that both \n\tn1 and n2 are present in BST */\n\tpublic virtual Node lca(Node node, int n1, int n2) \n\t{ \n\t\tif (node == null) \n\t\t{ \n\t\t\treturn null; \n\t\t} \n\n\t\t// If both n1 and n2 are smaller than root, then LCA lies in left \n\t\tif (node.data > n1 && node.data > n2) \n\t\t{ \n\t\t\treturn lca(node.left, n1, n2); \n\t\t} \n\n\t\t// If both n1 and n2 are greater than root, then LCA lies in right \n\t\tif (node.data < n1 && node.data < n2) \n\t\t{ \n\t\t\treturn lca(node.right, n1, n2); \n\t\t} \n\n\t\treturn node; \n\t} \n\n\t/* Driver program to test lca() */\n\tpublic static void Main(string[] args) \n\t{ \n\t\t// Let us construct the BST shown in the above figure \n\t\tBinaryTree tree = new BinaryTree(); \n\t\ttree.root = new Node(20); \n\t\ttree.root.left = new Node(8); \n\t\ttree.root.right = new Node(22); \n\t\ttree.root.left.left = new Node(4); \n\t\ttree.root.left.right = new Node(12); \n\t\ttree.root.left.right.left = new Node(10); \n\t\ttree.root.left.right.right = new Node(14); \n\n\t\tint n1 = 10, n2 = 14; \n\t\tNode t = tree.lca(tree.root, n1, n2); \n\t\tConsole.WriteLine(\"LCA of \" + n1 + \" and \" + n2 + \" is \" + t.data); \n\n\t\tn1 = 14; \n\t\tn2 = 8; \n\t\tt = tree.lca(tree.root, n1, n2); \n\t\tConsole.WriteLine(\"LCA of \" + n1 + \" and \" + n2 + \" is \" + t.data); \n\n\t\tn1 = 10; \n\t\tn2 = 22; \n\t\tt = tree.lca(tree.root, n1, n2); \n\t\tConsole.WriteLine(\"LCA of \" + n1 + \" and \" + n2 + \" is \" + t.data); \n\n\t} \n} "
  },
  {
    "path": "Algorithms/Tree/LCA/LCA.js",
    "content": "// Lowest Common Ancestor of a Binary Tree\r\n\r\n/**\r\n * Definition for a binary tree node.\r\n * function TreeNode(val) {\r\n *     this.val = val;\r\n *     this.left = this.right = null;\r\n * }\r\n */\r\n/**\r\n * @param {TreeNode} root\r\n * @param {TreeNode} p\r\n * @param {TreeNode} q\r\n * @return {TreeNode}\r\n */\r\n\r\nvar lowestCommonAncestor = function (root, p, q) {\r\n  if (!root || root === p || root === q) return root;\r\n  var left = LCA(root.left, p, q); // left traversal\r\n  var right = LCA(root.right, p, q); // right traversal\r\n  return left && right ? root : left || right;\r\n};\r\n"
  },
  {
    "path": "Algorithms/Tree/LCA/LCA.py",
    "content": "# Leetcode Problem Link:\n# https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/\n\n# Definition for a binary tree node.\n# class TreeNode:\n#     def __init__(self, x):\n#         self.val = x\n#         self.left = None\n#         self.right = None\n\nclass Solution:\n    def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':\n        if root == None or root == p or root == q:\n            return root\n        left = self.lowestCommonAncestor(root.left,p,q)\n        right = self.lowestCommonAncestor(root.right,p,q)\n        if left == None:\n            return right\n        if right == None:\n            return left\n        return root\n"
  },
  {
    "path": "Algorithms/Tree/Max_Heap_Construction/minmaxheap.cpp",
    "content": "#include <iostream>\n\nusing namespace std;\n\nvoid min_heapify(int *heap,int i,int n)\n{\n    int j, temp;\n    temp = heap[i];\n    j = 2 * i;\n    while (j <= n)\n    {\n        if (j < n && heap[j+1] < heap[j])\n            j = j + 1;\n        if (temp < heap[j])\n            break;\n        else if (temp >= heap[j])\n        {\n            heap[j/2] = heap[j];\n            j = 2 * j;\n        }\n    }\n    heap [j/2] = temp;\n    return;\n}\nvoid build_minheap(int *heap, int n)\n{\n    int i;\n    for(i = n/2; i >= 1; i--)\n    {\n        min_heapify(heap,i,n);\n    }\n}\nvoid max_heapify(int *heap, int i, int n)\n{\n    int j, temp;\n    temp = heap[i];\n    j = 2 * i;\n    while (j <= n)\n    {\n        if (j < n && heap[j+1] > heap[j])\n            j = j + 1;\n        if (temp > heap[j])\n            break;\n        else if (temp <= heap[j])\n        {\n            heap[j / 2] = heap[j];\n            j = 2 * j;\n        }\n    }\n    heap[j/2] = temp;\n    return;\n}\nvoid build_maxheap(int *heap,int n)\n{\n    int i;\n    for(i = n/2; i >= 1; i--)\n    {\n        max_heapify(heap,i,n);\n    }\n}\n\nint main()\n{\n    int n, i, ch;\n    cout<<\"\\n ENTER THE SIZE OF HEAP :\";\n    cin>>n;\n    int heap[20];\n    cout<<\"\\n ENTER THE ELEMENTS : \";\n    for (i = 1; i <= n; i++)\n    {\n          cin>>heap[i];\n    }\n    do\n    {\n    cout<<\"\\n\\n\\t\\t  OPERATIONS MENU\\n\\t\\t1.Min Heap\\n\\t\\t2.Max Heap\\n\\t\\t3.Exit \";\n    cout<<\"\\n ENTER YOUR CHOICE :\";\n    cin>>ch;\n    switch(ch)\n    {\n        case 1:\n          {\n            build_minheap(heap, n);\n            cout<<\"Min Heap\\n\";\n            for (i = 1; i <= n; i++)\n            {\n                cout<<heap[i]<<endl;\n            }\n            break;\n          }\n        case 2:\n            {\n                build_maxheap(heap,n);\n                cout<<\"Max Heap\\n\";\n                for (i = 1; i <= n; i++)\n                {\n                    cout<<heap[i]<<endl;\n                }\n                break;\n            }\n        case 3:\n            {\n                exit(0);\n            }\n    }\n }while(ch!=3);\n}\n"
  },
  {
    "path": "Algorithms/Tree/Max_Path_Sum_BST/Max_Path_Sum_BST.cpp",
    "content": "//Question Link - https://leetcode.com/problems/binary-tree-maximum-path-sum/\n/**\n * Definition for a binary tree node.\n * struct TreeNode {\n *     int val;\n *     TreeNode *left;\n *     TreeNode *right;\n *     TreeNode() : val(0), left(nullptr), right(nullptr) {}\n *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}\n *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}\n * };\n */\nclass Solution {\npublic:\n    int maxSum=-1e8;\n    int maxPathSum_(TreeNode* root)\n    {\n        if(root==NULL)\n            return 0;\n        int leftNodeToNode=maxPathSum_(root->left);\n        int rightNodeToNode=maxPathSum_(root->right);\n        \n        int max_=max(leftNodeToNode,rightNodeToNode)+root->val;\n        maxSum= max(maxSum,max(leftNodeToNode+rightNodeToNode+root->val,max(root->val,max_)));\n        \n        return max(max_,root->val);\n    }\n    int maxPathSum(TreeNode* root) {\n        maxPathSum_(root);\n        \n        return maxSum;\n    }\n};\n"
  },
  {
    "path": "Algorithms/Tree/Max_Path_Sum_BST/Max_Path_Sum_BST.py",
    "content": "\"\"\"Max Path Sum In Binary Tree - Write a function that takes in a Binary Tree and returns its max path sum. A path is a collection of connected nodes in a tree where no node is connected to more than two other nodes; a path sum is the sum of the values of the nodes in a particular path. Each BinaryTree node has an integer value , a left child node, and a right child node. Children nodes can either be BinaryTree nodes themselves or None / null .\"\"\"\n\n# For dynamic user input\n\nimport unittest\n\nnumberList = []\nn = int(input(\"Enter the list size : \"))\n\nprint(\"\\n\")\nfor i in range(0, n):\n    print(\"Enter number at location\", i, \":\")\n    item = int(input())\n    numberList.append(item)\n\nprint(\"User List is \", numberList)\n\n\nclass TestProgram(unittest.TestCase):\n    def test_case_1(self):\n        test = BinaryTree(1).insert(numberList)\n        maxPathSum(test)\n\n\nclass BinaryTree:\n    def __init__(self, value):\n        self.value = value\n        self.left = None\n        self.right = None\n\n    def insert(self, values, i=0):\n        if i >= len(values):\n            return\n        queue = [self]\n        while len(queue) > 0:\n            current = queue.pop(0)\n            if current.left is None:\n                current.left = BinaryTree(values[i])\n                break\n            queue.append(current.left)\n            if current.right is None:\n                current.right = BinaryTree(values[i])\n                break\n            queue.append(current.right)\n        self.insert(values, i + 1)\n        return self\n\n\n# O(N) T | O(1) S\n\n\ndef maxPathSum(tree):\n    _, maxSum = findMaxSum(tree)\n    return maxSum\n\n\ndef findMaxSum(tree):\n    if tree is None:\n        return(0, float(\"-inf\"))\n\n    leftSumAsBranch, leftMaxPathSum = findMaxSum(tree.left)\n    rightSumAsBranch, rightMaxPathSum = findMaxSum(tree.right)\n    maxChildSumAsBranch = max(leftSumAsBranch, rightSumAsBranch)\n\n    value = tree.value\n    maxSumAsBranch = max(maxChildSumAsBranch+value, value)\n    maxSumUsingRootNode = max(\n        maxSumAsBranch, leftSumAsBranch + value + rightSumAsBranch)\n    runningMaxPathSum = max(\n        leftMaxPathSum, rightMaxPathSum, maxSumUsingRootNode)\n\n    return (maxSumAsBranch, runningMaxPathSum)\n"
  },
  {
    "path": "Algorithms/Tree/Min_Heap_Construction/README.md",
    "content": "### Min Heap Construction \nImplement a MinHeap class that supports: - Building a Min Heap from an input array of integers. - Inserting integers in the heap. - Removing the heap's minimum / root value. - Peeking at the heap's minimum / root value. - Sifting integers up and down the heap, which is to be used when inserting and removing values. Note that the heap should be represented in the form of an array."
  },
  {
    "path": "Algorithms/Tree/Min_Heap_Construction/min-heap-construc.cpp",
    "content": "using System;\nusing System.Collections.Generic;\npublic\nclass Program\n{\npublic\n    class MinHeap\n    {\n    public\n        List<int> heap = new List<int>();\n\n    public\n        MinHeap(List<int> array)\n        {\n            heap = buildHeap(array);\n        }\n\n        //O(n) time | O(1) space\n    public\n        List<int> buildHeap(List<int> array)\n        {\n            int firstParentIdx = (array.Count - 2) / 2;\n            for (int currentIdx = firstParentIdx; currentIdx >= 0; currentIdx--)\n            {\n                siftDown(currentIdx, array.Count - 1, array);\n            }\n            return array;\n        }\n\n        // O(log(n)) time | O(1) space\n    public\n        void siftDown(int currentIdx, int endIdx, List<int> heap)\n        {\n            int childOneIdx = currentIdx * 2 + 1;\n            while (childOneIdx <= endIdx)\n            {\n                int childTwoIdx = currentIdx * 2 + 2 <=\n                                          endIdx\n                                      ? currentIdx * 2 + 2\n                                      : -1;\n                int idxToSwap;\n                if (childTwoIdx != -1 && heap[childTwoIdx] < heap[childOneIdx])\n                {\n                    idxToSwap = childTwoIdx;\n                }\n                else\n                {\n                    idxToSwap = childOneIdx;\n                }\n                if (heap[idxToSwap] < heap[currentIdx])\n                {\n                    swap(currentIdx, idxToSwap, heap);\n                    currentIdx = idxToSwap;\n                    currentIdx = currentIdx * 2 + 1;\n                }\n                else\n                {\n                    return;\n                }\n            }\n        }\n\n        //O(log(n)) time | O(1) space\n    public\n        void siftUp(int currentIdx, List<int> heap)\n        {\n            int parentIdx = (currentIdx - 1) / 2;\n            while (currentIdx > 0 && heap[currentIdx] < heap[parentIdx])\n            {\n                swap(currentIdx, parentIdx, heap);\n                currentIdx = parentIdx;\n                parentIdx = (currentIdx - 1) / 2;\n            }\n        }\n\n    public\n        int Peek()\n        {\n            return heap[0];\n        }\n\n    public\n        int Remove()\n        {\n            swap(0, heap.Count - 1, heap);\n            int valueToRemove = heap[heap.Count - 1];\n            heap.RemoveAt(heap.Count - 1);\n            siftDown(0, heap.Count - 1, heap);\n            return valueToRemove;\n        }\n\n    public\n        void Insert(int value)\n        {\n            heap.Add(value);\n            siftUp(heap.Count - 1, heap);\n        }\n\n    public\n        void swap(int i, int j, List<int> heap)\n        {\n            int temp = heap[j];\n            heap[j] = heap[i];\n            heap[i] = temp;\n        }\n    }\n}\n"
  },
  {
    "path": "Algorithms/Tree/Min_Heap_Construction/min-heap-construc.py",
    "content": "class MinHeap:\n    def __init__(self, array):\n        self.heap = self.buildHeap(array)\n\n\t# O(N)T | O(1)S\n    def buildHeap(self, array):\n        firstParentIdx = (len(array)-2) // 2\n\t\tfor currIdx in reversed(range(firstParentIdx+1)):\n\t\t\tself.siftDown(currIdx, len(array)-1, array)\n\t\treturn array\n\n\t# O(logN)T | O(1)S\n    def siftDown(self, currIdx, endIdx, heap):\n\t\tchildOneIdx = currIdx*2 + 1\n\t\twhile childOneIdx <= endIdx:\n\t\t\tchildTwoIdx = currIdx*2 + 2 if currIdx*2 + 2 <= endIdx else -1\n\t\t\tif childTwoIdx != -1 and heap[childTwoIdx] < heap[childOneIdx]:\n\t\t\t\tidxToSwap = childTwoIdx\n\t\t\telse:\n\t\t\t\tidxToSwap = childOneIdx\n\t\t\tif heap[idxToSwap] < heap[currIdx]:\n\t\t\t\tself.swap(currIdx, idxToSwap, heap)\n\t\t\t\tcurrIdx = idxToSwap\n\t\t\t\tchildOneIdx = currIdx*2+1\n\t\t\telse:\n\t\t\t\treturn\n\n\t# O(logN)T | O(1)S\n    def siftUp(self, currIdx, heap):\n\t\tparentIdx = (currIdx-1) // 2\n\t\twhile currIdx > 0 and heap[currIdx] < heap[parentIdx]:\n\t\t\tself.swap(currIdx, parentIdx, heap)\n\t\t\tcurrIdx = parentIdx\n\t\t\tparentIdx = (currIdx-1) // 2\n\n\t# O(1)T | O(1)S\n    def peek(self):\n        # Write your code here.\n    \treturn self.heap[0]\n\n\t# O(logN)T  | O(1)S\n    def remove(self):\n\t\tself.swap(0, len(self.heap)-1, self.heap)\n        valueToRemove = self.heap.pop()\t\n\t\tself.siftDown(0,len(self.heap)-1,self.heap)\n\t\treturn valueToRemove\n\n\t# O(logN)T | O(1)S\n    def insert(self, value):\n\t\tself.heap.append(value)\n\t\tself.siftUp(len(self.heap)-1,self.heap)\n\t\t\n\tdef swap(self,i,j,heap):\n\t\theap[i],heap[j]=heap[j],heap[i]\n"
  },
  {
    "path": "Algorithms/Tree/README.md",
    "content": "# This folder is empty.\n"
  },
  {
    "path": "Algorithms/Tree/Sorted-Array-To-BST/Sorted-Array-To-BST.cpp",
    "content": "#include<bits/stdc++.h>\nusing namespace std;\n\n/* A Binary Tree node */\nclass TNode\n{\n\tpublic:\n\tint data;\n\tTNode* left;\n\tTNode* right;\n};\n\nTNode* newNode(int data);\n\n/* A function that constructs Balanced\nBinary Search Tree from a sorted array */\nTNode* sortArrayToBST(int arr[], int start, int end)\n{\n\t/* Base Case */\n\tif (start > end)\n\treturn NULL;\n\n\t/* Get the middle element and make it root */\n\tint mid = (start + end)/2;\n\tTNode *root = newNode(arr[mid]);\n\n\t/* Recursively construct the left subtree\n\tand make it left child of root */\n\troot->left = sortArrayToBST(arr, start, mid - 1);\n\n\t/* Recursively construct the right subtree\n\tand make it right child of root */\n\troot->right = sortArrayToBST(arr, mid + 1, end);\n\n\treturn root;\n}\n\n/* Helper function that allocates a new node\nwith the given data and NULL left and right\npointers. */\nTNode* newNode(int data)\n{\n\tTNode* node = new TNode();\n\tnode->data = data;\n\tnode->left = NULL;\n\tnode->right = NULL;\n\n\treturn node;\n}\n\n/* A utility function to print\npreorder traversal of BST */\nvoid preOrder(TNode* node)\n{\n\tif (node == NULL)\n\t\treturn;\n\tcout << node->data << \" \";\n\tpreOrder(node->left);\n\tpreOrder(node->right);\n}\n\n// Driver Code\nint main()\n{\n\tint n;\n\tcin>>n;\n\tint arr[n];\n\tfor(i=0;i<n:i++)\n\t{\n\t  cin>>arr;\n\t}\n\n\t/* Convert List to BST */\n\tTNode *root = sortArrayToBST(arr, 0, n-1);\n\tcout << \"PreOrder Traversal of constructed BST \\n\";\n\tpreOrder(root);\n\n\treturn 0;\n}\n"
  },
  {
    "path": "Algorithms/Tree/Sorted_Array_To_BST/SortedArrayToBST.java",
    "content": "class Node {\n     \n    int data;\n    Node left, right;\n     \n    Node(int d) {\n        data = d;\n        left = right = null;\n    }\n}\n \nclass BinaryTree {\n \n    Node sortedArrayToBST(int arr[], int start, int end) {\n \n        if (start > end) {\n            return null;\n        }\n \n        /* Get the middle element and make it root */\n        int mid = (start + end) / 2;\n        Node node = new Node(arr[mid]);\n \n        //Construct the left subtree and make it\n        //left child of root using recursion\n        node.left = sortedArrayToBST(arr, start, mid - 1);\n \n        //Construct the right subtree and make it\n        //right child of root using recursion\n        node.right = sortedArrayToBST(arr, mid + 1, end);\n         \n        return node;\n    }\n \n    //Print preorder traversal of BST \n    void preOrder(Node node) {\n        if (node == null) {\n            return;\n        }\n        System.out.print(node.data + \" \");\n        preOrder(node.left);\n        preOrder(node.right);\n    }\n}\n\npublic class SortedArrayToBST {\n\n\tpublic static void main(String[] args) {\n\t\t\n\t\tScanner sc = new Scanner(System.in);\n\n\t\t\tBinaryTree tree = new BinaryTree();\n\n\t\t\tSystem.out.println(\"Please Enter the Size of the Array:\");\n\t\t\tint n = sc.nextInt();\n\n\t\tint arr[] = new int[n];\n\n\t\tfor(int i=0; i<n; i++) {\n\t\t\tSystem.out.println(\"Enter Array element \" + (i+1) + \": \");\n\t\t\tarr[i] = sc.nextInt();\n\t\t}\n\n\t\tSystem.out.println(\"\\nProcessing Array....\");\n\t\tArrays.sort(arr);\n\t\tSystem.out.printf(\"Sorted Array -> %s \\n\", Arrays.toString(arr));\n\n\t\tSystem.out.println(\"\\nGenerating BST from Sorted Array....\");\n\t\tNode root = tree.sortedArrayToBST(arr, 0, n - 1);\n\n\t\tSystem.out.println(\"\\nPreorder traversal of generated BST\");\n\t\ttree.preOrder(root);\n    }\n}\n\n/* \n * OUTPUT=>\n * \n *  Please Enter the Size of the Array:\n *\t6\n *\tEnter Array element 1: \n *\t46\n *\tEnter Array element 2: \n *\t88\n *\tEnter Array element 3: \n *\t15\n *\tEnter Array element 4: \n *\t76\n *\tEnter Array element 5: \n *\t31\n *\tEnter Array element 6: \n *\t62\n *\t\n *\tProcessing Array....\n *\tSorted Array -> [15, 31, 46, 62, 76, 88] \n *\t\n *\tGenerating BST from Sorted Array....\n *\t\n *\tPreorder traversal of generated BST\n *\t46 15 31 76 62 88  \n * \n */\n\n"
  },
  {
    "path": "Algorithms/Tree/Validate_BST/Validate_BST.cpp",
    "content": "#include <iostream>\n#define MIN -1000\n#define MAX  1000\nusing namespace std;\n\n\n// helper structures and functions\nstruct node {\n\tstruct node * left;\n\tstruct node * right;\n\tint val;\n\tint maxTillNow;\n\tint minTillNow;\n\t\n\tnode(int k): val(k), left(NULL), right(NULL), maxTillNow(MIN), minTillNow(MAX) {}\n};\n\nint max(int a, int b){\n\treturn a > b  ? a : b;\n}\nint min(int a, int b){\n\treturn a < b  ? a : b;\n}\n\n\n\n\n\n\n\n// This method sets the min and max at each node // when the node represents a root of a subtree starting from that node\n// this a a resursive // dfs // implementation\nvoid setMaxMinTillNode( node * root){\n\tif(root == NULL){\n\t\treturn;\n\t}\n\t\n\tint ansMx = root->val;\n\tint ansMn = root->val;\n\t\n\tif( root->left != NULL){\n\t\tsetMaxMinTillNode(root->left);\n\t\tansMx = max(ansMx, root->left->maxTillNow);\n\t\tansMn = min(ansMn, root->left->minTillNow);\n\t}\n\t\n\tif( root->right != NULL){\n\t\tsetMaxMinTillNode(root->right);\n\t\tansMx = max(ansMx, root->right->maxTillNow);\n\t\tansMn = min(ansMn, root->right->minTillNow);\n\t}\n\t\n\troot->maxTillNow = ansMx; \n\troot->minTillNow = ansMn; \n}\n\n\n\n\n\n\n\n\n\n// this method checks the current node with the min of the right subtree and with the max of left subtree\n// the is a resursive // dfs // implementation \nbool isBST(node * root){\n\tif( root == NULL ){\n\t\tfalse;\n\t}\n\t\n\tif( root->left == NULL && root->right == NULL){\n\t\treturn true;\n\t}\n\t\n\tbool leftResult = true;\n\tif( root->left != NULL){\n\t\tif( root->val < root->left->maxTillNow){\n\t\t\tleftResult = false;\n\t\t\treturn leftResult;\n\t\t}\n\t\tleftResult = isBST(root->left);\n\t}\n\t\n\tbool rightResult = true;\n\tif( root->right != NULL){\n\t\tif( root->val > root->right->minTillNow){\n\t\t\trightResult = false;\n\t\t\treturn rightResult;\n\t\t}\n\t\trightResult = isBST(root->right);\n\t}\n\t\n\treturn leftResult && rightResult;\n}\n\n\n\n\n\n\n\n\n\n// this is the driver function\nint main() {\n\t// your code goes here\n\tnode * root = new node(4);\n\tnode * a = new node(1);\n\tnode * b = new node(2);\n\tnode * c = new node(3);\n\tnode * d = new node(5);\n\troot->left = b;\n\tb->left = a;\n\tb->right = c;\n\troot->right = d;\n\t\n\t\n\tsetMaxMinTillNode(root);\n\tcout << \"Is the Tree a Valid BST?  Ans:\" << ( isBST(root) ? \"yes :)\" : \"nops :(\") << endl;\n\t\n\n\tnode * e = new node(1);\n\td->right = e;\n\t\n\tsetMaxMinTillNode(root);\n\tcout << \"Is the Tree a Valid BST?  Ans:\" << ( isBST(root) ? \"yes :)\" : \"nops :(\") << endl;\n\t\n\t\n\t\n\te->val = 10;\n\t\n\tsetMaxMinTillNode(root);\n\tcout << \"Is the Tree a Valid BST?  Ans:\" << ( isBST(root) ? \"yes :)\" : \"nops :(\") << endl;\n\n\treturn 0;\n}\n"
  },
  {
    "path": "Algorithms/Tree/Validate_BST/Validate_BST.cs",
    "content": "using System;\n\ninternal class Node\n{\n    public int value;\n    public Node left, right;\n\n    public Node(int item)\n    {\n        value = item;\n        left = right = null;\n    }\n}\n\npublic class Validate_BST\n{\n    static bool IsBST(\n        Node node,\n        int currentMinimum = Int32.MinValue,\n        int currentMaximum = Int32.MaxValue)\n    {\n        if (node == null)\n        {\n            return true;\n        }\n\n        if (node.value < currentMinimum || node.value > currentMaximum)\n        {\n            return false;\n        }\n\n        return (IsBST(node.left, currentMinimum, node.value - 1) &&\n                IsBST(node.right, node.value + 1, currentMaximum));\n    }\n\n    public static void Main(string[] args)\n    {\n        Node treeRoot1 = new Node(7);\n        treeRoot1.left = new Node(5);\n        treeRoot1.right = new Node(8);\n        treeRoot1.left.left = new Node(4);\n        treeRoot1.left.right = new Node(6);\n        Console.WriteLine(IsBST(treeRoot1) ? \"This tree is a BST\" : \"This tree is not a BST\");\n\n        Node treeRoot2 = new Node(2);\n        treeRoot2.left = new Node(6);\n        treeRoot2.left.right = new Node(5);\n        treeRoot2.right = new Node(1);\n        treeRoot2.right.left = new Node(8);\n        treeRoot2.right.right = new Node(10);\n        Console.WriteLine(IsBST(treeRoot2) ? \"This tree is a BST\" : \"This tree is not a BST\");\n    }\n}\n"
  },
  {
    "path": "Algorithms/Tree/Validate_BST/Validate_BST.java",
    "content": "import java.util.*;\n\nclass Node {\n//class describing structure of the tree node\n  int value;\n  Node left;\n  Node right;\n  Node(int value) { \n    this.value = value; \n    left = right = null;\n    }\n }\n \n class Solution {\n //Recursive functions to determine whether given tree is valid BST or not\n    public boolean isValidBST(Node root) {\n        return helper(root,null,null);\n    }\n    public boolean helper(Node root, Integer small, Integer large) \n    {\n        if(root==null)\n            return true;\n        if(small!=null && root.val<=small)\n            return false;\n        if(large!=null && root.val>=large)\n            return false;\n        return helper(root.left,small,root.val) && helper(root.right,root.val,large);\n    }\n}\n\npublic class Validate_BST\n{\n//main class\n  public static void main(String[] args){\n        Scanner scanner = new Scanner(System.in);\n        Solution object = new Solution();\n        Node TreeRoot1 = new Node(10);\n        TreeRoot1.left = new Node(5);\n        TreeRoot1.right = new Node(12);\n        TreeRoot1.left.left = new Node(4);\n        TreeRoot1.left.right = new Node(6);\n        boolean answer1 = object.isValidBST(TreeRoot1);\n        if(answer1==true)\n          System.out.println(\"Tree is a valid BST\");\n        else\n          System.out.println(\"Tree is not a valid BST\");\n\n        Node TreeRoot2 = new Node(2);\n        TreeRoot2.left = new Node(6);\n        TreeRoot2.right = new Node(1);\n        TreeRoot2.left.right = new Node(5);\n        TreeRoot2.right.left = new Node(8);\n        TreeRoot2.right.right = new Node(11);\n        boolean answer2 = object.isValidBST(TreeRoot2);\n        if(answer2==true)\n          System.out.println(\"Tree is a valid BST\");\n        else\n          System.out.println(\"Tree is not a valid BST\");\n\n  }\n}\n"
  },
  {
    "path": "Algorithms/Tree/level_traversing/level_traversing.php",
    "content": "<?php \n\n class TreeNode {//Definition for binary tree node.\n      public $val = null;\n      public $left = null;\n      public $right = null;\n     function __construct($val = 0, $left = null, $right = null) {\n          $this->val = $val;\n          $this->left = $left;\n          $this->right = $right;\n      }\n  }\n\nclass Solution {//Recursive solution for level order traversal\n\n    /**\n     * @param TreeNode $root\n     * @return Integer[][]\n     */\n    function levelOrder($root) {\n        $res = [];\n        $level = 0;\n        $this->helper($root, $res, $level);\n        return $res;\n    }\n    \n    function helper($node, &$mainList, $level) {\n        if (is_null($node)) return;\n        $size = count($mainList);\n        if ($level > $size) {\n            $cur = array($node->val);\n            $mainList[$level] = $cur;\n        } else {\n            $mainList[$level][] = $node->val;\n        }\n\n        $this->helper($node->left, $mainList, $level+1);\n        $this->helper($node->right, $mainList, $level+1);\n        \n    }\n}\n?>\n"
  },
  {
    "path": "Algorithms/Tree/level_traversing/level_traversing.py",
    "content": "# author: Karthik Hegde\n# date: 2/10/2021\n# Level order traversal on BST implementation in python\n\n\nfrom collections import deque\nfrom typing import List, Optional\nimport sys\n\n\n#Definition for a binary tree node.\nclass TreeNode:\n    def __init__(self, val=0, left=None, right=None):\n        self.val = val\n        self.left = left\n        self.right = right\n\n\ndef levelOrder(root: TreeNode) -> List[List[int]]:\n    traversal = []\n    if not root: # if root doesn't exist\n        return traversal\n\n    queue = deque([root])\n    # level order traversal\n\n    while(queue):\n        level_lst =[]\n        queue_len = len(queue)\n\n        for i in range(queue_len):\n            node = queue.popleft()\n            print(node.val)\n            level_lst.append(node.val)\n            \n            if (node.left): # if node.left exists\n                queue.append(node.left)\n            \n            if (node.right): # if node.right exists\n                queue.append(node.right)\n                \n        traversal.append(level_lst)        \n        \n    return traversal\n\n\n## ---- taking input and running -----###\n\ndef recurse_input(i, node_lst):\n    if (i>=len(node_lst) or node_lst[i]=='None'):\n        return None\n    \n    root = TreeNode(int(node_lst[i]))\n    root.left = recurse_input(2*i+1, node_lst)\n    root.right = recurse_input(2*i+2, node_lst)\n\n    return root\n\ndef run():\n    ## as input pls give a list of ints \n    # in the input list, children of element at index i are elements at 2*i + 1 and 2*i + 2\n    # if particular node is null, type None\n    # example input: 0 1 2 None 5 6 None None None 8\n\n    '''\n         0\n        / \\\n      1     2\n      /\\    / \n        5  6\n        /\n        8\n    '''\n\n    node_lst = sys.stdin.readline().split()\n    root = recurse_input(0, node_lst)\n\n    lst = levelOrder(root)\n    print(lst)\n\nif __name__ == \"__main__\":\n    run()\n"
  },
  {
    "path": "CNAME",
    "content": "dsa.ahampriyanshu.com"
  },
  {
    "path": "CODE_OF_CONDUCT.md",
    "content": "# Contributor Covenant Code of Conduct\n\n## Our Pledge\n\nIn the interest of fostering an open and welcoming environment, we as\ncontributors and maintainers pledge to making participation in our project and\nour community a harassment-free experience for everyone, regardless of age, body\nsize, disability, ethnicity, sex characteristics, gender identity and expression,\nlevel of experience, education, socio-economic status, nationality, personal\nappearance, race, religion, or sexual identity and orientation.\n\n## Our Standards\n\nExamples of behavior that contributes to creating a positive environment\ninclude:\n\n* Using welcoming and inclusive language\n* Being respectful of differing viewpoints and experiences\n* Gracefully accepting constructive criticism\n* Focusing on what is best for the community\n* Showing empathy towards other community members\n\nExamples of unacceptable behavior by participants include:\n\n* The use of sexualized language or imagery and unwelcome sexual attention or\n advances\n* Trolling, insulting/derogatory comments, and personal or political attacks\n* Public or private harassment\n* Publishing others' private information, such as a physical or electronic\n address, without explicit permission\n* Other conduct which could reasonably be considered inappropriate in a\n professional setting\n\n## Our Responsibilities\n\nProject maintainers are responsible for clarifying the standards of acceptable\nbehavior and are expected to take appropriate and fair corrective action in\nresponse to any instances of unacceptable behavior.\n\nProject maintainers have the right and responsibility to remove, edit, or\nreject comments, commits, code, wiki edits, issues, and other contributions\nthat are not aligned to this Code of Conduct, or to ban temporarily or\npermanently any contributor for other behaviors that they deem inappropriate,\nthreatening, offensive, or harmful.\n\n## Scope\n\nThis Code of Conduct applies both within project spaces and in public spaces\nwhen an individual is representing the project or its community. Examples of\nrepresenting a project or community include using an official project e-mail\naddress, posting via an official social media account, or acting as an appointed\nrepresentative at an online or offline event. Representation of a project may be\nfurther defined and clarified by project maintainers.\n\n## Enforcement\n\nInstances of abusive, harassing, or otherwise unacceptable behavior may be\nreported by contacting the project team at ahampriyanshu@gmail.com. All\ncomplaints will be reviewed and investigated and will result in a response that\nis deemed necessary and appropriate to the circumstances. The project team is\nobligated to maintain confidentiality with regard to the reporter of an incident.\nFurther details of specific enforcement policies may be posted separately.\n\nProject maintainers who do not follow or enforce the Code of Conduct in good\nfaith may face temporary or permanent repercussions as determined by other\nmembers of the project's leadership.\n\n## Attribution\n\nThis Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,\navailable at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html\n\n[homepage]: https://www.contributor-covenant.org\n\nFor answers to common questions about this code of conduct, see\nhttps://www.contributor-covenant.org/faq\n"
  },
  {
    "path": "CONTRIBUTING.md",
    "content": "# Contributing Guidelines\n\n## Naming Convention\n\n* Title Case (not camel case, lowercase or uppercase)\n*  ``-`` or no-space in between the words (not ``_`` , whitespace, or anything else)\n\n| Example | |\n|-- |--\n| heapsort.cpp  | ❌\n| Heap-sort.cpp | ❌\n| heap_sort.cpp | ❌\n| heap sort.cpp | ❌❌❌\n| Heap-Sort.cpp | ✅\n| HeapSort.cpp  | ✅\n\n## Here are some suggestions you should be following while contributing to this repository:\n\n* Always verify if the issue you wish to create already exists or not.\n* Ask for the issue that you plan to complete.\n* Commit message should be of the stated syntax.\n* Do not commit multiple files.\n* In ``algorithms`` always commit programs that take dynamic input and more preferably through stdin over reading a file.\n* When naming the functions or variables use meaningfull name instead of a1,a2,a3.\n* Every PR would be reviewed before it gets merged."
  },
  {
    "path": "CONTRIBUTORS.md",
    "content": "### Contributors\n\n<table>\n<tr>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/ahampriyanshu>\n            <img src=https://avatars.githubusercontent.com/u/54521023?v=4 width=\"100;\"  alt=Priyanshu Tiwari/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Priyanshu Tiwari</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/Vimlesh-Kumar>\n            <img src=https://avatars.githubusercontent.com/u/53998024?v=4 width=\"100;\"  alt=Vimlesh Kumar/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Vimlesh Kumar</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/Nirali0029>\n            <img src=https://avatars.githubusercontent.com/u/58932139?v=4 width=\"100;\"  alt=Nirali Sanghvi/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Nirali Sanghvi</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/Mr-Vaibhav-Shukla>\n            <img src=https://avatars.githubusercontent.com/u/54389264?v=4 width=\"100;\"  alt=Vaibhav Shukla/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Vaibhav Shukla</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/p-davide>\n            <img src=https://avatars.githubusercontent.com/u/52355319?v=4 width=\"100;\"  alt=p-davide/>\n            <br />\n            <sub style=\"font-size:14px\"><b>p-davide</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/chinmaym07>\n            <img src=https://avatars.githubusercontent.com/u/44670961?v=4 width=\"100;\"  alt=Chinmay Mehta/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Chinmay Mehta</b></sub>\n        </a>\n    </td>\n</tr>\n<tr>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/JayantGoel001>\n            <img src=https://avatars.githubusercontent.com/u/54479676?v=4 width=\"100;\"  alt=Jayant Goel/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Jayant Goel</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/monishamandal02>\n            <img src=https://avatars.githubusercontent.com/u/56168558?v=4 width=\"100;\"  alt=MONISHA MANDAL/>\n            <br />\n            <sub style=\"font-size:14px\"><b>MONISHA MANDAL</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/Astrogeek77>\n            <img src=https://avatars.githubusercontent.com/u/54165628?v=4 width=\"100;\"  alt=Gautam Jain/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Gautam Jain</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/subham5230>\n            <img src=https://avatars.githubusercontent.com/u/65271698?v=4 width=\"100;\"  alt=Subham Mohanty/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Subham Mohanty</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/huisenbr>\n            <img src=https://avatars.githubusercontent.com/u/55811776?v=4 width=\"100;\"  alt=huisenbr/>\n            <br />\n            <sub style=\"font-size:14px\"><b>huisenbr</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/Samkit-shah>\n            <img src=https://avatars.githubusercontent.com/u/65543606?v=4 width=\"100;\"  alt=Samkit Shah/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Samkit Shah</b></sub>\n        </a>\n    </td>\n</tr>\n<tr>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/aakashsoni-cloud>\n            <img src=https://avatars.githubusercontent.com/u/56084559?v=4 width=\"100;\"  alt=Aakash Deep Soni/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Aakash Deep Soni</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/realvaibhav>\n            <img src=https://avatars.githubusercontent.com/u/56718659?v=4 width=\"100;\"  alt=Vaibhav Sharma/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Vaibhav Sharma</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/AnshMishra2001>\n            <img src=https://avatars.githubusercontent.com/u/55917516?v=4 width=\"100;\"  alt=Anshmish/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Anshmish</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/belphegor-s>\n            <img src=https://avatars.githubusercontent.com/u/65305602?v=4 width=\"100;\"  alt=Ayush Sharma/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Ayush Sharma</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/dicieous>\n            <img src=https://avatars.githubusercontent.com/u/54718365?v=4 width=\"100;\"  alt=Happy singh/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Happy singh</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/Mr-Destructive>\n            <img src=https://avatars.githubusercontent.com/u/40317114?v=4 width=\"100;\"  alt=Meet Rajesh Gor/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Meet Rajesh Gor</b></sub>\n        </a>\n    </td>\n</tr>\n<tr>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/abkabd>\n            <img src=https://avatars.githubusercontent.com/u/35420737?v=4 width=\"100;\"  alt=abkabd/>\n            <br />\n            <sub style=\"font-size:14px\"><b>abkabd</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/manvendra3>\n            <img src=https://avatars.githubusercontent.com/u/60265986?v=4 width=\"100;\"  alt=manvendra3/>\n            <br />\n            <sub style=\"font-size:14px\"><b>manvendra3</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/architgarg603>\n            <img src=https://avatars.githubusercontent.com/u/57831888?v=4 width=\"100;\"  alt=Archit garg/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Archit garg</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/atorr5555>\n            <img src=https://avatars.githubusercontent.com/u/31078782?v=4 width=\"100;\"  alt=Antonio Torres/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Antonio Torres</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/Deepak2417>\n            <img src=https://avatars.githubusercontent.com/u/71579689?v=4 width=\"100;\"  alt=Deepak2417/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Deepak2417</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/Harshalszz>\n            <img src=https://avatars.githubusercontent.com/u/61976596?v=4 width=\"100;\"  alt=Harshal S Zodape />\n            <br />\n            <sub style=\"font-size:14px\"><b>Harshal S Zodape </b></sub>\n        </a>\n    </td>\n</tr>\n<tr>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/mk1107>\n            <img src=https://avatars.githubusercontent.com/u/55909616?v=4 width=\"100;\"  alt=Mohanish Kashiwar/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Mohanish Kashiwar</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/Pratik-Sanghavi>\n            <img src=https://avatars.githubusercontent.com/u/64033247?v=4 width=\"100;\"  alt=Pratik Sanghavi/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Pratik Sanghavi</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/Rudransh24>\n            <img src=https://avatars.githubusercontent.com/u/55325635?v=4 width=\"100;\"  alt=Rudransh24/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Rudransh24</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/shristi428>\n            <img src=https://avatars.githubusercontent.com/u/42990196?v=4 width=\"100;\"  alt=Shristi Negi/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Shristi Negi</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/Toulik-Das>\n            <img src=https://avatars.githubusercontent.com/u/39211262?v=4 width=\"100;\"  alt=Toulik Das/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Toulik Das</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/adaugochi>\n            <img src=https://avatars.githubusercontent.com/u/43061141?v=4 width=\"100;\"  alt=Adaa Mgbede/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Adaa Mgbede</b></sub>\n        </a>\n    </td>\n</tr>\n<tr>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/hanyangl>\n            <img src=https://avatars.githubusercontent.com/u/51980145?v=4 width=\"100;\"  alt=hanyangl/>\n            <br />\n            <sub style=\"font-size:14px\"><b>hanyangl</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/264pranjal>\n            <img src=https://avatars.githubusercontent.com/u/37728750?v=4 width=\"100;\"  alt=Pranjal Agrawal/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Pranjal Agrawal</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/shadab-me>\n            <img src=https://avatars.githubusercontent.com/u/38420725?v=4 width=\"100;\"  alt=Shadab Ali/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Shadab Ali</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/esheetaparulekar>\n            <img src=https://avatars.githubusercontent.com/u/64092444?v=4 width=\"100;\"  alt=esheetaparulekar/>\n            <br />\n            <sub style=\"font-size:14px\"><b>esheetaparulekar</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/ThomasBiede>\n            <img src=https://avatars.githubusercontent.com/u/40736712?v=4 width=\"100;\"  alt=Thomas Biedermann/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Thomas Biedermann</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/manishita24>\n            <img src=https://avatars.githubusercontent.com/u/60927308?v=4 width=\"100;\"  alt=Manishita Choudhary/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Manishita Choudhary</b></sub>\n        </a>\n    </td>\n</tr>\n<tr>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/SuperAayush>\n            <img src=https://avatars.githubusercontent.com/u/78820926?v=4 width=\"100;\"  alt=Aayush Sharma/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Aayush Sharma</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/Prodip-Kumar-Paul>\n            <img src=https://avatars.githubusercontent.com/u/71282021?v=4 width=\"100;\"  alt=Prodip Kumar Paul/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Prodip Kumar Paul</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/tanuj1811>\n            <img src=https://avatars.githubusercontent.com/u/54256549?v=4 width=\"100;\"  alt=Tanuj Sharma/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Tanuj Sharma</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/sanjiti0606>\n            <img src=https://avatars.githubusercontent.com/u/44472481?v=4 width=\"100;\"  alt=sanjiti0606/>\n            <br />\n            <sub style=\"font-size:14px\"><b>sanjiti0606</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/0x6f736f646f>\n            <img src=https://avatars.githubusercontent.com/u/28790446?v=4 width=\"100;\"  alt=b1ackd0t/>\n            <br />\n            <sub style=\"font-size:14px\"><b>b1ackd0t</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/SoundaryaKhanapur>\n            <img src=https://avatars.githubusercontent.com/u/36791174?v=4 width=\"100;\"  alt=Soundarya Khanapur/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Soundarya Khanapur</b></sub>\n        </a>\n    </td>\n</tr>\n<tr>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/vaishnavyogesh>\n            <img src=https://avatars.githubusercontent.com/u/54815584?v=4 width=\"100;\"  alt=Yogesh Vaishnav/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Yogesh Vaishnav</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/g-jindal2001>\n            <img src=https://avatars.githubusercontent.com/u/54766681?v=4 width=\"100;\"  alt=Geetansh Jindal/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Geetansh Jindal</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/BYZANTINE26>\n            <img src=https://avatars.githubusercontent.com/u/62672863?v=4 width=\"100;\"  alt=BYZANTINE26/>\n            <br />\n            <sub style=\"font-size:14px\"><b>BYZANTINE26</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/Aarti002>\n            <img src=https://avatars.githubusercontent.com/u/70666307?v=4 width=\"100;\"  alt=Aarti singh/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Aarti singh</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/abhinav-idle>\n            <img src=https://avatars.githubusercontent.com/u/62979241?v=4 width=\"100;\"  alt=Abhinav Tiwari/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Abhinav Tiwari</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/Aj12345616>\n            <img src=https://avatars.githubusercontent.com/u/68468062?v=4 width=\"100;\"  alt=Akshat Jain/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Akshat Jain</b></sub>\n        </a>\n    </td>\n</tr>\n<tr>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/Dkgiri619>\n            <img src=https://avatars.githubusercontent.com/u/43544067?v=4 width=\"100;\"  alt=Deepak Kumar Giri/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Deepak Kumar Giri</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/meghna25>\n            <img src=https://avatars.githubusercontent.com/u/59365740?v=4 width=\"100;\"  alt=Meghna Saxena/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Meghna Saxena</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/rahulsunil2>\n            <img src=https://avatars.githubusercontent.com/u/22911414?v=4 width=\"100;\"  alt=Rahul Sunil/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Rahul Sunil</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/rushitote>\n            <img src=https://avatars.githubusercontent.com/u/31135699?v=4 width=\"100;\"  alt=Rushikesh Tote/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Rushikesh Tote</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/Dutta-SD>\n            <img src=https://avatars.githubusercontent.com/u/57990650?v=4 width=\"100;\"  alt=Sandip Dutta/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Sandip Dutta</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/Sanika1999>\n            <img src=https://avatars.githubusercontent.com/u/51399803?v=4 width=\"100;\"  alt=Sanika/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Sanika</b></sub>\n        </a>\n    </td>\n</tr>\n<tr>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/Sidj581>\n            <img src=https://avatars.githubusercontent.com/u/72346771?v=4 width=\"100;\"  alt=Sidj581/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Sidj581</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/yashsharma8415>\n            <img src=https://avatars.githubusercontent.com/u/65597694?v=4 width=\"100;\"  alt=Yash Sharma/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Yash Sharma</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/harlansgs>\n            <img src=https://avatars.githubusercontent.com/u/70712183?v=4 width=\"100;\"  alt=harlansgs/>\n            <br />\n            <sub style=\"font-size:14px\"><b>harlansgs</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/LDiazN>\n            <img src=https://avatars.githubusercontent.com/u/41093870?v=4 width=\"100;\"  alt=Luis Diaz/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Luis Diaz</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/JayavardhaniKathika>\n            <img src=https://avatars.githubusercontent.com/u/53208676?v=4 width=\"100;\"  alt=JayavardhaniKathika/>\n            <br />\n            <sub style=\"font-size:14px\"><b>JayavardhaniKathika</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/arron-tij>\n            <img src=https://avatars.githubusercontent.com/u/40382117?v=4 width=\"100;\"  alt=Ronit Raj/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Ronit Raj</b></sub>\n        </a>\n    </td>\n</tr>\n<tr>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/jayanta007>\n            <img src=https://avatars.githubusercontent.com/u/13706523?v=4 width=\"100;\"  alt=Jayanta Saren/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Jayanta Saren</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/AlessandroArosio>\n            <img src=https://avatars.githubusercontent.com/u/28343603?v=4 width=\"100;\"  alt=Alessandro Arosio/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Alessandro Arosio</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/DanielVip3>\n            <img src=https://avatars.githubusercontent.com/u/36603306?v=4 width=\"100;\"  alt=Daniele De Martino/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Daniele De Martino</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/iamHrithikRaj>\n            <img src=https://avatars.githubusercontent.com/u/50907893?v=4 width=\"100;\"  alt=Hrithik Raj/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Hrithik Raj</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/Jaswantsinghh>\n            <img src=https://avatars.githubusercontent.com/u/54163759?v=4 width=\"100;\"  alt=Jaswant Singh/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Jaswant Singh</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/KKghub>\n            <img src=https://avatars.githubusercontent.com/u/25261656?v=4 width=\"100;\"  alt=KKghub/>\n            <br />\n            <sub style=\"font-size:14px\"><b>KKghub</b></sub>\n        </a>\n    </td>\n</tr>\n<tr>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/rachleona>\n            <img src=https://avatars.githubusercontent.com/u/34417799?v=4 width=\"100;\"  alt=Rachel Leona/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Rachel Leona</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/rezwan2525>\n            <img src=https://avatars.githubusercontent.com/u/30120066?v=4 width=\"100;\"  alt=Rezwan Al Kaoser/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Rezwan Al Kaoser</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/Vivek-Raman>\n            <img src=https://avatars.githubusercontent.com/u/32368598?v=4 width=\"100;\"  alt=Vivek Raman/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Vivek Raman</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/ukitta555>\n            <img src=https://avatars.githubusercontent.com/u/37906830?v=4 width=\"100;\"  alt=Vladyslav Nekriach/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Vladyslav Nekriach</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/anshupatel06>\n            <img src=https://avatars.githubusercontent.com/u/72225878?v=4 width=\"100;\"  alt=anshupatel06/>\n            <br />\n            <sub style=\"font-size:14px\"><b>anshupatel06</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/cuber485>\n            <img src=https://avatars.githubusercontent.com/u/57671649?v=4 width=\"100;\"  alt=cuber485/>\n            <br />\n            <sub style=\"font-size:14px\"><b>cuber485</b></sub>\n        </a>\n    </td>\n</tr>\n<tr>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/harshita-sharma11>\n            <img src=https://avatars.githubusercontent.com/u/72275553?v=4 width=\"100;\"  alt=harshita-sharma11/>\n            <br />\n            <sub style=\"font-size:14px\"><b>harshita-sharma11</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/rhea2801>\n            <img src=https://avatars.githubusercontent.com/u/52540852?v=4 width=\"100;\"  alt=Rhea/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Rhea</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/taresh18>\n            <img src=https://avatars.githubusercontent.com/u/58368119?v=4 width=\"100;\"  alt=taresh18/>\n            <br />\n            <sub style=\"font-size:14px\"><b>taresh18</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/crew-guy>\n            <img src=https://avatars.githubusercontent.com/u/69717009?v=4 width=\"100;\"  alt=Ankit Sanghvi/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Ankit Sanghvi</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/M4rkoHR>\n            <img src=https://avatars.githubusercontent.com/u/31570481?v=4 width=\"100;\"  alt=Marko/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Marko</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/git12121>\n            <img src=https://avatars.githubusercontent.com/u/28541089?v=4 width=\"100;\"  alt=git12121/>\n            <br />\n            <sub style=\"font-size:14px\"><b>git12121</b></sub>\n        </a>\n    </td>\n</tr>\n<tr>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/Amulya-coder>\n            <img src=https://avatars.githubusercontent.com/u/66437295?v=4 width=\"100;\"  alt=Amulya/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Amulya</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/Heisenberg-Vardan>\n            <img src=https://avatars.githubusercontent.com/u/55507414?v=4 width=\"100;\"  alt=Vardan Narula/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Vardan Narula</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/AjinkyaSahu>\n            <img src=https://avatars.githubusercontent.com/u/65594598?v=4 width=\"100;\"  alt=AjinkyaSahu/>\n            <br />\n            <sub style=\"font-size:14px\"><b>AjinkyaSahu</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/arihantbansal>\n            <img src=https://avatars.githubusercontent.com/u/17180950?v=4 width=\"100;\"  alt=Arihant Bansal/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Arihant Bansal</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/DIV1SINGH>\n            <img src=https://avatars.githubusercontent.com/u/72353222?v=4 width=\"100;\"  alt=DIV1SINGH/>\n            <br />\n            <sub style=\"font-size:14px\"><b>DIV1SINGH</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/danrockdave>\n            <img src=https://avatars.githubusercontent.com/u/29715116?v=4 width=\"100;\"  alt=Davi Fontenele/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Davi Fontenele</b></sub>\n        </a>\n    </td>\n</tr>\n<tr>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/Diadochokinetic>\n            <img src=https://avatars.githubusercontent.com/u/45292173?v=4 width=\"100;\"  alt=Diadochokinetic/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Diadochokinetic</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/beccadaniel>\n            <img src=https://avatars.githubusercontent.com/u/19220215?v=4 width=\"100;\"  alt=Folashade/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Folashade</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/mhimanshu712>\n            <img src=https://avatars.githubusercontent.com/u/41316051?v=4 width=\"100;\"  alt=Himanshu Mishra/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Himanshu Mishra</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/khusboobothra>\n            <img src=https://avatars.githubusercontent.com/u/59091399?v=4 width=\"100;\"  alt=Khusboo Bothra/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Khusboo Bothra</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/Krishna3102>\n            <img src=https://avatars.githubusercontent.com/u/57854052?v=4 width=\"100;\"  alt=Krishna Kumar/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Krishna Kumar</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/lashewi>\n            <img src=https://avatars.githubusercontent.com/u/27916115?v=4 width=\"100;\"  alt=Lakshitha Wisumperuma/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Lakshitha Wisumperuma</b></sub>\n        </a>\n    </td>\n</tr>\n<tr>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/kushkamisha>\n            <img src=https://avatars.githubusercontent.com/u/22060090?v=4 width=\"100;\"  alt=Misha Kushka/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Misha Kushka</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/nehalgupta8501>\n            <img src=https://avatars.githubusercontent.com/u/61117568?v=4 width=\"100;\"  alt=Nehal Gupta/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Nehal Gupta</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/sachinjindal01>\n            <img src=https://avatars.githubusercontent.com/u/45817023?v=4 width=\"100;\"  alt=Sachin Jindal/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Sachin Jindal</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/Tusharsd123>\n            <img src=https://avatars.githubusercontent.com/u/44468541?v=4 width=\"100;\"  alt=Tushar Diwakar/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Tushar Diwakar</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/vikkastiwari>\n            <img src=https://avatars.githubusercontent.com/u/51874681?v=4 width=\"100;\"  alt=Vikas Tiwari/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Vikas Tiwari</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/VishwaroopShah>\n            <img src=https://avatars.githubusercontent.com/u/40748423?v=4 width=\"100;\"  alt=VishwaroopShah/>\n            <br />\n            <sub style=\"font-size:14px\"><b>VishwaroopShah</b></sub>\n        </a>\n    </td>\n</tr>\n<tr>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/adrputra>\n            <img src=https://avatars.githubusercontent.com/u/56150878?v=4 width=\"100;\"  alt=adrputra/>\n            <br />\n            <sub style=\"font-size:14px\"><b>adrputra</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/aishuo07>\n            <img src=https://avatars.githubusercontent.com/u/45160006?v=4 width=\"100;\"  alt=aishuo07/>\n            <br />\n            <sub style=\"font-size:14px\"><b>aishuo07</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/betsystevens>\n            <img src=https://avatars.githubusercontent.com/u/8739700?v=4 width=\"100;\"  alt=Betsy Stevens/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Betsy Stevens</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/firehawk23>\n            <img src=https://avatars.githubusercontent.com/u/53555104?v=4 width=\"100;\"  alt=Sai Suraj/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Sai Suraj</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/GerardoUbuntu>\n            <img src=https://avatars.githubusercontent.com/u/23072832?v=4 width=\"100;\"  alt=Gerardo A. Abantao Jr./>\n            <br />\n            <sub style=\"font-size:14px\"><b>Gerardo A. Abantao Jr.</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/nikhiltanna>\n            <img src=https://avatars.githubusercontent.com/u/46378893?v=4 width=\"100;\"  alt=nikhiltanna/>\n            <br />\n            <sub style=\"font-size:14px\"><b>nikhiltanna</b></sub>\n        </a>\n    </td>\n</tr>\n<tr>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/prajwlr>\n            <img src=https://avatars.githubusercontent.com/u/35843440?v=4 width=\"100;\"  alt=prajwlr/>\n            <br />\n            <sub style=\"font-size:14px\"><b>prajwlr</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/rebelfire888>\n            <img src=https://avatars.githubusercontent.com/u/55150908?v=4 width=\"100;\"  alt=rebelfire888/>\n            <br />\n            <sub style=\"font-size:14px\"><b>rebelfire888</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/uV3301>\n            <img src=https://avatars.githubusercontent.com/u/43047036?v=4 width=\"100;\"  alt=Yuvraj Singh/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Yuvraj Singh</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/juneadkhan>\n            <img src=https://avatars.githubusercontent.com/u/54591708?v=4 width=\"100;\"  alt=Junead Khan/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Junead Khan</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/parth93QA>\n            <img src=https://avatars.githubusercontent.com/u/55730488?v=4 width=\"100;\"  alt=parthzz/>\n            <br />\n            <sub style=\"font-size:14px\"><b>parthzz</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/raazanand>\n            <img src=https://avatars.githubusercontent.com/u/88097156?v=4 width=\"100;\"  alt=Raj Anand/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Raj Anand</b></sub>\n        </a>\n    </td>\n</tr>\n<tr>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/PrakashAditya17>\n            <img src=https://avatars.githubusercontent.com/u/48592289?v=4 width=\"100;\"  alt=Aditya Prakash/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Aditya Prakash</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/adrikagupta>\n            <img src=https://avatars.githubusercontent.com/u/55001132?v=4 width=\"100;\"  alt=Adrika />\n            <br />\n            <sub style=\"font-size:14px\"><b>Adrika </b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/appsx13>\n            <img src=https://avatars.githubusercontent.com/u/40395283?v=4 width=\"100;\"  alt=Apoorva/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Apoorva</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/aa-ryan>\n            <img src=https://avatars.githubusercontent.com/u/61882780?v=4 width=\"100;\"  alt=Aryan/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Aryan</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/Avninder99>\n            <img src=https://avatars.githubusercontent.com/u/53931646?v=4 width=\"100;\"  alt=Avninder Preet Singh/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Avninder Preet Singh</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/daviddavo>\n            <img src=https://avatars.githubusercontent.com/u/10263941?v=4 width=\"100;\"  alt=David Davó/>\n            <br />\n            <sub style=\"font-size:14px\"><b>David Davó</b></sub>\n        </a>\n    </td>\n</tr>\n<tr>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/dwij2212>\n            <img src=https://avatars.githubusercontent.com/u/55494681?v=4 width=\"100;\"  alt=Dwij Mehta/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Dwij Mehta</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/gamezcua1>\n            <img src=https://avatars.githubusercontent.com/u/27114469?v=4 width=\"100;\"  alt=Gerald Amezcua />\n            <br />\n            <sub style=\"font-size:14px\"><b>Gerald Amezcua </b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/hansholani>\n            <img src=https://avatars.githubusercontent.com/u/69589823?v=4 width=\"100;\"  alt=Hans Holani/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Hans Holani</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/Mrsterius>\n            <img src=https://avatars.githubusercontent.com/u/7753768?v=4 width=\"100;\"  alt=Himanshu Hansaria/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Himanshu Hansaria</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/jkendall327>\n            <img src=https://avatars.githubusercontent.com/u/68479543?v=4 width=\"100;\"  alt=Jack Kendall/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Jack Kendall</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/snehaa1989>\n            <img src=https://avatars.githubusercontent.com/u/61073116?v=4 width=\"100;\"  alt=KNVS Sai Sneha/>\n            <br />\n            <sub style=\"font-size:14px\"><b>KNVS Sai Sneha</b></sub>\n        </a>\n    </td>\n</tr>\n<tr>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/Kadermiyanyedi>\n            <img src=https://avatars.githubusercontent.com/u/48386782?v=4 width=\"100;\"  alt=Kader M./>\n            <br />\n            <sub style=\"font-size:14px\"><b>Kader M.</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/KamalAres>\n            <img src=https://avatars.githubusercontent.com/u/53576033?v=4 width=\"100;\"  alt=KamalAres/>\n            <br />\n            <sub style=\"font-size:14px\"><b>KamalAres</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/LUCIFER-dev-king>\n            <img src=https://avatars.githubusercontent.com/u/51146796?v=4 width=\"100;\"  alt=Nihal Ahamed />\n            <br />\n            <sub style=\"font-size:14px\"><b>Nihal Ahamed </b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/Mihir2527>\n            <img src=https://avatars.githubusercontent.com/u/66313569?v=4 width=\"100;\"  alt=Mihir Mahajani/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Mihir Mahajani</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/Mikadore>\n            <img src=https://avatars.githubusercontent.com/u/35429782?v=4 width=\"100;\"  alt=Mikadore/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Mikadore</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/nayanika0208>\n            <img src=https://avatars.githubusercontent.com/u/38004490?v=4 width=\"100;\"  alt=Nayanika/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Nayanika</b></sub>\n        </a>\n    </td>\n</tr>\n<tr>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/reyadkhan>\n            <img src=https://avatars.githubusercontent.com/u/13221780?v=4 width=\"100;\"  alt=Reyad Khan/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Reyad Khan</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/Sachin19k>\n            <img src=https://avatars.githubusercontent.com/u/91717088?v=4 width=\"100;\"  alt=Sachin19k/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Sachin19k</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/Sayantan-world>\n            <img src=https://avatars.githubusercontent.com/u/16864511?v=4 width=\"100;\"  alt=Sayantan Pal/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Sayantan Pal</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/baniksudipto>\n            <img src=https://avatars.githubusercontent.com/u/20445189?v=4 width=\"100;\"  alt=Sudipta Banik/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Sudipta Banik</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/ulieckstein>\n            <img src=https://avatars.githubusercontent.com/u/4375295?v=4 width=\"100;\"  alt=ulieckstein/>\n            <br />\n            <sub style=\"font-size:14px\"><b>ulieckstein</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/vrinda22>\n            <img src=https://avatars.githubusercontent.com/u/43755279?v=4 width=\"100;\"  alt=VRINDA GOYAL/>\n            <br />\n            <sub style=\"font-size:14px\"><b>VRINDA GOYAL</b></sub>\n        </a>\n    </td>\n</tr>\n<tr>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/jytaloramon>\n            <img src=https://avatars.githubusercontent.com/u/27650282?v=4 width=\"100;\"  alt=J.Y. Ramon Almeida G. />\n            <br />\n            <sub style=\"font-size:14px\"><b>J.Y. Ramon Almeida G. </b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/aanneettgg>\n            <img src=https://avatars.githubusercontent.com/u/54851318?v=4 width=\"100;\"  alt=aanneettgg/>\n            <br />\n            <sub style=\"font-size:14px\"><b>aanneettgg</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/bobbysaprey420>\n            <img src=https://avatars.githubusercontent.com/u/40564214?v=4 width=\"100;\"  alt=bobbysaprey420/>\n            <br />\n            <sub style=\"font-size:14px\"><b>bobbysaprey420</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/codewithrathi>\n            <img src=https://avatars.githubusercontent.com/u/91717327?v=4 width=\"100;\"  alt=Aarti Rathi/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Aarti Rathi</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/bharatchhipa>\n            <img src=https://avatars.githubusercontent.com/u/36991847?v=4 width=\"100;\"  alt=bharatchhipa/>\n            <br />\n            <sub style=\"font-size:14px\"><b>bharatchhipa</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/SayaniG371>\n            <img src=https://avatars.githubusercontent.com/u/55864408?v=4 width=\"100;\"  alt=SayaniG371/>\n            <br />\n            <sub style=\"font-size:14px\"><b>SayaniG371</b></sub>\n        </a>\n    </td>\n</tr>\n<tr>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/deepdhar>\n            <img src=https://avatars.githubusercontent.com/u/53803245?v=4 width=\"100;\"  alt=Deep Dhar/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Deep Dhar</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/DHTALAN>\n            <img src=https://avatars.githubusercontent.com/u/91721897?v=4 width=\"100;\"  alt=DHTALAN/>\n            <br />\n            <sub style=\"font-size:14px\"><b>DHTALAN</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/harshitashankar>\n            <img src=https://avatars.githubusercontent.com/u/68508399?v=4 width=\"100;\"  alt=harshitashankar/>\n            <br />\n            <sub style=\"font-size:14px\"><b>harshitashankar</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/hemangdtu>\n            <img src=https://avatars.githubusercontent.com/u/55807508?v=4 width=\"100;\"  alt=Hemang Sinha/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Hemang Sinha</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/julianasinai>\n            <img src=https://avatars.githubusercontent.com/u/38883336?v=4 width=\"100;\"  alt=Juliana Sinai/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Juliana Sinai</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/lucid-dreem>\n            <img src=https://avatars.githubusercontent.com/u/59326141?v=4 width=\"100;\"  alt=lucid-dreem/>\n            <br />\n            <sub style=\"font-size:14px\"><b>lucid-dreem</b></sub>\n        </a>\n    </td>\n</tr>\n<tr>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/maityankan10>\n            <img src=https://avatars.githubusercontent.com/u/56226421?v=4 width=\"100;\"  alt=maityankan10/>\n            <br />\n            <sub style=\"font-size:14px\"><b>maityankan10</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/marioa98>\n            <img src=https://avatars.githubusercontent.com/u/33180745?v=4 width=\"100;\"  alt=Mario Martinez/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Mario Martinez</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/rohanBrid18>\n            <img src=https://avatars.githubusercontent.com/u/40038755?v=4 width=\"100;\"  alt=Rohan Brid/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Rohan Brid</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/sbhavya18>\n            <img src=https://avatars.githubusercontent.com/u/54139395?v=4 width=\"100;\"  alt=sbhavya18/>\n            <br />\n            <sub style=\"font-size:14px\"><b>sbhavya18</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/utkarshgupta2504>\n            <img src=https://avatars.githubusercontent.com/u/52123629?v=4 width=\"100;\"  alt=Utkarsh Gupta/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Utkarsh Gupta</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/sourabmaity>\n            <img src=https://avatars.githubusercontent.com/u/62734958?v=4 width=\"100;\"  alt=Sourab Maity/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Sourab Maity</b></sub>\n        </a>\n    </td>\n</tr>\n<tr>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/ashish-garg18>\n            <img src=https://avatars.githubusercontent.com/u/57340919?v=4 width=\"100;\"  alt=Ashish garg/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Ashish garg</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/bryan-wu>\n            <img src=https://avatars.githubusercontent.com/u/26911618?v=4 width=\"100;\"  alt=Bryan Wu/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Bryan Wu</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/kcirym10>\n            <img src=https://avatars.githubusercontent.com/u/19197227?v=4 width=\"100;\"  alt=Alejandro Myrick/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Alejandro Myrick</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/ashivamj2105>\n            <img src=https://avatars.githubusercontent.com/u/54582829?v=4 width=\"100;\"  alt=ashivamj2105/>\n            <br />\n            <sub style=\"font-size:14px\"><b>ashivamj2105</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/krabhisharma>\n            <img src=https://avatars.githubusercontent.com/u/59818632?v=4 width=\"100;\"  alt=Abhishek Kumar/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Abhishek Kumar</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/Adigoo>\n            <img src=https://avatars.githubusercontent.com/u/26068367?v=4 width=\"100;\"  alt=Aditya Gonnade/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Aditya Gonnade</b></sub>\n        </a>\n    </td>\n</tr>\n<tr>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/threedotspast>\n            <img src=https://avatars.githubusercontent.com/u/56748230?v=4 width=\"100;\"  alt=Aishwarya Singh/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Aishwarya Singh</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/Amanj2000>\n            <img src=https://avatars.githubusercontent.com/u/54628038?v=4 width=\"100;\"  alt=Aman Jain/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Aman Jain</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/Arsenic-ATG>\n            <img src=https://avatars.githubusercontent.com/u/54987647?v=4 width=\"100;\"  alt=Arsenic/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Arsenic</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/Athi223>\n            <img src=https://avatars.githubusercontent.com/u/31766648?v=4 width=\"100;\"  alt=Atharv Phadnis/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Atharv Phadnis</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/chandresh189>\n            <img src=https://avatars.githubusercontent.com/u/48803866?v=4 width=\"100;\"  alt=Chandresh Singh/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Chandresh Singh</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/dandynaufaldi>\n            <img src=https://avatars.githubusercontent.com/u/27524382?v=4 width=\"100;\"  alt=Dandy Naufaldi/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Dandy Naufaldi</b></sub>\n        </a>\n    </td>\n</tr>\n<tr>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/Danotsonof>\n            <img src=https://avatars.githubusercontent.com/u/22982031?v=4 width=\"100;\"  alt=Daniel Otulagun/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Daniel Otulagun</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/GGolfz>\n            <img src=https://avatars.githubusercontent.com/u/52349645?v=4 width=\"100;\"  alt=GGolfz/>\n            <br />\n            <sub style=\"font-size:14px\"><b>GGolfz</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/garimamishraa>\n            <img src=https://avatars.githubusercontent.com/u/55507571?v=4 width=\"100;\"  alt=Garima Mishra/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Garima Mishra</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/null-sys>\n            <img src=https://avatars.githubusercontent.com/u/53622761?v=4 width=\"100;\"  alt=Gaurav/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Gaurav</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/geoffgeorgein>\n            <img src=https://avatars.githubusercontent.com/u/52931060?v=4 width=\"100;\"  alt=Geoff George/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Geoff George</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/Pancreax>\n            <img src=https://avatars.githubusercontent.com/u/16858827?v=4 width=\"100;\"  alt=Guilherme Andrade/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Guilherme Andrade</b></sub>\n        </a>\n    </td>\n</tr>\n<tr>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/nimishh7>\n            <img src=https://avatars.githubusercontent.com/u/54949793?v=4 width=\"100;\"  alt=Nimish Srivastava/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Nimish Srivastava</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/pranesh6876>\n            <img src=https://avatars.githubusercontent.com/u/46838529?v=4 width=\"100;\"  alt=PRANESH GUPTA/>\n            <br />\n            <sub style=\"font-size:14px\"><b>PRANESH GUPTA</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/parjanyaacoder>\n            <img src=https://avatars.githubusercontent.com/u/46294122?v=4 width=\"100;\"  alt=Parjanya Aditya Shukla/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Parjanya Aditya Shukla</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/Parth-Gupta10>\n            <img src=https://avatars.githubusercontent.com/u/58802407?v=4 width=\"100;\"  alt=Parth Gupta/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Parth Gupta</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/PRIYAMANDAL-21>\n            <img src=https://avatars.githubusercontent.com/u/65490775?v=4 width=\"100;\"  alt=Priya Mandal/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Priya Mandal</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/RgnDunes>\n            <img src=https://avatars.githubusercontent.com/u/61814592?v=4 width=\"100;\"  alt=Divyansh Singh/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Divyansh Singh</b></sub>\n        </a>\n    </td>\n</tr>\n<tr>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/Rj-coder-iitian>\n            <img src=https://avatars.githubusercontent.com/u/55445973?v=4 width=\"100;\"  alt=Rishabh Jain/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Rishabh Jain</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/SalmonKing72>\n            <img src=https://avatars.githubusercontent.com/u/6287664?v=4 width=\"100;\"  alt=SalmonKing72/>\n            <br />\n            <sub style=\"font-size:14px\"><b>SalmonKing72</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/Shreyash0713>\n            <img src=https://avatars.githubusercontent.com/u/29332072?v=4 width=\"100;\"  alt=Shreyash0713/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Shreyash0713</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/shubham2704>\n            <img src=https://avatars.githubusercontent.com/u/40126673?v=4 width=\"100;\"  alt=Shubham Goswami/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Shubham Goswami</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/Procoder16>\n            <img src=https://avatars.githubusercontent.com/u/71066110?v=4 width=\"100;\"  alt=Soumik Mukherjee/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Soumik Mukherjee</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/swas1820>\n            <img src=https://avatars.githubusercontent.com/u/43683080?v=4 width=\"100;\"  alt=Swastika Sarangi/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Swastika Sarangi</b></sub>\n        </a>\n    </td>\n</tr>\n<tr>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/TanishqPorwar>\n            <img src=https://avatars.githubusercontent.com/u/45430401?v=4 width=\"100;\"  alt=Tanishq R Porwar/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Tanishq R Porwar</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/tintindas>\n            <img src=https://avatars.githubusercontent.com/u/47525983?v=4 width=\"100;\"  alt=Upamanyu Das/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Upamanyu Das</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/vaishnavirshah>\n            <img src=https://avatars.githubusercontent.com/u/61752840?v=4 width=\"100;\"  alt=Vaishnavi Shah/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Vaishnavi Shah</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/varad64>\n            <img src=https://avatars.githubusercontent.com/u/42909741?v=4 width=\"100;\"  alt=Varadraj Galgali/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Varadraj Galgali</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/ivinaypathak>\n            <img src=https://avatars.githubusercontent.com/u/48496808?v=4 width=\"100;\"  alt=Vinay Pathak/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Vinay Pathak</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/Yatindra29>\n            <img src=https://avatars.githubusercontent.com/u/53404890?v=4 width=\"100;\"  alt=Yatindra Kumar Srivastava/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Yatindra Kumar Srivastava</b></sub>\n        </a>\n    </td>\n</tr>\n<tr>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/malik-aditya-r>\n            <img src=https://avatars.githubusercontent.com/u/69135820?v=4 width=\"100;\"  alt=Aditya Malik/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Aditya Malik</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/ashima0699>\n            <img src=https://avatars.githubusercontent.com/u/56577619?v=4 width=\"100;\"  alt=ashima0699/>\n            <br />\n            <sub style=\"font-size:14px\"><b>ashima0699</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/brane>\n            <img src=https://avatars.githubusercontent.com/u/236706?v=4 width=\"100;\"  alt=brane/>\n            <br />\n            <sub style=\"font-size:14px\"><b>brane</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/demonslayer99>\n            <img src=https://avatars.githubusercontent.com/u/72668963?v=4 width=\"100;\"  alt=demonslayer99/>\n            <br />\n            <sub style=\"font-size:14px\"><b>demonslayer99</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/dipankargoswami>\n            <img src=https://avatars.githubusercontent.com/u/20933006?v=4 width=\"100;\"  alt=Dipankar Goswami/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Dipankar Goswami</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/edoardottt>\n            <img src=https://avatars.githubusercontent.com/u/35783570?v=4 width=\"100;\"  alt=vrenzolaverace/>\n            <br />\n            <sub style=\"font-size:14px\"><b>vrenzolaverace</b></sub>\n        </a>\n    </td>\n</tr>\n<tr>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/Sj-001>\n            <img src=https://avatars.githubusercontent.com/u/50135847?v=4 width=\"100;\"  alt=Shruti Jain/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Shruti Jain</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/harshitgupta2000>\n            <img src=https://avatars.githubusercontent.com/u/56402525?v=4 width=\"100;\"  alt=harshitgupta2000/>\n            <br />\n            <sub style=\"font-size:14px\"><b>harshitgupta2000</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/harshitsuthar77731>\n            <img src=https://avatars.githubusercontent.com/u/65647274?v=4 width=\"100;\"  alt=Harshit Suthar/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Harshit Suthar</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/manan288>\n            <img src=https://avatars.githubusercontent.com/u/56118739?v=4 width=\"100;\"  alt=manan288/>\n            <br />\n            <sub style=\"font-size:14px\"><b>manan288</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/jayaganeshkumar>\n            <img src=https://avatars.githubusercontent.com/u/56192588?v=4 width=\"100;\"  alt=Jaya Ganesh Kumar Gudipati/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Jaya Ganesh Kumar Gudipati</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/krishnmohan19>\n            <img src=https://avatars.githubusercontent.com/u/63198422?v=4 width=\"100;\"  alt=krishnmohan Baghel/>\n            <br />\n            <sub style=\"font-size:14px\"><b>krishnmohan Baghel</b></sub>\n        </a>\n    </td>\n</tr>\n<tr>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/kugiyasan>\n            <img src=https://avatars.githubusercontent.com/u/44143656?v=4 width=\"100;\"  alt=kugiyasan/>\n            <br />\n            <sub style=\"font-size:14px\"><b>kugiyasan</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/melissahuertadev>\n            <img src=https://avatars.githubusercontent.com/u/52439373?v=4 width=\"100;\"  alt=Melissa Huerta Dev/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Melissa Huerta Dev</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/rgarg-2711>\n            <img src=https://avatars.githubusercontent.com/u/53249496?v=4 width=\"100;\"  alt=Rashmi garg/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Rashmi garg</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/rohg007>\n            <img src=https://avatars.githubusercontent.com/u/32675945?v=4 width=\"100;\"  alt=Rohan Gupta/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Rohan Gupta</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/swat-rash>\n            <img src=https://avatars.githubusercontent.com/u/72001516?v=4 width=\"100;\"  alt=swat-rash/>\n            <br />\n            <sub style=\"font-size:14px\"><b>swat-rash</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/syamilAbdillah>\n            <img src=https://avatars.githubusercontent.com/u/58422839?v=4 width=\"100;\"  alt=Syamil Abdillah/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Syamil Abdillah</b></sub>\n        </a>\n    </td>\n</tr>\n<tr>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/yogesh-kansal>\n            <img src=https://avatars.githubusercontent.com/u/64928842?v=4 width=\"100;\"  alt=yogesh-kansal/>\n            <br />\n            <sub style=\"font-size:14px\"><b>yogesh-kansal</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/zerox029>\n            <img src=https://avatars.githubusercontent.com/u/23341997?v=4 width=\"100;\"  alt=Etienne Plante/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Etienne Plante</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/aj-ya>\n            <img src=https://avatars.githubusercontent.com/u/59968173?v=4 width=\"100;\"  alt=Ajeya Bhat/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Ajeya Bhat</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/Alifbhanvadiya14>\n            <img src=https://avatars.githubusercontent.com/u/61405258?v=4 width=\"100;\"  alt=Alifbhanvadiya14/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Alifbhanvadiya14</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/EnzoRobaina>\n            <img src=https://avatars.githubusercontent.com/u/9217480?v=4 width=\"100;\"  alt=Enzo Robaina/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Enzo Robaina</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/GhostUser>\n            <img src=https://avatars.githubusercontent.com/u/35362972?v=4 width=\"100;\"  alt=Rahul Raj/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Rahul Raj</b></sub>\n        </a>\n    </td>\n</tr>\n<tr>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/mandloiaditi>\n            <img src=https://avatars.githubusercontent.com/u/34851288?v=4 width=\"100;\"  alt=Aditi Mandloi/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Aditi Mandloi</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/3t8>\n            <img src=https://avatars.githubusercontent.com/u/62209650?v=4 width=\"100;\"  alt=3t8/>\n            <br />\n            <sub style=\"font-size:14px\"><b>3t8</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/AdhitiS>\n            <img src=https://avatars.githubusercontent.com/u/64094979?v=4 width=\"100;\"  alt=AdhitiS/>\n            <br />\n            <sub style=\"font-size:14px\"><b>AdhitiS</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/adityaharsh2001>\n            <img src=https://avatars.githubusercontent.com/u/52870951?v=4 width=\"100;\"  alt=Aditya Harsh/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Aditya Harsh</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/ajeurkar>\n            <img src=https://avatars.githubusercontent.com/u/52557440?v=4 width=\"100;\"  alt=Ajinkya Jeurkar/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Ajinkya Jeurkar</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/AlxGration>\n            <img src=https://avatars.githubusercontent.com/u/14952054?v=4 width=\"100;\"  alt=Alexander/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Alexander</b></sub>\n        </a>\n    </td>\n</tr>\n<tr>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/korolr>\n            <img src=https://avatars.githubusercontent.com/u/11715165?v=4 width=\"100;\"  alt=Alexsey Ramzaev/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Alexsey Ramzaev</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/alvinuday>\n            <img src=https://avatars.githubusercontent.com/u/72704414?v=4 width=\"100;\"  alt=Alvin Uday/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Alvin Uday</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/amitagarwalaa57>\n            <img src=https://avatars.githubusercontent.com/u/36447666?v=4 width=\"100;\"  alt=Amit Kumar Agarwal/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Amit Kumar Agarwal</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/aniketrochwani>\n            <img src=https://avatars.githubusercontent.com/u/59789530?v=4 width=\"100;\"  alt=Aniket Rochwani/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Aniket Rochwani</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/ankitgoel25>\n            <img src=https://avatars.githubusercontent.com/u/54956353?v=4 width=\"100;\"  alt=Ankit Goel/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Ankit Goel</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/ankur-kayal>\n            <img src=https://avatars.githubusercontent.com/u/44806622?v=4 width=\"100;\"  alt=Ankur Kayal/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Ankur Kayal</b></sub>\n        </a>\n    </td>\n</tr>\n<tr>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/arjank>\n            <img src=https://avatars.githubusercontent.com/u/457006?v=4 width=\"100;\"  alt=Arjan/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Arjan</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/itsarjun12>\n            <img src=https://avatars.githubusercontent.com/u/46817093?v=4 width=\"100;\"  alt=Arjun Gaud/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Arjun Gaud</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/Atithi360>\n            <img src=https://avatars.githubusercontent.com/u/58621078?v=4 width=\"100;\"  alt=Atithi kumari/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Atithi kumari</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/TechLead-War>\n            <img src=https://avatars.githubusercontent.com/u/53389091?v=4 width=\"100;\"  alt=War Machine/>\n            <br />\n            <sub style=\"font-size:14px\"><b>War Machine</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/not4YU5H>\n            <img src=https://avatars.githubusercontent.com/u/77970015?v=4 width=\"100;\"  alt=Ayush Jain/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Ayush Jain</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/ayush-670>\n            <img src=https://avatars.githubusercontent.com/u/52285240?v=4 width=\"100;\"  alt=Ayush Singh/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Ayush Singh</b></sub>\n        </a>\n    </td>\n</tr>\n<tr>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/MonarchChakri>\n            <img src=https://avatars.githubusercontent.com/u/23417550?v=4 width=\"100;\"  alt=Chakradhar Palaparthi/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Chakradhar Palaparthi</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/dheerajvenugopal96>\n            <img src=https://avatars.githubusercontent.com/u/53091403?v=4 width=\"100;\"  alt=DCoder/>\n            <br />\n            <sub style=\"font-size:14px\"><b>DCoder</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/DevanshiJain>\n            <img src=https://avatars.githubusercontent.com/u/35057972?v=4 width=\"100;\"  alt=Devanshi Jain/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Devanshi Jain</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/Digislaw>\n            <img src=https://avatars.githubusercontent.com/u/26792425?v=4 width=\"100;\"  alt=Digislaw/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Digislaw</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/divigarg>\n            <img src=https://avatars.githubusercontent.com/u/55062037?v=4 width=\"100;\"  alt=Divyansh Garg/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Divyansh Garg</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/elshaek>\n            <img src=https://avatars.githubusercontent.com/u/21217702?v=4 width=\"100;\"  alt=Elsha E. Kwee/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Elsha E. Kwee</b></sub>\n        </a>\n    </td>\n</tr>\n<tr>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/kachus22>\n            <img src=https://avatars.githubusercontent.com/u/7953280?v=4 width=\"100;\"  alt=Enrique García Torres/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Enrique García Torres</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/gaurigithub>\n            <img src=https://avatars.githubusercontent.com/u/58972896?v=4 width=\"100;\"  alt=Gauri Mishra/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Gauri Mishra</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/harikesh409>\n            <img src=https://avatars.githubusercontent.com/u/3501554?v=4 width=\"100;\"  alt=Harikesh Pallantla/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Harikesh Pallantla</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/Harsh-1906>\n            <img src=https://avatars.githubusercontent.com/u/68503473?v=4 width=\"100;\"  alt=Harsh-1906/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Harsh-1906</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/ishangala16>\n            <img src=https://avatars.githubusercontent.com/u/51944781?v=4 width=\"100;\"  alt=Ishan Gala/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Ishan Gala</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/italovinicius18>\n            <img src=https://avatars.githubusercontent.com/u/39673124?v=4 width=\"100;\"  alt=Ítalo Vinícius/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Ítalo Vinícius</b></sub>\n        </a>\n    </td>\n</tr>\n<tr>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/Jaynish007>\n            <img src=https://avatars.githubusercontent.com/u/48377029?v=4 width=\"100;\"  alt=Jaynish007/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Jaynish007</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/JimmyFromRobotics>\n            <img src=https://avatars.githubusercontent.com/u/34200973?v=4 width=\"100;\"  alt=JimmyFromRobotics/>\n            <br />\n            <sub style=\"font-size:14px\"><b>JimmyFromRobotics</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/joaopedrocampos>\n            <img src=https://avatars.githubusercontent.com/u/20289185?v=4 width=\"100;\"  alt=Joao Pedro Campos Silva/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Joao Pedro Campos Silva</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/Kartik-byte>\n            <img src=https://avatars.githubusercontent.com/u/72177299?v=4 width=\"100;\"  alt=Kartik Kumar Thakur/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Kartik Kumar Thakur</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/KevalPrajapati>\n            <img src=https://avatars.githubusercontent.com/u/63007835?v=4 width=\"100;\"  alt=Keval Prajapati/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Keval Prajapati</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/Kishore-abhimanyu>\n            <img src=https://avatars.githubusercontent.com/u/72184554?v=4 width=\"100;\"  alt=Kishore/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Kishore</b></sub>\n        </a>\n    </td>\n</tr>\n<tr>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/junyongxlee>\n            <img src=https://avatars.githubusercontent.com/u/66911725?v=4 width=\"100;\"  alt=Lee Jun Yong/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Lee Jun Yong</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/LuisFerTR>\n            <img src=https://avatars.githubusercontent.com/u/47088091?v=4 width=\"100;\"  alt=Luis F. Talavera R./>\n            <br />\n            <sub style=\"font-size:14px\"><b>Luis F. Talavera R.</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/mahimasawant>\n            <img src=https://avatars.githubusercontent.com/u/41326514?v=4 width=\"100;\"  alt=Mahima Sawant/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Mahima Sawant</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/MananOO12>\n            <img src=https://avatars.githubusercontent.com/u/71601963?v=4 width=\"100;\"  alt=Manan Jain/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Manan Jain</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/megabyte98>\n            <img src=https://avatars.githubusercontent.com/u/61015154?v=4 width=\"100;\"  alt=megabyte98/>\n            <br />\n            <sub style=\"font-size:14px\"><b>megabyte98</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/mhechavarria>\n            <img src=https://avatars.githubusercontent.com/u/41266443?v=4 width=\"100;\"  alt=Mariano Echavarria/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Mariano Echavarria</b></sub>\n        </a>\n    </td>\n</tr>\n<tr>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/matheuslincolnss>\n            <img src=https://avatars.githubusercontent.com/u/12600520?v=4 width=\"100;\"  alt=Matheus Pereira/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Matheus Pereira</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/mrselukar>\n            <img src=https://avatars.githubusercontent.com/u/35305019?v=4 width=\"100;\"  alt=Mayur Selukar/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Mayur Selukar</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/mohit0204>\n            <img src=https://avatars.githubusercontent.com/u/71942407?v=4 width=\"100;\"  alt=Mohit/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Mohit</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/MohitBhagchandani0601>\n            <img src=https://avatars.githubusercontent.com/u/72273848?v=4 width=\"100;\"  alt=SNIPERSHOTAA/>\n            <br />\n            <sub style=\"font-size:14px\"><b>SNIPERSHOTAA</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/MrNaif2018>\n            <img src=https://avatars.githubusercontent.com/u/39452697?v=4 width=\"100;\"  alt=MrNaif2018/>\n            <br />\n            <sub style=\"font-size:14px\"><b>MrNaif2018</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/NEENA-XAVIER>\n            <img src=https://avatars.githubusercontent.com/u/67526438?v=4 width=\"100;\"  alt=NEENA-XAVIER/>\n            <br />\n            <sub style=\"font-size:14px\"><b>NEENA-XAVIER</b></sub>\n        </a>\n    </td>\n</tr>\n<tr>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/Namanmittal0007>\n            <img src=https://avatars.githubusercontent.com/u/31571822?v=4 width=\"100;\"  alt=Naman Mittal/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Naman Mittal</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/NathanPickard>\n            <img src=https://avatars.githubusercontent.com/u/10966652?v=4 width=\"100;\"  alt=Nathan Pickard/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Nathan Pickard</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/neha07kumari>\n            <img src=https://avatars.githubusercontent.com/u/47255445?v=4 width=\"100;\"  alt=Neha Kumari/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Neha Kumari</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/nikku971>\n            <img src=https://avatars.githubusercontent.com/u/63146359?v=4 width=\"100;\"  alt=Nikitha Rangineni/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Nikitha Rangineni</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/EANimesha>\n            <img src=https://avatars.githubusercontent.com/u/37245819?v=4 width=\"100;\"  alt=Nimesha Dilini/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Nimesha Dilini</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/OverPoweredDev>\n            <img src=https://avatars.githubusercontent.com/u/64774148?v=4 width=\"100;\"  alt=Omkar Prabhune/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Omkar Prabhune</b></sub>\n        </a>\n    </td>\n</tr>\n<tr>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/onkargagare>\n            <img src=https://avatars.githubusercontent.com/u/13161686?v=4 width=\"100;\"  alt=Onkar Gagare/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Onkar Gagare</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/Esoiya>\n            <img src=https://avatars.githubusercontent.com/u/20611435?v=4 width=\"100;\"  alt=Ose Oaiya/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Ose Oaiya</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/Pranjal81>\n            <img src=https://avatars.githubusercontent.com/u/54803412?v=4 width=\"100;\"  alt=Pranjal Bansal/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Pranjal Bansal</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/Prasheel-IITI>\n            <img src=https://avatars.githubusercontent.com/u/70912843?v=4 width=\"100;\"  alt=Prasheel-IITI/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Prasheel-IITI</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/Rajwrita>\n            <img src=https://avatars.githubusercontent.com/u/47374547?v=4 width=\"100;\"  alt=Rajwrita/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Rajwrita</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/rishikasoni67>\n            <img src=https://avatars.githubusercontent.com/u/53947523?v=4 width=\"100;\"  alt=Rishika Soni/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Rishika Soni</b></sub>\n        </a>\n    </td>\n</tr>\n<tr>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/SahilKesarwani>\n            <img src=https://avatars.githubusercontent.com/u/80140802?v=4 width=\"100;\"  alt=Sahil Kesarwani/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Sahil Kesarwani</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/sayan2044>\n            <img src=https://avatars.githubusercontent.com/u/49563939?v=4 width=\"100;\"  alt=Sayan Majhi/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Sayan Majhi</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/ShubhamJamuar>\n            <img src=https://avatars.githubusercontent.com/u/55888890?v=4 width=\"100;\"  alt=ShubhamJamuar/>\n            <br />\n            <sub style=\"font-size:14px\"><b>ShubhamJamuar</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/shwhite17>\n            <img src=https://avatars.githubusercontent.com/u/57324656?v=4 width=\"100;\"  alt=Shweta Singh/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Shweta Singh</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/sid-1207>\n            <img src=https://avatars.githubusercontent.com/u/52534279?v=4 width=\"100;\"  alt=Siddharth Shah/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Siddharth Shah</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/SnehjeetBenz>\n            <img src=https://avatars.githubusercontent.com/u/72383820?v=4 width=\"100;\"  alt=SnehjeetBenz/>\n            <br />\n            <sub style=\"font-size:14px\"><b>SnehjeetBenz</b></sub>\n        </a>\n    </td>\n</tr>\n<tr>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/noob-26>\n            <img src=https://avatars.githubusercontent.com/u/56394033?v=4 width=\"100;\"  alt=Souraprabha Ganguly/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Souraprabha Ganguly</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/sudesh1611>\n            <img src=https://avatars.githubusercontent.com/u/10352292?v=4 width=\"100;\"  alt=Sudesh Kumar/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Sudesh Kumar</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/SumitKuSahu>\n            <img src=https://avatars.githubusercontent.com/u/72408755?v=4 width=\"100;\"  alt=Sumit Kumar Sahu/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Sumit Kumar Sahu</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/Sushantrimurti>\n            <img src=https://avatars.githubusercontent.com/u/56467504?v=4 width=\"100;\"  alt=Sushantrimurti/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Sushantrimurti</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/Swarn10>\n            <img src=https://avatars.githubusercontent.com/u/54739905?v=4 width=\"100;\"  alt=Swarn10/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Swarn10</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/Swatigupta-droid>\n            <img src=https://avatars.githubusercontent.com/u/64798478?v=4 width=\"100;\"  alt=Swati Gupta/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Swati Gupta</b></sub>\n        </a>\n    </td>\n</tr>\n<tr>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/TechnoPhasePRO>\n            <img src=https://avatars.githubusercontent.com/u/59903104?v=4 width=\"100;\"  alt=Yash Raj Singh Bisht/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Yash Raj Singh Bisht</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/TheBlckCat>\n            <img src=https://avatars.githubusercontent.com/u/70791006?v=4 width=\"100;\"  alt=The Black Cat/>\n            <br />\n            <sub style=\"font-size:14px\"><b>The Black Cat</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/tomasloksa>\n            <img src=https://avatars.githubusercontent.com/u/28986303?v=4 width=\"100;\"  alt=Tomáš Lokša/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Tomáš Lokša</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/william-gooch>\n            <img src=https://avatars.githubusercontent.com/u/40644139?v=4 width=\"100;\"  alt=William Gooch/>\n            <br />\n            <sub style=\"font-size:14px\"><b>William Gooch</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/Yash00git>\n            <img src=https://avatars.githubusercontent.com/u/65126639?v=4 width=\"100;\"  alt=Yash khandelwal/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Yash khandelwal</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/YJDoc2>\n            <img src=https://avatars.githubusercontent.com/u/54112038?v=4 width=\"100;\"  alt=Yashodhan Joshi/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Yashodhan Joshi</b></sub>\n        </a>\n    </td>\n</tr>\n<tr>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/YatharthVyas>\n            <img src=https://avatars.githubusercontent.com/u/53610833?v=4 width=\"100;\"  alt=Yatharth Vyas/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Yatharth Vyas</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/aanshi18>\n            <img src=https://avatars.githubusercontent.com/u/60308101?v=4 width=\"100;\"  alt=aanshi18/>\n            <br />\n            <sub style=\"font-size:14px\"><b>aanshi18</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/aayushi02agarwal>\n            <img src=https://avatars.githubusercontent.com/u/65224590?v=4 width=\"100;\"  alt=Aayushi Agarwal/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Aayushi Agarwal</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/abhinav889>\n            <img src=https://avatars.githubusercontent.com/u/39915943?v=4 width=\"100;\"  alt=abhinav889/>\n            <br />\n            <sub style=\"font-size:14px\"><b>abhinav889</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/abhinavjonnada82>\n            <img src=https://avatars.githubusercontent.com/u/30497847?v=4 width=\"100;\"  alt=ABHINAV JONNADA/>\n            <br />\n            <sub style=\"font-size:14px\"><b>ABHINAV JONNADA</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/xanaDev>\n            <img src=https://avatars.githubusercontent.com/u/6085192?v=4 width=\"100;\"  alt=Abid/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Abid</b></sub>\n        </a>\n    </td>\n</tr>\n<tr>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/afeefaa333>\n            <img src=https://avatars.githubusercontent.com/u/70969985?v=4 width=\"100;\"  alt=Afeefa Abdullah Manjanoor/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Afeefa Abdullah Manjanoor</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/alekz7>\n            <img src=https://avatars.githubusercontent.com/u/29360377?v=4 width=\"100;\"  alt=Alejandro Aragon/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Alejandro Aragon</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/alkatrivedi>\n            <img src=https://avatars.githubusercontent.com/u/58396306?v=4 width=\"100;\"  alt=alkatrivedi/>\n            <br />\n            <sub style=\"font-size:14px\"><b>alkatrivedi</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/anuva04>\n            <img src=https://avatars.githubusercontent.com/u/57056078?v=4 width=\"100;\"  alt=Anuva Bhattacharjee/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Anuva Bhattacharjee</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/aorellano>\n            <img src=https://avatars.githubusercontent.com/u/43689818?v=4 width=\"100;\"  alt=aorellano/>\n            <br />\n            <sub style=\"font-size:14px\"><b>aorellano</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/aroradhruv2308>\n            <img src=https://avatars.githubusercontent.com/u/67088080?v=4 width=\"100;\"  alt=Dhruv Arora/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Dhruv Arora</b></sub>\n        </a>\n    </td>\n</tr>\n<tr>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/Ayushmanglani>\n            <img src=https://avatars.githubusercontent.com/u/61349816?v=4 width=\"100;\"  alt=ayush_manglani/>\n            <br />\n            <sub style=\"font-size:14px\"><b>ayush_manglani</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/deepampriyadarshi>\n            <img src=https://avatars.githubusercontent.com/u/65447610?v=4 width=\"100;\"  alt=Deepam Priyadarshi/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Deepam Priyadarshi</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/erikkvalvik>\n            <img src=https://avatars.githubusercontent.com/u/42551121?v=4 width=\"100;\"  alt=erikkvalvik/>\n            <br />\n            <sub style=\"font-size:14px\"><b>erikkvalvik</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/hello-fri-end>\n            <img src=https://avatars.githubusercontent.com/u/43880587?v=4 width=\"100;\"  alt=Anwaar Khalid/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Anwaar Khalid</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/varuogm>\n            <img src=https://avatars.githubusercontent.com/u/44859494?v=4 width=\"100;\"  alt=gourav majee/>\n            <br />\n            <sub style=\"font-size:14px\"><b>gourav majee</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/itIsBrando>\n            <img src=https://avatars.githubusercontent.com/u/56180881?v=4 width=\"100;\"  alt=Brandon/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Brandon</b></sub>\n        </a>\n    </td>\n</tr>\n<tr>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/jyotiGambhir>\n            <img src=https://avatars.githubusercontent.com/u/19373481?v=4 width=\"100;\"  alt=Jyoti Gambhir/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Jyoti Gambhir</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/parauliya>\n            <img src=https://avatars.githubusercontent.com/u/30143812?v=4 width=\"100;\"  alt=Aman Parauliya/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Aman Parauliya</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/piemme>\n            <img src=https://avatars.githubusercontent.com/u/1160567?v=4 width=\"100;\"  alt=pmanca/>\n            <br />\n            <sub style=\"font-size:14px\"><b>pmanca</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/P-cpu>\n            <img src=https://avatars.githubusercontent.com/u/54592810?v=4 width=\"100;\"  alt=pradyumn sharma/>\n            <br />\n            <sub style=\"font-size:14px\"><b>pradyumn sharma</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/pulkitsapra>\n            <img src=https://avatars.githubusercontent.com/u/16730739?v=4 width=\"100;\"  alt=Pulkit Sapra/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Pulkit Sapra</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/rexa0310>\n            <img src=https://avatars.githubusercontent.com/u/67274027?v=4 width=\"100;\"  alt=Mayank Goyal/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Mayank Goyal</b></sub>\n        </a>\n    </td>\n</tr>\n<tr>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/rishab1128>\n            <img src=https://avatars.githubusercontent.com/u/63293155?v=4 width=\"100;\"  alt=Rishab Purkayastha/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Rishab Purkayastha</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/rishikeshreddyakkireddy>\n            <img src=https://avatars.githubusercontent.com/u/83630220?v=4 width=\"100;\"  alt=rishikeshreddyakkireddy/>\n            <br />\n            <sub style=\"font-size:14px\"><b>rishikeshreddyakkireddy</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/sairam-kakarla>\n            <img src=https://avatars.githubusercontent.com/u/67178651?v=4 width=\"100;\"  alt=Lakshmi Sairam Kakarla/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Lakshmi Sairam Kakarla</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/shagunarora>\n            <img src=https://avatars.githubusercontent.com/u/35228934?v=4 width=\"100;\"  alt=shagun/>\n            <br />\n            <sub style=\"font-size:14px\"><b>shagun</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/shockedeel>\n            <img src=https://avatars.githubusercontent.com/u/39538189?v=4 width=\"100;\"  alt=shockedeel/>\n            <br />\n            <sub style=\"font-size:14px\"><b>shockedeel</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/coding-sourabh>\n            <img src=https://avatars.githubusercontent.com/u/66876061?v=4 width=\"100;\"  alt=sourabh kumar/>\n            <br />\n            <sub style=\"font-size:14px\"><b>sourabh kumar</b></sub>\n        </a>\n    </td>\n</tr>\n<tr>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/souvickroy02>\n            <img src=https://avatars.githubusercontent.com/u/52229131?v=4 width=\"100;\"  alt=Souvick roy/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Souvick roy</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/strikeraryu>\n            <img src=https://avatars.githubusercontent.com/u/37619410?v=4 width=\"100;\"  alt=Aryamaan jain/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Aryamaan jain</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/subhadeep1912>\n            <img src=https://avatars.githubusercontent.com/u/37493730?v=4 width=\"100;\"  alt=subhadeep1912/>\n            <br />\n            <sub style=\"font-size:14px\"><b>subhadeep1912</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/superconscript>\n            <img src=https://avatars.githubusercontent.com/u/48189821?v=4 width=\"100;\"  alt=superconscript/>\n            <br />\n            <sub style=\"font-size:14px\"><b>superconscript</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/Veguinho>\n            <img src=https://avatars.githubusercontent.com/u/26579048?v=4 width=\"100;\"  alt=Rafael Vieira Rosenzvaig/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Rafael Vieira Rosenzvaig</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/venkyvt7>\n            <img src=https://avatars.githubusercontent.com/u/26019764?v=4 width=\"100;\"  alt=venkyvt7/>\n            <br />\n            <sub style=\"font-size:14px\"><b>venkyvt7</b></sub>\n        </a>\n    </td>\n</tr>\n<tr>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/Dheeraj-01>\n            <img src=https://avatars.githubusercontent.com/u/54698983?v=4 width=\"100;\"  alt=Dheeraj Bhagchandani/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Dheeraj Bhagchandani</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/Gagan-Shenoy>\n            <img src=https://avatars.githubusercontent.com/u/58648842?v=4 width=\"100;\"  alt=Gagan-Shenoy/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Gagan-Shenoy</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/KevinMathewTh>\n            <img src=https://avatars.githubusercontent.com/u/44275582?v=4 width=\"100;\"  alt=KevinMathewTh/>\n            <br />\n            <sub style=\"font-size:14px\"><b>KevinMathewTh</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/kinshukdua>\n            <img src=https://avatars.githubusercontent.com/u/57797818?v=4 width=\"100;\"  alt=Kinshuk Dua/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Kinshuk Dua</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/Mayankjha997>\n            <img src=https://avatars.githubusercontent.com/u/57581165?v=4 width=\"100;\"  alt=Mayank Jha/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Mayank Jha</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/2knal>\n            <img src=https://avatars.githubusercontent.com/u/32769793?v=4 width=\"100;\"  alt=Kunal D. Sonawane/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Kunal D. Sonawane</b></sub>\n        </a>\n    </td>\n</tr>\n<tr>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/ASHMITA-DE>\n            <img src=https://avatars.githubusercontent.com/u/59888276?v=4 width=\"100;\"  alt=ASHMITA DE/>\n            <br />\n            <sub style=\"font-size:14px\"><b>ASHMITA DE</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/Aaryan0424>\n            <img src=https://avatars.githubusercontent.com/u/77140684?v=4 width=\"100;\"  alt=Aaryan Gupta/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Aaryan Gupta</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/Abantika20>\n            <img src=https://avatars.githubusercontent.com/u/72135695?v=4 width=\"100;\"  alt=Abantika20/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Abantika20</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/abhaybhatt>\n            <img src=https://avatars.githubusercontent.com/u/53853574?v=4 width=\"100;\"  alt=Abhay Bhatt/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Abhay Bhatt</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/Abheetarora>\n            <img src=https://avatars.githubusercontent.com/u/62665287?v=4 width=\"100;\"  alt=Abheet Arora/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Abheet Arora</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/abhishek-shukla21>\n            <img src=https://avatars.githubusercontent.com/u/50260867?v=4 width=\"100;\"  alt=Abhishek Shukla/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Abhishek Shukla</b></sub>\n        </a>\n    </td>\n</tr>\n<tr>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/Adil-S786>\n            <img src=https://avatars.githubusercontent.com/u/71209995?v=4 width=\"100;\"  alt=Adil-S786/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Adil-S786</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/adityawisecoder>\n            <img src=https://avatars.githubusercontent.com/u/72189258?v=4 width=\"100;\"  alt=Aditya Krishna/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Aditya Krishna</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/akaash11>\n            <img src=https://avatars.githubusercontent.com/u/27217463?v=4 width=\"100;\"  alt=Akaash Trivedi/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Akaash Trivedi</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/amishaagarwal1998>\n            <img src=https://avatars.githubusercontent.com/u/34367385?v=4 width=\"100;\"  alt=amishaagarwal1998/>\n            <br />\n            <sub style=\"font-size:14px\"><b>amishaagarwal1998</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/AnaGVF>\n            <img src=https://avatars.githubusercontent.com/u/39038388?v=4 width=\"100;\"  alt=AnaGVF/>\n            <br />\n            <sub style=\"font-size:14px\"><b>AnaGVF</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/AnkitJuyal009>\n            <img src=https://avatars.githubusercontent.com/u/43692967?v=4 width=\"100;\"  alt=Ankit Juyal/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Ankit Juyal</b></sub>\n        </a>\n    </td>\n</tr>\n<tr>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/ankurj00>\n            <img src=https://avatars.githubusercontent.com/u/102207264?v=4 width=\"100;\"  alt=ankurj00/>\n            <br />\n            <sub style=\"font-size:14px\"><b>ankurj00</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/Ace117MC>\n            <img src=https://avatars.githubusercontent.com/u/52137018?v=4 width=\"100;\"  alt=Ace117MC/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Ace117MC</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/Sinha199>\n            <img src=https://avatars.githubusercontent.com/u/48489081?v=4 width=\"100;\"  alt=Anshu Sinha/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Anshu Sinha</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/BabesGotByte>\n            <img src=https://avatars.githubusercontent.com/u/37226108?v=4 width=\"100;\"  alt=Anshul Agarwal/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Anshul Agarwal</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/anshul-bhatia>\n            <img src=https://avatars.githubusercontent.com/u/39267296?v=4 width=\"100;\"  alt=Anshul Bhatia/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Anshul Bhatia</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/Anu9518>\n            <img src=https://avatars.githubusercontent.com/u/51081273?v=4 width=\"100;\"  alt=Anu9518/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Anu9518</b></sub>\n        </a>\n    </td>\n</tr>\n<tr>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/apoorvlodhi21>\n            <img src=https://avatars.githubusercontent.com/u/51700471?v=4 width=\"100;\"  alt=Apoorv Lodhi/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Apoorv Lodhi</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/apostolosdiavolitsis>\n            <img src=https://avatars.githubusercontent.com/u/22724616?v=4 width=\"100;\"  alt=Apostolos Diavolitsis/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Apostolos Diavolitsis</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/ApurvaBhaskar>\n            <img src=https://avatars.githubusercontent.com/u/56476496?v=4 width=\"100;\"  alt=Apurva Chandra Bhaskar/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Apurva Chandra Bhaskar</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/ArchanaDhaker>\n            <img src=https://avatars.githubusercontent.com/u/42279677?v=4 width=\"100;\"  alt=ArchanaDhaker/>\n            <br />\n            <sub style=\"font-size:14px\"><b>ArchanaDhaker</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/rarchitgupta>\n            <img src=https://avatars.githubusercontent.com/u/52240360?v=4 width=\"100;\"  alt=Archit Gupta/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Archit Gupta</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/ArpitDarklord>\n            <img src=https://avatars.githubusercontent.com/u/56078545?v=4 width=\"100;\"  alt=Arpit Mallick/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Arpit Mallick</b></sub>\n        </a>\n    </td>\n</tr>\n<tr>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/ashutoshkumar6>\n            <img src=https://avatars.githubusercontent.com/u/46455005?v=4 width=\"100;\"  alt=Ashutosh Kumar/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Ashutosh Kumar</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/ashwin2125>\n            <img src=https://avatars.githubusercontent.com/u/47941624?v=4 width=\"100;\"  alt=Ashwin G/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Ashwin G</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/eraviral34>\n            <img src=https://avatars.githubusercontent.com/u/43290012?v=4 width=\"100;\"  alt=Aviral Gupta/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Aviral Gupta</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/Balaguru4580>\n            <img src=https://avatars.githubusercontent.com/u/61746056?v=4 width=\"100;\"  alt=Balaguru Ragupathi/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Balaguru Ragupathi</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/thebhushanmhatre>\n            <img src=https://avatars.githubusercontent.com/u/44663470?v=4 width=\"100;\"  alt=Bhushan Mhatre/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Bhushan Mhatre</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/bidya01>\n            <img src=https://avatars.githubusercontent.com/u/49316989?v=4 width=\"100;\"  alt=Bidya Dasgupta/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Bidya Dasgupta</b></sub>\n        </a>\n    </td>\n</tr>\n<tr>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/webdott>\n            <img src=https://avatars.githubusercontent.com/u/52088600?v=4 width=\"100;\"  alt=Uchechukwu Nwafor/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Uchechukwu Nwafor</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/chiragjagad>\n            <img src=https://avatars.githubusercontent.com/u/68422478?v=4 width=\"100;\"  alt=Chirag Jagad/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Chirag Jagad</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/cgoxo>\n            <img src=https://avatars.githubusercontent.com/u/50276480?v=4 width=\"100;\"  alt=Chitresh Goel/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Chitresh Goel</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/spidergon>\n            <img src=https://avatars.githubusercontent.com/u/6226268?v=4 width=\"100;\"  alt=Christopher Servius/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Christopher Servius</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/CommitIt55>\n            <img src=https://avatars.githubusercontent.com/u/30253833?v=4 width=\"100;\"  alt=CommitIt55/>\n            <br />\n            <sub style=\"font-size:14px\"><b>CommitIt55</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/divyansh1511>\n            <img src=https://avatars.githubusercontent.com/u/75711789?v=4 width=\"100;\"  alt=DIVYANSH GARG/>\n            <br />\n            <sub style=\"font-size:14px\"><b>DIVYANSH GARG</b></sub>\n        </a>\n    </td>\n</tr>\n<tr>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/deepjyot>\n            <img src=https://avatars.githubusercontent.com/u/23016536?v=4 width=\"100;\"  alt=Deepjyot Kaur/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Deepjyot Kaur</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/Devenkapoor7303>\n            <img src=https://avatars.githubusercontent.com/u/73438023?v=4 width=\"100;\"  alt=Devenkapoor7303/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Devenkapoor7303</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/dheerajodha>\n            <img src=https://avatars.githubusercontent.com/u/43273420?v=4 width=\"100;\"  alt=Dheeraj/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Dheeraj</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/Divya247>\n            <img src=https://avatars.githubusercontent.com/u/40147180?v=4 width=\"100;\"  alt=Divya Agarwal/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Divya Agarwal</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/divyanshrastogi51>\n            <img src=https://avatars.githubusercontent.com/u/54467001?v=4 width=\"100;\"  alt=Divyansh Rastogi/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Divyansh Rastogi</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/Divyessh>\n            <img src=https://avatars.githubusercontent.com/u/67703282?v=4 width=\"100;\"  alt=Divyessh Maheshwari/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Divyessh Maheshwari</b></sub>\n        </a>\n    </td>\n</tr>\n<tr>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/durgeshahire07>\n            <img src=https://avatars.githubusercontent.com/u/68327306?v=4 width=\"100;\"  alt=Durgesh Ahire/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Durgesh Ahire</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/dvir019>\n            <img src=https://avatars.githubusercontent.com/u/30556126?v=4 width=\"100;\"  alt=dvir019/>\n            <br />\n            <sub style=\"font-size:14px\"><b>dvir019</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/GarvitBanga>\n            <img src=https://avatars.githubusercontent.com/u/37771583?v=4 width=\"100;\"  alt=Garvit Banga/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Garvit Banga</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/girishgr8>\n            <img src=https://avatars.githubusercontent.com/u/43734717?v=4 width=\"100;\"  alt=Girish Thatte/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Girish Thatte</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/GitanshKapoor>\n            <img src=https://avatars.githubusercontent.com/u/72307552?v=4 width=\"100;\"  alt=Gitansh Kapoor/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Gitansh Kapoor</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/Druffl3>\n            <img src=https://avatars.githubusercontent.com/u/28187687?v=4 width=\"100;\"  alt=Goutham R/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Goutham R</b></sub>\n        </a>\n    </td>\n</tr>\n<tr>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/Grasstown>\n            <img src=https://avatars.githubusercontent.com/u/42019030?v=4 width=\"100;\"  alt=Kevin Wu/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Kevin Wu</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/guygreenleaf>\n            <img src=https://avatars.githubusercontent.com/u/27166054?v=4 width=\"100;\"  alt=Guy Greenleaf/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Guy Greenleaf</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/ahmeddrawy>\n            <img src=https://avatars.githubusercontent.com/u/26177966?v=4 width=\"100;\"  alt=Ahmed Hanafy/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Ahmed Hanafy</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/hadron43>\n            <img src=https://avatars.githubusercontent.com/u/55682057?v=4 width=\"100;\"  alt=Harsh Kumar/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Harsh Kumar</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/Harsh-Udai-robomq>\n            <img src=https://avatars.githubusercontent.com/u/50704886?v=4 width=\"100;\"  alt=HarshUdai/>\n            <br />\n            <sub style=\"font-size:14px\"><b>HarshUdai</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/harshvardhan56>\n            <img src=https://avatars.githubusercontent.com/u/77070444?v=4 width=\"100;\"  alt=Harsh Vardhan/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Harsh Vardhan</b></sub>\n        </a>\n    </td>\n</tr>\n<tr>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/Harshgupta5901>\n            <img src=https://avatars.githubusercontent.com/u/75782910?v=4 width=\"100;\"  alt=Harshgupta5901/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Harshgupta5901</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/harshith-venkatesh>\n            <img src=https://avatars.githubusercontent.com/u/44545218?v=4 width=\"100;\"  alt=Harshith Venkatesh/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Harshith Venkatesh</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/hnishal>\n            <img src=https://avatars.githubusercontent.com/u/65018541?v=4 width=\"100;\"  alt=Himanshu Nishal/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Himanshu Nishal</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/Himanshu-Nagle>\n            <img src=https://avatars.githubusercontent.com/u/72325752?v=4 width=\"100;\"  alt=Himanshu-Nagle/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Himanshu-Nagle</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/hritik5102>\n            <img src=https://avatars.githubusercontent.com/u/44053202?v=4 width=\"100;\"  alt=Hritik Jaiswal/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Hritik Jaiswal</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/hyunjiLeeTech>\n            <img src=https://avatars.githubusercontent.com/u/45149474?v=4 width=\"100;\"  alt=Hyun Ji Lee />\n            <br />\n            <sub style=\"font-size:14px\"><b>Hyun Ji Lee </b></sub>\n        </a>\n    </td>\n</tr>\n<tr>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/Wekananda>\n            <img src=https://avatars.githubusercontent.com/u/21331447?v=4 width=\"100;\"  alt=I Gusti Agung Vivekananda/>\n            <br />\n            <sub style=\"font-size:14px\"><b>I Gusti Agung Vivekananda</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/janavmakkar>\n            <img src=https://avatars.githubusercontent.com/u/46678040?v=4 width=\"100;\"  alt=Janav/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Janav</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/jatingarg36>\n            <img src=https://avatars.githubusercontent.com/u/46717453?v=4 width=\"100;\"  alt=Jatin Garg/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Jatin Garg</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/choijean>\n            <img src=https://avatars.githubusercontent.com/u/56896631?v=4 width=\"100;\"  alt=choijean/>\n            <br />\n            <sub style=\"font-size:14px\"><b>choijean</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/Rainbow-Ninja>\n            <img src=https://avatars.githubusercontent.com/u/48858686?v=4 width=\"100;\"  alt=Jo Dunham/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Jo Dunham</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/joyeta148>\n            <img src=https://avatars.githubusercontent.com/u/51826235?v=4 width=\"100;\"  alt=Joyeta Saha/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Joyeta Saha</b></sub>\n        </a>\n    </td>\n</tr>\n<tr>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/juanmaotegui>\n            <img src=https://avatars.githubusercontent.com/u/17624205?v=4 width=\"100;\"  alt=Juan Manuel Otegui/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Juan Manuel Otegui</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/Kashish888>\n            <img src=https://avatars.githubusercontent.com/u/72927436?v=4 width=\"100;\"  alt=Kashish888/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Kashish888</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/kasirajr>\n            <img src=https://avatars.githubusercontent.com/u/19857340?v=4 width=\"100;\"  alt=Kasi Raj/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Kasi Raj</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/kwong21>\n            <img src=https://avatars.githubusercontent.com/u/9203201?v=4 width=\"100;\"  alt=Kelvin Wong/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Kelvin Wong</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/Phoenix6296>\n            <img src=https://avatars.githubusercontent.com/u/72021425?v=4 width=\"100;\"  alt=Krishna Biswakarma/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Krishna Biswakarma</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/KritiGandotra>\n            <img src=https://avatars.githubusercontent.com/u/52518026?v=4 width=\"100;\"  alt=Kriti Gandotra/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Kriti Gandotra</b></sub>\n        </a>\n    </td>\n</tr>\n<tr>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/kritika2311>\n            <img src=https://avatars.githubusercontent.com/u/55829077?v=4 width=\"100;\"  alt=Kritika Pathak/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Kritika Pathak</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/Lakshay-Singhal>\n            <img src=https://avatars.githubusercontent.com/u/60272166?v=4 width=\"100;\"  alt=Lakshay Singhal/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Lakshay Singhal</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/LuanDevecchi>\n            <img src=https://avatars.githubusercontent.com/u/27377250?v=4 width=\"100;\"  alt=LuanDevecchi/>\n            <br />\n            <sub style=\"font-size:14px\"><b>LuanDevecchi</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/lucasbivar>\n            <img src=https://avatars.githubusercontent.com/u/60802661?v=4 width=\"100;\"  alt=Lucas Bivar />\n            <br />\n            <sub style=\"font-size:14px\"><b>Lucas Bivar </b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/Kingarturs>\n            <img src=https://avatars.githubusercontent.com/u/53494602?v=4 width=\"100;\"  alt=Luis Arturo García Gonzalez/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Luis Arturo García Gonzalez</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/nibble-4bits>\n            <img src=https://avatars.githubusercontent.com/u/38052706?v=4 width=\"100;\"  alt=Luis De Anda/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Luis De Anda</b></sub>\n        </a>\n    </td>\n</tr>\n<tr>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/Satyagovind>\n            <img src=https://avatars.githubusercontent.com/u/55746080?v=4 width=\"100;\"  alt=M Satyagovind/>\n            <br />\n            <sub style=\"font-size:14px\"><b>M Satyagovind</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/ManasUniyal>\n            <img src=https://avatars.githubusercontent.com/u/35189722?v=4 width=\"100;\"  alt=Manas Uniyal/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Manas Uniyal</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/Manas173>\n            <img src=https://avatars.githubusercontent.com/u/31970009?v=4 width=\"100;\"  alt=Manas173/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Manas173</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/ManavArora26>\n            <img src=https://avatars.githubusercontent.com/u/72567005?v=4 width=\"100;\"  alt=Manav Arora/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Manav Arora</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/silentwraith6>\n            <img src=https://avatars.githubusercontent.com/u/46311762?v=4 width=\"100;\"  alt=Manav Gupta/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Manav Gupta</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/mjavier2k>\n            <img src=https://avatars.githubusercontent.com/u/22145?v=4 width=\"100;\"  alt=Marvin Javier/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Marvin Javier</b></sub>\n        </a>\n    </td>\n</tr>\n<tr>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/Mayukh-1999>\n            <img src=https://avatars.githubusercontent.com/u/66203366?v=4 width=\"100;\"  alt=Mayukh Mitra/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Mayukh Mitra</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/TheMixu>\n            <img src=https://avatars.githubusercontent.com/u/49287947?v=4 width=\"100;\"  alt=Mika/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Mika</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/codewithmini>\n            <img src=https://avatars.githubusercontent.com/u/91717400?v=4 width=\"100;\"  alt=Mini/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Mini</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/MojoAlpha>\n            <img src=https://avatars.githubusercontent.com/u/61064253?v=4 width=\"100;\"  alt=Mohit Pandey/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Mohit Pandey</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/stellaharmony>\n            <img src=https://avatars.githubusercontent.com/u/13765264?v=4 width=\"100;\"  alt=Mukund Bhole/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Mukund Bhole</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/NEERAJAP2001>\n            <img src=https://avatars.githubusercontent.com/u/65017645?v=4 width=\"100;\"  alt=Neeraj Ap/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Neeraj Ap</b></sub>\n        </a>\n    </td>\n</tr>\n<tr>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/niladribit69>\n            <img src=https://avatars.githubusercontent.com/u/58898879?v=4 width=\"100;\"  alt=NILADRI BIT/>\n            <br />\n            <sub style=\"font-size:14px\"><b>NILADRI BIT</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/NidhiNivedita6>\n            <img src=https://avatars.githubusercontent.com/u/56748276?v=4 width=\"100;\"  alt=Nidhi Nivedita/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Nidhi Nivedita</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/Nishit278>\n            <img src=https://avatars.githubusercontent.com/u/56290154?v=4 width=\"100;\"  alt=Nishit Bansal/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Nishit Bansal</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/omarahmed1111>\n            <img src=https://avatars.githubusercontent.com/u/30423288?v=4 width=\"100;\"  alt=Omar Ahmed/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Omar Ahmed</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/PUSHPASINGH00>\n            <img src=https://avatars.githubusercontent.com/u/72371689?v=4 width=\"100;\"  alt=PUSHPASINGH00/>\n            <br />\n            <sub style=\"font-size:14px\"><b>PUSHPASINGH00</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/NumberPiOso>\n            <img src=https://avatars.githubusercontent.com/u/46936498?v=4 width=\"100;\"  alt=poloso/>\n            <br />\n            <sub style=\"font-size:14px\"><b>poloso</b></sub>\n        </a>\n    </td>\n</tr>\n<tr>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/Pacifier25>\n            <img src=https://avatars.githubusercontent.com/u/64539670?v=4 width=\"100;\"  alt=PIYUSH BIST/>\n            <br />\n            <sub style=\"font-size:14px\"><b>PIYUSH BIST</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/OfiliPatrick>\n            <img src=https://avatars.githubusercontent.com/u/44137944?v=4 width=\"100;\"  alt=Patrick Ofili/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Patrick Ofili</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/pc-beast>\n            <img src=https://avatars.githubusercontent.com/u/56963647?v=4 width=\"100;\"  alt=Pavnesh Chaturvedi/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Pavnesh Chaturvedi</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/pranjalkumar153>\n            <img src=https://avatars.githubusercontent.com/u/46496408?v=4 width=\"100;\"  alt=pranjalkumar153/>\n            <br />\n            <sub style=\"font-size:14px\"><b>pranjalkumar153</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/priyankkumar218>\n            <img src=https://avatars.githubusercontent.com/u/12366834?v=4 width=\"100;\"  alt=Priyank Kumar/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Priyank Kumar</b></sub>\n        </a>\n    </td>\n    <td align=\"center\" style=\"word-wrap: break-word; width: 150.0; height: 150.0\">\n        <a href=https://github.com/Priyanka-hub-bit>\n            <img src=https://avatars.githubusercontent.com/u/56428439?v=4 width=\"100;\"  alt=Priyanka Yadav/>\n            <br />\n            <sub style=\"font-size:14px\"><b>Priyanka Yadav</b></sub>\n        </a>\n    </td>\n</tr>\n</table>\n\n"
  },
  {
    "path": "Collection/ArrayDeque/ArrayDeque.java",
    "content": "import java.util.*;\n\n/*\nArrayDeque abstract data structure :- \nAn ArrayDeque (also known as an \"Array Double Ended Queue\", pronounced as \"ArrayDeck\") is a special kind of a growable array that allows us to add or remove an element from both sides.\n\nThe ArrayDeque data structure is implemented in java collections framework through the ArrayDeque interface\nWe can also say that ArrayDeque is a collections framework API that realizes the ArrayDeque abstract data structure\n*/\n\npublic class ArrayDequeDemo\n{\n    public static void main(String[] args)\n    {\n        Scanner in = new Scanner(System.in);\n        // Creating an ArrayDeque of integers\n        ArrayDeque<Integer> ArrDq = new ArrayDeque<Integer>();\n        // We can also create an ArrayDeque of other data types like Character or String etc.\n\n        System.out.println(\"Instruction Format : command_ name element_value\");\n        System.out.println(\"1. Add an element to the front or left end of ArrayDeque : command-> \\\"addFirst value\\\". Example \\\"addFirst 20\\\" will add 20 to the front of ArrayDeque\");\n        System.out.println(\"2. Add an element to the end or right end of ArrayDeque : command-> \\\"addLast value\\\" .Example \\\"addLast 50\\\" will add 50 to the rear end of ArrayDeque\");\n        System.out.println(\"3. Remove the element at the front or left end of ArrayDeque : command-> \\\"removeFirst\\\"\");\n        System.out.println(\"4. Remove the element at the rear end or right end of ArrayDeque : command-> \\\"removeLast\\\"\");\n        System.out.println(\"5. Show the present size of the ArrayDeque : command-> \\\"size\\\"\");\n        System.out.println(\"6. Check if the ArrayDeque is empty : command-> \\\"isEmpty\\\"\");\n        System.out.println(\"7. Exit the program: command-> \\\"Exit\\\"\");\n        // Note that the method names are same the commands to do a specific operation on ArrayDeque\n\n        while(true)\n        {\n            String[] command = in.nextLine().split(\" \");\n            boolean got_value = false;\n            try\n            {\n                String command_name = command[0];\n                int value = 0;\n                int output = 0;\n                if (command.length > 1)\n                {\n                    value = Integer.parseInt(command[1]);\n                    got_value = true;\n                }\n                switch(command_name)\n                {\n                    case \"addFirst\" : \n                        // addFirst method adds an element to the front (left) end of the ArrayDeque\n                        if (got_value)\n                            ArrDq.addFirst(value);\n                        else\n                            throw new NumberFormatException();\n                        break;\n                    case \"addLast\" : \n                        // addLast method adds an element to the rear (right) end of the ArrayDeque\n                        if (got_value)\n                            ArrDq.addLast(value);\n                        else\n                            throw new NumberFormatException();\n                        break;\n                    case \"removeFirst\" :     \n                        // removeFirst method removes and returns an element from the front (left) end of the ArrayDeque\n                        output = ArrDq.removeFirst();\n                        System.out.println(\"Removed \" + output + \" from the front of the ArrayDeque\");\n                        break;\n                    case \"removeLast\" : \n                        // removeLast method removes and return an element from the rear (right) end of the ArrayDeque\n                        output = ArrDq.removeLast();\n                        System.out.println(\"Removed \" + output + \" from the end of the ArrayDeque\");\n                        break;\n                    case \"size\" : \n                        // size method returns the present size of ArrayDeque\n                        output = ArrDq.size();\n                        System.out.println(\"Size of the ArrayDeque is : \" + output);\n                        break;\n                    case \"isEmpty\" :\n                        // isEmpty method returns a boolean true if the ArrayDeque is empty else it return false\n                        Boolean empty = ArrDq.isEmpty();\n                        if (empty)\n                            System.out.println(\"Array deque is Empty\");\n                        else\n                            System.out.println(\"Array deque is not Empty\");\n                        break;\n                    case \"Exit\":\n                        in.close();\n                        return;\n                    default :\n                        System.out.println(\"Please enter a valid command\");\n                }\n                System.out.println(\"ArrayDeque : \");\n                System.out.println(ArrDq); \n            }\n            catch(NumberFormatException e)\n            {\n                System.out.println(\"Please enter a valid number\");\n            }\n            catch(Exception e)\n            {\n                System.out.println(\"Exception :\" + e.getMessage());\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "Collection/ArrayDeque/README.md",
    "content": "# This folder is empty.\n"
  },
  {
    "path": "Collection/ArrayList/ArrayList .java",
    "content": "import java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.Scanner;\n\npublic class Arraylist {\n\n\tpublic static void main(String[] args) {\n\t\tScanner sc = new Scanner(System.in);\n\t\t//Array List implementation\n\t\tArrayList<Integer> number = new ArrayList<Integer>();\n\t\t//Entering elements from 1 to 5 using add method\n\t\tfor(int i=1;i<=5;i++) {\n\t\t\tnumber.add(i);\n\t\t}\n\t\t//size() method can be used to tell number of elements in the list\n\t\tfor(int i=0;i<number.size();i++) {\n\t\t\t//Printing the array elements using get method\n\t\t\tSystem.out.print(number.get(i)+\" \");\n\t\t}\n\t\t//To insert an element at specified index\n\t\tnumber.add(2,7);\n\t\tArrayList<Integer> newlist = new ArrayList<Integer>();\n\t\tfor(int i=10;i<=15;i++) {\n\t\t\tnewlist.add(i);\n\t\t}\n\t\t//To add another list elements to previous list\n\t\tnumber.addAll(newlist);\n\t\t//To delete all elements in a list\n\t\tnewlist.clear();\n\t\tSystem.out.println();\n\t\t//To check whether the list is empty or not\n\t\tif(newlist.isEmpty()) {\n\t\t\tSystem.out.println(\"The list is empty\");\n\t\t}\n\t\t//To get index of an element\n\t\tint index = number.indexOf(new Integer(7));\n\t\t//To remove the element with index\n\t\tnumber.remove(index);\n\t\t//We can also sort an list using\n\t\tCollections.sort(number);\n\t\tfor(int i=0;i<number.size();i++) {\n\t\t\tSystem.out.print(number.get(i)+\" \");\n\t\t}\n\t\t\n\n\t}\n\n}\n"
  },
  {
    "path": "Collection/ArrayList/README.md",
    "content": "# This folder is empty.\n"
  },
  {
    "path": "Collection/HashMap/HashMap.java",
    "content": "import java.util.HashMap;\nimport java.util.Scanner;\n\nclass HashMapDemo {\n    //constant command strings\n    private static final String COMMAND_ADD= \"a\";\n    private static final String COMMAND_REMOVE = \"r\";\n    private static final String COMMAND_VALUE = \"v\";\n    private static final String COMMAND_IS_KEY_EXISTS = \"?k\";\n    private static final String COMMAND_IS_VALUE_EXISTS = \"?v\";\n    private static final String COMMAND_ALL_KEY = \"ak\";\n    private static final String COMMAND_ALL_VALUE = \"av\";\n    private static final String COMMAND_SIZE = \"si\";\n    private static final String COMMAND_SHOW = \"sh\";\n    private static final String COMMAND_QUIT= \"q\";\n\n    public static void main(String[] args) {\n\n        Scanner myScanner = new Scanner(System.in);\n\n        // HashMap is a key-value pair data structure. Here, Key ( String ) - value (String ) type\n        HashMap<String, String > hashMap = new HashMap<>();\n\n\n        System.out.println(\"Instructions:\");\n        System.out.println(\"\\t1. Add value: \\\"\"+COMMAND_ADD+\" key value\\\" . Example: \\\"a name Rezwan\\\" here, key = 'name' , value = 'Rezwan' \");\n        System.out.println(\"\\t2. Show value: \\\"\"+COMMAND_VALUE+\" key_name_here\\\"\");\n        System.out.println(\"\\t3. Remove value: \\\"\"+COMMAND_REMOVE+\" key_name_here\\\"\");\n\n        System.out.println(\"\\t4. check if key exists : \\\"\"+COMMAND_IS_KEY_EXISTS+\" key_name_here\\\"\");\n        System.out.println(\"\\t5. check if value exists : \\\"\"+COMMAND_IS_VALUE_EXISTS+\" value_name_here\\\"\");\n\n        System.out.println(\"\\t7. See ALl Keys : \\\"\"+COMMAND_ALL_KEY+\"\\\"\");\n        System.out.println(\"\\t8. See ALl Values : \\\"\"+COMMAND_ALL_VALUE+\"\\\"\");\n\n        System.out.println(\"\\t9. See current HashMap conditions: \\\"\"+COMMAND_SHOW+\"\\\"\");\n        System.out.println(\"\\t10. Size of the HashMap: \\\"\"+COMMAND_SIZE+\"\\\"\");\n        System.out.println(\"\\t11. Exit program: \\\"\"+COMMAND_QUIT+\"\\\"\");\n\n        while (true) {\n\n            // dividing the command string and number value\n            String[] tempCommand = myScanner.nextLine().split(\" \");\n\n            try{\n                String commandName = String.valueOf(tempCommand[0]);\n                String str1 = \"\", str2 = \"\";\n\n                if(tempCommand.length == 2){\n                    str1 = String.valueOf(tempCommand[1]);\n                }\n                else if(tempCommand.length == 3){\n                    str1 = String.valueOf(tempCommand[1]);\n                    str2 = String.valueOf(tempCommand[2]);\n                }\n\n                //checking command name and performing accordingly\n\n                switch (commandName){\n                    case COMMAND_ADD:\n                        hashMap.put(str1, str2);\n                        System.out.println(str1+ \"-\" +str2 + \" added\");\n                        break;\n\n                    case COMMAND_VALUE:\n                        System.out.println( hashMap.get(str1) + \" is the value of KEY = \"+ str1);\n                        break;\n\n                    case COMMAND_REMOVE:\n                        hashMap.remove(str1);\n                        System.out.println( \"Pair of \" +str1 + \" KEY is removed\");\n                        break;\n\n                    case COMMAND_IS_KEY_EXISTS:\n                        if(hashMap.containsKey(str1)){\n                            System.out.println(str1 + \" key exists in the hashmap\");\n                        }\n                        else{\n                            System.out.println(str1 + \" key doesn't exist in the hashmap\");\n                        }\n                        break;\n\n                    case COMMAND_IS_VALUE_EXISTS:\n\n                        if(hashMap.containsValue(str1)){\n                            System.out.println(str1 + \" value exists in the hashmap\");\n                        }\n                        else{\n                            System.out.println(str1 + \" value doesn't exist in the hashmap\");\n                        }\n                        break;\n\n                    case COMMAND_ALL_KEY:\n                        System.out.println(\"All Keys: \"+hashMap.keySet());\n                        break;\n\n                    case COMMAND_ALL_VALUE:\n                        System.out.println(\"All Values: \"+hashMap.values());\n                        break;\n\n                    case COMMAND_SIZE:\n                        System.out.println(\"HashMap size is \"+hashMap.size()+\" right now\");\n                        break;\n\n                    case COMMAND_SHOW:\n                        System.out.println(hashMap);\n                        break;\n\n                    case COMMAND_QUIT:\n                        return;\n\n                    default:\n                        System.out.println(\"Invalid command format\");\n                        break;\n                }\n            }\n            catch (NumberFormatException e){\n                System.out.println(\"Invalid command format\");\n            }\n            catch (Exception e){\n                System.out.println(\"Exception: \"+ e.getMessage());\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "Collection/HashMap/README.md",
    "content": "# This folder is empty.\n"
  },
  {
    "path": "Collection/HashSet/HashSet.java",
    "content": "import java.util.HashSet;\nimport java.util.Iterator;\nimport java.util.Scanner;\n\nclass HashSetDemo {\n     //constant command strings\n     private static final String COMMAND_ADD= \"a\";\n     private static final String COMMAND_REMOVE = \"r\";\n\n     private static final String COMMAND_IS_VALUE_EXISTS = \"?v\";\n\n     private static final String COMMAND_ALL_VALUE = \"av\";\n\n     private static final String COMMAND_ITERATE_ALL_VALUE = \"i\";\n\n     private static final String COMMAND_CLEAR = \"c\";\n\n     private static final String COMMAND_SIZE = \"si\";\n     private static final String COMMAND_SHOW = \"sh\";\n     private static final String COMMAND_QUIT= \"q\";\n\n     public static void main(String[] args) {\n\n      Scanner myScanner = new Scanner(System.in);\n\n      // HashSet ensure there is no duplicate value in it\n      HashSet<Integer> hashSet = new HashSet<>();\n\n\n      System.out.println(\"Instructions:\");\n      System.out.println(\"\\t1. Add value: \\\"\"+COMMAND_ADD+\" value\\\" . Example: \\\"a 44\\\" here, 44 is added\");\n      System.out.println(\"\\t2. Remove value: \\\"\"+COMMAND_REMOVE+\" value_here\\\"\");\n      System.out.println(\"\\t3. check if value exists : \\\"\"+COMMAND_IS_VALUE_EXISTS+\" value_here\\\"\");\n      System.out.println(\"\\t4. See ALl Values : \\\"\"+COMMAND_ALL_VALUE+\"\\\"\");\n      System.out.println(\"\\t5. Iterate through all values : \\\"\"+COMMAND_ITERATE_ALL_VALUE+\"\\\"\");\n      System.out.println(\"\\t6. Clear HashSet : \\\"\"+COMMAND_CLEAR+\"\\\"\");\n      System.out.println(\"\\t7. See current HashSet conditions: \\\"\"+COMMAND_SHOW+\"\\\"\");\n      System.out.println(\"\\t8. Size of the HashSet: \\\"\"+COMMAND_SIZE+\"\\\"\");\n      System.out.println(\"\\t9. Exit program: \\\"\"+COMMAND_QUIT+\"\\\"\");\n\n\n      while (true) {\n\n         // dividing the command string and number value\n         String[] tempCommand = myScanner.nextLine().split(\" \");\n\n         try{\n          String commandName = String.valueOf(tempCommand[0]);\n          int value = 0;\n\n          if(tempCommand.length == 2){\n              value = Integer.parseInt(tempCommand[1]);\n          }\n\n          //checking command name and performing accordingly\n          switch (commandName){\n               case COMMAND_ADD:\n                    if(hashSet.add(value)){\n                        System.out.println(value+ \" is added to the hashset\");\n\n                    }\n                    else{\n                        System.out.println(value+ \" is already on the hashset\");\n                    }\n                    break;\n\n               case COMMAND_REMOVE:\n                   if(hashSet.remove(value)){\n                       System.out.println(value+ \" is removed from hashset\");\n\n                   }\n                   else{\n                       System.out.println(value+ \" remove failed\");\n                   }\n                   break;\n\n\n               case COMMAND_IS_VALUE_EXISTS:\n                    if(hashSet.contains(value)){\n                        System.out.println(value + \" value exists in the hashset\");\n                    }\n                    else{\n                        System.out.println(value + \" value doesn't exist in the hashset\");\n                    }\n                    break;\n\n               case COMMAND_ALL_VALUE:\n                    System.out.println(\"All Values: \"+hashSet);\n                    break;\n\n              case COMMAND_ITERATE_ALL_VALUE:\n                  Iterator<Integer> i = hashSet.iterator();\n                  int c = 1;\n                  while (i.hasNext()){\n                      System.out.println(\"Serial \"+ c + \" is : \" +i.next());\n                      c++;\n                  }\n                  System.out.println(\"----------------\");\n                  break;\n\n               case COMMAND_SIZE:\n                    System.out.println(\"HashSet size is \"+hashSet.size()+\" right now\");\n                    break;\n\n               case COMMAND_SHOW:\n                    System.out.println(hashSet);\n                    break;\n\n               case COMMAND_QUIT:\n                    return;\n\n               default:\n                    System.out.println(\"Invalid command format\");\n                    break;\n              }\n         }\n         catch (NumberFormatException e){\n          System.out.println(\"Invalid command format\");\n         }\n         catch (Exception e){\n          System.out.println(\"Exception: \"+ e.getMessage());\n         }\n         }\n     }\n}\n"
  },
  {
    "path": "Collection/HashSet/README.md",
    "content": "# This folder is empty.\n"
  },
  {
    "path": "Collection/LinkedList/LinkedHashSet/README.md",
    "content": "# This folder is empty.\n"
  },
  {
    "path": "Collection/LinkedList/LinkedList.java",
    "content": " // LinkedList is a very useful and famous data structure which is linear in nature. This data structure is used to add elements dynamically without any fixed memory size. \n // This feature makes it advantageous over simple arrays, where initially the array size gets fixed and which may result in unused extra memory or shortange of memory size.\n\n//Here we try to implement in-built LinkedList in java and see some of its methods like add(),addFist(),addLast(),remove(),removeFirst(),removeLast(),set()..etc.\n\n//This package has the LinkedList class(which implements List interface.\nimport java.util.*;\nclass LinkedListDemo{\n  public static void main(String args[]){\n    //This is how we initialise a linkedlist named 'list' with Data type as String which will be stored.\n    LinkedList<String> list=new LinkedList<String>();\n    \n    Scanner sc=new Scanner(System.in);\n    System.out.println(\"Enter the number strings to be added in list initially\");\n    int n=sc.nextInt();\n    while(n-->0){\n     String str=sc.next();  //Use this to input from user.\n     list.add(str);  //keep on adding the strings.\n    }\n    //The list elements get added one after the other and its printed as in order.\n    System.out.println(list);\n    \n   // we can use other methods like addFirst() and addLast() to add elements at the beginning and the last\n    System.out.println(\"Enter the string you want to add at the beginning\");\n    String starting_str=sc.next();\n    list.addFirst(starting_str);\n    \n    System.out.println(\"Enter the string you want to add at the ending\");\n    String ending_str=sc.next();\n    list.addLast(ending_str); \n    \n    \n    \n    System.out.println(\"Updated list->\"+list);    \n    \n    //Other common methods are removing elements from front and last;\n    list.removeFirst();\n    list.removeLast();\n    \n    System.out.println(\"Updated list after deleting first and last node->\"+list);\n    \n    String str1=list.getFirst();\n    String str2=list.getLast();\n    \n    System.out.println(\"First Node is\"+str1);\n    System.out.println(\"Last Node is\"+str2);\n    \n    //Since its indexed, we can also set element at specified position and also remove by specifying the position\n    System.out.println(\"Enter the index and String you want to insert at\");\n    int ind=sc.nextInt();\n    String new_str=sc.next();\n    list.set(ind,new_str); \n \n    list.addFirst(\"LinkedList DEMO from @PrakashAditya17::\");  //Random string added here\n   \n    System.out.println(\"UPDATED LIST->\"+list); \n    System.out.println(\"Enter the position of any String you want to remove\");\n    int ind_remove=sc.nextInt();\n    list.remove(ind_remove);       \n    \n   //For iteration we can use use the following way.\n    for(String ele : list)\n      System.out.print(ele+\",\");\n  }\n}\n"
  },
  {
    "path": "Collection/LinkedList/README.md",
    "content": "# This folder is empty.\n"
  },
  {
    "path": "Collection/Queue/Deque/Deque.java",
    "content": "import java.util.*;\n\nclass DequeDemo{\n\n    //constant command strings\n    private static final String COMMAND_ADDLAST = \"al\";\n    private static final String COMMAND_REMOVELAST = \"rl\";\n    private static final String COMMAND_ADDFIRST = \"af\";\n    private static final String COMMAND_REMOVEFIRST = \"rf\";\n    private static final String COMMAND_FIRSTVALUE = \"f\";\n    private static final String COMMAND_SHOWREMOVEFIRST = \"srf\";\n    private static final String COMMAND_SHOWREMOVELAST = \"srl\";\n    private static final String COMMAND_LASTVALUE = \"l\";\n    private static final String COMMAND_SIZE = \"si\";\n    private static final String COMMAND_SHOW = \"sh\";\n    private static final String COMMAND_QUIT= \"q\";\n\n    public static void main(String[] args) {\n\n        Scanner myScanner = new Scanner(System.in);\n\n        // Deque is an interface. there are two deque implementations :\n        Deque<Integer> arrayDeque = new ArrayDeque<Integer>(); // 1. using ArrayDeque instance\n        Deque<Integer> linkedListDeque = new ArrayDeque<Integer>(); //2. using LinkedList instance\n\n        //Deque is a double ended queue. It's possible to add or remove element from both head and tail\n        System.out.println(\"Instructions: \\\"command_name _value\\\" , for example: al 44\");\n        System.out.println(\"\\t1. Add value at the end command: \\\"\"+COMMAND_ADDLAST+\"\\\" . Example: \\\"al 11\\\" will add 11 at the end\");\n        System.out.println(\"\\t2. Remove value from the end command: \\\"\"+COMMAND_REMOVELAST+\"\\\" \");\n        System.out.println(\"\\t3. Add value at the beginning command: \\\"\"+COMMAND_ADDFIRST+\"\\\"\");\n        System.out.println(\"\\t4. Remove value from the beginning command: \\\"\"+COMMAND_REMOVEFIRST+\"\\\"\");\n        System.out.println(\"\\t5. First value: \\\"\"+COMMAND_FIRSTVALUE+\"\\\"\");\n        System.out.println(\"\\t6. Last value: \\\"\"+COMMAND_LASTVALUE+\"\\\"\");\n        System.out.println(\"\\t7. Show and Remove First value: \\\"\"+COMMAND_SHOWREMOVEFIRST+\"\\\"\");\n        System.out.println(\"\\t8. Show and Remove Last value: \\\"\"+COMMAND_SHOWREMOVELAST+\"\\\"\");\n        System.out.println(\"\\t9. Size of the Deque: \\\"\"+COMMAND_SIZE+\"\\\"\");\n        System.out.println(\"\\t10. See current Deque conditions: \\\"\"+COMMAND_SHOW+\"\\\"\");\n        System.out.println(\"\\t11. Exit program: \\\"\"+COMMAND_QUIT+\"\\\"\");\n\n        while (true) {\n\n            // dividing the command string and number value\n            String[] tempCommand = myScanner.nextLine().split(\" \");\n\n            try{\n                String commandName = String.valueOf(tempCommand[0]);\n                int value = 0;\n\n                //if only command without value, then we need not try parsing value\n                if(tempCommand.length > 1){\n                    value = Integer.parseInt(tempCommand[1]);\n                }\n\n                //checking command name and performing accordingly\n                boolean isDone = false;\n                switch (commandName){\n                    case COMMAND_ADDLAST:\n                        isDone = arrayDeque.offerLast(value);\n                        if(isDone){\n                            System.out.println(value + \" is added to last\");\n                        }\n                        break;\n                    case COMMAND_ADDFIRST:\n                        isDone = arrayDeque.offerFirst(value);\n                        if(isDone){\n                            System.out.println(value + \" is added to the first\");\n                        }\n                        break;\n                    case COMMAND_REMOVEFIRST:\n                        System.out.println(arrayDeque.removeFirst() + \" is removed from first\");\n                        break;\n                    case COMMAND_FIRSTVALUE:\n                        System.out.println(arrayDeque.getFirst() + \" is first value right now\");\n                        break;\n                    case COMMAND_SHOWREMOVEFIRST:\n                        System.out.println(arrayDeque.pollFirst() + \" is first value which is just removed from deque.\");\n                        break;\n                    case  COMMAND_SHOWREMOVELAST :\n                        System.out.println(arrayDeque.pollLast() + \" is last value which is just removed from deque.\");\n                        break;\n                    case COMMAND_LASTVALUE:\n                        System.out.println(arrayDeque.getLast() + \" is last value right now\");\n                        break;\n                    case COMMAND_SIZE:\n                        System.out.println(\"Deque size is \"+arrayDeque.size()+\" right now\");\n                        break;\n                    case COMMAND_SHOW:\n                        System.out.println(arrayDeque);\n                        break;\n                    case COMMAND_QUIT:\n                        return;\n                    default:\n                        System.out.println(\"Invalid command format\");\n                        break;\n                }\n            }\n            catch (NumberFormatException e){\n                System.out.println(\"Invalid command format\");\n            }\n            catch (Exception e){\n                System.out.println(\"Exception: \"+ e.getMessage());\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "Collection/Queue/Deque/README.md",
    "content": "# This folder is empty.\n"
  },
  {
    "path": "Collection/Queue/PriorityQueue/PriorityQueue.java",
    "content": "import java.util.PriorityQueue;\nimport java.util.Scanner;\n\nclass PriorityQueueDemo{\n\n    //constant command strings\n    private static final String COMMAND_ADD= \"a\";\n    private static final String COMMAND_REMOVE = \"r\";\n    private static final String COMMAND_FIRSTVALUE = \"f\";\n    private static final String COMMAND_SHOWREMOVE = \"sr\";\n    private static final String COMMAND_SIZE = \"si\";\n    private static final String COMMAND_SHOW = \"sh\";\n    private static final String COMMAND_QUIT= \"q\";\n\n    public static void main(String[] args) {\n\n        Scanner myScanner = new Scanner(System.in);\n        //the elements keeping on PriorityQueue must be implements  Comparable interface.\n        // In this case, Integer implements Comparable interface\n        // PriorityQueue is automatically rearranged based on priority set by toCompare() overridden method\n        PriorityQueue<Integer> priorityQueue = new PriorityQueue<Integer>();\n\n\n        System.out.println(\"Instructions: \\\"command_name _value\\\" , for example: a 44\");\n        System.out.println(\"\\t1. Add value: \\\"\"+COMMAND_ADD+\"\\\" . Example: \\\"a 11\\\" will add 11 at the priority queue\");\n        System.out.println(\"\\t2. First/Peek value: \\\"\"+COMMAND_FIRSTVALUE+\"\\\"\");\n        System.out.println(\"\\t3. Remove First/Peek value: \\\"\"+COMMAND_REMOVE+\"\\\"\");\n        System.out.println(\"\\t4. Show and Remove First/Peek value: \\\"\"+COMMAND_SHOWREMOVE+\"\\\"\");\n        System.out.println(\"\\t5. Size of the Deque: \\\"\"+COMMAND_SIZE+\"\\\"\");\n        System.out.println(\"\\t6. See current Deque conditions: \\\"\"+COMMAND_SHOW+\"\\\"\");\n        System.out.println(\"\\t7. Exit program: \\\"\"+COMMAND_QUIT+\"\\\"\");\n\n        while (true) {\n\n            // dividing the command string and number value\n            String[] tempCommand = myScanner.nextLine().split(\" \");\n\n            try{\n                String commandName = String.valueOf(tempCommand[0]);\n                int value = 0;\n\n                //if only command without value, then we need not try parsing value\n                if(tempCommand.length > 1){\n                    value = Integer.parseInt(tempCommand[1]);\n                }\n\n                //checking command name and performing accordingly\n                boolean isDone = false;\n                switch (commandName){\n                    case COMMAND_ADD:\n                        isDone = priorityQueue.offer(value);\n                        if(isDone){\n                            System.out.println(value + \" is added\");\n                        }\n                        else{\n                            System.out.println(value + \" couldn't add !\");\n                        }\n                        break;\n                    case COMMAND_REMOVE:\n                        priorityQueue.remove();\n                        System.out.println( \"first value is removed from  priority queue.\");\n                        break;\n                    case COMMAND_FIRSTVALUE:\n                        System.out.println(priorityQueue.peek() + \" is first value right now\");\n                        break;\n                    case COMMAND_SHOWREMOVE:\n                        System.out.println(priorityQueue.poll() + \" is first value which is just removed from priority queue.\");\n                        break;\n\n                    case COMMAND_SIZE:\n                        System.out.println(\"PriorityQueue size is \"+priorityQueue.size()+\" right now\");\n                        break;\n                    case COMMAND_SHOW:\n                        System.out.println(priorityQueue);\n                        break;\n                    case COMMAND_QUIT:\n                        return;\n                    default:\n                        System.out.println(\"Invalid command format\");\n                        break;\n                }\n            }\n            catch (NumberFormatException e){\n                System.out.println(\"Invalid command format\");\n            }\n            catch (Exception e){\n                System.out.println(\"Exception: \"+ e.getMessage());\n            }\n        }\n    }\n\n}\n"
  },
  {
    "path": "Collection/Queue/PriorityQueue/README.md",
    "content": "# This folder is empty.\n"
  },
  {
    "path": "Collection/Queue/Queue.java",
    "content": "import java.util.ArrayDeque;\nimport java.util.Queue;\nimport java.util.Scanner;\n \npublic class Main {\n    public static void main(String[] args) {\n        //get dynamic inputs\n        Scanner sc = new Scanner(System.in);\n        String[] inputNumbers = sc.nextLine().split(\" \");\n        \n        //define queue\n        Queue<Integer> q = new ArrayDeque();\n        \n        // Add values to queue\n        for (String n: inputNumbers)\n            q.add(Integer.parseInt(n));\n        // Display contents of the queue.\n        System.out.println(\"Elements of queue \"\n                           + q);\n        \n        //To view the size of the queue\n        int size = q.size();\n        System.out.println(\"Size of queue is: \"\n                           + size);\n                           \n                           \n        // To remove the head of queue.\n        int removedele = q.remove();\n        System.out.println(\"removed element is: \"\n                           + removedele);\n        System.out.println(\"Elements of queue after remove \"\n                           + q);    \n                 \n        // To view the head of queue without removing.\n        int head = q.peek();\n        System.out.println(\"head of queue is: \"\n                           + head);\n                           \n        //To check if it is empty or not.\n        System.out.println(\"Is queue empty : \"\n                           + q.isEmpty());\n                           \n        //clearing the whole queue\n        q.clear();\n        System.out.println(\"After clearing queue \"\n                           + q);\n    }\n}\n"
  },
  {
    "path": "Collection/Queue/README.md",
    "content": "# This folder is empty.\n"
  },
  {
    "path": "Collection/README.md",
    "content": "# Index\n\n* [ArrayList](ArrayList/)\n* [ArrayDeque](ArrayDeque/)\n* [Vector](Vector/)\n* [LinkedList](LinkedList/)\n* [HashSet](HashSet/)   \n* [HashMap](HashMap/) \n* [Queue](Queue/) \n* [Stack](Stack/)"
  },
  {
    "path": "Collection/Stack/README.md",
    "content": "# This folder is empty.\n"
  },
  {
    "path": "Collection/Stack/StackCollection.java",
    "content": "import java.io.*;\nimport java.util.*;\n\npublic class StackCollection{\n    public static void main(String[] args) {\n        Scanner input = new Scanner(System.in);\n        Stack<Integer> st = new Stack<Integer>(); //create a object of class stack\n        //Adding 5 elements to the stack\n        int n = 5; \n        for(int i=0;i<n;i++){\n            int element = input.nextInt();\n            st.push(element);   //add element to the stack\n        }\n\n        int top = st.peek(); //get topmost element\n        System.out.println(top); \n\n        st.pop(); //removes the top most element from stack and return's it\n\n        int sizeOfStack = st.size(); // return's size of stack\n\n        if(st.empty()){ // if stack is empty return's true\n            System.out.println(\"Stack is empty\");\n        }else{\n            System.out.println(\"Stack is not empty\");\n        }// Print's stack is not empty.\n    }\n}"
  },
  {
    "path": "Collection/Vector/README.md",
    "content": "# This folder is empty.\n"
  },
  {
    "path": "Collection/Vector/Vector.java",
    "content": "import java.io.*;\nimport java.util.*;\n  \nclass Main {\n    \n    public static void main(String[] args)\n    {\n        Scanner sc = new Scanner( System.in );\n      \n        int n = sc.nextInt();\n      \n        Vector<Integer> vec = new Vector<Integer>(n);\n  \n        for (int i = 0; i < n; i++)\n            vec.add(sc.nextInt());\n      \n        System.out.println(vec);\n      \n        vec.remove(0);\n\n        System.out.println(vec);\n  \n    }\n}\n"
  },
  {
    "path": "DOCUMENTATION.md",
    "content": "# Title\n* Description\n\n<!-- Remove this if there aren't any valid sub topics -->\n# Sub Topics\n* [Name](Relative_path/)\n* [Name](Relative_path/)\n* [Name](Relative_path/)\n\n<!-- For Data Structures Only -->\n# Methods\n\n| Operation | Description\n|:--|:--\n| Name | Desc\n| Name | Desc\n| Name | Desc\n\n# Time Complexity\n\n| Operation | Complexity\n|:--|:--\n|Access | O() \n|Search | O() \n|Insertion | O() \n|Deletion | O() \n\n# Implementation\n\n| Language | View | Code\n|:--: |:--: |:--:\n| c++ | [Github](https://github.com/ahampriyanshu/algo_ds_101/blob/main/folder/subfolder/filename.ext) | [Raw](filename.cpp)\n| c | [Github](https://github.com/ahampriyanshu/algo_ds_101/blob/main/folder/subfolder/filename.ext) | [Raw](filename.c)\n| java | [Github](https://github.com/ahampriyanshu/algo_ds_101/blob/main/folder/subfolder/filename.ext) | [Raw](filename.java)\n| js | [Github](https://github.com/ahampriyanshu/algo_ds_101/blob/main/folder/subfolder/filename.ext) | [Raw](filename.js)\n| ts | [Github](https://github.com/ahampriyanshu/algo_ds_101/blob/main/folder/subfolder/filename.ext) | [Raw](filename.ts)\n| py | [Github](https://github.com/ahampriyanshu/algo_ds_101/blob/main/folder/subfolder/filename.ext) | [Raw](filename.py)\n| cs | [Github](https://github.com/ahampriyanshu/algo_ds_101/blob/main/folder/subfolder/filename.ext) | [Raw](filename.cs)\n| rb | [Github](https://github.com/ahampriyanshu/algo_ds_101/blob/main/folder/subfolder/filename.ext) | [Raw](filename.rb)\n| php | [Github](https://github.com/ahampriyanshu/algo_ds_101/blob/main/folder/subfolder/filename.ext) | [Raw](filename.php)\n| go | [Github](https://github.com/ahampriyanshu/algo_ds_101/blob/main/folder/subfolder/filename.ext) | [Raw](filename.go)\n| scala | [Github](https://github.com/ahampriyanshu/algo_ds_101/blob/main/folder/subfolder/filename.ext) | [Raw](filename.scala)\n| swift | [Github](https://github.com/ahampriyanshu/algo_ds_101/blob/main/folder/subfolder/filename.ext) | [Raw](filename.swift)\n| haskell | [Github](https://github.com/ahampriyanshu/algo_ds_101/blob/main/folder/subfolder/filename.ext) | [Raw](filename.haskell)\n| bash | [Github](https://github.com/ahampriyanshu/algo_ds_101/blob/main/folder/subfolder/filename.ext) | [Raw](filename.bash)\n| kotlin | [Github](https://github.com/ahampriyanshu/algo_ds_101/blob/main/folder/subfolder/filename.ext) | [Raw](filename.kotlin)"
  },
  {
    "path": "Data-Structures/Array/Array.c",
    "content": "#include <stdio.h>\n#include <stdlib.h>\n \nint main()\n{\n \n    int* ptr;\n    int n;\n \n    printf(\"Enter number of elements:\\n\");\n    scanf(\"%d\",&n);\n \n    // Dynamically allocate memory using malloc()\n    ptr = (int*)malloc(n * sizeof(int));\n  \n \n    // Get the elements of the array\n    printf(\"Input the elements of the array\\n\");\n    for (int i = 0; i < n; ++i) \n    {\n        scanf(\"%d\",&ptr[i]);\n    }\n \n    printf(\"The elements of the array are:\\n\");\n    for (int i = 0; i < n; ++i) \n    {\n        printf(\"%d \", ptr[i]);\n    }\n    \n    return 0;\n}\n"
  },
  {
    "path": "Data-Structures/Array/Array.cpp",
    "content": "#include<bits/stdc++.h>\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n\tint n;\r\n\t//number of elements as input\r\n\tcin >> n;\r\n\tint arr[n]; //initiallize array\r\n\tfor(int i =0;i<n;i++)\r\n\t{\r\n\t\tcin >> arr[i]; // input the elements\r\n\t}\r\n\tfor(int i=0;i<n;i++)\r\n\t{\r\n\t\tcout << arr[i] << \" \";//traverse the array and print the elements\r\n\t}\r\n\treturn 0;\r\n}"
  },
  {
    "path": "Data-Structures/Array/Array.go",
    "content": "package main\n\nimport \"fmt\"\n\nfunc main() {\n\tvar size int\n   \t fmt.Printf(\"Enter size of your array: \")\n   \t// takes size from user\n    \tfmt.Scanln(&size)\n\t// declaration of the array\n   \t var elements = make([]int, size)\n\t \n\tfor i := 0; i < size; i++ {\n    \t// take input elements from the user\t\n\t\tfmt.Scanln(&elements[i])\n\t}\n  \t// print out the elements array\n\tfmt.Println(elements)\n}\n"
  },
  {
    "path": "Data-Structures/Array/Array.java",
    "content": "\nimport java.util.ArrayList;\nimport java.util.Scanner;\n\npublic class Array {\n\n\tpublic static void main(String[] args) {\n\t\t//Scanner to get input\n\t\tScanner sc = new Scanner(System.in);\n\t\t//ArrayList to dynamic array elements\n\t\tArrayList elements = new ArrayList();\n\t\t//While loop for iterating dynamically\n\t\twhile(true) {\n\t\t\tString element = sc.next();\n\t\t\t//Enter exit when done entering the elements\n\t\t\tif(element.equalsIgnoreCase(\"exit\")) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\telements.add(element);\n\t\t}\n\t\t//Printing the elements\n\t\tfor(int i=0;i<elements.size();i++) {\n\t\t\tSystem.out.print(elements.get(i)+\" \");\n\t\t}\n\t\t\n\n\t}\n\n}\n"
  },
  {
    "path": "Data-Structures/Array/Array.js",
    "content": "// Importing the module\nconst readline = require(\"readline-sync\");\n  \n// Enter the size of an array\nlet size = Number(readline.question(\"Enter the size of an array: \"));\n\n// Initializing an empty array\nlet number = [];\n\n// Storing the values in the array\nfor (let i = 0; i < size; ++i) {\n  number.push(Number(readline.question(\"Enter the value for element \"+ ( i+1 ) +\" : \" )));\n}\n\n//Traversing through the array\nconsole.log(\"The array elements are: \")\nfor(let i = 0; i < size; ++i){\n    console.log(number[i]);\n}\n"
  },
  {
    "path": "Data-Structures/Array/Array.py",
    "content": "n = int(input(\"Enter number of elements : \"))\narr=[]\nfor i in range(0,n):\n    a = int(input())\n\n    arr.append(a)\n\nprint(arr)\n"
  },
  {
    "path": "Data-Structures/Array/Array.ts",
    "content": "import process from 'process';\nimport readline from 'readline';\n\n/**\n * Helper function to read input from stdin asynchronously using the `readline` module and promises\n * @param prompt The prompt to show to the user in the terminal\n * @returns A promise that resolves to the user input\n */\nfunction readInput(prompt: string): Promise<string> {\n  const rl = readline.createInterface({\n    input: process.stdin,\n    output: process.stdout,\n  });\n\n  return new Promise((resolve, reject) => {\n    try {\n      rl.question(prompt, (answer) => {\n        rl.close();\n        resolve(answer);\n      });\n    } catch (error) {\n      rl.close();\n      reject(error);\n    }\n  });\n}\n\nasync function main() {\n  // Ask user the number of elements they want to enter\n  const n = await readInput('How many elements do you want to enter: ');\n  // Create a new array\n  const array = new Array(parseInt(n));\n\n  // Ask user to enter up to `n` elements in the array\n  // elements will be of type `string`\n  for (let i = 0; i < array.length; i++) {\n    array[i] = await readInput(`Enter element ${i}: `);\n  }\n\n  // Print the array\n  console.log(array);\n}\n\nmain();\n"
  },
  {
    "path": "Data-Structures/Array/README.md",
    "content": "##  Array \nAn array is a container to store a fixed number of items of the same data type under a single name. Each data item of the array can be accessed by using a number called an “index” or “subscript”.\n\n## Types of Arrays\n1. One Dimensional Array\n\n## Declaration of Single Dimensional Array\n```bash\ndatatype arrayName [ size ] ;\n```\n\n## Initialization of Single Dimensional Array\n```bash\ndatatype arrayName [ size ] = {value1, value2, ...} ;\n```\n## Accessing Elements of Single Dimensional Array\n```bash\narrayName [ indexValue ]\n```\n\n2. Two Dimensional Array\n\n## Declaration of Two Dimensional Array\n```bash\ndatatype arrayName [ rowSize ] [ columnSize ] ;\n```\n\n## Accessing Individual Elements of Two Dimensional Array\n```bash\narrayName [ rowIndex ] [ columnIndex ]\n```\n3. Multi Dimensional Array\n\n## Declaration of Multi Dimensional Array\n```bash\ndatatype arrayName [ 1stDimensionSize ] [ 2ndDimensionSize ] ... [ nthDimensionSize ] ;\n```\n\n## Accessing Individual Elements of Multi Dimensional Array\n```bash\narrayName [ 1stDimensionIndex ] [ 2ndDimensionIndex ] ... [ nthDimensionIndex ] ;\n```\n"
  },
  {
    "path": "Data-Structures/Array/array_menudriven.cpp",
    "content": "// this code is contributed by Harsh Vardhan\n#include <iostream>\nusing namespace std;\nclass Array\n{\n    private:\n    int *A;\n    int size;\n    int length;\n    void swap(int *x,int *y);\n\n    public:\n    Array()\n    {\n        size=10;\n        length=0;\n        A=new int[size];\n    }\n    Array(int sz)\n    {\n        size=sz;\n        length=0;\n        A=new int[size];\n    }\n    ~Array()\n    {\n        delete []A;\n    }\n    void Display();\n    void Append(int x);\n    void Insert(int index,int x);\n    int Delete(int index);\n    int LinearSearch(int key);\n    int BinarySearch(int key);\n    int Get(int index);\n    void Set(int index,int x); \n    int Max();\n    int Min();\n    int Sum();\n    float Avg();\n    void Reverse();\n    void Reverse2();\n    void InsertSort(int x);\n    int isSorted();\n    void Rearrange();\n    Array* Merge(Array arr2);\n    Array* Union(Array arr2);\n    Array* Diff(Array arr2);\n    Array* Inter(Array arr2);\n};\n\n// function for displaying element of array\n\nvoid Array::Display()\n{\n    int i;\n    cout<<\"\\nElements are\\n\";\n    for(i=0;i<length;i++)\n    cout<<A[i]<<\" \";\n}\n\n//function for appending in an array\n\nvoid Array::Append(int x)\n{\n    if(length<size)\n    A[length++]=x;\n\n}\n\n\n//function for inserting in an array\n\nvoid Array::Insert(int index,int x)\n{\n    int i;\n    if(index>=0 && index <=length)\n    {\n        for(i=length;i>index;i--)\n        A[i]=A[i-1];\n        A[index]=x;\n        length++;\n\n    }\n}\n\n//function for deleting from an array\n\nint Array::Delete(int index)\n{\n    int x=0;\n    int i;\n\n    if(index>=0 && index<length)\n    {\n        x=A[index];\n        for(i=index;i<length-1;i++)\n            A[i]=A[i+1];\n\n        length--;\n        return x;\n    }\n\n return 0;\n}\n\n//function for swaping elements of array\n\nvoid Array::swap(int *x,int *y)\n{\n    int temp;\n    temp=*x;\n    *x=*y;\n    *y=temp;\n}\n\n//function for implementation of linear search in an array\n\nint Array::LinearSearch(int key)\n{\n    int i;\n    for(i=0;i<length;i++)\n    {\n        if(key==A[i])\n        {\n            swap(&A[i],&A[0]);\n            return i;\n        }\n    }\n    return -1;\n}\n\n//function for implementation of  binary search in an array\nint Array::BinarySearch(int key)\n{\n    int l,mid,h;\n    l=0;\n    h=length-1;\n\n    while(l<=h)\n    {\n        mid=(l+h)/2;\n        if(key==A[mid])\n            return mid;\n        else if(key<A[mid])\n            h=mid-1;\n        else\n            l=mid+1;\n    }\n    return -1;\n}\n\n//function to get element in an array\n\nint Array::Get(int index)\n{\n    if(index>=0 && index<length)\n        return A[index];\n\n    return -1;\n}\n\n//function to set element in an array\n\nvoid Array::Set(int index,int x)\n{\n    if(index>=0 && index< length)\n        A[index]=x;\n}\n\n//function for finding max element in an array\n\nint Array::Max()\n{\n    int max=A[0];\n    int i;\n    for(i=1;i<length;i++)\n    {\n        if(A[i]>max)\n        max=A[i];\n    }\n\n    return max;\n}\n\n//function for finding min element in an array\n\nint Array::Min()\n{\n    int min=A[0];\n    int i;\n    for(i=1;i<length;i++)\n    {\n        if(A[i]<min)\n            min=A[i];\n    }\n\n    return min;\n}\n\n//function for finding sum in an array\n\nint Array::Sum()\n{\n    int s=0;\n    int i;\n    for(i=0;i<length;i++)\n        s+=A[i];\n\n    return s;\n}\n\n//function for finding average of elements in an array\n\nfloat Array::Avg()\n{\n    return (float)Sum()/length;\n}\n\n\n//function for reverse the element of an array\n\nvoid Array::Reverse()\n{\n    int *B;\n    int i,j;\n\n    B=(int *)malloc(length*sizeof(int));\n    for(i=length-1,j=0;i>=0;i--,j++)\n        B[j]=A[i];\n\n    for(i=0;i<length;i++)\n        A[i]=B[i];\n\n}\n\n//function for reverse element of array by using swap\n\nvoid Array::Reverse2()\n{\n    int i,j;\n    for(i=0,j= length-1;i<j;i++,j--)\n    {\n        swap(& A[i],& A[j]);\n    }\n}\n\n//function for insertion sort in array\n\nvoid Array::InsertSort(int x)\n{\n    int i= length-1;\n    if( length== size)\n        return;\n    while(i>=0 && A[i]>x)\n    {\n        A[i+1]= A[i];\n        i--;\n    }\n    A[i+1]=x;\n    length++;\n\n}\n\n//function for checking is array is sorted or not\n\nint Array::isSorted()\n{\n    int i;\n    for(i=0;i<length-1;i++)\n    {\n        if(A[i]>A[i+1])\n        return 0;\n    }\n\n    return 1;\n}\n\n//function for rearrange element of array\n\nvoid Array::Rearrange()\n{\n    int i,j;\n    i=0;\n    j= length-1;\n\n    while(i<j)\n    {\n        while( A[i]<0)i++;\n\n        while( A[j]>=0)j--;\n\n        if(i<j)swap(& A[i],& A[j]);\n\n    }\n\n}\n\n//function for merging two array\n\nArray* Array::Merge(Array arr2)\n{\n    int i,j,k;\n    i=j=k=0;\n\n    Array *arr3=new Array(length+arr2.length);\n\n    while(i<length && j<arr2.length)\n    {\n        if(A[i]<arr2.A[j])\n            arr3->A[k++]=A[i++];\n        else\n            arr3->A[k++]=arr2.A[j++];\n    }\n\n    for(;i<length;i++)\n        arr3->A[k++]=A[i];\n\n\n    for(;j<arr2.length;j++)\n        arr3->A[k++]=arr2.A[j];\n        arr3->length=length+arr2.length;\n\n\n    return arr3;\n}\n\n//function for finding union of array\n\nArray* Array::Union(Array arr2)\n{\n    int i,j,k;\n    i=j=k=0;\n\n    Array *arr3=new Array(length+arr2.length);\n\n    while(i<length && j<arr2.length)\n    {\n        if(A[i]<arr2.A[j])\n            arr3->A[k++]=A[i++];\n\n        else if(arr2.A[j]<A[i])\n            arr3->A[k++]=arr2.A[j++];\n\n        else\n        {\n            arr3->A[k++]=A[i++];\n            j++;\n        }\n    }\n\n    for(;i<length;i++)\n        arr3->A[k++]=A[i];\n\n    for(;j<arr2.length;j++)\n        arr3->A[k++]=arr2.A[j];\n\n\n    arr3->length=k;\n\n    return arr3;\n}\n\n//function for finding insertion of array\n\nArray* Array::Inter(Array arr2)\n{\n    int i,j,k;\n    i=j=k=0;\n\n    Array *arr3=new Array(length+arr2.length);\n\n    while(i<length && j<arr2.length)\n    {\n        if(A[i]<arr2.A[j])\n            i++;\n\n        else if(arr2.A[j]<A[i])\n            j++;\n\n        else if(A[i]==arr2.A[j])\n        {\n            arr3->A[k++]=A[i++];\n            j++;\n        }\n    }\n\n    arr3->length=k;\n\n    return arr3;\n}\n\n//function for finding diff of array\n\nArray* Array::Diff(Array arr2)\n{\n    int i,j,k;\n    i=j=k=0;\n\n    Array *arr3=new Array(length+arr2.length);\n\n    while(i<length && j<arr2.length)\n    {\n        if(A[i]<arr2.A[j])\n            arr3->A[k++]=A[i++];\n\n        else if(arr2.A[j]<A[i])\n            j++;\n        else\n        {\n            i++;\n            j++;\n        }\n    }\n\n    for(;i<length;i++)\n        arr3->A[k++]=A[i];\n\n\n    arr3->length=k;\n\n    return arr3;\n}\n\n//implementation of all above function by menu driven program\n\nint main()\n{\n    Array *arr1;\n    int ch,sz;\n    int x,index;\n\n    cout<<\"Enter Size of Array\";\n    scanf(\"%d\",&sz);\n    arr1=new Array(sz);\n\n    do\n    {\n        cout<<\"\\n\\nMenu\\n\";\n        cout<<\"1. Insert\\n\";\n        cout<<\"2. Delete\\n\";\n        cout<<\"3. Search\\n\";\n        cout<<\"4. Sum\\n\";\n        cout<<\"5. Display\\n\";\n        cout<<\"6.Exit\\n\";\n\n        cout<<\"enter you choice \";\n        cin>>ch;\n\n    switch(ch)\n    {\n        case 1: \n                cout<<\"Enter an element and index \";\n                cin>>x>>index;\n                arr1->Insert(index,x);\n                break;\n        case 2: \n                cout<<\"Enter index \";\n                cin>>index;\n                x=arr1->Delete(index);\n                cout<<\"Deleted Element is\"<<x;\n                break;\n        case 3:\n                cout<<\"Enter element to search\";\n                cin>>x;\n                index=arr1->LinearSearch(x);\n                cout<<\"Element index \"<<index;\n                break;\n        case 4:\n                cout<<\"Sum is \"<<arr1->Sum();\n                break;\n        case 5:\n                arr1->Display();\n\n }\n    }while(ch<6);\n\n return 0;\n}"
  },
  {
    "path": "Data-Structures/Graph/GraphUsingList.kt",
    "content": "import kotlin.collections.ArrayList\n\nclass Node<T>(val value: T) {\n    val neighbors = ArrayList<Node<T>>()\n    fun addNeighbor(node: Node<T>) = neighbors.add(node)\n    override fun toString(): String = value.toString()\n}\n\nclass Graph<T> {\n    private val nodes = HashSet<Node<T>>()\n\n    fun addNode(value: T) {\n        val newNode = Node(value)\n        nodes.add(newNode)\n    }\n\n    fun getNode(reference: T): Node<T>? {\n        return nodes.firstOrNull { it.value == reference }\n    }\n\n    fun addVertex(from: T, to: T) {\n        getNode(to)?.let { getNode(from)?.addNeighbor(it) }\n    }\n}\n\nfun <T> Graph<T>.bfs(reference: T): List<T> {\n    getNode(reference)?.let { referenceNode ->\n        val visited = ArrayList<Node<T>>()\n        val queue = ArrayList<Node<T>>()\n        queue.add(referenceNode)\n\n        while (queue.isNotEmpty()) {\n            val node = queue.removeAt(0)\n            if (!visited.contains(node)) {\n                visited.add(node)\n                node.neighbors\n                        .filter { !visited.contains(it) }\n                        .forEach { queue.add(it) }\n            }\n        }\n        return visited.map { it.value }\n    }\n    return emptyList()\n}\n\nfun <T> Graph<T>.dfs(reference: T): List<T> {\n    getNode(reference)?.let { referenceNode ->\n        val visited = ArrayList<Node<T>>()\n        val stack = ArrayList<Node<T>>()\n        stack.add(referenceNode)\n\n        while (stack.isNotEmpty()) {\n            val node = stack.removeAt(stack.lastIndex)\n            if (!visited.contains(node)) {\n                visited.add(node)\n                node.neighbors\n                        .filter { !visited.contains(it) }\n                        .forEach { stack.add(it) }\n            }\n        }\n        return visited.map { it.value }\n    }\n    return emptyList()\n}\n\nfun main() {\n    val namesGraph = Graph<String>()\n\n    namesGraph.addNode(\"Minato\")\n    namesGraph.addNode(\"Obito\")\n    namesGraph.addVertex(\"Minato\", \"Obito\")\n    namesGraph.addNode(\"Kakashi\")\n    namesGraph.addVertex(\"Minato\", \"Kakashi\")\n    namesGraph.addNode(\"Rin\")\n    namesGraph.addVertex(\"Minato\", \"Rin\")\n    namesGraph.addNode(\"Naruto\")\n    namesGraph.addVertex(\"Kakashi\", \"Naruto\")\n    namesGraph.addNode(\"Sakura\")\n    namesGraph.addVertex(\"Kakashi\", \"Sakura\")\n    namesGraph.addNode(\"Sasuke\")\n    namesGraph.addVertex(\"Kakashi\", \"Sasuke\")\n\n    print(namesGraph.bfs(\"Minato\"))\n    print(namesGraph.dfs(\"Minato\"))\n}\n"
  },
  {
    "path": "Data-Structures/Graph/README.md",
    "content": "# This folder is empty.\n"
  },
  {
    "path": "Data-Structures/Graph/UsingList.cpp",
    "content": "#include<iostream>\r\n#include<list>\r\n#include<iterator>\r\nusing namespace std;\r\nvoid displayAdjList(list<int> adj_list[], int v) {\r\n   for(int i = 0; i<v; i++) {\r\n      cout << i << \"--->\";\r\n      list<int> :: iterator it;\r\n      for(it = adj_list[i].begin(); it != adj_list[i].end(); ++it) {\r\n         cout << *it << \" \";\r\n      }\r\n      cout << endl;\r\n   }\r\n}\r\nvoid add_edge(list<int> adj_list[], int u, int v) {    //add v into the list u, and u into list v\r\n   adj_list[u].push_back(v);\r\n   adj_list[v].push_back(u);\r\n}\r\nmain(int argc, char* argv[]) {\r\n   int v = 6;    //there are 6 vertices in the graph\r\n   //create an array of lists whose size is 6\r\n   list<int> adj_list[v];\r\n   add_edge(adj_list, 0, 4);\r\n   add_edge(adj_list, 0, 3);\r\n   add_edge(adj_list, 1, 2);\r\n   add_edge(adj_list, 1, 4);\r\n   add_edge(adj_list, 1, 5);\r\n   add_edge(adj_list, 2, 3);\r\n   add_edge(adj_list, 2, 5);\r\n   add_edge(adj_list, 5, 3);\r\n   add_edge(adj_list, 5, 4);\r\n   displayAdjList(adj_list, v);\r\n}\r\n"
  },
  {
    "path": "Data-Structures/Graph/UsingList.py",
    "content": "# graph implementation with adjacency list\n\n# undirected version\n\n\nclass node():\n    \n    def __init__(self, node_name):\n        self.node_name   = node_name # node_name is unique name of node.\n        self.has_edge_to = [] # list which records the all edges of this node and their edge weights.\n        \n    def add_neigbor(self, neighbor): # neighbor is node name. not node object.\n        self.has_edge_to.append(neighbor)\n        \n    def list_edges_of(self):\n        return self.has_edge_to\n    \n    def get_node_name(self):\n        return self.node_name\n    \n    def __str__(self):\n        return str(self.node_name)\n    \n\nclass graph():\n    \n    def __init__(self):\n        self.adj_list_of_graph = {} # keys are node names. values are edge_lists of nodes\n        self.node_num_in_graph = 0\n        self.nodes_object_list = []\n    \n\n    def add_node(self, node_name):\n        self.node_num_in_graph += 1\n        new_node = node(node_name)\n        self.nodes_object_list.append(new_node)\n        #self.adj_list_of_graph[new_node.get_node_name()] = new_node.list_edges_of()\n        self.update_adj_list()\n        return new_node\n    \n    def get_node(self, node_name_to_search): # return node which its name is node_name_to_search\n        for x in self.nodes_object_list:\n            if node_name_to_search == x.get_node_name():\n                return x\n        return None\n\n\n    def get_edges_of_node(self, node_name_to_search): \n        return self.get_node(node_name_to_search).list_edges_of()\n        # return self.adj_list_of_graph[node_name_to_search]\n    \n    def update_adj_list(self):\n        for x in self.nodes_object_list:\n            if x.get_node_name() in self.adj_list_of_graph.keys():\n                # node is exist in adj list. it is good. lets update its edge list.\n                self.adj_list_of_graph[x.get_node_name()] = x.list_edges_of()\n            else:\n                # we need to cretae new row in adj list for this new node.\n                self.adj_list_of_graph[x.get_node_name()] = x.list_edges_of()\n\n\n    def add_edge(self, from_node, to_node): # in fact from and to notation is meaningless. b/c this is not directed graph. but i use them for convenience to modify.\n        # from_node and to_node are node names. not node object \n        self.exist_flag_of_from_node  = False\n        self.exist_flag_of_to_node    = False\n        for x in self.nodes_object_list:\n            if from_node == x.node_name:\n                # from_node is exist in graph. no need to create it again.\n                self.exist_flag_of_from_node=True\n\n            if to_node == x.node_name:\n                # to_node is exist in graph. no need to create it again.\n                self.exist_flag_of_to_node=True\n\n        if not self.exist_flag_of_from_node:\n            self.add_node(from_node)\n\n        if not self.exist_flag_of_to_node:\n            self.add_node(to_node)\n\n\n        for ii,x in enumerate(self.nodes_object_list):\n            if from_node == x.node_name:\n                self.nodes_object_list[ii].add_neigbor(to_node)\n            if to_node == x.node_name:\n                self.nodes_object_list[ii].add_neigbor(from_node)\n\n        self.update_adj_list()\n                \n        \n    def get_all_node_objects_in_graph(self):\n        return self.nodes_object_list.keys()\n    \n    def __iter__(self):\n        return iter(self.nodes_object_list)\n    \n    def __contains__(self, node_name_to_search):\n        flag=False\n        for x in self.adj_list_of_graph.keys():\n            if node_name_to_search == x.node_name:\n                flag=True\n        \n        return flag\n        \n        \n\n    \n\n##########################################################\n#### Breadth First Search (BFS) Algorithm\nfrom queue import Queue\n\ndef bfs(graph, entry_node):\n    visited = []\n    queue   = Queue()\n    queue.put(entry_node)\n    while not queue.empty():\n        node = queue.get()\n        if node.get_node_name() not in visited:\n            visited.append(node.get_node_name())\n            j = graph.get_edges_of_node(node.get_node_name())\n            for jj in j:\n                if not jj in visited:\n                    queue.put(graph.get_node(jj))\n\n    print(queue.empty())\n    print(visited)            \n    return visited\n\n\n\n\n\n##########################################################\n##### Depth First Search (DFS) Algorithm\ndef dfs(graph, start):\n    visited = [ ]\n    stack   = [start] # we will implement stack with python list\n    \n    while stack: # while stach is not empty\n        node = stack.pop()\n        if node.get_node_name() not in visited:\n            visited.append(node.get_node_name())\n            j = graph.get_edges_of_node(node.get_node_name())\n            for jj in j:\n                if not jj in visited:\n                    stack.append(graph.get_node(jj))\n\n\n    return visited\n##########################################################\n\ng_instance_2 = graph()\n\ng_instance_2.add_node(\"A\")\ng_instance_2.add_node(\"B\")\ng_instance_2.add_node(\"C\")\ng_instance_2.add_node(\"D\")\ng_instance_2.add_node(\"E\")\ng_instance_2.add_node(\"F\")\n\n\ng_instance_2.add_edge(\"A\",\"B\")\ng_instance_2.add_edge(\"A\",\"C\")\n\n#g_instance_2.add_edge(\"B\",\"A\")\ng_instance_2.add_edge(\"B\",\"D\")\ng_instance_2.add_edge(\"B\",\"E\")\n\n#g_instance_2.add_edge(\"C\",\"A\")\ng_instance_2.add_edge(\"C\",\"F\")\n\n#g_instance_2.add_edge(\"E\",\"B\")\ng_instance_2.add_edge(\"E\",\"F\")\n\n#g_instance_2.add_edge(\"F\",\"C\")\n#g_instance_2.add_edge(\"F\",\"E\")\n\n#print(g_instance_2.adj_list_of_graph)\nfor v in g_instance_2.adj_list_of_graph:\n    print(v,g_instance_2.adj_list_of_graph[v])\n\nvisited = bfs(g_instance_2, g_instance_2.get_node(\"A\"))\nprint(\"bfs traversal:\",visited)\n\nvisited = dfs(g_instance_2,g_instance_2.get_node(\"A\"))\nprint(\"dfs traversal:\", visited)\n\n##########################################################\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n"
  },
  {
    "path": "Data-Structures/Graph/UsingMatrix.cpp",
    "content": "#include <iostream>\r\n#include <vector>\r\n#include <cstring>\r\n#include <bits/stdc++.h>\r\nusing namespace std;\r\nint n=5;\r\nvoid DFS(int matrix[5][5], int visit[],int visitTo=0){\r\n    cout<<(char)(visitTo+65)<<\" \";\r\n    visit[visitTo]=1;\r\n    for(int i=0; i<5; i++){\r\n        if(matrix[visitTo][i] && !visit[i])\r\n            DFS(matrix,visit,i);\r\n    }\r\n}\r\nvoid BFS(int matrix[5][5], int visit[], int row=0){\r\n    int queue[n];\r\n    int top =-1, i, bottom =-1;\r\n    visit[row]=1;\r\n    queue[++bottom] = row;\r\n    cout<<(char)(row+65)<<\" \";\r\n    while(top != bottom){\r\n        row= queue[++top];\r\n        for(i=0; i<n; i++){\r\n            if(matrix[row][i] && !visit[i]){\r\n                visit[i]=1;\r\n                cout<<row<<\" \"<<(char)(i+65)<<\" \";\r\n                queue[++bottom] =i;\r\n            }\r\n        }\r\n    }\r\n}\r\nint main()\r\n{\r\n   int matrix[5][5]={ {0,0,3,0,4}, {0,0,6,0,1},{3,6,0,5,0},{0,0,5,0,7},{4,1,0,7,0} };\r\n   int visit[5]={0};\r\n    DFS(matrix,visit);\r\n    return 0;\r\n}\r\n//Contributed by Vaishnavi Shah"
  },
  {
    "path": "Data-Structures/Graph/graph_implementation_in_C_bfs_dfs.c",
    "content": "/**\n* This is a Implementation of Undirected Graph in C using Both BFS (Breadth First Search) & DFS(Depth First Search).\n*\n*/\n\n\n#include<stdio.h>\n#include<stdlib.h>\n#define SIZE 40\n\nstruct node{\n int vertex;\n struct node* next;\n};\n\n//Creating a Node\nstruct node* createNode(int v){\nstruct node* newNode = malloc( sizeof( struct node ) );\nnewNode->vertex = v;\nnewNode->next = NULL;\nreturn newNode;\n};\n\nstruct Graph{\n int numVertices;\n struct node** adjLists;\n int* visited;\n};\n\n//Creating a Graph\nstruct Graph* createGraph(int vertices){\n struct Graph* graph = malloc( sizeof( struct Graph ) );\n graph->numVertices = vertices;\n\n graph->adjLists = malloc( vertices * sizeof( struct node* ));\n graph->visited = malloc( vertices * sizeof(int) );\nint i ;\n for(  i = 0; i < vertices; i++){\n    graph->adjLists[i] = NULL;\n    graph->visited[i] = 0;\n }\n return graph;\n}\n\n// Adding a Edge in a Graph\nvoid addEdge(struct Graph* graph, int src, int dest){\n //Adding edge from source to destination\n struct node* newNode = createNode(dest);\n newNode->next = graph->adjLists[src];\n graph->adjLists[src] = newNode;\n\n //Adding edge from destination to source\n newNode = createNode( src );\n newNode->next = graph->adjLists[dest];\n graph->adjLists[dest] = newNode;\n}\n\nstruct queue{\n int items[SIZE];\n int front;\n int rear;\n};\n\n// Creating a Queue\nstruct queue* createQueue(){\n struct queue* q = malloc( sizeof( struct queue) );\n q->front = -1;\n q->rear = -1;\n return q;\n};\n\n//Adding Elements into a Queue\nvoid enqueue( struct queue* q, int value ){\n if( q->rear == SIZE - 1 )\n    printf(\"Queue is Full !!!\");\n else{\n    if( q->front == -1)\n        q->front = 0;\n    q->rear++;\n    q->items[ q->rear ] = value;\n }\n}\n\n// Check weather a queue is empty\nint isEmpty( struct queue* q ){\n    if( q->rear == -1 )\n        return 1;\n    else\n        return 0;\n}\n\n//Removing Elements From Queue\nint dequeue( struct queue* q ){\n int item;\n if( isEmpty( q ) ){\n    printf(\"Queue is Empty\");\n    item = -1;\n } else {\n  item = q->items[q->front];\n  q->front++;\n  if( q->front > q->rear ){\n//    printf(\"Resetting Queue\");\n    q->front = q->rear = -1;\n  }\n }\n return item;\n}\n\n// Print the queue\nvoid printQueue( struct queue* q ){\n    int i = q->front;\n    if( isEmpty(q) ){\n        printf(\"Queue is Empty\");\n    }else{\n        printf(\"\\nQueue Front: \");\n        for( i = q->front; i < q->rear ; i++){\n            printf(\"%d\", q->items[i]);\n        }\n    }\n}\n\n// Breadth First Search Algorithm\nvoid bfs( struct Graph* graph, int startVertex ){\n struct queue* q = createQueue();\n\n graph->visited[ startVertex ] = 1;\n enqueue( q, startVertex );\n\n while ( !isEmpty(q) ){\n//    printQueue( q );\n    int currentVertex = dequeue( q );\n    printf(\"Visited : %d \\n\", currentVertex);\n\n    struct node* temp = graph->adjLists[currentVertex];\n\n    while( temp ){\n        int adjVertex = temp->vertex;\n\n        if( graph->visited[adjVertex] == 0 ){\n            graph->visited[adjVertex] = 1;\n            enqueue( q, adjVertex );\n        }\n        temp = temp->next;\n    }\n }\n}\n\n//Depth First Search Algorithm\nvoid DFS(struct Graph* graph, int vertex){\n struct node* adjList = graph->adjLists[vertex];\n struct node* temp = adjList;\n\n graph->visited[vertex] = 1;\n printf(\"Visited %d \\n\", vertex);\n\n while( temp != NULL){\n    int connectedVertex = temp->vertex;\n\n    if( graph->visited[connectedVertex] == 0 ){\n        DFS(graph , connectedVertex);\n    }\n    temp = temp->next;\n }\n}\n\n// It is the main calling function.\nint main(){\n int vertices=0,  edges = 0, src = 0 , dest = 0;\n printf(\"Enter the Number of Vertices:\");\n scanf(\"%d\", &vertices );\n struct Graph* graph =  createGraph(vertices);\n printf(\"Enter the Number of Edges in a Graph: \");\n scanf(\"%d\", &edges );\n \n for( int  i = 0 ; i < edges ; i++ ){\n    printf(\"Enter the Source and Destination of Edge %d :\", i+1);\n    scanf(\"%d%d\", &src, &dest);\n    addEdge( graph , src , dest);\n }\n\n printf(\"\\n<!-------Using Breadth First Search-------!>\\n\");\n bfs( graph, 0);\n \n for( int i = 0; i < vertices; i++ ){\n    graph->visited[i] = 0;\n }\n\n printf(\"\\n<!-------Using Deapth First Search-------!>\\n\");\n DFS(graph, 2);\n\n return 0;\n}\n"
  },
  {
    "path": "Data-Structures/HashMap/README.md",
    "content": "## This folder is empty.\n"
  },
  {
    "path": "Data-Structures/HashSet/Hash-Set.c",
    "content": "/*\n * This is an implementation of HashSet Data structure\n */\n#include <stdio.h>\n#include <stdlib.h>\n#define HS_REHASH_LIM(x) (x / 2)\n#define HS_REHASH_FAC 2\n\ntypedef struct {\n  long key;\n  void *value;\n} hashpair;\n\n/* Hashset struct\n * size : the maximum amount of elements it can store\n * used : number of elements currently stored\n * start : pointer to start of hashset\n * hash : function pointer to a function which takes in a void pointer (key) and\n *        return an long (hash) of that key\n */\ntypedef struct {\n  int size;\n  int used;\n  hashpair *start;\n  long (*hash)(void *);\n} Hashset;\n\n/*\n * Function to create Hashset structure\n * the structure received should be deleted after use by\n * using function hs_delete\n * Params :\n * size : Initial size allocated to hashset\n * hashfn : A function which takes in a void pointer (key)\n *          and returns an long representing the hash of that key\n * Returns : A struct Hashset.\n *\n * This allocates the given size from heap memory using calloc, and stores its\n * pointer,as well as the compair function and hash function in the returning\n * structure\n */\n\nHashset make_hashset(int size, long (*hashfn)(void *)) {\n  Hashset ret = {\n      .size = size,\n      .used = 0,\n      .start = (hashpair *)calloc(\n          size, sizeof(Hashset)), /* Use calloc so the returned memory will be\n                                   * zeroed and if any errors or invalid access,\n                                   * will be caught */\n      .hash = hashfn};\n  return ret;\n}\n\n/*\n * Internal function to rehash a Hashset and reallocate the keys and values\n * Should not be exposed\n *\n * this increases the current size of hashset by HS_REHASH_FAC factor,\n * and then rehashes all keys and puts then in this newly allocated memory\n * then frees the old memory\n */\nint hs_add(Hashset *hs, void *value);  // forward declaration\nstatic void rehash(Hashset *hs) {\n  int size = hs->size;\n  hashpair *temp = (hashpair *)calloc(size * HS_REHASH_FAC, sizeof(hashpair));\n  if (temp == NULL) {  // If cannot allocate memory , just return\n    return;\n  }\n  hashpair *newstart = temp;\n  hashpair *oldstart = hs->start;\n  // Change the HS info\n  hs->start = newstart;\n  hs->size = size * HS_REHASH_FAC;\n  hs->used = 0;\n\n  hashpair *iter = oldstart;\n\n  // move all key-value pairs to new locations, using the hs_add function\n  while (iter < oldstart + size) {\n    // As we have calloc-ed the memory, both key and value being zero\n    // means that the location was not allocated\n    if (iter->key >= 0 || iter->value != NULL) {\n      // If either is non-zero, add it to the new memory\n      hs_add(hs, iter->value);\n    }\n    ++iter;\n  }\n  free(oldstart);\n}\n\n/*\n * Function to add a value to hasset\n * Note that once the hashset reaches its max used capacity,\n * this internally rehashes and reallocates the whole hashset\n *\n * Params :\n * hs : pointer to the hashset in which the pair is to be added\n * value : pointer to value / value (must be typecasted to void *)\n *\n * Returns : int : 0 if succeeded\n *                 -1 if failed\n */\nint hs_add(Hashset *hs, void *value) {\n  long key = hs->hash(value);\n  int hash = key % hs->size;  // bound the hash inside the size\n\n  // If the used capacity of HS is more than max used allowed, reshah\n  if (hs->used >= HS_REHASH_LIM(hs->size)) {\n    rehash(hs);\n  }\n  // Start searching empty space at offset of hash\n  hashpair *search = hs->start + hash;\n  // loop until we find an empty space or we get to end of memory\n  while (search->key >= 0 && search->value != NULL &&\n         search < hs->start + hs->size) {\n    ++search;\n  }\n\n  if (search >= hs->start + hs->size) {\n    return -1;  // Failed to add\n  } else {\n    search->key = key;\n    search->value = value;\n    ++hs->used;\n  }\n  return 0;\n}\n\n/*\n * Function to check if given value exists in hashset\n *\n * Params :\n * hs : pointer to the hashset from which the value is to be retrieved\n *\n * Returns : 0 if value is not found in given hashset\n *           1 if value is found in hashset\n */\nint hs_contains(Hashset *hs, void *value) {\n  hashpair *start = hs->start;\n  long key = hs->hash(value);\n  int hash = (key % hs->size);  // bound the hash in memory size\n\n  // start searching for key at offset of hash\n  hashpair *search = start + hash;\n\n  // As we have calloc-ed the memory, both key and value being zero\n  // means that the location was not allocated\n  while (search->key >= 0 && search->value != NULL &&\n         search < start + hs->size) {\n    // Compair the found and required key\n    if (key == search->key) {\n      return 1;\n    }\n    ++search;\n  }\n  return 0;\n}\n\n/*\n * A function to delete a perticular value from given hashset\n * Note : This only removes the value from hashset.\n *        this returns the value as given to hs_add,\n *        which if were manually allocated, must be manually freed by user.\n *\n * Params :\n * hs : A pointer to hashset from which value is to be deleted\n * value : the value as void *, which is to be removed\n *\n * Returns : if value is found : value as void* as given to hs_add\n *           if value is not found : NULL\n */\nvoid *hs_delete_key(Hashset *hs, void *value) {\n  hashpair *start = hs->start;\n  long key = hs->hash(value);\n  int hash = (key % hs->size);  // bound the hash in memory size\n\n  // start searching for key at offset of hash\n  hashpair *search = start + hash;\n\n  // As we have calloc-ed the memory, both key and value being zero\n  // means that the location was not allocated\n  while (search->key >= 0 && search->value != NULL &&\n         search < start + hs->size) {\n    if (key == search->key) {\n      // if we found the key, save the key and value in structure\n      // and set both in the HS to NULL\n      void *ret = search->value;\n      search->key = -1;\n      search->value = NULL;\n      --hs->used;\n      return ret;\n    }\n    ++search;\n  }\n  // We did not find the required key, so return NULL in structure\n  return NULL;\n}\n\n/*\n * A function to delete the hashset\n * frees the memory allocated to the hashset\n * Params :\n * hs : pointer to Hashset structure as returned by the make_hashset function\n * delfn : A function which takes in a void pointer (value)\n *         This will be called on each value in Hashset.\n *         Should be used to free the memory allocated to value, if\n *         required\n *\n */\nvoid hs_delete(Hashset *hs, void (*delfn)(void *)) {\n  hashpair *start = hs->start;\n  hashpair *iter = start;\n\n  while (iter < start + hs->size) {\n    // As we have calloc-ed the memory, both key and value being zero\n    // means that the location was not allocated\n    if (iter->key >= 0 || iter->value != NULL) {\n      // call delfn on giving the key and value\n      delfn(iter->value);\n    }\n    ++iter;\n  }\n  // Finally free the memory that was allocated to the HS\n  free(start);\n  hs->size = 0;\n  hs->start = NULL;\n}\n\n// Tests\n\nstatic inline long __hash__(void *val) { return (long)val; }\n\nstatic inline void __del__(\n    void *val) { /* do nothing as the values are just ints */\n}\n\nvoid main() {\n  // A Hasset for numbers\n  Hashset hs = make_hashset(10, __hash__);\n  hs_add(&hs, (void *)55);\n  hs_add(&hs, (void *)23);\n  hs_add(&hs, (void *)785);\n  hs_add(&hs, (void *)78);\n\n  if (hs_contains(&hs, (void *)5)) {\n    printf(\"This is error\\n\");\n  } else {\n    printf(\"Test 1 is correct\\n\");\n  }\n\n  if (hs_contains(&hs, (void *)23)) {\n    printf(\"Test 2 is correct\\n\");\n  } else {\n    printf(\"This is error\\n\");\n  }\n\n  long ret = (long)hs_delete_key(&hs, (void *)785);\n  if (ret != 785) {\n    printf(\"This is error\\n\");\n  } else {\n    printf(\"Test 3 is correct\\n\");\n  }\n\n  hs_delete(&hs, __del__);\n}"
  },
  {
    "path": "Data-Structures/HashSet/README.md",
    "content": "# This folder is empty.\n"
  },
  {
    "path": "Data-Structures/Heap/README.md",
    "content": "\n"
  },
  {
    "path": "Data-Structures/LinkedList/Circular_Linked_List/CircularLinkedList.c",
    "content": "#include <stdio.h>\n#include <string.h>\n#include <stdlib.h>\n#include <stdbool.h>\n\nstruct node {\n   int data;\n   int key;\n\t\n   struct node *next;\n};\n\nstruct node *head = NULL;\nstruct node *current = NULL;\n\nbool isEmpty() {\n   return head == NULL;\n}\n\nint length() {\n   int length = 0;\n\n   //if list is empty\n   if(head == NULL) {\n      return 0;\n   }\n\n   current = head->next;\n\n   while(current != head) {\n      length++;\n      current = current->next;   \n   }\n\t\n   return length;\n}\n\n//insert link at the first location\nvoid insertFirst(int key, int data) {\n\n   //create a link\n   struct node *link = (struct node*) malloc(sizeof(struct node));\n   link->key = key;\n   link->data = data;\n\t\n   if (isEmpty()) {\n      head = link;\n      head->next = head;\n   } else {\n      //point it to old first node\n      link->next = head;\n\t\t\n      //point first to new first node\n      head = link;\n   }    \n}\n\n//delete first item\nstruct node * deleteFirst() {\n\n   //save reference to first link\n   struct node *tempLink = head;\n\t\n   if(head->next == head) {  \n      head = NULL;\n      return tempLink;\n   }     \n\n   //mark next to first link as first \n   head = head->next;\n\t\n   //return the deleted link\n   return tempLink;\n}\n\n//display the list\nvoid printList() {\n\n   struct node *ptr = head;\n   printf(\"\\n[ \");\n\t\n   //start from the beginning\n   if(head != NULL) {\n\t\n      while(ptr->next != ptr) {     \n         printf(\"(%d,%d) \",ptr->key,ptr->data);\n         ptr = ptr->next;\n      }\n   }\n\t\n   printf(\" ]\");\n}\n\nvoid main() {\n   insertFirst(1,10);\n   insertFirst(2,20);\n   insertFirst(3,30);\n   insertFirst(4,1);\n   insertFirst(5,40);\n   insertFirst(6,56); \n\n   printf(\"Original List: \"); \n\t\n   //print list\n   printList();\n\n   while(!isEmpty()) {            \n      struct node *temp = deleteFirst();\n      printf(\"\\nDeleted value:\");  \n      printf(\"(%d,%d) \",temp->key,temp->data);\n   }   \n\t\n   printf(\"\\nList after deleting all items: \");\n   printList();   \n}\n"
  },
  {
    "path": "Data-Structures/LinkedList/Circular_Linked_List/CircularLinkedList.java",
    "content": "public class CircularLinkedList {\n    public Node head;\n    public Node tail;\n\n    public CircularLinkedList() {\n        this.head = this.tail = null;\n    }\n\n    public boolean isEmpty() {\n        return this.head == null;\n    }\n\n    public void addToTail(int el) {\n        if (isEmpty()) {\n            this.head = new Node(el);\n            this.head.next = head;\n            this.head.prev = head;\n            this.tail = this.head;\n        } else {\n            this.tail.next = new Node(el, this.tail.next, this.tail);\n            this.tail = this.tail.next;\n            this.head.prev = this.tail;\n\n        }\n    }\n\n    public void printAll() {\n        Node temp;\n        int i = 0;\n        for (temp = head; i < 5; temp = temp.next, i += 1) {\n            System.out.println(temp.info + \" > \" + temp.next.info + \" > \" + temp.prev.info);\n        }\n        System.out.println();\n    }\n\n}\n\nclass Node {\n    public int info;\n    public Node next;\n    public Node prev;\n\n    public Node(int el) {\n        this.info = el;\n        this.next = null;\n        this.prev = null;\n    }\n\n    public Node(int el, Node next, Node prev) {\n        this.info = el;\n        this.next = next;\n        this.prev = prev;\n    }\n}"
  },
  {
    "path": "Data-Structures/LinkedList/Circular_Linked_List/Circular_Link_List.cpp",
    "content": "#include<iostream>\n#include<conio.h>\nusing namespace std;\nclass Node{\n    public:\n        int data;\n        Node *link;\n};\nNode *head=NULL;\nvoid createNode(){\n    char ch;\n    do{\n        Node *current;\n        Node *new_node=new Node;\n        cout<<\"\\nEnter the data:\";\n        cin>>new_node->data;\n        new_node->link=NULL;\n        if (head==NULL){\n            head=new_node;\n            current=new_node;\n        }\n        else{\n            current->link=new_node;\n            current=new_node;\n            current->link=head;\n        }\n        cout<<\"\\nDo you want to add more nodes?\";\n        ch=getche();\n    }while(ch!='n');\n}\nvoid print(){\n    Node *new_node;\n    new_node=head;\n    if (new_node==NULL){\n        cout<<\"\\nLink list is empty.\";\n    }\n    else{\n        cout<<\"\\nData in list is as follows:\"<<endl;\n        cout<<new_node->data<<\"\\t\";\n        new_node=new_node->link;\n        while(new_node!=head){\n            cout<<new_node->data<<\"\\t\";\n            new_node=new_node->link;\n        }\n        cout<<new_node->data<<\"\\t\";\n    }\n}\nint main(){\n    createNode();\n    print();\n}\n"
  },
  {
    "path": "Data-Structures/LinkedList/Circular_Linked_List/README.md",
    "content": "## This folder is empty.\n"
  },
  {
    "path": "Data-Structures/LinkedList/Circular_Linked_List/circularLinkedList.js",
    "content": "function circularLinkedList() {\n  //Node\n  let Node = function(element) {\n    this.element = element;\n    this.next = null;\n  }\n\n  let length = 0;\n  let head = null;\n\n  //Other methods go here \n  //Get element at specific index\n  this.getElementAt = function(index) {\n    if(index >= 0 && index <= length){\n      let node = head;\n      for(let i = 0; i < index && node != null; i++){\n        node = node.next;\n      }\n      return node;\n    }\n    return undefined;\n  }\n  \n  //Add new node\n  this.append = function(element){\n    //Create new node\n    const node = new Node(element);\n    let current;\n    \n    //If head is empty\n    //Then make new node head\n    if(head === null){\n      head = node;\n    }else{\n      //Else add the new node as the next node\n      //And mark the next of new node to the head\n      current = this.getElementAt(length - 1);\n      current.next = node;\n    }\n    \n    node.next = head;\n    length++;\n  }\n  \n  //Insert at given position\n  this.insert = function(element, index){\n    if(index >= 0 && index <= length){\n      const node = new Node(element);\n      let current = head;\n      \n      //Insert at head\n      if(index === 0){      \n        if(head === null){\n          head = node;\n          node.next = head;\n        }else{\n          node.next = current;\n          current = this.getElementAt(length);\n          head = node;\n          current.next = head;\n        }\n      }else{\n        //Insert at given index (middle or end)\n        const previous = this.getElementAt(index - 1);\n        node.next = previous.next;\n        previous.next = node;\n      }\n      \n      length++;\n      return true;\n    }\n    return false;\n  }\n  \n  //Remove at any position\n  this.removeAt = function (index) {\n    if(index >= 0 && index < length){\n      let current = head;\n      \n      //Remove from head\n      if(index === 0){\n        if(length === 1){\n          head = undefined;\n        }else{\n          const removed = head;\n          current = this.getElementAt(length - 1);\n          head = head.next;\n          current.next = head;\n          current = removed;\n        }\n      }else{\n        //Remove at given index (middle or end)\n        const previous = this.getElementAt(index - 1);\n        current = previous.next;\n        previous.next = current.next;\n      }\n      \n      length--;\n      return current.element;\n    }\n    return undefined;\n  }\n  \n  //Get the indexOf item \n  this.indexOf = function(elm){\n    let current = head,\n    index = -1;\n\n    //If element found then return its position\n    while(current){\n      if(elm === current.element){\n         return ++index;\n      }\n\n       index++;\n       current = current.next;\n     }\n\n    //Else return -1\n    return -1;\n  };\n  \n  //Find the item in the list\n  this.isPresent = (elm) => {\n    return this.indexOf(elm) !== -1;\n  };\n  \n  //Get the head\n  this.getHead = function(){\n    return head;\n  }\n  \n  //Delete an item from the list\n  this.delete = (elm) => {\n     return this.removeAt(this.indexOf(elm));\n  }; \n  \n  //Delete the first item from the list\n  this.deleteHead = function(){\n    this.removeAt(0);\n  }\n  \n  //Print item of the string\n  this.toString = function(){\n    let current = head,\n    string = '';\n    const temp = head.element;\n    \n    while(current){\n      if(temp === current.next.element){\n        string += current.element + (current.next ? '\\n' : '');\n        break;\n      }\n      \n      string += current.element + (current.next ? '\\n' : '');\n      current = current.next;\n    }\n\n    return string;\n  };\n  \n  //Convert list to array\n  this.toArray = function(){\n    let arr = [],\n    current = head;\n    const temp = head.element\n\n    while(current){\n      //Break if first element detected\n      if(temp === current.next.element){\n        arr.push(current.element);\n        break;\n      }\n      \n      arr.push(current.element);\n      current = current.next;\n    }\n\n    return arr;\n  };\n  \n  //Check if list is empty\n  this.isEmpty = function(){\n    return length === 0;\n  };\n  \n  //Get the size of the list\n  this.size = function(){\n    return length;\n  }\n  \n}Copy\nInput:\nlet cLL = new circularLinkedList();\ncLL.append(20);\ncLL.append(30);\ncLL.append(40);\ncLL.append(50);\nconsole.log(cLL.removeAt(3));\ncLL.insert(70, 3);\ncLL.deleteHead();\ncLL.delete(70);\nconsole.log(cLL.toArray());\n"
  },
  {
    "path": "Data-Structures/LinkedList/Circular_Linked_List/circularLinkedList.py",
    "content": "class Node:\n  def __init__(self, data):\n    self.data = data\n    self.next = None\n\nclass CircularLinkedList:\n  def __init__(self, key):\n    z = Node(key)\n    z.next = z\n    self.last = z\n\ndef insert_after(n, a):\n  n.next = a.next\n  a.next = n\n\ndef insert_at_last(l, n):\n  n.next = l.last.next\n  l.last.next = n\n  l.last = n\n\ndef delete(l, n):\n  temp = l.last\n  while temp.next != n:\n    temp = temp.next\n\n  if n == l.last: #last node\n    if n.next == n: #only one node\n      l.last = NULL\n    else: #more than one node and last node\n      temp.next = n.next\n      l.last = temp #updating last pointer\n  else: #not last node\n    temp.next = n.next\n  del n\n\ndef traversal(l):\n  temp = l.last\n  a = str(temp.data)+\"\\t\"\n  temp = temp.next\n\n  while temp != l.last:\n    a = a + str(temp.data) + \"\\t\"\n    temp = temp.next\n  print(a)\n\nif __name__ == '__main__':\n  l = CircularLinkedList(10)\n\n  a = Node(20)\n  b = Node(30)\n  c = Node(40)\n\n  l.last.next = a\n  a.next = b\n  b.next = c\n  c.next = l.last\n\n  traversal(l)\n\n  z = Node(50)\n  insert_after(z, c)\n  z = Node(25)\n  insert_after(z, a)\n  z = Node(100)\n  insert_at_last(l, z)\n\n  traversal(l)\n\n  delete(l, l.last);\n  delete(l, b);\n\n  traversal(l);\n"
  },
  {
    "path": "Data-Structures/LinkedList/Circular_Linked_List/csharp/CircularLinkedList.cs",
    "content": "// https://www.csharpstar.com/circular-singly-linked-list-csharp/\nusing System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nnamespace CircularLinkedList\n{\n    class Circularlist\n    {\n        private int currentdata;\n        private Circularlist nextdata;\n        public Circularlist()\n        {\n            currentdata = 0;\n            nextdata = this;\n        }\n        public Circularlist(int value)\n        {\n            currentdata = value;\n            nextdata = this;\n        }\n        public Circularlist Insdata(int value)\n        {\n            Circularlist node = new Circularlist(value);\n            if (this.nextdata == this)\n            {\n                node.nextdata = this;\n                this.nextdata = node;\n            }\n            else\n            {\n                Circularlist temp = this.nextdata;\n                node.nextdata = temp;\n                this.nextdata = node;\n            }\n            return node;\n        }\n        public int Deldata()\n        {\n            if (this.nextdata == this)\n            {\n                System.Console.WriteLine(\"\\nOnly one node...\");\n                return 0;\n            }\n            Circularlist node = this.nextdata;\n            this.nextdata = this.nextdata.nextdata;\n            node = null;\n            return 1;\n        }\n        public void Traverse()\n        {\n            Traverse(this);\n        }\n        public void Traverse(Circularlist node)\n        {\n            if (node == null)\n                node = this;\n            System.Console.WriteLine(\"Forward Direction...\");\n            Circularlist snode = node;\n            do\n            {\n                System.Console.WriteLine(node.currentdata);\n                node = node.nextdata;\n            }\n            while (node != snode);\n        }\n        public int Gnodes()\n        {\n            return Gnodes(this);\n        }\n        public int Gnodes(Circularlist node)\n        {\n            if (node == null)\n                node = this;\n            int count = 0;\n            Circularlist snode = node;\n            do\n            {\n                count++;\n                node = node.nextdata;\n            }\n            while (node != snode);\n            System.Console.WriteLine(\"\\nCurrent Node Value : \" + node.currentdata.ToString());\n            System.Console.WriteLine(\"\\nTotal nodes :\" + count.ToString());\n            return count;\n        }\n        static void Main(string[] args)\n        {\n            Circularlist node1 = new Circularlist(100);\n            node1.Deldata();\n            Circularlist node2 = node1.Insdata(200);\n            node1.Deldata();\n            node2 = node1.Insdata(200);\n            Circularlist node3 = node2.Insdata(300);\n            Circularlist node4 = node3.Insdata(400);\n            Circularlist node5 = node4.Insdata(500);\n            node1.Gnodes();\n            node3.Gnodes();\n            node5.Gnodes();\n            node1.Traverse();\n            node5.Deldata();\n            node2.Traverse();\n            node1.Gnodes();\n            node2.Gnodes();\n            node5.Gnodes();\n            Console.Read();\n        }\n    }\n}"
  },
  {
    "path": "Data-Structures/LinkedList/Doubly_Linked_List/Double linked List circular with double headers C++/LDLCCED.cbp",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\" ?>\n<CodeBlocks_project_file>\n\t<FileVersion major=\"1\" minor=\"6\" />\n\t<Project>\n\t\t<Option title=\"LDLCCED\" />\n\t\t<Option pch_mode=\"2\" />\n\t\t<Option compiler=\"gcc\" />\n\t\t<Build>\n\t\t\t<Target title=\"Debug\">\n\t\t\t\t<Option output=\"bin/Debug/LDLCCED\" prefix_auto=\"1\" extension_auto=\"1\" />\n\t\t\t\t<Option object_output=\"obj/Debug/\" />\n\t\t\t\t<Option type=\"1\" />\n\t\t\t\t<Option compiler=\"gcc\" />\n\t\t\t\t<Compiler>\n\t\t\t\t\t<Add option=\"-g\" />\n\t\t\t\t</Compiler>\n\t\t\t</Target>\n\t\t\t<Target title=\"Release\">\n\t\t\t\t<Option output=\"bin/Release/LDLCCED\" prefix_auto=\"1\" extension_auto=\"1\" />\n\t\t\t\t<Option object_output=\"obj/Release/\" />\n\t\t\t\t<Option type=\"1\" />\n\t\t\t\t<Option compiler=\"gcc\" />\n\t\t\t\t<Compiler>\n\t\t\t\t\t<Add option=\"-O2\" />\n\t\t\t\t</Compiler>\n\t\t\t\t<Linker>\n\t\t\t\t\t<Add option=\"-s\" />\n\t\t\t\t</Linker>\n\t\t\t</Target>\n\t\t</Build>\n\t\t<Compiler>\n\t\t\t<Add option=\"-Wall\" />\n\t\t\t<Add option=\"-fexceptions\" />\n\t\t</Compiler>\n\t\t<Unit filename=\"dllist.cpp\" />\n\t\t<Unit filename=\"dllist.h\" />\n\t\t<Unit filename=\"dlnode.cpp\" />\n\t\t<Unit filename=\"dlnode.h\" />\n\t\t<Unit filename=\"listexception.h\" />\n\t\t<Unit filename=\"main.cpp\" />\n\t\t<Unit filename=\"nodeexception.h\" />\n\t\t<Extensions>\n\t\t\t<code_completion />\n\t\t\t<envvars />\n\t\t\t<debugger />\n\t\t</Extensions>\n\t</Project>\n</CodeBlocks_project_file>\n"
  },
  {
    "path": "Data-Structures/LinkedList/Doubly_Linked_List/Double linked List circular with double headers C++/LDLCCED.layout",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\" ?>\n<CodeBlocks_layout_file>\n\t<FileVersion major=\"1\" minor=\"0\" />\n\t<ActiveTarget name=\"Debug\" />\n\t<File name=\"main.cpp\" open=\"1\" top=\"0\" tabpos=\"1\" split=\"0\" active=\"1\" splitpos=\"0\" zoom_1=\"0\" zoom_2=\"0\">\n\t\t<Cursor>\n\t\t\t<Cursor1 position=\"0\" topLine=\"0\" />\n\t\t</Cursor>\n\t</File>\n\t<File name=\"dllist.h\" open=\"1\" top=\"0\" tabpos=\"2\" split=\"0\" active=\"1\" splitpos=\"0\" zoom_1=\"0\" zoom_2=\"0\">\n\t\t<Cursor>\n\t\t\t<Cursor1 position=\"891\" topLine=\"17\" />\n\t\t</Cursor>\n\t</File>\n\t<File name=\"dlnode.cpp\" open=\"1\" top=\"0\" tabpos=\"3\" split=\"0\" active=\"1\" splitpos=\"0\" zoom_1=\"0\" zoom_2=\"0\">\n\t\t<Cursor>\n\t\t\t<Cursor1 position=\"109\" topLine=\"0\" />\n\t\t</Cursor>\n\t</File>\n\t<File name=\"dlnode.h\" open=\"1\" top=\"1\" tabpos=\"4\" split=\"0\" active=\"1\" splitpos=\"0\" zoom_1=\"0\" zoom_2=\"0\">\n\t\t<Cursor>\n\t\t\t<Cursor1 position=\"269\" topLine=\"6\" />\n\t\t</Cursor>\n\t</File>\n</CodeBlocks_layout_file>\n"
  },
  {
    "path": "Data-Structures/LinkedList/Doubly_Linked_List/Double linked List circular with double headers C++/dllist.cpp",
    "content": "#include \"dllist.h\"\n\n\n\nDLList::DLList() {\n    header = new DLNode;\n    if(header == nullptr) {\n        throw ListException(\"Memoria no disponible an inicializar la lista\");\n\n        }\n    header ->setPrev(header);\n    header ->setNext(header);\n    }\n\nbool DLList::isEmpty() {\n\n    return header->getNext() == header;\n    }\n\n\nvoid DLList::print() {\n    DLNode* aux = header->getNext();\n    while(aux != header) {\n        aux->getData().toString();\n        aux = aux->getNext();\n        }\n    }\n\n\nDLNode* DLList::insertData(DLNode *p, Agent&e) {\n    if(p != nullptr && !isValidPos(p)) {\n\n        throw ListException(\"Posicion invalida al tratar de insertar\");\n        }\n    if(p == nullptr) {\n\n        p = header;\n        }\n    DLNode* aux;\n    try {\n        aux= new DLNode(e);\n        }\n    catch(NodeException ex) {\n\n        throw ListException(ex.what());\n        }\n\n    if(aux == nullptr) {\n        throw ListException(\"Memoria no disponible al insertar\");\n        }\n    if(p == nullptr) {\n        aux->setPrev(nullptr);\n        aux->setNext(header);\n\n        if(header != nullptr) {\n            header->setPrev(aux);\n            }\n        header=aux;\n        }\n    else {\n        aux->setPrev(p);\n        aux->setNext(p->getNext());\n        if(p->getNext() != nullptr) {\n            p->getNext()->setPrev(aux);\n            }\n\n        p->setNext(aux);\n        }\n\n    return aux;\n\n    }\n\n\nbool DLList::isValidPos(DLNode* p) {\n    if(p == nullptr || isEmpty()) {\n        return false;\n        }\n    DLNode* aux=header;\n    do {\n        if(aux==p) {\n            return true;\n            }\n        aux = aux->getNext();\n        }\n    while(aux != header);\n    return false;\n    }\n///*******\n\nDLNode *DLList::getPrevPos(DLNode*p) {\n    if(!isValidPos(p)||p==header->getNext()) {\n        return nullptr;\n        }\n    return p->getPrev();\n\n    }\n\nDLNode *DLList::getNextPos(DLNode* p) {\n    if(!isValidPos(p)||p==header->getPrev()) {\n        return nullptr;\n        }\n    return p->getNext();\n    }\n\nDLNode *DLList::findData(Agent& e) {\n    DLNode* aux= header->getNext();\n    while(aux!= header) {\n        if(aux->getData()== e) {\n            return aux;\n            }\n        aux=aux->getNext();\n        }\n    return nullptr;\n\n    }\n\nvoid DLList::deleteData(DLNode*p) {\n    if(!isValidPos(p)) {\n        throw ListException(\"Posiccion no valida al tratar de eliminar\");\n        }\n    p->getPrev()->setNext(p->getNext());\n    p->getNext()->setPrev(p->getPrev());\n\n    delete p;\n    }\nvoid DLList::deleteAll() {\n    DLNode* aux;\n    while(header->getNext()!= header) {\n        aux= header->getNext();\n        header->setNext(header->getNext()->getNext());\n\n        delete aux;\n        }\n    header->setNext(header);\n\n    }\nDLList::~DLList() {\n    deleteAll();\n    delete header;\n    }\n\nDLList::DLList(DLList& l) : DLList() {\n    DLNode* aux= l.header->getNext();\n    while(aux != l.header) {\n        insertData(getLastPos(), aux->getData());\n        aux=aux->getNext();\n        }\n    }\n///*******\n\nDLNode* DLList::getFirstPos() {\n    if(isEmpty()) {\n        return nullptr;\n        }\n    return header -> getNext();\n    }\nDLNode* DLList::getLastPos() {\n    if(isEmpty()) {\n        return nullptr;\n        }\n    return header -> getPrev();\n    }\n\nAgent& DLList::retrieve(DLNode* p) {\n    if(!isValidPos(p)) {\n        throw ListException(\"Posicion invalida al usar retrieve \");\n        }\n    return p->getData();\n    }\n\n\nvoid DLList::sortByName() {\n    sortByName(getFirstPos(),getLastPos());\n\n    }\n\nvoid DLList::sortByDepartment() {\n\n    sortByDepartment(getFirstPos(),getLastPos());\n\n    }\n\nvoid DLList::exchange(DLNode*a, DLNode*b) {\n\n    Agent* aux = a->getDataPtr();\n    a->setDataPtr(b->getDataPtr());\n    b->setDataPtr(aux);\n\n    }\n\nvoid DLList::sortByName(DLNode*leftP, DLNode*rightP) {\n    if(leftP==rightP) {\n        return;\n        }\n\n    DLNode* pivot = rightP;\n    DLNode* i= leftP;\n    DLNode* j= rightP;\n\n    while(i != j) {\n        while(i != j && i->getData().getName()<=pivot->getData().getName()) {\n            i = i->getNext();\n            }\n        while(i != j && j->getData().getName()>=pivot->getData().getName()) {\n            j = j->getPrev();\n            }\n        if(i != j) {\n            exchange(i,j);\n            }\n\n        }\n    if(i != pivot) {\n        exchange(i,pivot);\n        }\n    if(i != leftP) {\n        sortByName(leftP, i->getPrev());\n        }\n    if(i != rightP) {\n        sortByName(i->getNext(),rightP);\n        }\n\n    }\nvoid DLList::sortByDepartment(DLNode*leftP, DLNode*rightP) {\n    if(leftP==rightP) {\n        return;\n        }\n\n    DLNode* pivot = rightP;\n    DLNode* i= leftP;\n    DLNode* j= rightP;\n\n    while(i != j) {\n        while(i != j and i->getData().getDepart()<=pivot->getData().getDepart()) {\n            i = i->getNext();\n            }\n        while(i != j and j->getData().getDepart()>=pivot->getData().getDepart()) {\n            j = j->getPrev();\n            }\n        if(i != j) {\n            exchange(i,j);\n            }\n\n        }\n    if(i != pivot) {\n        exchange(i,pivot);\n        }\n    if(i != leftP) {\n        sortByDepartment(leftP, i->getPrev());\n        }\n    if(i != rightP) {\n        sortByDepartment(i->getNext(),rightP);\n        }\n\n    }\n\nvoid DLList::writeToDisk(const std::string& fileName) {\n    std::ofstream myFile;\n\n    myFile.open(fileName, myFile.trunc);\n    if(!myFile.is_open()) {\n        throw ListException(\"No se pudo Abrir el Archivo\"+ fileName + \"Para escritura\");\n        }\n    DLNode* aux = header->getNext();\n    while(aux != header) {\n        myFile << aux->getData()<<std::endl;\n\n        aux->getData().getClientList().writeToDisk(aux->getData().getAgentNum());\n\n        aux=aux->getNext();\n        }\n    myFile.close();\n\n    }\nvoid DLList::readFromDisk(const std::string& fileName) {\n    std::ifstream myFile;\n    Agent myAgent;\n    DLNode* myPos;\n\n    myFile.open(fileName);\n    if(!myFile.is_open()) {\n        throw ListException(\"No se pudo Abrir el Archivo\"+ fileName + \"Para escritura\");\n        }\n\n    deleteAll();\n\n    while(myFile>>myAgent) {\n        myPos=insertData(getLastPos(), myAgent);\n\n        myPos->getData().getClientList().readFromDisk(myAgent.getAgentNum());\n        }\n    myFile.close();\n    }\n\n"
  },
  {
    "path": "Data-Structures/LinkedList/Doubly_Linked_List/Double linked List circular with double headers C++/dllist.h",
    "content": "#ifndef DLLIST_H_INCLUDED\n#define DLLIST_H_INCLUDED\n#include <iostream>\n#include <fstream>\n#include \"listexception.h\"\n#include\"dlnode.h\"\n#include\"agent.h\"\nclass DLList {\n    private:\n        DLNode* header;\n        bool isValidPos(DLNode*);\n        void exchange(DLNode*, DLNode*);\n        void sortByName(DLNode*, DLNode*);\n        void sortByDepartment(DLNode*, DLNode*);\n\n    public:\n        DLList();\n        DLList(DLList&);\n        ~DLList();\n\n        bool isEmpty();\n\n        DLNode* insertData(DLNode*,Agent&);\n        void deleteData(  DLNode*);\n\n        DLNode*  getFirstPos();\n        DLNode*  getLastPos();\n        DLNode*  getPrevPos( DLNode*);\n        DLNode*  getNextPos( DLNode*);\n        DLNode*  findData(Agent&);\n        void deleteAll();\n\n        Agent& retrieve( DLNode*);\n\n        void sortByName();\n        void sortByDepartment();\n\n        void print();\n        void writeToDisk(const std::string&);\n        void readFromDisk(const  std::string&);\n\n    };\n\n#endif // DLLIST_H_INCLUDED\n"
  },
  {
    "path": "Data-Structures/LinkedList/Doubly_Linked_List/Double linked List circular with double headers C++/dlnode.cpp",
    "content": "#include \"dlnode.h\"\nDLNode::DLNode() {\n    prev = next = nullptr;\n    dataPtr = nullptr;\n    }\nDLNode::~DLNode(){\n    delete dataPtr;\n}\n\n\nDLNode::DLNode(Agent& s):DLNode() {\n    dataPtr = new Agent(s);\n\n    if(dataPtr == nullptr) {\n        throw NodeException(\"Memoria no disponible al inicializar nodo\");\n        }\n    }\n\nAgent* DLNode::getDataPtr() {\n    return dataPtr;\n    }\n\nAgent& DLNode::getData() {\n    if(dataPtr==nullptr) {\n        throw NodeException(\"Dato Inexistente, o memoria no disponible\")\n        }\n\n    return *dataPtr;\n    }\n\nDLNode* DLNode::getPrev() {\n    return prev;\n    }\n\nDLNode* DLNode::getNext() {\n    return next;\n    }\nvoid DLNode::setDataPtr(Agent*p) {\n    dataPtr = p;\n    }\n\n\nvoid DLNode::setData(Agent&s) {\n    if(dataPtr == nullptr) {\n        dataPtr = new Agent(s);\n        if(dataPtr == nullptr) {\n            throw NodeException(\"Memoria no disponible al inicializar nodo\");\n            }\n        }\n\n    else {\n        *dataPtr = s;\n        }\n    }\nvoid DLNode::setPrev( DLNode*p) {\n    prev = p;\n    }\nvoid DLNode::setNext( DLNode*n) {\n    next = n;\n    }\n\n"
  },
  {
    "path": "Data-Structures/LinkedList/Doubly_Linked_List/Double linked List circular with double headers C++/dlnode.h",
    "content": "#ifndef DLNODE_H_INCLUDED\n#define DLNODE_H_INCLUDED\n#include \"agent.h\"\n#include \"nodeexception.h\"\nclass DLNode {\n    private:\n        Agent* dataPtr;\n        DLNode*prev;\n        DLNode*next;\n\n    public:\n        DLNode();\n        DLNode(Agent&);\n        ~DLNode();\n\n\n        Agent* getDataPtr();\n        Agent& getData();\n        DLNode* getNext();\n        DLNode* getPrev();\n\n        void setDataPtr(Agent*);\n        void setData(  Agent&);\n        void setNext(  DLNode*);\n        void setPrev(  DLNode*);\n\n    };\n#endif // DLNODE_H_INCLUDED\n"
  },
  {
    "path": "Data-Structures/LinkedList/Doubly_Linked_List/Double linked List circular with double headers C++/listexception.h",
    "content": "#ifndef ListException_H_INCLUDED\n#define ListException_H_INCLUDED\n#include <exception>\n#include <string>\n\nclass ListException : public std::exception {\n    private:\n        std::string msg;\n    public:\n        explicit ListException(const char* message) : msg(message) {}\n        explicit ListException(const std::string& message) : msg(message) {}\n        ~ListException() throw () {}\n        virtual const char* what() const throw () {\n            return msg.c_str();\n            }\n    };\ntemplate <class T, int arraySize = 1024>\nclass List {\n    private:\n        T data[arraySize];\n        int last;\n        bool isPosValidate(int);\n    public:\n        List();\n    };\n#endif // ListException_H_INCLUDED\n\n"
  },
  {
    "path": "Data-Structures/LinkedList/Doubly_Linked_List/Double linked List circular with double headers C++/main.cpp",
    "content": "#include <iostream>\n\nusing namespace std;\n\nint main() {\n    cout << \"Hello world!\" << endl;\n    return 0;\n    }\n"
  },
  {
    "path": "Data-Structures/LinkedList/Doubly_Linked_List/Double linked List circular with double headers C++/nodeexception.h",
    "content": "#ifndef NODEEXCEPTION_H_INCLUDED\n#define NODEEXCEPTION_H_INCLUDED\n#include <exception>\n#include <string>\nclass NodeException : public std::exception {\n    private:\n        std::string msg;\n    public:\n        explicit NodeException(const char* message) : msg(message) {}\n        explicit NodeException(const std::string& message) : msg(message) {}\n        NodeException() throw () {}\n        virtual const char* what() const throw () {\n            return msg.c_str();\n            }\n    };\ntemplate <class T, int arraySize = 1024>\nclass Node {\n    private:\n        T data[arraySize];\n        int last;\n        bool isPosValidate(int);\n    public:\n        Node();\n    };\n\n\n\n#endif // NODEEXCEPTION_H_INCLUDED\n"
  },
  {
    "path": "Data-Structures/LinkedList/Doubly_Linked_List/DoubleLinkedList.java",
    "content": "class DoubleLinkedList<T>\n{\n  private T value;\n  private LinkedList<T> next;\n  private LinkedList<T> prev;\n\n  public LinkedList(LinkedList<T> prev, T value, LinkedList<T> next) {\n    SetPrev(prev);\n    SetValue(value);\n    SetNext(next);\n  }\n\n  public LinkedList(T value) {\n    this(null, value, null);\n  }\n\n  public LinkedList<T> GetPrev() {\n    return prev;\n  }\n\n  public T GetValue() {\n    return value;\n  }\n\n  public LinkedList<T> GetNext() {\n    return next;\n  }\n\n  public void SetPrev(LinkedList<T> prev) {\n    this.prev = prev;\n  }\n\n  public void SetValue(T value) {\n    this.value = value;\n  }\n\n  public void SetNext(LinkedList<T> next) {\n    this.next = next;\n  }\n}"
  },
  {
    "path": "Data-Structures/LinkedList/Doubly_Linked_List/DoublyLinkedList.cs",
    "content": "﻿using System;\nusing System.Collections.Generic;\n\n/// <summary>\n/// A DoublyLinkedList\n/// </summary>\nnamespace DataStructures\n{\n    public class DoublyLinkedListNode<T>\n    {\n        // Constructs a new node with the specified value.\n        public DoublyLinkedListNode(T value)\n        {\n            Value = value;\n            Next = null;\n            Prev = null;\n        }\n        // The node value\n        public T Value { get; set; }\n        // The next node in the Doubly linked list (null if last node)\n        public DoublyLinkedListNode<T> Next { get; set; }\n        public DoublyLinkedListNode<T> Prev { get; set; }\n    }\n\n    /// <summary>\n    /// A Doubly linked list collection capable of basic operations such as \n    /// Add, Remove, Check, Search, IsEmpty, Size, Insert and Index\n    /// </summary>\n    public class DoublyLinkedList<T>\n    {\n        /// <summary>\n        /// Adds the specified value to the tail of the doublylinked list\n        /// </summary>\n        public int Add(T item)\n        {\n            DoublyLinkedListNode<T> node = new DoublyLinkedListNode<T>(item);\n            if (count == 0)\n            {\n                head = node;\n                tail = head;\n            }\n            else\n            {\n                node.Prev = tail;\n                tail.Next = node;\n                tail = node;\n            }\n\n            return ++count;\n        }\n\n        /// <summary>\n        /// Inserts the specified item at the specified index\n        /// </summary>\n        /// <param name=\"index\"></param>\n        /// <param name=\"item\"></param>\n        public void Insert(int index, T item)\n        {\n            if (index > count + 1 || (count == 0 && index > 0) || index < 0)\n            {\n                throw new IndexOutOfRangeException(\"Index out of range.\");\n            }\n            if (count == 0 || index == count)\n            {\n                Add(item);\n                return;\n            }\n            var currentIndex = 0;\n            DoublyLinkedListNode<T> current = head;\n            DoublyLinkedListNode<T> node = new DoublyLinkedListNode<T>(item);\n            while (currentIndex <= index)\n            {\n                if(currentIndex == index)\n                {\n                    DoublyLinkedListNode<T> previous = current.Prev;\n                    if (previous == null) head = node;\n                    node.Prev = previous;\n                    node.Next = current;\n                    //previous.Next = node;\n                    current.Prev = node;\n                    count++;\n                    return;\n                }\n                current = current.Next;\n                currentIndex++;\n            }\n            return;\n        }\n\n        /// <summary>\n        /// Removes a VALUE from the list if found.\n        /// </summary>\n        public bool Remove(T item)\n        {\n            var check = false;\n\n            DoublyLinkedListNode<T> node = new DoublyLinkedListNode<T>(item);\n\n            // Checks if only one item is in the list\n            // and if the item is the same as the item to be removed\n            if (count == 1 && item.Equals(head.Value))\n            {\n                check = true;\n                head = null;\n                tail = head;\n            }\n\n            // Iterates through the doublylinked list to check for the item\n            while (Check(item))\n            {\n                check = true;\n\n                DoublyLinkedListNode<T> current = head;\n                while (current != null)\n                {\n                    if (current.Value.Equals(item))\n                    {\n                        DoublyLinkedListNode<T> previous = current.Prev;\n                        DoublyLinkedListNode<T> next = current.Next;\n\n                        if (previous == null)\n                        {\n                            head = next;\n                            next.Prev = null;\n                        }\n                        else if (next == null)\n                        {\n                            tail = previous;\n                            previous.Next = null;\n                        }\n                        else\n                        {\n                            previous.Next = current.Next;\n                            next.Prev = current.Prev;\n\n                        }\n                        count--;\n                    }\n\n                    current = current.Next;\n                }                \n            }\n            return check;\n        }\n\n        /// <summary>\n        /// Returns true if the list contains the specified item,\n        /// false otherwise.\n        /// </summary>\n        public bool Check(T item)\n        {\n            DoublyLinkedListNode<T> current = head;\n            while (current != null)\n            {\n                if (current.Value.Equals(item))\n                {\n                    return true;\n                }\n\n                current = current.Next;\n            }\n            return false;\n        }\n\n        /// <summary>\n        /// Returns item if the list contains the specified item\n        /// </summary>\n        /// <returns>Returns item if found</returns>\n        public T Search(T item)\n        {\n            if (!Check(item))\n            {\n                throw new InvalidOperationException(\"Item not found in list.\");\n            }\n\n            DoublyLinkedListNode<T> current = head;\n            while (current != null)\n            {\n                if (current.Value.Equals(item))\n                {\n                    return current.Value;\n                }\n\n                current = current.Next;\n            }\n\n            return item;\n        }\n\n        /// <summary>\n        /// Returns true if the list is empty, otherwise false.\n        /// </summary>\n        public bool isEmpty()\n        {\n            return count == 0;\n        }\n\n        /// <summary>\n        /// Checks for the length of list\n        /// </summary>\n        /// <returns>Length of list</returns>\n        public int Size()\n        {\n            return count;\n        }\n\n        /// <summary>\n        /// Finds the index of the specified item\n        /// </summary>\n        /// <param name=\"item\"></param>\n        /// <returns>the index of item</returns>\n        public int Index(T item)\n        {\n            if (!Check(item))\n            {\n                throw new InvalidOperationException(\"Item not in list\");\n            }\n\n            DoublyLinkedListNode<T> current = head;\n            var currentIndex = 0;\n\n            while (currentIndex != count)\n            {\n                if (current.Value.Equals(item))\n                {\n                    return currentIndex;\n                }\n\n                current = current.Next;\n                currentIndex++;\n            }\n            return -1;\n        }\n\n        /// <summary>\n        /// Length of list, zero if list is empty\n        /// </summary>\n        public int count\n        {\n            get;\n            private set;\n        }\n\n        /// <summary>\n        /// The first node in the list or null if empty\n        /// </summary>\n        private DoublyLinkedListNode<T> head\n        {\n            get;\n            set;\n        }\n\n        /// <summary>\n        /// The last node in the list or null if empty\n        /// </summary>\n        private DoublyLinkedListNode<T> tail\n        {\n            get;\n            set;\n        }\n    }\n}\n"
  },
  {
    "path": "Data-Structures/LinkedList/Doubly_Linked_List/DoublyLinkedList.hs",
    "content": "module DoublyLinkedLists where\n\nimport Prelude hiding (last, elem)\n\n-- Implementation without a header/trailer sentinel, meaning some operations\n-- take O(n) instead of O(1).\ndata DList a\n  = Empty\n  | Node { prev :: DList a\n         , elem :: a\n         , next :: DList a }\n  deriving (Eq)\n\ninstance Show a => Show (DList a) where\n  show (Node Empty x Empty) = \"[\" ++ show x ++ \"]\"\n  show (Node Empty x next) = \"[\" ++ show x ++ \",\" ++ show next\n  show (Node _ x Empty) = show x ++ \"]\"\n  show (Node _ x next) = show x ++ \",\" ++ show next\n  show Empty = \"[]\"\n\nfromList :: [a] -> DList a\nfromList = append Empty\n  where\n    append :: DList a -> [a] -> DList a\n    append _ [] = Empty\n    append prev (x:xs) = head\n      where\n        head = Node prev x tail\n        tail = append head xs\n\nsize :: DList a -> Int\nsize Empty = 0\nsize (Node _ _ next) = 1 + size next\n\nisEmpty :: DList a -> Bool\nisEmpty Empty = True\nisEmpty _ = False\n\nfirst :: DList a -> Maybe a\nfirst Empty = Nothing\nfirst (Node _ a _) = Just a\n\nlast :: Eq a => DList a -> Maybe a\nlast Empty = Nothing\nlast (Node _ a next)\n  | next == Empty = Just a\n  | otherwise = last next\n\naddFirst :: a -> DList a -> DList a\naddFirst x Empty = Node Empty x Empty\naddFirst x (Node prev y next) =\n  let newFirst = Node Empty x newSecond\n      newSecond = Node newFirst y next\n   in newFirst\n\n-- WIP: doesnt work for lists with length > 1\naddLast :: a -> DList a -> DList a\naddLast x Empty = Node Empty x Empty\naddLast x list = let last' = lastNode list\n                     secondToLast = Node (prev last') (elem last') newLast\n                     newLast = Node secondToLast x Empty\n                 in rewind newLast\n  where\n    lastNode :: DList a -> DList a\n    lastNode Empty = Empty\n    lastNode (Node prev x Empty) = Node prev x Empty\n    lastNode (Node _ _ next) = lastNode next\n\n    rewind :: DList a -> DList a\n    rewind Empty = Empty\n    rewind (Node Empty x next) = Node Empty x next\n    rewind (Node prev _ _) = rewind prev\n"
  },
  {
    "path": "Data-Structures/LinkedList/Doubly_Linked_List/DoublyLinkedList_C++_Template/DLL.h",
    "content": "#include <iostream>\n\n/*\nClass DLList is Double Linked List without a sentinel node\nClass Sentinel is Double Linked List using a sentinel node\nIf you want to know more about sentinel node, here is the explanation from Wikipedia\nhttps://en.wikipedia.org/wiki/Sentinel_node#:~:text=The%20list%20starts%20out%20with,previous%20pointers%20point%20to%20itself.&text=In%20a%20non%2Dempty%20list,the%20tail%20of%20the%20list.\n\n*/\n\n/* DLL Class without a sentinel node */\ntemplate <typename T>\nclass DLL {\n\tstruct Node {\n\t\tT m_data;\n\t\tNode* m_next;\n\t\tNode* m_prev;\n\t\tNode(const T& data = T{}, Node* next = nullptr, Node* prev = nullptr) {\n\t\t\tm_data = data;\n\t\t\tm_next = next;\n\t\t\tm_prev = prev;\n\t\t}\n\t};\n\tNode* m_front;\n\tNode* m_back;\npublic:\n\tDLL() {\n\t\tm_front = nullptr;\n\t\tm_back = nullptr;\n\t}\n\tvoid push_front(const T& data);\n\tvoid push_back(const T& data);\n\tvoid pop_front();\n\tvoid pop_back();\n\tvoid print() const;\n\tvoid reversePrint() const;\n\t~DLL();\n};\n\n\ntemplate <typename T>\nvoid DLL<T>::push_front(const T& data) {\n\tNode* nn = new Node(data, m_front);\n\tif (m_front != nullptr) {\n\t\tm_front->m_prev = nn;\n\t}\n\telse {\n\t\tm_back = nn;\n\t}\n\tm_front = nn;\n}\n\n\ntemplate <typename T>\nvoid DLL<T>::push_back(const T& data) {\n\tNode* nn = new Node(data, nullptr, m_back);\n\tif (m_back != nullptr) {\n\t\tm_back->m_next = nn;\n\t}\n\telse {\n\t\tm_front = nn;\n\t}\n\tm_back = nn;\n}\n\n\ntemplate <typename T>\nvoid DLL<T>::pop_front() {\n\tif (m_front != nullptr) {\n\t\tNode* rm = m_front;\n\t\tm_front = rm->m_next;\n\t\tif (m_front != nullptr) {\n\t\t\tm_front->m_prev = nullptr;\n\t\t}\n\t\telse {\n\t\t\tm_back = nullptr;\n\t\t}\n\t\tdelete rm;\n\t}\n\n}\n\n\ntemplate <typename T>\nvoid DLL<T>::pop_back() {\n\tif (m_back != nullptr) {\n\t\tNode* rm = m_back;\n\t\tm_back = rm->m_prev;\n\t\tif (m_back != nullptr) {\n\t\t\tm_back->m_next = nullptr;\n\t\t}\n\t\telse {\n\t\t\tm_front = nullptr;\n\t\t}\n\t\tdelete rm;\n\t}\n\n}\n\n\ntemplate <typename T>\nvoid DLL<T>::print() const {\n\tNode* curr = m_front;\n\twhile (curr != nullptr) {\n\t\tstd::cout << curr->m_data << \" \";\n\t\tcurr = curr->m_next;\n\t}\n\tif (!m_front) {\n\t\tstd::cout << \"empty list\";\n\t}\n\tstd::cout << std::endl;\n}\n\n\ntemplate <typename T>\nvoid DLL<T>::reversePrint() const {\n\tNode* curr = m_back;\n\twhile (curr != nullptr) {\n\t\tstd::cout << curr->m_data << \" \";\n\t\tcurr = curr->m_prev;\n\t}\n\tif (!m_back) {\n\t\tstd::cout << \"empty list\";\n\t}\n\tstd::cout << std::endl;\n}\n\n\ntemplate <typename T>\nDLL<T>::~DLL() {\n\twhile (m_front) {\n\t\tNode* it = m_front;\n\t\tm_front = it->m_next;\n\t\tdelete it;\n\t}\n}\n\n/* Sentinel Class using a sentinel node */\ntemplate <typename T>\nclass Sentinel {\n\tstruct Node {\n\t\tT m_data;\n\t\tNode* m_next;\n\t\tNode* m_prev;\n\t\tNode(const T& data = T{}, Node* next = nullptr, Node* prev = nullptr) {\n\t\t\tm_data = data;\n\t\t\tm_next = next;\n\t\t\tm_prev = prev;\n\t\t}\n\t};\n\tNode* m_front;\n\tNode* m_back;\npublic:\n\tSentinel() {\n\t\tm_front = new Node();\n\t\tm_back = new Node();\n\t\tm_front->m_next = m_back;\n\t\tm_back->m_prev = m_front;\n\t}\n\tvoid push_front(const T& data);\n\tvoid push_back(const T& data);\n\tvoid pop_front();\n\tvoid pop_back();\n\tvoid print() const;\n\tvoid reversePrint() const;\n\t~Sentinel();\n};\n\n\ntemplate <typename T>\nvoid Sentinel<T>::push_front(const T& data) {\n\tNode* nn = new Node(data, m_front->m_next, m_front);\n\tm_front->m_next->m_prev = nn;\n\tm_front->m_next = nn;\n}\n\n\ntemplate <typename T>\nvoid Sentinel<T>::push_back(const T& data) {\n\tNode* nn = new Node(data, m_back, m_back->m_prev);\n\tm_back->m_prev->m_next = nn;\n\tm_back->m_prev = nn;\n}\n\n\ntemplate <typename T>\nvoid Sentinel<T>::pop_front() {\n\t//if its an empty list... note that it means\n\t//front sentinel's next node is the back sentinel\n\tif (m_front->m_next != m_back) {\n\t\tNode* rm = m_front->m_next;\n\t\tNode* B = rm->m_next;\n\t\tm_front->m_next = B;\n\t\tB->m_prev = m_front;\n\t\tdelete rm;\n\t}\n}\n\n\ntemplate <typename T>\nvoid Sentinel<T>::pop_back() {\n\tif (m_back->m_prev != m_front) {\n\t\tNode* rm = m_back->m_prev;\n\t\trm->m_prev->m_next = m_back;\n\t\tm_back->m_prev = rm->m_prev;\n\t\tdelete rm;\n\t}\n}\n\n\ntemplate <typename T>\nvoid Sentinel<T>::print() const {\n\tNode* curr = m_front->m_next;\n\twhile (curr != m_back) {\n\t\tstd::cout << curr->m_data << \" \";\n\t\tcurr = curr->m_next;\n\t}\n\tif (m_front->m_next == m_back) {\n\t\tstd::cout << \"empty list\";\n\t}\n\tstd::cout << std::endl;\n}\n\n\ntemplate <typename T>\nvoid Sentinel<T>::reversePrint() const {\n\tNode* curr = m_back->m_prev;\n\twhile (curr != m_front) {\n\t\tstd::cout << curr->m_data << \" \";\n\t\tcurr = curr->m_prev;\n\t}\n\tif (m_back->m_prev == m_front) {\n\t\tstd::cout << \"empty list\";\n\t}\n\tstd::cout << std::endl;\n}\n\n\ntemplate <typename T>\nSentinel<T>::~Sentinel() {\n\twhile (m_front != m_back) {\n\t\tNode* it = m_front;\n\t\tm_front = it->m_next;\n\t\tdelete it;\n\t}\n}\n\n"
  },
  {
    "path": "Data-Structures/LinkedList/Doubly_Linked_List/DoublyLinkedList_C++_Template/DLLtest.cpp",
    "content": "/* tester */\n\n#include \"DLL.h\"\n#include <iostream>\n\nint main(void) {\n\tDLL<int> regular;\n\tSentinel<int> sentinel;\n\n\t/* DLL class test */\n\tstd::cout << \"testing regular doubly linked list\" << std::endl;\n\t\n\t// test push_front();\n\tfor (int i = 0; i < 3; i++) {\n\t\tregular.push_front(i);\n\t\tregular.print(); \t\t\t\t\n\t}\n\tregular.reversePrint();    \n\n\t//test push_back();\n\tfor (int i = 3; i < 6; i++) {\n\t\tregular.push_back(i);\n\t\tregular.print();\n\t}\n\tregular.reversePrint();\n\n\t//test pop_front() & pop_back()\n\tfor (int i = 0; i < 7; i++) {\n\t\tif (i % 2 == 0) {\n\t\t\tregular.pop_front();\n\t\t}\n\t\telse {\n\t\t\tregular.pop_back();\n\t\t}\n\t\tregular.print();\n\t}\n\tregular.reversePrint();\n\n\t//test push_back();\n\tfor (int i = 0; i < 3; i++) {\n\t\tregular.push_back(i);\n\t\tregular.print();\n\t}\n\tregular.reversePrint();\n\t\n\n\tfor (int i = 3; i < 6; i++) {\n\t\tregular.push_front(i);\n\t\tregular.print();\n\t}\n\tregular.reversePrint();\n\n\t//test pop_front()\n\tfor (int i = 0; i < 7; i++) {\n\t\tif (i % 2) {\n\t\t\tregular.pop_front();\n\t\t}\n\t\telse {\n\t\t\tregular.pop_back();\n\t\t}\n\t\tregular.print();\n\t}\n\tregular.reversePrint();\n\n   \n\tfor (int i = 0; i < 3; i++) {\n\t\tregular.push_front(i);\n\t\tregular.print();\n\t}\n\tregular.reversePrint();\n\n\n\t/* Sentinel class test */\n\n\tstd::cout << \"testing sentinel list\" << std::endl;\n\n\t//test push_front()\n\tfor (int i = 0; i < 3; i++) {\n\t\tsentinel.push_front(i);\n\t\tsentinel.print();\n\t}\n\tsentinel.reversePrint();\n\n\t//test push_back()\n\tfor (int i = 3; i < 6; i++) {\n\t\tsentinel.push_back(i);\n\t\tsentinel.print();\n\t}\n\tsentinel.reversePrint();\n\n\t//test pop_front() & pup_back()\n\tfor (int i = 0; i < 7; i++) {\n\t\tif (i % 2 == 0) {\n\t\t\tsentinel.pop_front();\n\t\t}\n\t\telse {\n\t\t\tsentinel.pop_back();\n\t\t}\n\t\tsentinel.print();\n\t}\n\tsentinel.reversePrint();\n\n\tfor (int i = 0; i < 3; i++) {\n\t\tsentinel.push_back(i);\n\t\tsentinel.print();\n\t}\n\tsentinel.reversePrint();\n\n\tfor (int i = 3; i < 6; i++) {\n\t\tsentinel.push_front(i);\n\t\tsentinel.print();\n\t}\n\tsentinel.reversePrint();\n\n\tfor (int i = 0; i < 7; i++) {\n\t\tif (i % 2) {\n\t\t\tsentinel.pop_front();\n\t\t}\n\t\telse {\n\t\t\tsentinel.pop_back();\n\t\t}\n\t\tsentinel.print();\n\t}\n\tsentinel.reversePrint();\n\n\tfor (int i = 0; i < 3; i++) {\n\t\tsentinel.push_front(i);\n\t\tsentinel.print();\n\t}\n\tsentinel.reversePrint();\n\n\n\treturn 0;\n}\n"
  },
  {
    "path": "Data-Structures/LinkedList/Doubly_Linked_List/Doubly_Linked_List.py",
    "content": "\nclass Node:\n    def __init__(self, value):\n        self.value = value\n        self.prev = None\n        self.next = None\n\n\nclass DoublyLinkedList:\n    def __init__(self):\n        self.head = None\n        self.tail = None\n\n    def setHead(self, node):\n        # O(1) T | O (1) S\n\t\tif self.head is None:\n\t\t\tself.head = node\n\t\t\tself.tail = node\n\t\t\treturn\n\t\tself.insertBefore(self.head, node)\n\n    def setTail(self, node):\n        # O(1) T | O(1) S\n\t\tif self.tail is None:\n\t\t\tself.setHead(node)\n\t\tself.insertAfter(self.tail, node)\n\n    def insertBefore(self, node, nodeToInsert):\n        # O(1) T | O(1) S\n\t\t# First we gotta tackle case that what if n=there is no linked list therefore no node. In that case, we were asked to insert a node before something that does not exist and hence, we gotta return\n\t\tif (nodeToInsert == self.head and nodeToInsert == self.tail):\n\t\t\treturn\n\t\tself.remove(nodeToInsert)\n\t\tnodeToInsert.prev = node.prev\n\t\tnodeToInsert.next = node\n\t\tif node.prev is None:\n\t\t\tself.head = nodeToInsert\n\t\telse:\n\t\t\tnode.prev.next = nodeToInsert\n\t\tnode.prev = nodeToInsert\n\n    def insertAfter(self, node, nodeToInsert):\n        # O(1) T | O(1) S\n\t\tif (nodeToInsert == self.head and nodeToInsert == self.tail):\n\t\t\treturn\n\t\tself.remove(nodeToInsert)\n\t\tnodeToInsert.prev = node\n\t\tnodeToInsert.next = node.next\n\t\tif node.next is None:\n\t\t\tself.tail = nodeToInsert\n\t\telse:\n\t\t\tnode.next.prev = nodeToInsert\n\t\tnode.next = nodeToInsert\n\n    def insertAtPosition(self, position, nodeToInsert):\n        # O(P) T | O(1) S\n\t\tif position == 1:\n\t\t\tself.setHead(nodeToInsert)\n\t\t\treturn\n\t\tcurrentPosition = 1\n\t\tnode = self.head\n\t\twhile node is not None and currentPosition != position:\n\t\t\tcurrentPosition += 1\n\t\t\tnode = node.next\n\t\tif node is not None:\n\t\t\tself.insertBefore(node, nodeToInsert)\n\t\telse:\n\t\t\tself.setTail(nodeToInsert)\n\n    def removeNodesWithValue(self, value):\n        # O(N) T | O(1) S\n\t\tnode = self.head\n\t\twhile node is not None:\n\t\t\tnodeToRemove = node\n\t\t\tnode = node.next\n\t\t\tif nodeToRemove.value == value:\n\t\t\t\tself.remove(nodeToRemove)\n\n    def remove(self, node):\n        # O(1) T | O(1) S\n\t\tif (node == self.head):\n\t\t\tself.head = self.head.next\n\t\tif(node == self.tail):\n\t\t\tself.tail = self.tail.prev\n\t\tself.removeNodeBindings(node)\n\n\tdef removeNodeBindings(self,node):\n\t\t# O(1) T | O(1) S\n\t\tif node.prev is not None:\n\t\t\tnode.prev.next=node.next\n\t\tif node.next is not None:\n\t\t\tnode.next.prev = node.prev\n\t\tnode.prev=None\n\t\tnode.next=None\n\n    def containsNodeWithValue(self, value):\n        # O(N) T | O(1) S\n\t\tnode = self.head\n\t\twhile node is not None and node.value!=value:\n\t\t\tnode=node.next\n\t\treturn node is not None\n"
  },
  {
    "path": "Data-Structures/LinkedList/Doubly_Linked_List/README.md",
    "content": "## This folder is empty.\n"
  },
  {
    "path": "Data-Structures/LinkedList/Doubly_Linked_List/double_linked_list.c",
    "content": "#include <stdio.h>\n#include<stdlib.h>\nstruct Node\n{\nstruct Node *prev;\nint data;\nstruct Node *next;\n}*first=NULL;\nvoid create(int A[],int n)\n{\nstruct Node *t,*last;\nint i;\nfirst=(struct Node *)malloc(sizeof(struct Node));\nfirst->data=A[0];\nfirst->prev=first->next=NULL;\nlast=first;\nfor(i=1;i<n;i++)\n{\nt=(struct Node *)malloc(sizeof(struct Node));\nt->data=A[i];\nt->next=last->next;\nt->prev=last;\nlast->next=t;\nlast=t;\n}\n}\nvoid Display(struct Node *p)\n{\nwhile(p)\n{\n\tprintf(\"%d \",p->data);\np=p->next;\n}\nprintf(\"\\n\");\n}\nint Length(struct Node *p)\n{\nint len=0;\nwhile(p)\n{\nlen++;\np=p->next;\n}\nreturn len;\n}\nvoid Insert(struct Node *p,int index,int x)\n{\nstruct Node *t;\nint i;\nif(index < 0 || index > Length(p))\nreturn;\nif(index==0)\n{\nt=(struct Node *)malloc(sizeof(struct Node));\nt->data=x;\nt->prev=NULL;\nt->next=first;\nfirst->prev=t;\nfirst=t;\n}\nelse\n{\nfor(i=0;i<index-1;i++)\np=p->next;\nt=(struct Node *)malloc(sizeof(struct Node));\nt->data=x;\n{\nstruct Node *temp;\nwhile(p!=NULL)\n{\ntemp=p->next;\np->next=p->prev;\np->prev=temp;\np=p->prev;\nif(p!=NULL && p->next==NULL)\nfirst=p;\n}\n}\nint main()\n{\nint A[]={10,20,30,40,50};\ncreate(A,5);\nReverse(first);\nDisplay(first);\nreturn 0;\n}\n"
  },
  {
    "path": "Data-Structures/LinkedList/Doubly_Linked_List/doubly.c",
    "content": "#include<stdio.h>\n#include<stdlib.h>\n\nstruct node{\n    int value;\n    struct node *lptr,*rptr;\n};\n\nvoid insert(struct node **LH,struct node **RH,int val){\n        struct node *NewNode,*temp;\n        temp = *LH;\n        NewNode = (struct node*)malloc(sizeof(struct node));\n        NewNode->value = val;\n        if(*LH == NULL && *RH == NULL){\n            (*LH) = (*RH) = NewNode;\n            NewNode->lptr = NewNode->rptr =NULL;\n        }else{\n            printf(\"1) insert at first\\n2) insert at last\\n3) insert at order\\nWhere u want to insert :\");\n            int n;\n            scanf(\"%d\",&n);\n            if(n==1){\n                // insert at front\n                NewNode->rptr = *LH;\n                NewNode->lptr = NULL;\n                (*LH)->lptr = NewNode;\n                *LH = NewNode;\n            }else if(n==2){\n                NewNode->rptr = NULL;\n                NewNode->lptr = *RH;\n                (*RH)->rptr = NewNode;\n                *RH = NewNode;\n            }else if(n==3){\n                if(temp->lptr == NULL){\n                    if(temp->value >= val){\n                NewNode->rptr = *LH;\n                NewNode->lptr = NULL;\n                (*LH)->lptr = NewNode;\n                *LH = NewNode;\n                    }\n                    else{\n                NewNode->rptr = NULL;\n                NewNode->lptr = *RH;\n                (*RH)->rptr = NewNode;\n                *RH = NewNode;\n                    }\n                return;\n                }\n                if(temp->value >= val){\n                NewNode->rptr = *LH;\n                NewNode->lptr = NULL;\n                (*LH)->lptr = NewNode;\n                *LH = NewNode;\n                return;\n                }\n\n                while(temp->rptr->value <= val)\n                    temp = temp->rptr;\n                 if(temp->rptr == *RH){\n                NewNode->rptr = NULL;\n                NewNode->lptr = *RH;\n                (*RH)->rptr = NewNode;\n                *RH = NewNode;\n                }else{\n                        NewNode->lptr = temp;\n                        NewNode->rptr = temp->rptr;\n                        temp->rptr->lptr = NewNode;\n                        temp->rptr = NewNode;\n                }\n            }\n            else printf(\"\\nsomething wrong\");\n        }\n}\nvoid Display(struct node **LH,struct node ** RH){\n    struct node *temp;\n    temp = *LH;\n    while(temp != NULL){\n        printf(\" %d \",temp->value);\n        temp = temp->rptr;\n    }\n    printf(\"\\n\");\n}\n\nvoid delete_Link(struct node **LH,struct node **RH){\n            struct node *NodetoBeDeleted,*temp;\n            int n, val;\n            temp = *LH;\n            if(*LH == NULL ){\n                    printf(\"\\nsorry Link List is Empty\\n\");\n                    return;\n            }\n            if(temp->lptr == NULL && temp->rptr == NULL){\n                NodetoBeDeleted = temp;\n                free(NodetoBeDeleted);\n                *LH= *RH= NULL;\n            }else{\n                printf(\"1) Delete first Link\\n2) Delete Last link\\n3) Delete specific value  \\nwhich value u want to Delete\");\n                scanf(\"%d\",&n);\n                if(n==3){\n                    printf(\"Enter value :\");\n                    scanf(\"%d\",&val);\n                }\n                if(n==1){\n                    NodetoBeDeleted = *LH;\n                    (*LH) = (*LH)->rptr;\n                    free(NodetoBeDeleted);\n                    return;\n                }else if(n==2){\n                    NodetoBeDeleted = *RH;\n                     (*RH)->lptr->rptr = NULL;\n                    *RH = (*RH)->lptr;\n                    free(NodetoBeDeleted);\n                    return;\n\n                }else if(n==3){\n                    if((*RH)->value == val){\n                         NodetoBeDeleted = *RH;\n\n                    *RH = (*RH)->lptr;\n                    free(NodetoBeDeleted);\n                    return;\n                    }\n                    if((*LH)->value == val){\n                        NodetoBeDeleted = *LH;\n                    *LH = (*LH)->rptr;\n                    free(NodetoBeDeleted);\n                    return;\n                    }else{\n\n\n                    while(temp->rptr->value != val)\n                        temp = temp->rptr;\n\n                     NodetoBeDeleted = temp->rptr;\n                     temp->rptr = temp->rptr->rptr;\n                     temp->rptr->lptr = temp;\n                     free(NodetoBeDeleted);\n                    }\n                }else{\n                printf(\"sorry something wrong\\n\");\n                }\n\n            }\n}\n\nint main(){\n    struct node *LH,*RH;\n    LH = RH = NULL;\n    int c,n;\n    printf(\"1) Insert\\n2) Delete\\n3) Display\\n4) Exit\");\n    while(c!=4){\n        printf(\"\\nEnter your choice :\");\n        scanf(\"%d\",&c);\n    switch(c){\n    case  1:\n        printf(\"Enter value :\");\n        scanf(\"%d\",&n);\n        insert(&LH,&RH,n);\n        break;\n    case 2:\n        delete_Link(&LH,&RH);\n        break;\n    case 3:\n        Display(&LH,&RH);\n        break;\n    case 4:\n        exit(0);\n        break;\n    default:\n        printf(\"Please Enter Between 1 to 4\");\n        break;\n\n    }\n            }\n\n    return 0;\n}\n"
  },
  {
    "path": "Data-Structures/LinkedList/Doubly_Linked_List/doubly_ll.py",
    "content": "\n#this file has complete implementation of doubly linked list using python language and this class defined below has also reverse method which reverse given doubly linked list\n\nclass Node(object):\n    # Singly linked node\n    def __init__(self, data=None, next=None, prev=None):\n        self.data = data\n        self.next = next\n        self.prev = prev\n\n\nclass doubly_linked_list(object):\n    def __init__(self):\n        self.head = None\n        self.tail = None\n        self.count = 0\n\n    def append_item(self, data):\n        # Append an item\n        new_item = Node(data, None, None)\n        if self.head is None:\n            self.head = new_item\n            self.tail = self.head\n        else:\n            new_item.prev = self.tail\n            self.tail.next = new_item\n            self.tail = new_item\n        self.count += 1\n\n    def iter(self):\n        # Iterate the list\n        current = self.head\n        while current:\n            item_val = current.data\n            current = current.next\n            yield item_val\n\n    def print_foward(self):\n        for node in self.iter():\n            print(node)\n\n    def reverse(self):\n        \"\"\" Reverse linked list. \"\"\"\n        current = self.head\n        while current:\n            temp = current.next\n            current.next = current.prev\n            current.prev = temp\n            current = current.prev\n        temp = self.head\n        self.head = self.tail\n        self.tail = temp\n\n\nitems = doubly_linked_list()\nitems.append_item(4)\nitems.append_item(6)\nitems.append_item(8)\nitems.append_item(9)\nitems.append_item(2)\nitems.append_item(1)\n\nprint(\"Reversed doubly linked list \")\nitems.reverse()\nitems.print_foward()\n"
  },
  {
    "path": "Data-Structures/LinkedList/Doubly_Linked_List/simple linked list circular without header/LSLCSE.cbp",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\" ?>\n<CodeBlocks_project_file>\n\t<FileVersion major=\"1\" minor=\"6\" />\n\t<Project>\n\t\t<Option title=\"LSLCSE\" />\n\t\t<Option pch_mode=\"2\" />\n\t\t<Option compiler=\"gcc\" />\n\t\t<Build>\n\t\t\t<Target title=\"Debug\">\n\t\t\t\t<Option output=\"bin/Debug/LSLCSE\" prefix_auto=\"1\" extension_auto=\"1\" />\n\t\t\t\t<Option object_output=\"obj/Debug/\" />\n\t\t\t\t<Option type=\"1\" />\n\t\t\t\t<Option compiler=\"gcc\" />\n\t\t\t\t<Compiler>\n\t\t\t\t\t<Add option=\"-g\" />\n\t\t\t\t</Compiler>\n\t\t\t</Target>\n\t\t\t<Target title=\"Release\">\n\t\t\t\t<Option output=\"bin/Release/LSLCSE\" prefix_auto=\"1\" extension_auto=\"1\" />\n\t\t\t\t<Option object_output=\"obj/Release/\" />\n\t\t\t\t<Option type=\"1\" />\n\t\t\t\t<Option compiler=\"gcc\" />\n\t\t\t\t<Compiler>\n\t\t\t\t\t<Add option=\"-O2\" />\n\t\t\t\t</Compiler>\n\t\t\t\t<Linker>\n\t\t\t\t\t<Add option=\"-s\" />\n\t\t\t\t</Linker>\n\t\t\t</Target>\n\t\t</Build>\n\t\t<Compiler>\n\t\t\t<Add option=\"-Wall\" />\n\t\t\t<Add option=\"-fexceptions\" />\n\t\t</Compiler>\n\t\t<Unit filename=\"main.cpp\" />\n\t\t<Unit filename=\"sllist.cpp\" />\n\t\t<Unit filename=\"sllist.h\" />\n\t\t<Unit filename=\"slnode.cpp\" />\n\t\t<Unit filename=\"slnode.h\" />\n\t\t<Extensions>\n\t\t\t<code_completion />\n\t\t\t<envvars />\n\t\t\t<debugger />\n\t\t\t<lib_finder disable_auto=\"1\" />\n\t\t</Extensions>\n\t</Project>\n</CodeBlocks_project_file>\n"
  },
  {
    "path": "Data-Structures/LinkedList/Doubly_Linked_List/simple linked list circular without header/LSLCSE.layout",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\" ?>\n<CodeBlocks_layout_file>\n\t<FileVersion major=\"1\" minor=\"0\" />\n\t<ActiveTarget name=\"Debug\" />\n\t<File name=\"slnode.h\" open=\"1\" top=\"0\" tabpos=\"1\" split=\"0\" active=\"1\" splitpos=\"0\" zoom_1=\"0\" zoom_2=\"0\">\n\t\t<Cursor>\n\t\t\t<Cursor1 position=\"343\" topLine=\"0\" />\n\t\t</Cursor>\n\t</File>\n\t<File name=\"sllist.cpp\" open=\"1\" top=\"1\" tabpos=\"3\" split=\"0\" active=\"1\" splitpos=\"0\" zoom_1=\"0\" zoom_2=\"0\">\n\t\t<Cursor>\n\t\t\t<Cursor1 position=\"3169\" topLine=\"119\" />\n\t\t</Cursor>\n\t</File>\n\t<File name=\"sllist.h\" open=\"1\" top=\"0\" tabpos=\"2\" split=\"0\" active=\"1\" splitpos=\"0\" zoom_1=\"0\" zoom_2=\"0\">\n\t\t<Cursor>\n\t\t\t<Cursor1 position=\"162\" topLine=\"10\" />\n\t\t</Cursor>\n\t</File>\n</CodeBlocks_layout_file>\n"
  },
  {
    "path": "Data-Structures/LinkedList/Doubly_Linked_List/simple linked list circular without header/main.cpp",
    "content": "#include <iostream>\n\nusing namespace std;\n\nint main()\n{\n    cout << \"Hello world!\" << endl;\n    return 0;\n}\n"
  },
  {
    "path": "Data-Structures/LinkedList/Doubly_Linked_List/simple linked list circular without header/sllist.cpp",
    "content": "#include \"sllist.h\"\n\n\nvoid SLList::modifyClient(SLNode* p) {\n    if(!isValidPos(p)) {\n        throw ListException(\"Posicion invalida a la elminar\");\n        }\n    if(p==anchor) {\n        anchor= anchor-> getNext();\n        }\n    else {\n        getPrevPos(p) -> setNext(p->getNext());\n        }\n    delete p;\n    }\n\nSLNode* SLList::getPrevPos( SLNode*& p) {\n    if(isEmpty() or p==anchor) {\n        return nullptr;\n        }\n    SLNode* aux = anchor;\n    do {\n        if(aux->getNext()==p) {\n            return aux;\n            }\n        aux= aux->getNext()\n\n\n        }\n    while(aux != anchor);\n    return nullptr;\n\n    }\n\nvoid SLList::deleteData( SLNode* p) {\n    if(!isValidPos(p)) {\n        throw ListException(\"Posicion invalida al eliminar\");\n        }\n    if (p == anchor) {\n        if(p->getNext()==p) {\n            anchor =nullptr;\n            }\n        else {\n            getLastPos()->getNext(anchor->getNext());\n            anchor = anchor->getNext();\n            }\n        }\n    else {\n        getPrevPos(p)->setNext(p->next);\n        }\n    delete p;\n    }\n\nSLNode* SLList::findData( Client& e) {\n    if(isEmpty()) {\n        return nullptr\n        }\n    SLNode* aux = anchor;\n    do {\n        if(aux->getData()==e) {\n            return aux;\n            }\n        aux=aux->getNext();\n        }\n    while(aux!=anchor)\n        return nullptr;\n    }\n\nvoid SLList::deleteAll() {\n    SLNode* aux=anchor;\n    SLNode* mark=anchor\n    do {\n        aux=anchor;\n        anchor=anchor->getNext()\n               delete aux;\n        }\n    while(anchor != mark);\n\n    anchor=nullptr;\n    }\n\nSLList::~SLList() {\n    deleteAll();\n    }\n\nSLList::SLList() {\n    anchor =nullptr;\n    }\n\nbool SLList::isEmpty() {\n    return anchor == nullptr;\n    }\n\nvoid SLList::print() {\n    if(isEmpty()) {\n        return;\n        }\n    SLNode* aux = anchor;\n    do {\n        while(aux != nullptr) {\n            aux->getData().toString() ;\n            aux = aux->getNext();\n            }\n        while(aux!=anchor);\n        }\n    }\n\nvoid SLList::insertData( SLNode* p,  Client& e) { //insertar despus\n    if(p != nullptr and !isValidPos(p)) {\n        throw ListException(\"La posicion de insercion es invalida\");\n        }\n    SLNode* aux = new SLNode(e);\n    if(aux == nullptr) {\n        throw ListException(\"Memoria no disponible al insertar\");\n        }\n    if(p==nullptr) { //insercin al principio\n        if(anchor==nullptr) {\n            aux->getNext(aux);\n            }\n        else { //insercion en medio o al final de la lista\n            getLastPos()->setNext(aux);\n            }\n        anchor=aux;\n        else { //insercion en medio o al final de la lista\n            getLastPos()->setNext(aux);\n            }\n        }\n    bool SLList::isValidPos( SLNode*& p) {\n        SLNode* aux = anchor;\n        do {\n            if(aux==p);\n                {\n                return true;\n                }\n            }\n        while(aux != anchor) {\n            }\n\n        void SLList::insertOrdered( Client s) {\n            SLNode* aux = anchor;\n            SLNode* prev = nullptr;\n\n            while(aux != nullptr and s > aux->getData()) {\n                prev=aux;\n                aux = aux->getNext();\n                }\n            insertData(prev, s);\n            }\n\n\n        SLList::SLList( SLList*& l) : SLList() {\n            SLNode* aux = l->anchor;\n            while(aux != nullptr) {\n                insertData(getLastPos(), aux->getData());\n\n                aux = aux->getNext();\n                }\n            }\n\n\n\n        SLNode* SLList::getFirsPos() {\n            return anchor;\n            }\n\n        SLNode* SLList::getLastPos() {\n            if(isEmpty()) {\n                return nullptr;\n                }\n            SLNode* aux = anchor;\n\n            while(aux->getNext() != anchor) {\n                aux= aux->getNext();\n                }\n            return aux;\n            }\n\n        SLNode* SLList::getNextPos( SLNode*& p) { //pendiente\n            if(!isValidPos(p) or p->getNext()==anchor) {\n                return nullptr;\n                }\n            return p->getNext();\n            }\n\n\n        Client& SLList::retrieve( SLNode* p) {\n            if(!isValidPos(p)) {\n                throw ListException(\"Elemento inexistente al hacer retrieve\");\n                }\n            return p->getData();\n            }\n\n\n\n        void SLList::writeToDisk (const std::string&fileName) {\n            std::ofstream myFile;\n\n            myFile.open(fileName, myFile.trunc);\n            if(!myFile.is_open()) {\n                throw ListException(\"No se pudo Abrir el Archivo\"+ fileName + \"Para escritura\");\n                }\n            if(!isEmpty()) {\n                SLNode* aux = anchor;\n                }\n            while(aux!=nullptr) {\n                myFile << aux->getData()<<std::endl;\n                aux = aux->getNext();\n                }\n            myFile.close();\n\n            }\n\n        void SLList::readFromDisk(const std::string&fileName) {\n            std::ifstream myFile;\n            Client myClient;\n\n            myFile.open(fileName);\n            if(!myFile.is_open()) {\n                throw ListException(\"No se pudo Abrir el Archivo\"+ fileName + \"Para lectura\");\n\n                }\n\n            deleteAll();\n\n            while(myFile>>myClient) {\n                insertOrdered(myClient);\n                }\n            myFile.close();\n\n            }\n"
  },
  {
    "path": "Data-Structures/LinkedList/Doubly_Linked_List/simple linked list circular without header/sllist.h",
    "content": "#ifndef SLLIST_H_INCLUDED\n#define SLLIST_H_INCLUDED\n#include <iostream>\n#include <fstream>\n#include \"listexception.h\"\n#include \"sllist.h\"\n#include\"slnode.h\"\nclass SLList {\n    private:\n        SLNode* anchor;\n        bool isValidPos( SLNode*&);\n    public:\n        SLList();\n        SLList( SLList*&);\n        ~SLList();\n        bool isEmpty();\n        void insertData( SLNode*, Client&);\n        void insertOrdered( Client);\n        void deleteData( SLNode*);\n        void modifyClient(SLNode*);\n        SLNode* getFirsPos();\n        SLNode* getLastPos();\n        SLNode* getPrevPos( SLNode*&);\n        SLNode* getNextPos( SLNode*&);\n        SLNode* findData(Client&);\n        Client& retrieve(SLNode*);\n        void print();\n        void deleteAll();\n        void writeToDisk(const std::string&);\n        void readFromDisk(const  std::string&);\n    };\n#endif // SLLIST_H_INCLUDED\n"
  },
  {
    "path": "Data-Structures/LinkedList/Doubly_Linked_List/simple linked list circular without header/slnode.cpp",
    "content": "#include\"slnode.h\"\nSLNode::SLNode() {\n    next = nullptr;\n    }\nSLNode::SLNode( Client&s): SLNode() {\n    data = s;\n    }\nClient& SLNode::getData() {\n    return data;\n    }\nSLNode* SLNode::getNext() {\n    return next;\n    }\nvoid SLNode::setData( Client&s) {\n    data=s;\n    }\nvoid SLNode::setNext(SLNode*p) {\n    next=p;\n    }\n"
  },
  {
    "path": "Data-Structures/LinkedList/Doubly_Linked_List/simple linked list circular without header/slnode.h",
    "content": "#ifndef SLNODE_H_INCLUDED\n#define SLNODE_H_INCLUDED\n#include \"client.h\"\n\n\nclass SLNode {\n    private:\n        Client data;\n    public:\n        SLNode*next;\n        SLNode();\n        SLNode( Client&);\n        Client& getData();\n        SLNode* getNext();\n        void setData(   Client&);\n        void setNext(  SLNode*);\n    };\n#endif // SLNODE_H_INCLUDED\n"
  },
  {
    "path": "Data-Structures/LinkedList/README.md",
    "content": "# This folder is empty.\n"
  },
  {
    "path": "Data-Structures/LinkedList/Singly_Linked_List/Delete_Kth_Node_From_End/Delete_Kth_Node_From_End.cpp",
    "content": "#include <iostream>\nusing namespace std;\nstruct node\n{\n    long long int data;\n    struct node *next;\n};\ntypedef struct node *nodeptr;\nnodeptr getNode(long long int item)\n{\n    nodeptr p = (nodeptr)malloc(sizeof(struct node));\n    p->data = item;\n    p->next = NULL;\n    return p;\n}\nnodeptr insertAtTheBeginning(long long int item, nodeptr start)\n{\n    nodeptr p = getNode(item);\n    if (start == NULL)\n        start = p;\n    else\n    {\n        p->next = start;\n        start = p;\n    }\n    return start;\n}\nnodeptr insertAtTheEnd(long long int item, nodeptr start)\n{\n    if (start == NULL)\n        return insertAtTheBeginning(item, start);\n    nodeptr p = getNode(item);\n    nodeptr temp = start;\n    while (temp->next != NULL)\n        temp = temp->next;\n    temp->next = p;\n    return start;\n}\nnodeptr insertAtLocation(long long int item, nodeptr start, long long int location)\n{\n    nodeptr p = getNode(item);\n    long long int i;\n    nodeptr temp = start;\n    for (i = 1; i < location - 1; i++)\n        temp = temp->next;\n    if (i == 1)\n        return insertAtTheBeginning(item, start);\n    else\n    {\n        p->next = temp->next;\n        temp->next = p;\n        return start;\n    }\n}\nnodeptr deleteFirst(nodeptr start)\n{\n    nodeptr temp = start;\n    start = start->next;\n    free(temp);\n    return start;\n}\nnodeptr deleteGivenNode(long long int item, nodeptr start)\n{\n    if (item == start->data)\n        return deleteFirst(start);\n    else\n    {\n        nodeptr temp = start;\n        while (temp != NULL && (temp->next)->data != item)\n            temp = temp->next;\n        nodeptr toBeDeleted = temp->next;\n        temp->next = (temp->next)->next;\n        free(toBeDeleted);\n        return start;\n    }\n}\nvoid display(nodeptr start)\n{\n    nodeptr temp = start;\n    while (temp != NULL)\n    {\n        cout << temp->data << \" \";\n        temp = temp->next;\n    }\n    cout << endl;\n}\nlong long int countNodes(nodeptr start)\n{\n    nodeptr temp = start;\n    long long int counter = 1;\n    if (start != NULL)\n    {\n        while (temp->next != NULL)\n        {\n            temp = temp->next;\n            counter++;\n        }\n    }\n    return counter;\n}\nnodeptr deleteNode(nodeptr start, long long int counter, long long int k)\n{\n    if (start == NULL)\n    {\n        cout << \"VOID DELETION\" << endl;\n        return NULL;\n    }\n\n    else\n    {\n        long long int it;\n        nodeptr temp = start;\n        for (it = 1; it <= counter - k; it++)\n            temp = temp->next;\n        cout << temp->data << \" HAS BEEN DELETED\" << endl;\n        return deleteGivenNode(temp->data, start);\n    }\n}\nint main()\n{\n    nodeptr start = NULL;\n    nodeptr list2 = NULL;\n    nodeptr startSorted = NULL;\n    long long int choice, item, location, i, counter = 0, k;\n    for (i = 1; i; i++)\n    {\n        cout << \"(1)INSERT AT BEGINNING\\n(2)INSERT AT END\\n(3)INSERT AT A LOCATION\\n(4)DELETE NODE\\n(5)DISPLAY\\n(6)EXIT\" << endl;\n        cout << \"ENTER CHOICE: \";\n        cin >> choice;\n        switch (choice)\n        {\n        case 1:\n            cout << \"ENTER ELEMENT TO BE INSERTED: \";\n            cin >> item;\n            start = insertAtTheBeginning(item, start);\n            counter = countNodes(start);\n            break;\n        case 2:\n            cout << \"ENTER ELEMENT TO BE INSERTED: \";\n            cin >> item;\n            start = insertAtTheEnd(item, start);\n            counter = countNodes(start);\n            break;\n        case 3:\n            cout << \"ENTER ELEMENT TO BE INSERTED: \";\n            cin >> item;\n            cout << \"ENTER LOCATION: \";\n            cin >> location;\n            start = insertAtLocation(item, start, location);\n            counter = countNodes(start);\n            break;\n        case 4:\n            cout << \"ENTER POSITION OF ELEMENT TO BE DELETED FROM END: \";\n            cin >> k;\n            if (k > counter || counter == 0)\n                cout << \"VOID DELETION\" << endl;\n            else\n            {\n                start = deleteNode(start, counter, k);\n                counter = countNodes(start);\n            }\n\n            break;\n        case 5:\n            display(start);\n            break;\n        case 6:\n            return 0;\n        }\n    }\n    return 0;\n}\n"
  },
  {
    "path": "Data-Structures/LinkedList/Singly_Linked_List/Delete_Kth_Node_From_End/Delete_Kth_Node_From_End.java",
    "content": "import java.util.Scanner;\n\nclass Delete_Kth_Node_From_End \n{ \n\nstatic class Node \n{ \n\tint data; \n\tNode next; \n}; \n\nstatic Node create(Node head, int x) \n{ \n\tNode temp, ptr = head; \n\ttemp = new Node(); \n\ttemp.data = x; \n\ttemp.next = null; \n\tif (head == null) \n\t\thead = temp; \n\telse\n\t{ \n\t\twhile (ptr.next != null) \n\t\t{ \n\t\t\tptr = ptr.next; \n\t\t} \n\t\tptr.next = temp; \n\t} \n\treturn head; \n} \n\nstatic Node removeNthFromEnd(Node head, int B) \n{ \n\tint len = 0; \n\tNode tmp = head; \n\twhile (tmp != null) \n\t{ \n\t\tlen++; \n\t\ttmp = tmp.next; \n\t} \n\n\tif (B > len) \n\t{ \n\t\tSystem.out.print(\"Length of the linked list is \" + len); \n\t\tSystem.out.print(\" we can't remove \"+ B + \n\t\t\t\t\t\t\"th node from the\"); \n\t\tSystem.out.print(\" linked list\\n\"); \n\t\treturn head; \n\t} \n\telse if (B == len) \n\t{ \n\t\treturn head.next; \n\t\t\n\t} \n\telse\n\t{ \n\t\tint diff = len - B;\t\t \n\t\tNode prev= null;\t \n\t\tNode curr = head;\t\t \n\t\tfor(int i = 0; i < diff; i++) \n\t\t{ \n\t\t\tprev = curr;\t\t \n\t\t\tcurr = curr.next;\t \n\t\t} \n\t\tprev.next = curr.next; \n\t\treturn head; \n\t} \n\t\n} \n\nstatic void display(Node head) \n{ \n\tNode temp = head; \n\twhile (temp != null) \n\t{ \n\t\tSystem.out.print(temp.data + \" \"); \n\t\ttemp = temp.next; \n\t} \n\tSystem.out.println(); \n} \n\npublic static void main(String[] args) \n{ \n\tNode head = null; \n\tScanner sc = new Scanner(System.in);\n\tSystem.out.print(\"Enter number of nodes to be inserted: \");\n\tint n = sc.nextInt(), p;\n\tfor(int i=0;i<n;++i) {\n\tSystem.out.print(\"Enter node '\" + i + \"' data: \");\n\t\tp = sc.nextInt();\n\t\thead = create(head, p);\n\t}\n\tSystem.out.print(\"Linked list before modification: \\n\"); \n\tdisplay(head); \n\tSystem.out.print(\"Enter the value of K: \");\n\tn = sc.nextInt();\n\thead = removeNthFromEnd(head, n);\n\tSystem.out.print(\"Linked list after modification: \\n\"); \n\tdisplay(head); \n} \n} \n"
  },
  {
    "path": "Data-Structures/LinkedList/Singly_Linked_List/Delete_Kth_Node_From_End/Delete_Kth_Node_From_End.py",
    "content": "# Python3 program for Fibonacci search.\nfrom bisect import bisect_left\n\n\n# Returns index of x if present,  else\n# returns -1\ndef fibMonaccianSearch(arr, x, n):\n    # Initialize fibonacci numbers\n    fibMMm2 = 0  # (m-2)'th Fibonacci No.\n    fibMMm1 = 1  # (m-1)'th Fibonacci No.\n    fibM = fibMMm2 + fibMMm1  # m'th Fibonacci\n\n    # fibM is going to store the smallest\n    # Fibonacci Number greater than or equal to n\n    while (fibM < n):\n        fibMMm2 = fibMMm1\n        fibMMm1 = fibM\n        fibM = fibMMm2 + fibMMm1\n\n        # Marks the eliminated range from front\n    offset = -1;\n\n    # while there are elements to be inspected.\n    # Note that we compare arr[fibMm2] with x.\n    # When fibM becomes 1, fibMm2 becomes 0\n    while (fibM > 1):\n\n        # Check if fibMm2 is a valid location\n        i = min(offset + fibMMm2, n - 1)\n\n        # If x is greater than the value at\n        # index fibMm2, cut the subarray array\n        # from offset to i\n        if (arr[i] < x):\n            fibM = fibMMm1\n            fibMMm1 = fibMMm2\n            fibMMm2 = fibM - fibMMm1\n            offset = i\n\n            # If x is less than the value at\n        # index fibMm2, cut the subarray\n        # after i+1\n        elif (arr[i] > x):\n            fibM = fibMMm2\n            fibMMm1 = fibMMm1 - fibMMm2\n            fibMMm2 = fibM - fibMMm1\n\n            # element found. return index\n        else:\n            return i\n\n            # comparing the last element with x */\n    if (fibMMm1 and arr[offset + 1] == x):\n        return offset + 1;\n\n        # element not found. return -1\n    return -1\n\n\n# Driver Code\narr = [10, 22, 35, 40, 45, 50,\n       80, 82, 85, 90, 100]\nn = len(arr)\nx = 85\nprint(\"Found at index:\",\n      fibMonaccianSearch(arr, x, n)) "
  },
  {
    "path": "Data-Structures/LinkedList/Singly_Linked_List/Delete_Kth_Node_From_End/Delete_Kth_Node_From_End.rb",
    "content": "class Node\n    attr_reader :value\n    attr_accessor :next\n    def initialize(value)\n        @value = value\n        @next = nil\n    end\nend\n\nclass SinglyLinkedList\n    def initialize\n        @head = nil\n        @size = 0\n    end\n\n    def insert(value)\n        node = Node.new(value)\n        current = @head\n        while current && current.next do\n            current = current.next\n        end\n        if current.nil?\n            @head = node\n        else\n            current.next = node\n        end\n        @size += 1\n    end\n\n    def delete_kth_from_end(k)\n        return if (k > @size || @size <= 0)\n        if k == @size\n            @head = @head.next\n            return\n        end\n        prev_node_pos_from_start = @size - k - 1\n        current = @head\n        prev_node_pos_from_start.times do \n            current = current.next\n        end\n        current.next = current.next.next\n        @size -= 1\n    end\n\n    def print_list\n        current = @head\n        loop do\n            break if current.nil?\n            print \"#{current.value} \"\n            current = current.next\n        end\n        puts\n    end\n\nend\n\nlist = SinglyLinkedList.new\nlist.insert(1)\nlist.insert(2)\nlist.insert(3)\nlist.insert(4)\nlist.insert(5)\nlist.insert(6)\nlist.print_list # 1 2 3 4 5 6\nlist.delete_kth_from_end(3)\nlist.print_list # 1 2 3 5 6 \nlist.delete_kth_from_end(1)\nlist.print_list # 1 2 3 5\nlist.delete_kth_from_end(4)\nlist.print_list # 2 3 5\n"
  },
  {
    "path": "Data-Structures/LinkedList/Singly_Linked_List/Detect_Cycle/CycleDetection.c",
    "content": "#include <math.h>\n#include <stdio.h>\n#include <string.h>\n#include <stdlib.h>\n#include <assert.h>\n#include <limits.h>\n#include <stdbool.h>\ntypedef struct LinkedListNode LinkedListNode;\n\n// Node of a Linked List\nstruct LinkedListNode {\n    int val;\n    LinkedListNode *next;\n};\n\nLinkedListNode* _insert_node_into_singlylinkedlist(LinkedListNode *head, LinkedListNode *tail, int val) {\n    if(head == NULL) {\n        head = (LinkedListNode *) (malloc(sizeof(LinkedListNode)));\n        head->val = val;\n        head->next = NULL;\n        tail = head;\n    }\n    else {\n        LinkedListNode *node = (LinkedListNode *) (malloc(sizeof(LinkedListNode)));\n        node->val = val;\n        node->next = NULL;\n        tail->next = node;\n        tail = tail->next;\n    }\n    return tail;\n}\n\n//Function using Floyd Cycle detection algorithm\nbool hasCycle(LinkedListNode* head) {\n    struct LinkedListNode* slow=head,*fast=head;\n    while(slow && fast && fast->next)\n    {\n        slow=slow->next;\n        fast=fast->next->next;\n        if(slow==fast)\n        {\n            return true;\n        }\n    }\n    return false;\n}\n\n// Main function \nint main()\n{\n    FILE *f = stdout;\n    char *output_path = getenv(\"OUTPUT_PATH\");\n    if (output_path) {\n        f = fopen(output_path, \"w\");\n    }\n\n    bool res;\n    int head_size = 0;\n\n    LinkedListNode* head = NULL;\n    LinkedListNode* head_tail = NULL;\n\n    scanf(\"%d\\n\", &head_size);\n    for(int i = 0; i < head_size; i++) {\n        int head_item;\n        scanf(\"%d\", &head_item);\n        head_tail = _insert_node_into_singlylinkedlist(head, head_tail, head_item);\n\n        if(i == 0) {\n            head = head_tail;\n        }\n    }\n\tint x;\n  \tscanf(\"%d\", &x);\n  \tif (x > -1)\n    {\n      \tLinkedListNode* ptr = head;\n      \twhile (x--) ptr = ptr->next;\n      \thead_tail->next = ptr;\n    }\n\n    res = hasCycle(head);\n    fprintf(f, \"%d\\n\", res);\n\n    fclose(f);\n    return 0;\n}\n"
  },
  {
    "path": "Data-Structures/LinkedList/Singly_Linked_List/Detect_Cycle/CycleDetection.java",
    "content": "//Detecting a cycle in singly linked list\nimport java.util.*;\n\nclass Node {\n//class describing structure of the node\n  int data;\n  Node next;\n  Node(int value) { \n    data = value; \n    next = null;\n    }\n }\n \n class Solution{\n \n //creates a new linked list;\n    public void create_list(Node head,int node_value){\n    Node newNode = new Node(node_value);\n    if(head==null){\n      head = newNode;\n      }\n    else{\n      Node pointer = head;\n      while(pointer.next!=null)\n        pointer = pointer.next;\n      pointer.next = newNode;\n    } \n  }\n  \n  //detects cycle in list\n  public boolean hasCycle(Node head) {\n        Node fast=head,slow=head;\n        if(head==null || head.next==null)\n            return false;\n        while(fast!=null && fast.next!=null)\n        {\n            slow = slow.next;\n            fast = fast.next.next;\n            if(fast==slow)\n                return true;  \n        }\n        return false;\n    }\n }\n \n //main class\n public class CycleDetection{\n  public static void main(String[] args){\n    Solution object = new Solution();\n    Node head = new Node(10);\n    object.create_list(head,20);\n    object.create_list(head,30);\n    object.create_list(head,40);\n    object.create_list(head,50);\n    head.next.next.next = head;\n    boolean answer = object.hasCycle(head);\n    if(answer==true)\n      System.out.println(\"Cycle is present\");\n    else\n      System.out.println(\"Cycle is not present\");\n    \n  }\n}\n"
  },
  {
    "path": "Data-Structures/LinkedList/Singly_Linked_List/Detect_Cycle/DetectCycle.cpp",
    "content": "\n#include <iostream>\nusing namespace std;\n\n\nclass Node {\npublic:\n\tint data;\n\tNode* next;\n};\n\nvoid push(Node** head_ref, int new_data)\n{\n\n\tNode* new_node = new Node();\n\n\tnew_node->data = new_data;\n\n\t\n\tnew_node->next = (*head_ref);\n\n\t\n\t(*head_ref) = new_node;\n}\n\nint detectLoop(Node* list)\n{\n\tNode *slow_p = list, *fast_p = list;\n\n\twhile (slow_p && fast_p && fast_p->next) {\n\t\tslow_p = slow_p->next;\n\t\tfast_p = fast_p->next->next;\n\t\tif (slow_p == fast_p) {\n\t\t\treturn 1;\n\t\t}\n\t}\n\treturn 0;\n}\n\nint main()\n{\n\n\tNode* head = NULL;\n\n\tpush(&head, 20);\n\tpush(&head, 4);\n\tpush(&head, 15);\n\tpush(&head, 10);\n\n\t\n\thead->next->next->next->next = head;\n\tif (detectLoop(head))\n\t\tcout << \"Cycle found\";\n\telse\n\t\tcout << \"No Cycle Found\";\n\treturn 0;\n}\n\n\n"
  },
  {
    "path": "Data-Structures/LinkedList/Singly_Linked_List/Detect_Cycle/DetectCycle.py",
    "content": "# Node class \nclass Node:\n  \n    # Constructor to initialize\n    # the node object\n    def __init__(self, data):\n        self.data = data\n        self.next = None\n  \nclass LinkedList:\n  \n    # Function to initialize head\n    def __init__(self):\n        self.head = None\n  \n    # Function to insert a new\n    # node at the beginning\n    def push(self, new_data):\n        new_node = Node(new_data)\n        new_node.next = self.head\n        self.head = new_node\n  \n    # Utility function to print it\n    # the linked LinkedList\n    def printList(self):\n        temp = self.head\n        while(temp):\n            print (temp.data, end =\" \")\n            temp = temp.next\n  \n  \n    def detectCycle(self):\n         s = set()\n         temp = self.head\n         while (temp):\n         \n             # If we have already has\n             # this node in hashmap it\n             # means their is a cycle\n             # (Because you we encountering\n             # the node second time).\n            if (temp in s):\n                return True\n    \n            # If we are seeing the node for\n            # the first time, insert it in hash\n            s.add(temp)\n    \n            temp = temp.next\n         \n    \n         return False\n  \n# Driver program for testing\nllist = LinkedList()\nllist.push(20)\nllist.push(4)\nllist.push(15)\nllist.push(10)\n  \n# Create a loop for testing\nllist.head.next.next.next.next = llist.head;\n \nif( llist.detectCycle()):\n    print (\"Cycle found\")\nelse :\n    print (\"No Cycle found\")\n"
  },
  {
    "path": "Data-Structures/LinkedList/Singly_Linked_List/Detect_Cycle/DetectCycle.ts",
    "content": "// Node class \nclass ListNode {\n    public data;\n    public next: ListNode | null;\n\n    // Constructor to initialize\n    // the node object\n    constructor(data: any) {\n        this.data = data;\n        this.next = null;\n    }\n}\n\nclass LinkedList {\n    public head: ListNode | null;\n\n    // Constructor to initialize LinkedList\n    constructor() {\n        this.head = null;\n    }\n    \n    // Function to insert a new LinedListNode at the end of the list\n    // with the given value\n    append(data: any) {\n        const newNode = new ListNode(data)\n        if(!this.head) {\n            this.head = newNode;\n        } else {\n            let pointer: ListNode | null = this.head;\n            while (pointer.next) {\n                pointer = pointer.next\n            }\n            pointer.next = newNode;\n        }\n    }\n    \n    // Function that detects if there is a cycle in the list\n    // using Floyd's cycle-finding algorithm\n    hasCycle() {\n        // Floyd's Tortoise and Hare\n        let slowPointer: ListNode | null = this.head;\n        let fastPointer: ListNode | null = this.head;\n        while(slowPointer && fastPointer && fastPointer.next) {\n            slowPointer = slowPointer.next;\n            fastPointer = fastPointer.next.next;\n            if(slowPointer == fastPointer) {\n                return true;\n            }\n        }\n        return false;\n    }\n\n\n}\n  \n  \n// Create a LinkedList instance and append values\nconst linkedList = new LinkedList()\nlinkedList.append(22)\nlinkedList.append(4)\nlinkedList.append(97)\nlinkedList.append(1)\n  \n// Create a loop\n// assigning the `next` of the last node to be the head of the LinkedList\nlinkedList.head.next.next.next.next = linkedList.head;\n\nif(linkedList.hasCycle()) {\n    console.log(\"Cycle is present\");\n} else {\n    console.log(\"Cycle is not present\");\n}"
  },
  {
    "path": "Data-Structures/LinkedList/Singly_Linked_List/Detect_Cycle/Detect_Cycle.js",
    "content": "class ListNode {\n    constructor(data) {\n        this.data = data\n        this.next = null                \n    }\n}\n\nclass LinkedList {\n    constructor(head = null) {\n        this.head = head\n    }\n\n\n  add(element) \n  { \n      // creates a new node \n      let  node = new ListNode(element); \n    \n      // to store current node \n      let  current; \n    \n      // if list is Empty add the \n      // element and make it head \n      if (this.head == null) \n          this.head = node; \n      else { \n          current = this.head; \n    \n          // iterate to the end of the \n          // list \n          while (current.next) { \n              current = current.next; \n          } \n    \n          // add node \n          current.next = node; \n      } \n    \n} \n\nhasCycle (head) {\n if(!head) return false;\n    \n let slow=head;\n let fast=head.next;\n while(slow!=fast)\n {\n  if(!fast || !fast.next)\n    return false;\n     \n  slow=slow.next;\n  fast=fast.next.next;\n }\n \n return true;\n};\n\n}\nconst myList = new LinkedList(); \nmyList.add(20);\nmyList.add(30);\nmyList.add(50);\n\nmyList.head.next.next.next= myList.head;\nlet ans=myList.hasCycle(myList.head);\n\nif(ans == true){\n  console.log(\" The list contains cycle\");\n}\nelse{\n   console.log(\" The list does not contain cycle\");\n}"
  },
  {
    "path": "Data-Structures/LinkedList/Singly_Linked_List/Detect_Cycle/detect_cycle.cs",
    "content": "﻿using System;\nnamespace DSA\n{\n    public class Node\n    {\n        public int Value { get; set; }\n        public Node Next;\n        public Node(int val)\n        {\n            this.Value = val;\n        }\n    }\n\n    class ClosedLoop\n    {\n        public static bool DetectLoop(Node _head)\n        {\n            Node slow = _head, fast = _head.Next.Next;\n            while (slow != null && fast != null && fast.Next != null)\n            {\n                if (slow == fast)\n                {\n                    Console.WriteLine(\"Loop detected at: \" + slow.Value);\n                    return true;\n                }\n                slow = slow.Next; //1 step increment\n                fast = fast.Next.Next; //2 step increment\n            }\n            return false;\n        }\n\n        static void Main(string[] args)\n        {\n            Node tail = new Node(0);\n            Node _actualHead = tail;\n\n            Node intersection = null;\n\n            //Creating linked list by adding nodes to the end of the list.\n            for (int i = 1; i < 10; i++)\n            {\n                Node n = new Node(i);\n                tail.Next = n;\n                tail = n;\n                //Taking the loop intersection. Comment below 'if' to avoid loop.\n                if (i == 4)\n                    intersection = tail;\n            }\n\n            //Completing the loop\n            tail.Next = intersection;\n\n            if (!DetectLoop(_actualHead))\n                Console.WriteLine(\"No loop detected\");\n        }\n    }\n}\n"
  },
  {
    "path": "Data-Structures/LinkedList/Singly_Linked_List/Detect_Cycle/detect_cycle.go",
    "content": "package main\n\nimport \"fmt\"\n\ntype Node struct {\n\tValue int\n\tNext *Node\n}\n\nfunc NewNode(value int) *Node {\n\treturn &Node{\n\t\tValue: value,\n\t\tNext:  nil,\n\t}\n}\n\nfunc DetectLoop(head *Node) bool {\n\tslow := head\n\tfast := head\n\tfor slow != nil && fast != nil && fast.Next != nil{\n\t\tslow = slow.Next\n\t\tfast = fast.Next.Next\n\t\tif slow == fast && slow != nil{\n\t\t\tfmt.Println(\"Loop detected at \",slow.Value)\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc main()  {\n\ttail := NewNode(0)\n\t_actualHead := tail\n\tvar intersection *Node\n\t// creating linked list\n\tfor i := 1; i < 10; i++ {\n\t\tn := NewNode(i)\n\t\ttail.Next = n\n\t\ttail = n\n\n\t\tif i == 5 {\n\t\t\tintersection = tail // marking the loop node\n\t\t}\n\t}\n\t// completing the loop\n\ttail.Next = intersection\n\tif !DetectLoop(_actualHead) {\n\t\tfmt.Println(\"No loop detected\")\n\t}\n}\n\n\n\n\n"
  },
  {
    "path": "Data-Structures/LinkedList/Singly_Linked_List/Java/PalindromeLinkedList.java",
    "content": "\n\n  class ListNode {\n     int val;\n     ListNode next;\n     ListNode() {}\n     ListNode(int val) { this.val = val; }\n     ListNode(int val, ListNode next) { this.val = val; this.next = next; }\n }\n\nclass LinkedList {\n\tprivate ListNode head;\n\tpublic void addToTheLast(ListNode node) {\n\t\t \n\t\tif (head == null) {\n\t\t\thead = node;\n\t\t} else {\n\t\t\tListNode temp = head;\n\t\t\twhile (temp.next != null)\n\t\t\t\ttemp = temp.next;\n \n\t\t\ttemp.next = node;\n\t\t}\n\t}\n \n\t\n    public boolean isPalindrome(ListNode head) {\n    ListNode fast = head, slow = head;\n    while (fast != null && fast.next != null) {\n        fast = fast.next.next;\n        slow = slow.next;\n    }\n    if (fast != null) { // odd nodes: let right half smaller\n        slow = slow.next;\n    }\n    slow = reverse(slow);\n    fast = head;\n    \n    while (slow != null) {\n        if (fast.val != slow.val) {\n            return false;\n        }\n        fast = fast.next;\n        slow = slow.next;\n    }\n    return true;\n}\n\npublic ListNode reverse(ListNode head) {\n    ListNode prev = null;\n    while (head != null) {\n        ListNode next = head.next;\n        head.next = prev;\n        prev = head;\n        head = next;\n    }\n    return prev;\n}\n}\n\n\n class PalindromLinkedList{\n public static void main(String args[]){\n\t LinkedList list = new LinkedList();\n\t ListNode head=new ListNode(1);\n\t\tlist.addToTheLast(head);\n\t\tlist.addToTheLast(new ListNode(2));\n\t\tlist.addToTheLast(new ListNode(1));\n\t\tlist.addToTheLast(new ListNode(4));\n\t\tlist.addToTheLast(new ListNode(1));\n\n  \n  if(list.isPalindrome(head)){\n    System.out.println(\"Linked List is Palindrome!\");\n }else{\n    System.out.println(\"Linked List is Not Palindrome!\");\n  }\n}\n \n}\n"
  },
  {
    "path": "Data-Structures/LinkedList/Singly_Linked_List/LinkedList.cs",
    "content": "class LinkedList<T>\n{\n  private T value;\n  private LinkedList<T> next;\n\n  public LinkedList(T value, LinkedList<T> next)\n  {\n    SetValue(value);\n    SetNext(next);\n  }\n\n  public LinkedList(T value) : this(value, null) {}\n\n  public T GetValue()\n  {\n    return value;\n  }\n\n  public LinkedList<T> GetNext()\n  {\n    return next;\n  }\n\n  public void SetValue(T value)\n  {\n    this.value = value;\n  }\n\n  public void SetNext(LinkedList<T> next)\n  {\n    this.next = next;\n  }\n}"
  },
  {
    "path": "Data-Structures/LinkedList/Singly_Linked_List/LinkedList.java",
    "content": "class LinkedList<T>\n{\n  private T value;\n  private LinkedList<T> next;\n\n  public LinkedList(T value, LinkedList<T> next) {\n    SetValue(value);\n    SetNext(next);\n  }\n\n  public LinkedList(T value) {\n    this(value, null);\n    }\n\n  public T GetValue() {\n    return value;\n  }\n\n  public LinkedList<T> GetNext() {\n    return next;\n  }\n\n  public void SetValue(T value) {\n    this.value = value;\n  }\n\n  public void SetNext(LinkedList<T> next) {\n    this.next = next;\n  }\n}"
  },
  {
    "path": "Data-Structures/LinkedList/Singly_Linked_List/LinkedList.py",
    "content": "class Node:\n    def __init__(self, dataval=None):\n        self.dataval = dataval\n        self.nextval = None\n\n\nclass SLinkedList:\n    def __init__(self):\n        self.headval = None\n\n\nlist1 = SLinkedList()\nlist1.headval = Node(\"Mon\")\na2 = Node(\"Tue\")\na3 = Node(\"Wed\")\n\n# Link first Node to second node\nlist1.headval.nextval = a2\n\n# Link second Node to third node\na2.nextval = a3\n"
  },
  {
    "path": "Data-Structures/LinkedList/Singly_Linked_List/LinkedListAndOperations.cpp",
    "content": "#include<iostream>\nusing namespace std;\n\n\nstruct list{\nint data;\nlist *link;\n};\n\n\n\nlist * head;\n\nvoid display_list(){\n    list *l=new list();\n    if(head==NULL){\n        cout<<\"List is empty\";\n    }\n    else{ \n        l=head;\n        while(l!=NULL){\n            cout<<l->data<<\" \";\n            l=l->link;\n        }\n    }\n}\n\n\nvoid insert_at_first(int z){\n    list *b=new list();\n    b->data=z;\n    b->link=NULL;\n    if(head==NULL){\n     head=b;\n    }\n    else {\n        b->link=head;\n        head=b; \n        }\n    }\n\n void insert_at_last(int n){\n    list *c=new list();\n    c->data=n;\n    list *q=head;\n    c->link=NULL;\n    if(head==NULL){\n        head=c;\n    }      \n    else {\n      while(q->link!=NULL){\n          q=q->link;\n      }\n      q->link=c;\n        }\n}\n\nvoid insert_at_mid(int a,int b){\n    list *d=new list();\n    list *q=head;\n    d->data=b;                   \n    while(q!=NULL){\n        if(q->data==a){   \n        d->link=q->link;\n        q->link=d;\n         return;\n        }\n        q=q->link;\n        } \n    \n}\n   \n\nvoid delete_first(){\n   list *p=head;\n   p=p->link;\n   head=p;\n   }\n\nvoid delete_last(){\n    list *q=head;\n    list*t;\n    t=head;\n    while(q->link!=0){\n        t=q;\n        q=q->link;\n    }  \n    if(t==head){\n        head=t->link;\n    }\n    else{\n    t->link=NULL;\n    }     \n}\n\nvoid delete_any(int a){\n    list *q=head;\n    list *z=head;\n    if(a==q->data){\n      head=q->link;\n    }\n    else{\n    while(q!=NULL){\n        if(a==q->data){\n        z->link=q->link;\n        break;\n    }\n    z=q;\n    q=q->link;\n    }\n } \n}\n\n\nvoid count_list(){\n    int count=0;\n    list *l=new list();\n    if(head==NULL){\n        cout<<\"List is empty\";\n    }\n    else{\n        l=head;\n        while(l!=NULL){\n        count++;\n        l=l->link;\n        }\n    }\n    cout<<count;\n}\n\nvoid get_max_from_list(){\n    list*q=head;\n    int max=q->data;\n    if(head==NULL){\n        cout<<0;\n    }\n    else{\n   while(q!=NULL){\n       if(max<q->data){\n         max=q->data;\n       }\n       q=q->link;\n   }\n    }\n    cout<< max;\n}\n\nvoid reverse_list(){\n    list *q=head;\n    list*next=NULL;\n    list*prev=NULL;\n    while(q!=NULL){\n        next=q->link;\n        q->link=prev;\n        prev=q;\n        q=next;\n    }\n  head =prev;\n}\n\n int main(){\n     int size,num1,num2;\n     cout<<\"Enter how many element you want to give to the list:-\\t\";\n     cin>>size;\n     for(int i=0;i<size;i++){\n         cout<<\"Enter the new number you want to add :-\\t\";\n         cin>>num1;\n         insert_at_first(num1);\n     }\n     cout<<\"\\n\";\n     display_list();\n     cout<<\"\\nEnter the number you want to add at last :-\\t\";\n     cin>>num2;\n     insert_at_last(num2);\n     cout<<\"\\n\";\n     display_list();\n     cout<<\"\\nEnter the number after which you want to add new element :-\\t\";\n     cin>>num1;\n    cout<<\"\\nEnter the number  which you want to add :-\\t\";\n    cin>>num2;\n    insert_at_mid(num1,num2);\n    cout<<\"\\n\";\n    display_list();\n    cout<<\"\\nDelete 1st element\";\n    delete_first();\n    cout<<\"\\n\";\n    display_list();\n    cout<<\"\\nDelete last element\";\n    delete_last();\n    cout<<\"\\n\";\n    display_list();\n    cout<<\"\\nEnter the number you want to delete :-\\t\";\n    cin>>num1;\n    delete_any(num1);\n    cout<<\"\\n\";\n    display_list();\n    cout<<\"\\n\";\n    cout<<\"Number of element left in list : \";\n    count_list();\n    cout<<\"\\n\";\n    cout<<\"\\nGiving maximum value:  \";\n    get_max_from_list();\n    cout<<\"\\nReversed the list : \";\n    reverse_list();\n    cout<<\"\\n\";\n    display_list();\n    return 0;\n }\n\n\n"
  },
  {
    "path": "Data-Structures/LinkedList/Singly_Linked_List/LoopDetection.cpp",
    "content": "#include <bits/stdc++.h> \nusing namespace std; \n\n//Templates start here\n#define pb push_back\n#define mp make_pair\n#define F first\n#define S second\n#define ll long long\n#define fo(i, j, k, in) for (int i = j; i < k; i += in)\n#define refo(i, j, k, in) for (int i = j; i >= k; i -= in)\n#define rep(i, j) fo(i, 0, j, 1)\n#define rerep(i, j) fo(i, j, 0, 1)\n#define all(cont) cont.begin(), cont.end()\n#define reall(cont) cont.end(), cont.begin()\n#define foreach(it, l) for (auto it = l.begin() l it != l.end(); it++)\n#define in(A, B, C) assert(B <= A && A <= C)\n#define MOD (int)1e9\n#define MOD7 1000000007\n#define PI 3.1415926535897932384626433832795\ntypedef pair<int, int> PII;\ntypedef pair<long long, long long> PLL;\ntypedef vector<int> VI;\ntypedef vector<long long> VL;\ntypedef vector<string> VS;\ntypedef vector<PII> VII;\ntypedef vector<PLL> VLL;\ntypedef vector<VI> VVI;\ntypedef vector<VL> VVL;\ntypedef map<int, int> MPII;\ntypedef map<long long, long long> MPLL;\ntypedef set<int> SETI;\ntypedef multiset<int> MSETI;\n//Templates end here\n\n//I haven't used above templates for your better understanding but you are free to use it\n\nstruct Node { \n\tint key; \n\tstruct Node* next; \n}; \nNode* newNode(int key) \n{ \n\tNode* temp = new Node; \n\ttemp->key = key; \n\ttemp->next = NULL; \n\treturn temp; \n} \nvoid printList(Node* head) \n{ \n\twhile (head != NULL) { \n\t\tcout << head->key << \" \"; \n\t\thead = head->next; \n\t} \n\tcout << endl; \n} \nint distance(Node* first, Node* last) \n{ \n\tint counter = 0; \n\tNode* curr; \n\tcurr = first; \n\twhile (curr != last) { \n\t\tcounter += 1; \n\t\tcurr = curr->next; \n\t} \n\treturn counter + 1; \n} \nbool detectLoop(Node* head) \n{ \n\tNode* temp = new Node; \n\tNode *first, *last; \n\tfirst = head; \n\tlast = head; \n\tint current_length = 0; \n\tint prev_length = -1; \n\twhile (current_length > prev_length && last != NULL) { \n\t\tprev_length = current_length; \n\t\tcurrent_length = distance(first, last); \n\t\tlast = last->next; \n\t} \n\tif (last == NULL) { \n\t\treturn false; \n\t} \n\telse { \n\t\treturn true; \n\t} \n} \nint main() \n{ \n\tNode* head = newNode(1); \n\thead->next = newNode(2); \n\thead->next->next = newNode(3); \n\thead->next->next->next = newNode(4); \n\thead->next->next->next->next = newNode(5); \n\thead->next->next->next->next->next = head->next->next; \n\tbool found = detectLoop(head); \n\tif (found) \n\t\tcout << \"Loop Found\"; \n\telse\n\t\tcout << \"No Loop Found\"; \n\treturn 0; \n}\n"
  },
  {
    "path": "Data-Structures/LinkedList/Singly_Linked_List/MiddleElementLL.cpp",
    "content": "#include <bits/stdc++.h>\nusing namespace std;\n\nstruct Node{\n      int data;\n      struct Node *next;\n}*head=NULL; \n\nint main() {\n      struct Node *temp,*mid,*prev=NULL;\n\tint n,x,i,midval=0;\n\tcout<<\"Enter the number of nodes:\";\n\tcin>>n;\n\tcout<<\"\\nEnter the elements\\n\";\n\tfor(i=0;i<n;i++)\n\t{\n\t      cin>>x;\n\t      temp=new Node;\n\t      temp->data=x;\n\t      temp->next=NULL;\n\t      if(head==NULL)\n\t      {\n\t            head=temp;\n\t            prev=head;\n\t            mid=head;\n\t      }\n\t      else\n\t      {\n\t            prev->next=temp;\n\t            prev=temp;\n\t            if(i/2==midval)\n\t            continue;\n\t            else\n\t            {\n\t                  mid=mid->next;\n\t                  midval++;\n\t            }\n\t      }\n\t}\n\tcout<<\"Middle element is:\"<<mid->data<<endl;\n\t\n\treturn 0;\n}\n"
  },
  {
    "path": "Data-Structures/LinkedList/Singly_Linked_List/MiddleElementLinkedList.java",
    "content": "import java.util.*;\npublic class Main \n{\n    static Node head;\n    class Node{\n    \tpublic int data;\n    \tpublic Node next;\n    \tNode(int data){\n    \t\tthis.data=data;\n    \t}\n    }\n    \n    public void insert_At_beginning(int data) {\n    \tNode ptr = new Node(data);\n    \tif(head!=null)\n          {\n    \t\tptr.next=head;\n    \t\thead=ptr;\n          }\n    \telse \n    \t  {     \n\t\tptr.next=null;\n    \t        head=ptr;\n       \t  }\n    }\n    public boolean isEmpty()\n    {\n      if(head==null)\n       return true;\n      return false;\n    }\n    public void print() {\n    \tNode ctr=head;\t\n    \twhile(ctr!=null)\n    \t{\n    \t\tSystem.out.print(ctr.data);\n    \t\tctr=ctr.next;\n    \t}\n    \tSystem.out.println();\n    }  \n    public void insert_At_End(int data)\n    {    Node ctr=head;\n    \t Node ptr = new Node(data);\n    \t if(ctr==null)\n    \t { head=ptr;\n    \t   ptr.next=null;\n    \t   return ;\n    \t }\n    \t else {\n    \t   while(ctr.next!=null)\n    \t\t ctr=ctr.next;\n    \t   ctr.next=ptr;\n           ptr.next=null;\n    \t }\n    } \n    public void delete_From_Beginning()\n    {   if(head!=null)\n    \t  head = head.next;\n        else \n    \tSystem.out.println(\"Linked list is empty\");\n    }\n    public void delete_From_End()\n    {   \n    \tNode ctr=head;\n    \tif(ctr!=null && ctr.next!=null)\n\t   {\n    \t     while(ctr.next.next!=null)\n    \t\tctr=ctr.next;\n    \t     ctr.next=null;\n    \t  }\n    \telse if( ctr!=null && ctr.next==null)\n    \t   head = null;\n    \telse\n    \t  System.out.println(\"Linked list is empty\");  \n    }\n    public void delete_At_Position(int c)\n    {   \n    \tint i=1;Node ctr=head,ptr;\n    \tif(ctr!=null && ctr.next!=null) \n\t{\n    \t   while(i<c-1 && ctr.next!=null)\n    \t\tctr=ctr.next;\n    \t   ptr=ctr.next;\n    \t   ctr.next=ptr.next;\n        }\n\telse if( ctr!=null && ctr.next==null)\n    \t   head = null;    \n        else\n    \t System.out.println(\"Linked list is empty\"); \n       return ;\n   }\n   public void insert_At_Position(int c,int data)\n    {\n    \tint i=1;Node ctr=head;\n    \tif(ctr!=null)\n\t{\n    \t  while(i<c-1 && ctr.next!=null)\n    \t  {\n    \t      ctr=ctr.next;\n    \t      i++;\n    \t  }\n    \t  Node ptr = new Node(data);\n    \t  ptr.next=ctr.next;\n    \t  ctr.next=ptr;\n    \t}\n    \telse\n    \t{\n    \t\tNode ptr = new Node(data);\n    \t\tptr.next=null;\n\t\thead=ptr;\n        }\n    }\n  public void count()\n    {\n    \tNode ptr = head;int count = 0;\n        while (ptr!=null)\n    \t\t{\n    \t\t\tcount++;\n    \t\t\tptr=ptr.next;\n    \t\t}\n    \tSystem.out.println(count);\n    }\n  public static void main(String[] args) {\n    Scanner sc=new Scanner(System.in);\n    Main ll = new Main();\n    System.out.println(\"Enter 1 to insert at beginning, 2 to insert at end, 3 to insert at position, 4 to delete from beginning, 5 to delete from end, 6 to delete at position and 7 to find the length of Linked List\");\n    System.out.println(\"Enter choice from 1-7\");\n    boolean f=true;int choice;\n    while(f)\n    {\n    \t choice = sc.nextInt();\n         switch(choice)\n\t {\n           case 1: {\n                    int data=sc.nextInt();\n                    ll.insert_At_beginning(data);ll.print();\n                     break;\n                   }\n           case 2:{\n    \t            int data=sc.nextInt();\n    \t            ll.insert_At_End(data);ll.print();break;\n                  }\n           case 3:{\n    \t           int data=sc.nextInt();\n                   int c=sc.nextInt();\n    \t           ll.insert_At_Position(c, data);ll.print();break;\n                  }\n           case 4:{\n    \t          ll.delete_From_Beginning();ll.print();break;\n                  }\n           case 5:{\n    \t          ll.delete_From_End();ll.print();break;\n                  }\n           case 6:{\n    \t          int c=sc.nextInt();\n    \t          ll.delete_At_Position(c);ll.print();break;\n                  }\n           case 7:{\n   \t          ll.count();\n   \t          break;\n                  }\n           default:f=false;break;\n        }\n        if(f)\n       System.out.println(\"Enter choice from 1-7\");\n       \n     }\n     int i=0;\n      if(ll.head==null)\n       System.out.println(\"Empty Linked List\");\n       else{\n  Node ptr = ll.head;\n   Node ctr = ll.head;\n   while(ctr.next!=null && ctr.next.next!=null)\n   {   i=i+2;\n       ptr=ptr.next;\n       ctr=ctr.next.next;\n       \n   }\n   while(ctr!=null)\n  {   i++;\n      ctr=ctr.next;\n  }\n   if(i==0)\n   {\n\n       System.out.println(ll.head.data);\n   }\n   else if(i%2==0)\n     System.out.println(((ptr.data + ptr.next.data)/2));\n   else \n   {\n       \n        System.out.println(ptr.data);\n          \n   }\n       }\n       \n   }\n}\n  \n"
  },
  {
    "path": "Data-Structures/LinkedList/Singly_Linked_List/Palindrome.ts",
    "content": "class LinkedList {\n    private head: LinkedListItem;\n    constructor(item: LinkedListItem) {\n        this.head = item;\n    }\n\n    // Adds the element at the end of the linked list\n    append(val: number) {\n        let currentItem: LinkedListItem = this.head;\n        let newItem = new LinkedListItem(val);\n\n        if (!currentItem) {\n            this.head = newItem;\n        } else {\n            while (true) {\n                if (currentItem.next) {\n                    currentItem = currentItem.next;\n                } else {\n                    currentItem.next = newItem;\n                    break;\n                }\n            }\n        }\n    }\n\n    // Add the element at the beginning of the linked list\n    prepend(val: number) {\n        let newItem = new LinkedListItem(val);\n        let oldHead = this.head;\n\n        this.head = newItem;\n        newItem.next = oldHead;\n    }\n\n    // Adds the element at a specific position inside the linked list\n    insert(val: number, previousItem: LinkedListItem) {\n        let newItem: LinkedListItem = new LinkedListItem(val);\n        let currentItem: LinkedListItem = this.head;\n\n        if (!currentItem) {\n            this.head = newItem;\n        } else {\n            while (true) {\n                if (currentItem === previousItem) {\n                    let tempNextItem = previousItem.next;\n                    currentItem.next = newItem;\n                    newItem.next = tempNextItem;\n                    break;\n                } else {\n                    currentItem = currentItem.next;\n                }\n            }\n        }\n    }\n\n    delete(val: number) {\n        var currentItem = this.head;\n\n        if (!currentItem) {\n            return;\n        }\n\n        if (currentItem.value === val) {\n            this.head = currentItem.next;\n        } else {\n            var previous = null;\n\n            while (true) {\n                if (currentItem.value === val) {\n                    if (currentItem.next) { // special case for last element\n                        previous.next = currentItem.next;\n                    } else {\n                        previous.next = null;\n                    }\n                    currentItem = null; // avoid memory leaks\n                    break;\n                } else {\n                    previous = currentItem;\n                    currentItem = currentItem.next;\n                }\n            }\n        }\n    }\n\n    showInArray() {\n        let arr = [];\n        let currentItem = this.head;\n\n        while (true) {\n            arr.push(currentItem.value);\n\n            if (currentItem.next) {\n                currentItem = currentItem.next;\n            } else {\n                break;\n            }\n        }\n\n        return arr;\n    }\n\n  isPalindrome(head: any) {\n\n      let front = head;\n\n      const traverse = (node: any) => {\n          if (!node) return true;\n          const reverse = traverse(node.next);\n          const valChecker = front.value == node.value;\n          front = front.next;\n          return reverse && valChecker;\n      }\n\n      return traverse(head)\n  };\n}\n\nclass LinkedListItem {\n    value: any;\n    next: LinkedListItem;\n\n    constructor(val: number) {\n        this.value = val;\n        this.next = null;\n    }\n}\n\nlet head = new LinkedListItem(5);\nlet linkedList = new LinkedList(head);\n\nlinkedList.append(10);\nlinkedList.append(2);\nlinkedList.append(2);\nlinkedList.append(10);\nlinkedList.append(5);\n\nconsole.log(linkedList.showInArray()); \nconsole.log(linkedList.isPalindrome(head)); \n\n"
  },
  {
    "path": "Data-Structures/LinkedList/Singly_Linked_List/PalindromeLinkedList.cpp",
    "content": "#include <bits/stdc++.h>\r\nusing namespace std;\r\n\r\nclass Node\r\n{\r\npublic:\r\n    int data;\r\n    Node(int d)\r\n    {\r\n        data = d;\r\n    }\r\n    Node *ptr;\r\n};\r\n\r\nbool isPalin(Node *head)\r\n{\r\n\r\n    Node *slow = head;\r\n\r\n    stack<int> s;\r\n\r\n    while (slow != NULL)\r\n    {\r\n        s.push(slow->data);\r\n\r\n        // Move ahead\r\n        slow = slow->ptr;\r\n    }\r\n\r\n    while (head != NULL)\r\n    {\r\n        int i = s.top();\r\n\r\n        s.pop();\r\n\r\n        if (head->data != i)\r\n        {\r\n            return false;\r\n        }\r\n\r\n        head = head->ptr;\r\n    }\r\n\r\n    return true;\r\n}\r\n\r\n// Driver Code\r\nint main()\r\n{\r\n\r\n    // Creating a Linked List\r\n    Node one = Node(1);\r\n    Node two = Node(2);\r\n    Node three = Node(3);\r\n    Node four = Node(2);\r\n    Node five = Node(1);\r\n\r\n    // Initializing next pointers\r\n    five.ptr = NULL;\r\n    one.ptr = &two;\r\n    two.ptr = &three;\r\n    three.ptr = &four;\r\n    four.ptr = &five;\r\n    Node *temp = &one;\r\n\r\n    int result = isPalin(&one);\r\n\r\n    if (result == 1)\r\n        cout << \"isPalindrome is true\\n\";\r\n    else\r\n        cout << \"isPalindrome is true\\n\";\r\n\r\n    return 0;\r\n}"
  },
  {
    "path": "Data-Structures/LinkedList/Singly_Linked_List/PalindromeLinkedList.js",
    "content": "//classes to create the linklist\nclass LinkedListNode {\n  constructor(char, next) {\n    this.value = char;\n    this.next = next;\n  }\n}\nclass LinkedList {\n  constructor(chars) {\n    const len = chars.length;\n    let currentNode = null;\n    for (let i = len - 1; i >= 0; i--) {\n      let node = new LinkedListNode(chars[i], currentNode);\n      currentNode = node;\n    }\n    this.head = currentNode;\n  }\n//function to check if the linked list iws a palindrome\n  isPalindrome() {\n    let center, slow, quick;\n    center = slow = quick = this.head;\n    if (slow.next == null) {\n      return true;\n    }\n    while(quick.next != null) {\n      slow = slow.next;\n      slow.prev = center;\n      center = slow\n      quick = quick.next\n      if (quick.next == null) {\n        // even number\n        center = slow.prev;\n      } else {\n        quick = quick.next;\n      }\n    }\n    do {\n      if(slow.value !== center.value) {\n        return false;\n      }\n      slow = slow.next;\n      center = center.prev;\n    } while(slow != null) \n    return true;\n  }\n}\nvar list=[],i,sizeofLinked=parseInt(prompt(\"enter the size of the linked list\",0),10);\nfor(i=0;i<sizeofLinked;i++)\n{\nvar x=prompt(\"enter the element:if done enter DONE\");\nlist.push(x);\n}\nalert(new LinkedList(list).isPalindrome());\n"
  },
  {
    "path": "Data-Structures/LinkedList/Singly_Linked_List/README.md",
    "content": "## This folder is empty.\n"
  },
  {
    "path": "Data-Structures/LinkedList/Singly_Linked_List/Remove duplicates from linked_list.c",
    "content": "#include <stdio.h>\n#include <stdlib.h>\n \nstruct node\n{\n    int num;\n    struct node *next;\n};\n \nvoid create(struct node **);\nvoid dup_delete(struct node **);\nvoid release(struct node **);\nvoid display(struct node *);\n \nint main()\n{\n    struct node *p = NULL;\n    struct node_occur *head = NULL;\n    int n;\n \n    printf(\"Enter data into the list\\n\");\n    create(&p);\n    printf(\"Displaying the nodes in the list:\\n\");\n    display(p);\n    printf(\"Deleting duplicate elements in the list...\\n\");\n    dup_delete(&p);\n    printf(\"Displaying non-deleted nodes in the list:\\n\");\n    display(p);\n    release(&p);\n \n    return 0;\n}\n \nvoid dup_delete(struct node **head)\n{\n    struct node *p, *q, *prev, *temp;\n \n    p = q = prev = *head;\n    q = q->next;\n    while (p != NULL)\n    {\n        while (q != NULL && q->num != p->num)\n        {\n            prev = q;\n            q = q->next;\n        }\n        if (q == NULL)\n        {\n            p = p->next;\n            if (p != NULL)\n            {\n                q = p->next;\n            }\n        }\n        else if (q->num == p->num)\n        {\n            prev->next = q->next;\n            temp = q;\n            q = q->next;\n            free(temp);\n        }\n    }\n}\n \nvoid create(struct node **head)\n{\n    int c, ch;\n    struct node *temp, *rear;\n \n    do\n    {\n        printf(\"Enter number: \");\n        scanf(\"%d\", &c);\n        temp = (struct node *)malloc(sizeof(struct node));\n        temp->num = c;\n        temp->next = NULL;\n        if (*head == NULL)\n        {\n            *head = temp;\n        }\n        else\n        {\n            rear->next = temp;\n        }\n        rear = temp;\n        printf(\"Do you wish to continue [1/0]: \");\n        scanf(\"%d\", &ch);\n    } while (ch != 0);\n    printf(\"\\n\");\n}\n \nvoid display(struct node *p)\n{\n    while (p != NULL)\n    {\n        printf(\"%d\\t\", p->num);\n        p = p->next;\n    }\n    printf(\"\\n\");\n}\n \nvoid release(struct node **head)\n{\n    struct node *temp = *head;\n    *head = (*head)->next;\n    while ((*head) != NULL)\n    {\n        free(temp);\n        temp = *head;\n        (*head) = (*head)->next;\n    }\n}\n"
  },
  {
    "path": "Data-Structures/LinkedList/Singly_Linked_List/Remove duplicates in a Linked List.cpp",
    "content": "#include <iostream>\nusing namespace std;\nclass Node{\n    public:\n    int data;\n    Node *next;\n}*head = NULL;\nvoid create(int size){\n    int data, i;\n    Node *temp;\n    temp = head;\n    cout << \"Enter data: \\n\";\n    for(int  i = 0; i < size; i++){\n        cin >> data;\n        if(temp == NULL){\n            cout << \"Couldn't allocate memory\";\n            break;\n        }\n        if( i == 0 ){\n            head -> data = data;\n            head -> next = NULL;\n        }\n        else{\n            Node *newNode = new Node();\n            newNode -> data = data;\n            newNode -> next = NULL;\n            temp -> next = newNode;\n            temp = temp -> next;\n        }\n        \n    }\n}\nvoid deleteNum(){\n    Node *ptr1, *ptr2, *prev;\n    ptr1 = head;\n    while(ptr1 != NULL){\n        ptr2 = ptr1 -> next;\n        prev = ptr1;\n        while(ptr2 != NULL){\n            if(ptr1 -> data == ptr2 -> data){\n                prev -> next = ptr2 -> next;\n            }\n            prev = ptr2;\n            ptr2 = ptr2 -> next;\n        }\n        ptr1 = ptr1 -> next;\n    }\n}\nvoid display(){\n    Node *temp = head;\n    if(head == NULL){\n        cout << \"Empty list\";\n    }\n    while(temp != NULL){\n        cout << temp -> data << \"\\t\";\n        temp = temp -> next;\n    }\n    cout << endl;\n}\nint main()\n{\n    int n, i;\n    head = new Node();\n    cout << \"Enter no.of nodes \\n\";\n    cin >> n;\n    create(n);\n    cout << \"Original Linked List: \\n\";\n    display();\n    deleteNum();\n    cout << \"After removin duplicates: \\n\";\n    display();\n    \n}\n\n\n"
  },
  {
    "path": "Data-Structures/LinkedList/Singly_Linked_List/Remove_Duplicates_in_LL.py",
    "content": "# Python3 program to remove duplicate\n# nodes from a sorted linked list \n \n# Node class \nclass Node: \n \n    # Constructor to initialize \n    # the node object \n    def __init__(self, data): \n        self.data = data \n        self.next = None\n \nclass LinkedList: \n \n    # Function to initialize head \n    def __init__(self): \n        self.head = None\n \n    # Function to insert a new node \n    # at the beginning \n    def push(self, new_data): \n        new_node = Node(new_data) \n        new_node.next = self.head \n        self.head = new_node \n \n    # Given a reference to the head of a \n    # list and a key, delete the first \n    # occurence of key in linked list \n    def deleteNode(self, key): \n         \n        # Store head node \n        temp = self.head \n \n        # If head node itself holds the \n        # key to be deleted \n        if (temp is not None): \n            if (temp.data == key): \n                self.head = temp.next\n                temp = None\n                return\n \n        # Search for the key to be deleted, \n        # keep track of the previous node as\n        # we need to change 'prev.next' \n        while(temp is not None): \n            if temp.data == key: \n                break\n            prev = temp \n            temp = temp.next\n \n        # if key was not present in \n        # linked list \n        if(temp == None): \n            return\n \n        # Unlink the node from linked list \n        prev.next = temp.next\n \n        temp = None\n \n    # Utility function to print the \n    # linked LinkedList \n    def printList(self): \n        temp = self.head \n        while(temp): \n            print(temp.data , end = ' ')\n            temp = temp.next\n     \n    # This function removes duplicates \n    # from a sorted list         \n    def removeDuplicates(self):\n        temp = self.head\n        if temp is None:\n            return\n        while temp.next is not None:\n            if temp.data == temp.next.data:\n                new = temp.next.next\n                temp.next = None\n                temp.next = new\n            else:\n                temp = temp.next\n        return self.head\n \n# Driver Code \nllist = LinkedList() \nprint(\"Enter Number of Nodes in Linked List\")\nN = int(input())\nprint(\"Enter Values For Linked List:\")\nfor _ in range(N):\n    llist.push(int(input())) \n\nprint (\"Created Linked List: \")\nllist.printList() \nprint()\nprint(\"Linked List after removing duplicate elements:\")\nllist.removeDuplicates()\nllist.printList() \n"
  },
  {
    "path": "Data-Structures/LinkedList/Singly_Linked_List/Reversed_Linked_List/ReversedLinkedList.js",
    "content": "class LinkedListNode {\n    //Constructor to initialize a node\n    constructor(value){\n        this.value = value;\n        this.next = null;\n    }\n  }\n\nclass LinkedList {\n    //Constructor to initialize head\n    constructor(){\n        this.head = null;\n    }\n\n    //Function to insert a new node at the start of list\n    push(value){\n        const newNode=new LinkedListNode(value);\n        newNode.next=this.head;\n        this.head=newNode;\n        \n    }\n   \n    //Function to reverse a linked list\n    reverse() {\n\n        let node = this.head,\n            previous,\n            tmp;\n      \n        while (node) {\n\n          //Save next before overwrite\n          tmp = node.next;\n      \n          //Next equals previous;\n          node.next = previous;\n      \n          //Move forward in the list\n          previous = node\n          node = tmp;\n        }\n      \n        return previous;\n      }\n\n}\n\n  //Initialize list and push a few nodes\n  const llist=new LinkedList()\n  llist.push(5);\n  llist.push(10);\n  llist.push(15);\n  llist.push(20);\n\n  //Print out results\n  console.log(llist.head)\n  console.log(llist.reverse())\n"
  },
  {
    "path": "Data-Structures/LinkedList/Singly_Linked_List/Reversed_Linked_List/reverseLinkedList.c",
    "content": "#include<stdio.h>\n#include<stdlib.h>\n\n// structure of node\ntypedef struct Node \n{\n\tstruct Node *next;\n\tint data;\n} NODE;\n\n// insert a new node at the beginning of the linked list\nNODE *insert(NODE* head, int val)\n{\n\tNODE *p = (NODE *)malloc(sizeof(NODE));\n\tp->data = val;\n\tp->next = (head == NULL) ? NULL : head;\n\treturn head = p;\n}\n\n// reverse the linked list\nNODE *reverse(NODE *head)\n{\n\tNODE *p, *q, *r;\n\tp = NULL;\n\tq = head;\n\twhile(q != NULL)\n\t{\n\t\tr = q->next;\n\t\tq->next = p;\n\t\tp = q;\n\t\tq = r;\n\t}\n\treturn p;\n}\n\n// print the linked list\nvoid print_(NODE *head)\n{\n\tif(head == NULL)\n\t{\n\t\tprintf(\"\\n\");\n\t\treturn;\n\t}\n\tprintf(\"%d \", head->data);\n\tprint_(head->next);\n}\n\nint main()\n{\n\tNODE *head = NULL;\n\t// inserting nodes in the linked list\n\thead = insert(head, 1);\n\thead = insert(head, 2);\n\thead = insert(head, 3);\n\thead = insert(head, 4);\n\thead = insert(head, 5);\n\t// printing the original linked list\n\tprint_(head);\t\t\t\t// Output 5 4 3 2 1\n\t// invoking the reverse head function\n\tNODE *revHead = reverse(head);\n\t// printing the reversed linked list\n\tprint_(revHead);\t\t\t// Output 1 2 3 4 5\n\treturn 0;\n}\n"
  },
  {
    "path": "Data-Structures/LinkedList/Singly_Linked_List/Sublist_Search.rb",
    "content": "# simple linked list implementation\nclass LinkedList\n    attr_accessor :head\n    # simple node implementation, constructor takes value and next ref\n    class Node\n        attr_accessor :value\n        attr_accessor :next\n\n        def initialize(val, nextNode)\n            @value = val\n            @next = nextNode\n        end\n    end\n\n    # paramterized list constructor\n    def initialize(val)\n        @head = Node.new(val, nil)\n    end\n\n    # simple linked list insertion method\n    def self.insert(node, val) \n        # if given node is null, insert at given ref\n        if not node then\n            node = Node.new(val, nil)\n        else\n            # otherwise, iterate until end of list\n            while node.next\n                node = node.next\n            end\n            # then insert the new node\n            node.next = Node.new(val, nil)\n        end\n    end\n\n    # sublist search function implementation\n    def self.search(listToFind, listBeingSearched)\n        # declare result var\n        res = false\n\n        # base case - empty listToFind implies true [empty list always exists in a given list]\n        if not listToFind then\n            return true\n        end\n\n        # otherwise, see if lists match starting with first node of listToFind\n        firstIteration = true\n        while listBeingSearched do\n            # update list2 to the corresponding node for this iteration\n            if not firstIteration then\n                # if list2 is eptied, return false\n                if not listBeingSearched then\n                    return false\n                end\n                listBeingSearched = listBeingSearched.next\n            end\n\n            # make ref to head of each list for iter. purposes\n            lookingFor = listToFind\n            searchingIn = listBeingSearched\n\n            # then try to match current form of list2 with list1 \n            while lookingFor do\n                # if list being searched is nil and list being searched for is not, fail\n                if not searchingIn then\n                    return false\n                # if a match fails, break and try from next list2 node\n                elsif lookingFor.value != searchingIn.value then\n                    break\n                end\n                # otherwise, continue checking nodes\n                lookingFor = lookingFor.next\n                searchingIn = searchingIn.next\n            end\n\n            # if a match was found...\n            if not lookingFor then\n                return true\n            end\n            # o.w., continue\n            firstIteration = false\n        end\n    end\n\n    # simple print function for demonstration purposes\n    def self.prettyPrint(node)        \n        while node\n            print \"#{node.value} -> \"\n            node = node.next\n        end\n        print \"nil\\n\"\n    end\nend\n\n# simple demonstration list setup via stdin\nputs \"Please enter three values to put in the list that will be looked for:\"\nlist1 = LinkedList.new(gets.strip)\nfor i in 1..2\n    LinkedList.insert(list1.head, gets.strip)\nend\nputs \"Please enter five values to put in the list that will be searched:\"\nlist2 = LinkedList.new(gets.strip)\nfor i in 1..4\n    LinkedList.insert(list2.head, gets.strip)\nend\n# pretty print the inputs\nputs \"Seeking:\"\nLinkedList.prettyPrint(list1.head)\nputs \"Inside of:\"\nLinkedList.prettyPrint(list2.head)\n# then demonstrate sublist search method\nputs \"Result: \"\nputs LinkedList.search(list1.head, list2.head)"
  },
  {
    "path": "Data-Structures/LinkedList/Singly_Linked_List/linked list.c",
    "content": "# include <stdio.h>\r\n# include <stdlib.h>\r\nvoid create();\r\nvoid display();\r\nvoid insert_beg();\r\nvoid count_node();\r\nvoid delete();\r\nstruct node{\r\n\tint data;\r\n\tstruct node *next;\r\n};\r\nstruct node *start=NULL;\r\nvoid create();\r\nvoid display();\r\nvoid insert_beg();\r\nvoid insert_end();\r\nvoid insert_at_loc();\r\nint main()\r\n{\r\n\tint c;\r\n\tcreate();\r\n\twhile(1){\r\n\t   printf(\"\\n Available options:\");\r\n\t   printf(\"1.DISPLAY\\n 2.INSERT AT BEGINNING\\n 3.INSERT AT END\\n 4.INSERT AT LOCATION\\n 5.COUNT\\n 6.DELETE\\n\");\t\r\n\t   printf(\"\\n Enter your choice\");\r\n\t   scanf(\"%d\",&c);\r\n\t   switch(c){\r\n\t        case 1: display();\r\n\t                break;\r\n\t        case 2: insert_beg();\r\n\t                break;\r\n\t        case 3: insert_end();\r\n\t                break;\r\n\t        case 4: insert_at_loc();\r\n\t                break;\r\n\t        case 5: count_node();\r\n\t                break;\r\n\t        case 6: delete();\r\n\t                break;\r\n        }\r\n   }\r\n    return 0;\r\n}\r\nvoid create()\r\n{\r\n\tint n,item,i=1;\r\n\tprintf(\"Enter the value of n\");\r\n\tscanf(\"%d\",&n);\r\n\tstruct node *p;\r\n\tp=(struct node*)malloc(sizeof(struct node));\r\n    start=p;\r\n    printf(\"\\n Enter the data for the node\");\r\n    scanf(\"%d\",&item);\r\n    p->data=item;\r\n    p->next=NULL;\r\n\tfor(i=2;i<=n;i++)\r\n\t{\r\n\t\tprintf(\"\\n Enter the data for the node\");\r\n\t\tscanf(\"%d\",&item);\r\n\t\tp->next = (struct node*)malloc(sizeof(struct node));\r\n\t\tp=p->next;\r\n\t\tp->data=item;\r\n\t\tp->next=NULL;\r\n\t}\r\n}\r\nvoid display()\r\n{\r\n\tstruct node *p=start;\r\n\twhile(p!=NULL){\r\n\t\tprintf(\"%d->\",p->data);\r\n\t\tp=p->next;\r\n\t}\r\n}\r\nvoid insert_beg()\r\n{\r\n\tint item;\r\n\tprintf(\"\\n Enter the data to be inserted\");\r\n\tscanf(\"%d\",&item);\r\n\tstruct node *temp;\r\n\ttemp=(struct node*)malloc(sizeof(struct node));\r\n\ttemp->data= item;\r\n\ttemp->next=start;\r\n\tstart=temp;\r\n}\r\nvoid insert_end()\r\n{\r\n\tstruct node *p=start,*temp;\r\n\tint item;\r\n\tprintf(\"\\n Enter the data to be inserted\");\r\n\tscanf(\"%d\",&item);\r\n\ttemp=(struct node*)malloc(sizeof(struct node));\r\n\ttemp->data=item;\r\n\ttemp->next=NULL;\r\n\twhile(p->next!=NULL)\r\n\t{\r\n\t\tp=p->next;\r\n\t}\r\n\tp->next=temp;\r\n}\r\nvoid insert_at_loc()\r\n{\r\n\tint i,item,loc;\r\n\tprintf(\"Enter the data to be inserted\\n\");\r\n\tscanf(\"%d\",&item);\r\n\tprintf(\"\\n Enter the location\");\r\n\tscanf(\"%d\",&loc);\r\n\tstruct node *p=start,*temp;\r\n\ttemp=(struct node*)malloc(sizeof(struct node));\r\n\ttemp->data=item;\r\n\tfor(i=1;i<loc;i++)\r\n\t{\r\n\t\tp=p->next;\r\n    }\r\n\ttemp->next=p->next;\t\r\n\tp->next=temp;\r\n}\r\nvoid count_node()\r\n{\r\n\tint count=0;\r\n\tstruct node *p=start;\r\n\twhile(p!=NULL)\r\n\t{\r\n\t\tcount=count+1;\r\n\t\tp=p->next;\r\n\t}\r\n\tprintf(\"Node count : %d\",count);\r\n}\r\nvoid delete()\r\n{\r\n\tint item;\r\n\tstruct node *p=start,*old;\r\n\tprintf(\"Enter the item to be deleted\\n\");\r\n\tscanf(\"%d\",&item);\r\n\twhile(p!=NULL)\r\n\t{\r\n\t\tif(p->data ==item){\r\n\t\t\tif(p==start){\r\n\t\t\t\tstart=p->next;\r\n\t\t\t\tfree(p);\r\n\t\t\t\treturn;\r\n\t\t\t}\r\n\t\t\telse{\r\n\t\t\t\told->next=p->next;\r\n\t\t\t\tfree(p);\r\n\t\t\t\treturn;\r\n\t\t\t}\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\told=p;\r\n\t\t\tp=p->next;\r\n\t\t}\r\n\t}\r\n}\r\n\r\n"
  },
  {
    "path": "Data-Structures/LinkedList/Singly_Linked_List/linked.cpp",
    "content": "#include<iostream>\n#include<stdlib.h>\n#include<process.h>\nusing namespace std;\n\nstruct Node\n{\n    int info;\n    Node* next;\n}*start,*newptr,*save,*ptr,*rear;\nNode* Create_New_Node(int);\nvoid Insert_End(Node*);\nvoid Display(Node*);\nvoid DelNode();\nvoid Search(Node*);\n\n\nint main()\n{\n    start=rear=NULL;\n    int inf;  char ch='y';\n    int choice;\n\n    while(1)\n    {\n        cout<<\"1:Insertion\\n2:Display\\n3:DelNode\\n4:Search\\n\";\n        cout<<\"ENTER YOUR CHOICE : \";\n        cin>>choice;\n        switch(choice)\n    {\n        case 1:\n        {\n        cout<<\"\\nEnter the Information for the new node...\";\n        cin>>inf;\n        newptr=Create_New_Node(inf);\n        if(newptr!=NULL)\n        {\n            cout<<\"\\n\";\n        }\n        else\n        {\n            cout<<\"\\nCannot create new node!!!\\n\";\n            exit(1);\n        }\n        Insert_End(newptr);\n        }break;\n        case 2:\n            cout<<endl<<endl;\n        Display(start);\n        break;\n        case 3:\n            cout<<endl;\n        DelNode();\n        break;\n        case 4:\n            cout<<endl;\n        Search(start);\n        break;\n    }\n    }\n\n    return 0;\n}\nNode*Create_New_Node(int n)\n{\n    ptr = new Node;\n    ptr->info=n;\n    ptr->next=NULL;\n    return ptr;\n}\nvoid Insert_End(Node*np)\n{\n    if(start==NULL)\n    {\n        start=rear=np;\n    }else\n    {\n        rear->next=np;\n        rear=np;\n    }\n}\nvoid Display(Node*np)\n{\n    while(np!=NULL)\n    {\n        cout<<np->info<<\"->\";\n        np=np->next;\n    }\n    cout<<\"!!!\\n\";\n}\n\nvoid DelNode()\n{\n    if(start==NULL)\n    {\n        cout<<\"UNDERFLOW!!!\\n\";\n    }\n\n    else\n    {\n        ptr=start;\n        start=start->next;\n        delete ptr;\n    }\n}\nvoid Search(Node*np)\n{\n    int element;\n    cout<<\"Enter the Element to Search \";\n    cin>>element;\n    while(np!=NULL)\n    {\n        if(np->info==element)\n        {\n            cout<<\"Search Successful  \\n\";\n            break;\n        }\n        else\n            cout<<\"\\n ELEMENT NOT FOUND \";\n        np=np->next;\n    }\n}\n\n"
  },
  {
    "path": "Data-Structures/LinkedList/Singly_Linked_List/linkedlist.cpp",
    "content": "#include<iostream>\n\n#include<cstdio>\n\n#include<cstdlib>\n\nusing namespace std;\n\n/*\n\n * Node Declaration\n\n */\n\nstruct node\n\n{\n\n    int info;\n\n    struct node *next;\n\n}*start;\n\n\n\n/*\n\n * Class Declaration\n\n */\n\nclass single_llist\n\n{\n\n    public:\n\n        node* create_node(int);\n\n        void insert_begin();\n\n        void insert_pos();\n\n        void insert_last();\n\n        void delete_pos();\n\n        void sort();\n\n        void search();\n\n        void update();\n\n        void reverse();\n\n        void display();\n\n        single_llist()\n\n        {\n\n            start = NULL;\n\n        }\n\n};\n\n\n\n/*\n\n * Main :contains menu\n\n */\n\nmain()\n\n{\n\n    int choice, nodes, element, position, i;\n\n    single_llist sl;\n\n    start = NULL;\n\n    while (1)\n\n    {\n\n        cout<<endl<<\"---------------------------------\"<<endl;\n\n        cout<<endl<<\"Operations on singly linked list\"<<endl;\n\n        cout<<endl<<\"---------------------------------\"<<endl;\n\n        cout<<\"1.Insert Node at beginning\"<<endl;\n\n        cout<<\"2.Insert node at last\"<<endl;\n\n        cout<<\"3.Insert node at position\"<<endl;\n\n        cout<<\"4.Sort Link List\"<<endl;\n\n        cout<<\"5.Delete a Particular Node\"<<endl;\n\n        cout<<\"6.Update Node Value\"<<endl;\n\n        cout<<\"7.Search Element\"<<endl;\n\n        cout<<\"8.Display Linked List\"<<endl;\n\n        cout<<\"9.Reverse Linked List \"<<endl;\n\n        cout<<\"10.Exit \"<<endl;\n\n        cout<<\"Enter your choice : \";\n\n        cin>>choice;\n\n        switch(choice)\n\n        {\n\n        case 1:\n\n            cout<<\"Inserting Node at Beginning: \"<<endl;\n\n            sl.insert_begin();\n\n            cout<<endl;\n\n            break;\n\n        case 2:\n\n            cout<<\"Inserting Node at Last: \"<<endl;\n\n            sl.insert_last();\n\n            cout<<endl;\n\n            break;\n\n        case 3:\n\n            cout<<\"Inserting Node at a given position:\"<<endl;\n\n            sl.insert_pos();\n\n            cout<<endl;\n\n            break;\n\n        case 4:\n\n            cout<<\"Sort Link List: \"<<endl;\n\n            sl.sort();\n\n            cout<<endl;\n\n            break;\n\n        case 5:\n\n            cout<<\"Delete a particular node: \"<<endl;\n\n            sl.delete_pos();\n\n            break;\n\n        case 6:\n\n            cout<<\"Update Node Value:\"<<endl;\n\n            sl.update();\n\n            cout<<endl;\n\n            break;\n\n        case 7:\n\n            cout<<\"Search element in Link List: \"<<endl;\n\n            sl.search();\n\n            cout<<endl;\n\n            break;\n\n        case 8:\n\n            cout<<\"Display elements of link list\"<<endl;\n\n            sl.display();\n\n            cout<<endl;\n\n            break;\n\n        case 9:\n\n            cout<<\"Reverse elements of Link List\"<<endl;\n\n            sl.reverse();\n\n            cout<<endl;\n\n            break;\n\n        case 10:\n\n            cout<<\"Exiting...\"<<endl;\n\n            exit(1);\n\n            break;\n\n        default:\n\n            cout<<\"Wrong choice\"<<endl;\n\n        }\n\n    }\n\n}\n\n\n\n/*\n\n * Creating Node\n\n */\n\nnode *single_llist::create_node(int value)\n\n{\n\n    struct node *temp, *s;\n\n    temp = new(struct node);\n\n    if (temp == NULL)\n\n    {\n\n        cout<<\"Memory not allocated \"<<endl;\n\n        return 0;\n\n    }\n\n    else\n\n    {\n\n        temp->info = value;\n\n        temp->next = NULL;\n\n        return temp;\n\n    }\n\n}\n\n\n\n/*\n\n * Inserting element in beginning\n\n */\n\nvoid single_llist::insert_begin()\n\n{\n\n    int value;\n\n    cout<<\"Enter the value to be inserted: \";\n\n    cin>>value;\n\n    struct node *temp, *p;\n\n    temp = create_node(value);\n\n    if (start == NULL)\n\n    {\n\n        start = temp;\n\n        start->next = NULL;\n\n    }\n\n    else\n\n    {\n\n        p = start;\n\n        start = temp;\n\n        start->next = p;\n\n    }\n\n    cout<<\"Element Inserted at beginning\"<<endl;\n\n}\n\n\n\n/*\n\n * Inserting Node at last\n\n */\n\nvoid single_llist::insert_last()\n\n{\n\n    int value;\n\n    cout<<\"Enter the value to be inserted: \";\n\n    cin>>value;\n\n    struct node *temp, *s;\n\n    temp = create_node(value);\n\n    s = start;\n\n    while (s->next != NULL)\n\n    {\n\n        s = s->next;\n\n    }\n\n    temp->next = NULL;\n\n    s->next = temp;\n\n    cout<<\"Element Inserted at last\"<<endl;\n\n}\n\n\n\n/*\n\n * Insertion of node at a given position\n\n */\n\nvoid single_llist::insert_pos()\n\n{\n\n    int value, pos, counter = 0;\n\n    cout<<\"Enter the value to be inserted: \";\n\n    cin>>value;\n\n    struct node *temp, *s, *ptr;\n\n    temp = create_node(value);\n\n    cout<<\"Enter the postion at which node to be inserted: \";\n\n    cin>>pos;\n\n    int i;\n\n    s = start;\n\n    while (s != NULL)\n\n    {\n\n        s = s->next;\n\n        counter++;\n\n    }\n\n    if (pos == 1)\n\n    {\n\n        if (start == NULL)\n\n        {\n\n            start = temp;\n\n            start->next = NULL;\n\n        }\n\n        else\n\n        {\n\n            ptr = start;\n\n            start = temp;\n\n            start->next = ptr;\n\n        }\n\n    }\n\n    else if (pos > 1  && pos <= counter)\n\n    {\n\n        s = start;\n\n        for (i = 1; i < pos; i++)\n\n        {\n\n            ptr = s;\n\n            s = s->next;\n\n        }\n\n        ptr->next = temp;\n\n        temp->next = s;\n\n    }\n\n    else\n\n    {\n\n        cout<<\"Positon out of range\"<<endl;\n\n    }\n\n}\n\n\n\n/*\n\n * Sorting Link List\n\n */\n\nvoid single_llist::sort()\n\n{\n\n    struct node *ptr, *s;\n\n    int value;\n\n    if (start == NULL)\n\n    {\n\n        cout<<\"The List is empty\"<<endl;\n\n        return;\n\n    }\n\n    ptr = start;\n\n    while (ptr != NULL)\n\n    {\n\n        for (s = ptr->next;s !=NULL;s = s->next)\n\n        {\n\n            if (ptr->info > s->info)\n\n            {\n\n                value = ptr->info;\n\n                ptr->info = s->info;\n\n                s->info = value;\n\n            }\n\n        }\n\n        ptr = ptr->next;\n\n    }\n\n}\n\n\n\n/*\n\n * Delete element at a given position\n\n */\n\nvoid single_llist::delete_pos()\n\n{\n\n    int pos, i, counter = 0;\n\n    if (start == NULL)\n\n    {\n\n        cout<<\"List is empty\"<<endl;\n\n        return;\n\n    }\n\n    cout<<\"Enter the position of value to be deleted: \";\n\n    cin>>pos;\n\n    struct node *s, *ptr;\n\n    s = start;\n\n    if (pos == 1)\n\n    {\n\n        start = s->next;\n\n    }\n\n    else\n\n    {\n\n        while (s != NULL)\n\n        {\n\n            s = s->next;\n\n            counter++;\n\n        }\n\n        if (pos > 0 && pos <= counter)\n\n        {\n\n            s = start;\n\n            for (i = 1;i < pos;i++)\n\n            {\n\n                ptr = s;\n\n                s = s->next;\n\n            }\n\n            ptr->next = s->next;\n\n        }\n\n        else\n\n        {\n\n            cout<<\"Position out of range\"<<endl;\n\n        }\n\n        free(s);\n\n        cout<<\"Element Deleted\"<<endl;\n\n    }\n\n}\n\n\n\n/*\n\n * Update a given Node\n\n */\n\nvoid single_llist::update()\n\n{\n\n    int value, pos, i;\n\n    if (start == NULL)\n\n    {\n\n        cout<<\"List is empty\"<<endl;\n\n        return;\n\n    }\n\n    cout<<\"Enter the node postion to be updated: \";\n\n    cin>>pos;\n\n    cout<<\"Enter the new value: \";\n\n    cin>>value;\n\n    struct node *s, *ptr;\n\n    s = start;\n\n    if (pos == 1)\n\n    {\n\n        start->info = value;\n\n    }\n\n    else\n\n    {\n\n        for (i = 0;i < pos - 1;i++)\n\n        {\n\n            if (s == NULL)\n\n            {\n\n                cout<<\"There are less than \"<<pos<<\" elements\";\n\n                return;\n\n            }\n\n            s = s->next;\n\n        }\n\n        s->info = value;\n\n    }\n\n    cout<<\"Node Updated\"<<endl;\n\n}\n\n\n\n/*\n\n * Searching an element\n\n */\n\nvoid single_llist::search()\n\n{\n\n    int value, pos = 0;\n\n    bool flag = false;\n\n    if (start == NULL)\n\n    {\n\n        cout<<\"List is empty\"<<endl;\n\n        return;\n\n    }\n\n    cout<<\"Enter the value to be searched: \";\n\n    cin>>value;\n\n    struct node *s;\n\n    s = start;\n\n    while (s != NULL)\n\n    {\n\n        pos++;\n\n        if (s->info == value)\n\n        {\n\n            flag = true;\n\n            cout<<\"Element \"<<value<<\" is found at position \"<<pos<<endl;\n\n        }\n\n        s = s->next;\n\n    }\n\n    if (!flag)\n\n        cout<<\"Element \"<<value<<\" not found in the list\"<<endl;\n\n}\n\n\n\n/*\n\n * Reverse Link List\n\n */\n\nvoid single_llist::reverse()\n\n{\n\n    struct node *ptr1, *ptr2, *ptr3;\n\n    if (start == NULL)\n\n    {\n\n        cout<<\"List is empty\"<<endl;\n\n        return;\n\n    }\n\n    if (start->next == NULL)\n\n    {\n\n        return;\n\n    }\n\n    ptr1 = start;\n\n    ptr2 = ptr1->next;\n\n    ptr3 = ptr2->next;\n\n    ptr1->next = NULL;\n\n    ptr2->next = ptr1;\n\n    while (ptr3 != NULL)\n\n    {\n\n        ptr1 = ptr2;\n\n        ptr2 = ptr3;\n\n        ptr3 = ptr3->next;\n\n        ptr2->next = ptr1;\n\n    }\n\n    start = ptr2;\n\n}\n\n\n\n/*\n\n * Display Elements of a link list\n\n */\n\nvoid single_llist::display()\n\n{\n\n    struct node *temp;\n\n    if (start == NULL)\n\n    {\n\n        cout<<\"The List is Empty\"<<endl;\n\n        return;\n\n    }\n\n    temp = start;\n\n    cout<<\"Elements of list are: \"<<endl;\n\n    while (temp != NULL)\n\n    {\n\n        cout<<temp->info<<\"->\";\n\n        temp = temp->next;\n\n    }\n\n    cout<<\"NULL\"<<endl;\n\n}\n"
  },
  {
    "path": "Data-Structures/LinkedList/Singly_Linked_List/merge2sortedlinkedlists.cpp",
    "content": "#include <iostream>\n#include <new>\n#define SIZE(arr) (sizeof(arr) / sizeof(arr[0]))\nusing namespace std;\nstruct node {\n   int data;\n   struct node *next;\n};\nnode *createList(int *arr, int n){\n   node *head, *p;\n   p = head = new node;\n   head->data = arr[0];\n   head->next = NULL;\n   for (int i = 1; i < n; ++i) {\n      p->next = new node;\n      p = p->next;\n      p->data = arr[i];\n      p->next = NULL;\n   }\nreturn head;\n}\nvoid displayList(node *head){\n   while (head != NULL) {\n      cout << head->data << \" \";\n      head = head->next;\n   }\n   cout << endl;\n}\nnode *mergeSortedLists(node *head1, node *head2){\n   node *result = NULL;\n   if (head1 == NULL) {\n      return head2;\n   }\n   if (head2 == NULL) {\n      return head1;\n   }\n   if (head1->data < head2->data) {\n      result = head1;\n      result->next = mergeSortedLists(head1->next, head2);\n   } else {\n      result = head2;\n      result->next = mergeSortedLists(head1, head2->next);\n   }\n   return result;\n}\nint main(){\n   int arr1[] = {10, 15, 17, 20};\n   int arr2[] = {5, 9, 13, 19};\n   node *head1, *head2, *result = NULL;\n   head1 = createList(arr1, SIZE(arr1));\n   head2 = createList(arr2, SIZE(arr1));\n   cout << \"First sorted list: \" << endl;\n   displayList(head1);\n   cout << \"Second sorted list: \" << endl;\n   displayList(head2);\n   result = mergeSortedLists(head1, head2);\n   cout << \"Final sorted list: \" << endl;\n   displayList(result);\n   return 0;\n}\n"
  },
  {
    "path": "Data-Structures/LinkedList/Singly_Linked_List/middle.ts",
    "content": "function main() {\n    const input: string = window.prompt(\"Insert the values separated by commas. (I.e.: 1,2,3)\");\n\n    const list = new SinglyLinkedList();\n    list.push(...input.split(','));\n    const middle: NodeCell = list.findMiddle();\n\n    console.log(`The middle of the list is ${middle.val}`);\n}\n\nclass NodeCell {\n    val: string;\n    next: NodeCell;\n\n    /**\n      * Constructs a NodeCell.\n      * @param {string} val - The value of the NodeCell.\n      */\n    constructor(val: string){\n        this.val = val;\n        this.next = null;\n    }\n}\n\nclass SinglyLinkedList {\n    head: NodeCell;\n    tail: NodeCell;\n\n    /**\n      * Constructs a SinglyLinkedList.\n      */\n    constructor(){\n        this.head = null;\n        this.tail = null;\n    }\n\n    /**\n      * Push values into the SinglyLinkedList converting them into NodeCells.\n      * @param {string[]} values - One or more values to be pushed into the List.\n      */\n    push(...values: string[]){\n        for (const val of values) {\n            const newNode = new NodeCell(val);\n            if (!this.head) {\n                this.head = newNode;\n                this.tail = newNode;\n            } else {\n                this.tail.next = newNode;\n                this.tail = newNode;\n            }\n        }\n    }\n\n    /**\n      * Find the middle NodeCell of the SinglyLinkedList.\n      * @returns {NodeCell} - The NodeCell currently in the middle of the List.\n      */\n    findMiddle(): NodeCell{\n        let slowIterator: NodeCell = this.head;\n        let fastIterator: NodeCell = this.head;\n\n        while (fastIterator && fastIterator.next) {\n            slowIterator = slowIterator.next;\n            fastIterator = fastIterator.next.next;\n        }\n\n        return slowIterator;\n    }\n}\n"
  },
  {
    "path": "Data-Structures/LinkedList/Singly_Linked_List/singly_linked_list.hs",
    "content": "module SinglyLinkedList where\n\nimport Prelude hiding (tail, last)\n\ndata List a = Cons a (List a) | Nil deriving (Show)\n\nsize :: List a -> Int\nsize Nil = 0\nsize (Cons _ tail) = 1 + size tail\n\nisEmpty :: List a -> Bool\nisEmpty Nil = True\nisEmpty _ = False\n\nfirst :: List a -> Maybe a\nfirst Nil = Nothing\nfirst (Cons x _) = Just x\n\nlast :: List a -> Maybe a\nlast Nil = Nothing\nlast (Cons x Nil) = Just x\nlast (Cons _ rest) = last rest\n\naddFirst :: a -> List a -> List a\naddFirst = Cons\n\naddLast :: a -> List a -> List a\naddLast x Nil = Cons x Nil\naddLast x (Cons el tail) = Cons el (addLast x tail)\n\n-- Convenience method.\nfromList :: [a] -> List a\nfromList = foldr Cons Nil\n"
  },
  {
    "path": "Data-Structures/LinkedList/detect_cycle.rb",
    "content": "# Definition for singly-linked list.\nclass ListNode\n    attr_accessor :val, :next\n    def initialize(val)\n        @val = val\n        @next = nil\n    end\nend\n\n# function to test if loop is there\n# @param {ListNode} head\n# @return {Boolean}\ndef detect_cycle(head)\n    slow = head\n    fast = head\n    while slow && fast && fast.next\n        slow = slow.next\n        fast = fast.next.next\n        if slow && slow == fast \n           return true \n        end\n    end\n    false\nend\n\n# script to test the above\ntail = ListNode.new(5)\nhead = tail\nloop_node = nil\n(2...9).each do |p|\n  n = ListNode.new(5*p)\n  tail.next = n\n  tail = n\n  if p == 7\n    loop_node = tail\n  end\nend\n\ntail.next = loop_node\n\nputs(\"Loop detected ? = #{detect_cycle(head)}\")\n"
  },
  {
    "path": "Data-Structures/LinkedList/sparce matrix/sparce addition.cpp",
    "content": "#include<stdio.h>\r\n#include<stdlib.h>\r\nstruct node\r\n{\r\n    int r,c,v;\r\n    struct node *next;\r\n};\r\nvoid create(struct node **h)\r\n{\r\n    struct node *cur,*ptr;\r\n    *h=(struct node *)malloc(sizeof(struct node));\r\n    printf(\"Enter number of rows, coloumns and number of non zero elements\");\r\n    scanf(\"%d%d%d\",&(*h)->r,&(*h)->c,&(*h)->v);\r\n    (*h)->next=NULL;\r\n    ptr=*h;\r\n    for(int i=0;i<(*h)->v;i++)\r\n    {\r\n        cur=(struct node *)malloc(sizeof(struct node));\r\n        printf(\"Enter row, coloumn and value of non zero elements\");\r\n        scanf(\"%d%d%d\",&cur->r,&cur->c,&cur->v);\r\n        cur->next=NULL;\r\n        ptr->next =cur;\r\n        ptr=cur;\r\n    }\r\n}\r\nvoid display1(struct node *h)\r\n{\r\n    struct node *ptr;\r\n    for(ptr=h;ptr!=NULL;ptr=ptr->next)\r\n    {\r\n        printf(\"%d\\t%d\\t%d\",ptr->r,ptr->c,ptr->v);\r\n        printf(\"\\n\");\r\n    }\r\n}\r\nvoid display2(struct node *h)\r\n{\r\n    struct node *ptr;\r\n    int c=0;\r\n    for(int i=0;i<h->r;i++)\r\n    {\r\n        for(int j=0;j<h->c;j++)\r\n        {\r\n            for(ptr=h->next;ptr!=NULL;ptr=ptr->next)\r\n            {\r\n                if(ptr->r==i && ptr->c==j)\r\n                {\r\n                    printf(\"%d\\t\",ptr->v);\r\n                    c=1;\r\n                    break;\r\n                }\r\n                else\r\n                    c=0;\r\n            }\r\n            if(c==0)\r\n                printf(\"%d\\t\",0);\r\n\r\n        }\r\n        printf(\"\\n\");\r\n    }\r\n}\r\nvoid add(struct node *h1,struct node *h2,struct node **h3)\r\n{\r\n    struct node *ptr,*cur,*p,*p2,*tmp;\r\n    if(!(h1->r==h2->r && h1->c==h2->c))\r\n        return;\r\n    *h3=(struct node *)malloc(sizeof(struct node));\r\n    (*h3)->r=h1->r;\r\n    (*h3)->c=h1->c;\r\n    (*h3)->v=h1->v+h2->v;\r\n    ptr=*h3;\r\n    for(p=h1->next;p!=NULL;p=p->next)\r\n    {\r\n        cur=(struct node *)malloc(sizeof(struct node));\r\n        cur->r=p->r;\r\n        cur->c=p->c;\r\n        cur->v=p->v;\r\n        cur->next=NULL;\r\n        ptr->next=cur;\r\n        ptr=cur;\r\n    }\r\n    for(p=h2->next;p!=NULL;p=p->next)\r\n    {\r\n        cur=(struct node *)malloc(sizeof(struct node));\r\n        cur->r=p->r;\r\n        cur->c=p->c;\r\n        cur->v=p->v;\r\n        cur->next=NULL;\r\n        ptr->next=cur;\r\n        ptr=cur;\r\n    }\r\n    for(p=(*h3)->next;p!=NULL;p=p->next)\r\n    {\r\n        tmp=p;\r\n        p2=p->next;\r\n        while(p2!=NULL)\r\n        {\r\n            if(p->r==p2->r && p->c==p2->c)\r\n            {\r\n                p->v=p->v+p2->v;\r\n                tmp->next=p2->next;\r\n                free(p2);\r\n                p2=tmp;\r\n            }\r\n            tmp=p2;\r\n            p2=p2->next;\r\n        }\r\n    }\r\n}\r\nint main()\r\n{\r\n    struct node *h1,*h2,*h3;\r\n    h1=h2=h3=NULL;\r\n    create(&h1);\r\n    create(&h2);\r\n    display1(h1);\r\n    printf(\"1st Matrix : \\n\");\r\n    display2(h1);\r\n    printf(\"2nd Matrix : \\n\");\r\n    display2(h2);\r\n    add(h1,h2,&h3);\r\n    printf(\"Sum of Matrix is : \\n\");\r\n    display2(h3);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Data-Structures/Queue/Circular-Queue/circular_queue.c",
    "content": "#include <stdio.h>\n#include <stdlib.h>\n#define MAX_SIZE 100\n\nstruct queue\n{\nint info;\nstruct queue *next;\n} *rear,*front,*temp;;\nint size = 0;\n\nvoid enqueue(int info);\nvoid dequeue();\nvoid display();\n\nvoid main(){\n    int choice,x;\n    do{\n        printf(\"1-Insert\\n2-Delete\\n3-Display\\n\\nEnter a choice: \");\n        scanf(\"%d\",&choice);\n        switch(choice){\n            case 1: printf(\"\\nEnter the info to be inserted in the Queue : \");\n                    scanf(\"%d\",&x);\n                    enqueue(x);\n                    display();\n                    break;\n            case 2: dequeue();\n                    display();\n                    break;\n            case 3: display();\n                    break;\n            default:printf(\"Invalid choice, please try again.\\n\");\n                    exit(0);\n        }\n    }while(choice!=4);\n}\n\nvoid enqueue(int x)\n{\n    temp = (struct queue*) malloc(sizeof(struct queue));\n    temp -> info = x;\n    if(front == NULL)\n        front = temp;\n    else\n    {\n        rear -> next = temp;\n        rear = temp;\n    }\n    rear -> next = front;\n    size++;\n}\n\nvoid dequeue()\n{\n    int x;\n    if (front == NULL)\n    {\n        printf(\"\\nQueue is Empty\");\n    }\n    else if (front == rear)\n    {\n        x = front->info;\n        free (front);\n        front = rear = NULL;\n    }\n    else\n    {\n        temp = front;\n        x = temp -> info;\n        front = front -> next;\n        rear -> next = front;\n        free (temp);\n    }\n    size--;\n    printf(\"\\nThe deleted element is: %d\",x);\n}\nvoid display()\n    {\n        if(front == NULL)\n            printf(\"\\nQueue is Empty!!!\\n\");\n\n        temp = front;\n        while (temp->next!=NULL) {\n        printf(\"%d\\n\", temp->info);\n        temp = temp->next;\n    }\n    printf(\"%d\\n\", temp->info);\n}\n\n"
  },
  {
    "path": "Data-Structures/Queue/Circular-Queue/circular_queue.cs",
    "content": "using System;\nusing System.Collections;\n\nnamespace belphegorS.DataStructures\n{\n\t/// <summary>\n\t/// Summary description for CsCircularQueue.\n\t/// </summary>\n\tpublic class CircularQueue\n\t{\n\t\tprivate int nMaxSize;\n\t\tprivate int nFrontPosition;\n\t\tprivate int nRearPosition;\n\t\tprivate ArrayList alstQueueContent;\n\n\t\tpublic CircularQueue(int MaxSize)\n\t\t{\n\t\t\tnMaxSize = MaxSize;\n\t\t\tnFrontPosition = 0;\n\t\t\tnRearPosition= -1;\n\t\t\talstQueueContent = new ArrayList(MaxSize);\n\t\t\tfor(int i = 0;i<nMaxSize;i++)\n\t\t\t\talstQueueContent.Add(null);\n\t\t\t\n \t\t}\n\t\tpublic void ResetQueue()\n\t\t{\n\t\t\tfor(int i = 0;i<nMaxSize;i++)\n\t\t\t\talstQueueContent[i] = null;\n\t\t\tnFrontPosition = 0;\n\t\t\tnRearPosition = -1;\n\t\t}\n\t\tpublic int FrontPosition\n\t\t{\n\t\t\tget\n\t\t\t{\n\t\t\t\treturn nFrontPosition;\n\t\t\t}\n\t\t}\n\t\tpublic int RearPosition\n\t\t{\n\t\t\tget\n\t\t\t{\n\t\t\t\treturn nRearPosition;\n\t\t\t}\n\t\t}\n\t\tpublic bool Enqueue(object obj)\n\t\t{\n\t\t\tif((nRearPosition == (nMaxSize-1) && nFrontPosition==0) ||((nRearPosition!=-1)&&(nRearPosition+1)==nFrontPosition))\n\t\t\t\treturn false;\n\n\t\t\tif(nRearPosition == (nMaxSize -1) && nFrontPosition > 0)\n\t\t\t{\n\t\t\t\tnRearPosition = -1;\n\t\t\t}\n\t\t\t\n\t\t\tnRearPosition+=1;\n\t\t\talstQueueContent[nRearPosition] = obj;\n\t\t\tif((nRearPosition-1) == nFrontPosition && alstQueueContent[nFrontPosition]==null)\n\t\t\t\tnFrontPosition = nFrontPosition+1;\n\t\t\treturn true;\n\t\t}\n\n\t\tpublic object Dequeue()\n\t\t{\n\t\t\t\tobject Output = \"Empty\" ;\n\t\t\t\tif(alstQueueContent[nFrontPosition] != null)\n\t\t\t\t{\n\t\t\t\t\tOutput = alstQueueContent[nFrontPosition];\n\t\t\t\t\talstQueueContent[nFrontPosition]=null;\n\t\t\t\t\tif((nFrontPosition+1)<nMaxSize && alstQueueContent[nFrontPosition+1] !=null)\n\t\t\t\t\t\tnFrontPosition += 1;\n\t\t\t\t\telse if(alstQueueContent[0] !=null && (nFrontPosition+1)== nMaxSize)\n\t\t\t\t\t\tnFrontPosition = 0;\n\t\t\t\t\t\n\t\t\t\t}\n\t\t\t\treturn Output;\t\n\t\t}\n\t\tprivate bool IsQueueFull()\n\t\t{\n\t\t\tif(nFrontPosition==(nRearPosition-1))\n\t\t\t{\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\treturn false;\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "Data-Structures/Queue/Circular-Queue/circular_queue_LL.c",
    "content": "#include <stdio.h>\n#include <stdlib.h>\n\nstruct node{\n  int data;\n  struct node *next;\n};\nstruct queue{\n  struct node *front;\n  struct node *rear;\n};\n\n  void enqueue(struct queue *q){\n  struct node *n=(struct node*)malloc(sizeof(struct node));\n  printf(\"\\nEnter data for node\\n\");\n  scanf(\"%d\",&n->data);\n  if(q->front==NULL){\n    q->front=n;\n  }\n  else{\n    q->rear->next=n;\n  }\n  q->rear=n;\n  q->rear->next=q->front;\n}\nvoid dequeue(struct queue *q){\n  if(q->front==NULL){\n    printf(\"\\nQueue is empty\\n\");\n  }\n  else if(q->front==q->rear){\n    printf(\"\\nDeleted element=%d\\n\",q->front->data);\n    q->front=NULL;\n    q->rear=NULL;\n  }\n  else{\n    printf(\"\\nDeleted element=%d\\n\",q->front->data);\n    struct node *temp=q->front;\n    q->front=q->front->next;\n    q->rear->next=q->front;\n    free(temp);\n  }\n}\nvoid display(struct queue *q){\n  printf(\"\\n\");\n  struct node *temp=q->front;\n  while(temp->next!=q->front){\n    printf(\"%d \",temp->data);\n    temp=temp->next;\n  }\n  printf(\"%d \",temp->data);\n}\nint main(){\n  struct queue *p=(struct queue*)malloc(sizeof(struct queue));\n  p->front=NULL;\n  p->rear=NULL;\n  printf(\"\\nEnter i->insertion, d->deletion, p->print and q->quit\\n\");\n  char ch;\n  ch=getche();\n  while (ch!='q') {\n    switch(ch){\n      case 'i': ;\n      enqueue(p);\n      break;\n      case 'd': ;\n      dequeue(p);\n      break;\n      case 'p': ;\n      display(p);\n      break;\n      case 'q': ;\n      break;\n      default:\n      printf(\"\\n Wrong input\\n\");\n      break;\n    }\n    /* code */\n    printf(\"\\n Enter i->insertion, d->deletion, p->print and q->quit\\n\");\n    ch=getche();\n  }\nreturn 0;\n}"
  },
  {
    "path": "Data-Structures/Queue/Circular-Queue/circular_queue_array_implementation.c",
    "content": "#include <stdio.h>\nint front=-1;\nint rear=-1;\nint isFull(int size){\n  if((front==rear+1)||(front==0 && rear==size-1))\n  return 1;\n  return 0;\n}\nint isEmpty(){\n  if(front==-1){\n  return 1;\n}\n  return 0;\n}\nvoid display(int queue[],int size){\n  printf(\"\\n\");\n  int i;\n  if(front>rear){\n    for(i=front;i<size;i++){\n      printf(\"%d \",queue[i]);\n    }\n    for(i=0;i<=rear;i++){\n      printf(\"%d \",queue[i]);\n    }\n  }\n  else{\n    for(i=front;i<=rear;i++){\n      printf(\"%d \",queue[i]);\n    }\n  }\n}\nvoid enqueue(int queue[],int element,int size){\n  if(isFull(size)){\n    printf(\"\\nOverflow\\n\");\n    return;\n  }\n  else{\n    if(rear==-1){\n      rear++;\n      front++;\n    }\n    else if(front>0 && rear==size-1)\n    rear=0;\n    else\n    rear++;\n    queue[rear]=element;\n  }\n}\nvoid dequeue(int queue[]){\n  if(isEmpty()){\n    printf(\"\\nUnderflow\\n\");\n  }\n  else{\n    if(front==rear){\n      printf(\"\\nDeleted %d\\n\",queue[front]);\n      front=-1;\n      rear=-1;\n    }\n    else{\n      printf(\"\\nDeleted %d\\n\",queue[front]);\n      front++;\n    }\n  }\n}\nint main(){\nint size;\nprintf(\"Enter the size of the circular queue\\n\");\nscanf(\"%d\",&size);\nint queue[size];\nprintf(\"Enter the character from the following menu to perform the given operations\\n\");\nprintf(\"f->Display front element\\nr->Display rear element\\np->Display circular queue\\ne->add an element from queue\\nd->delete an element from queue\\nq->quit\");\nchar ch;\nwhile (1) {\n  printf(\"\\nEnter a character\\n\");\n  ch=getche();\n  if(ch=='q')\n  break;\n  else{\n  switch (ch) {\n    case 'f': ;\n    if(front!=-1)\n    printf(\"\\nFront element is %d\\n\",queue[front]);\n    else\n    printf(\"\\nNo element present\\n\");\n    break;\n    case 'r': ;\n    if(rear!=-1)\n    printf(\"\\nRear element is %d\\n\",queue[rear]);\n    else\n    printf(\"\\nNo element present\\n\");\n    break;\n    case 'p': ;\n    display(queue,size);\n    break;\n    case 'e': ;\n    int tbe;\n    printf(\"\\nEnter the number to be inserted\\n\");\n    scanf(\"%d\",&tbe);\n    enqueue(queue,tbe,size);\n    break;\n    case 'd': ;\n    dequeue(queue);\n    break;\n    default:\n    printf(\"\\nIllegal character\\n\");\n    break;\n  }\n}\n}\n}\n"
  },
  {
    "path": "Data-Structures/Queue/Circular-Queue/cirqueue.cpp",
    "content": "#include<iostream>\n#include<stdlib.h>\n#include<process.h>\n\nusing namespace std;\n\nvoid enqueue(int);\nvoid dequeue();\nvoid display_CQ();\n\nconst int size = 5;\nint Cqueue[size],front=-1,rear=-1;\n\nint main()\n{\n    int item,choice;\n     cout<<(\"\\n\\n\\t\\t OPERATION MENU \");\n     cout<<(\"\\n\\n\\t\\t 1.PUSH\\n\\t\\t 2.POP\\n\\t\\t 3.DISPLAY\\n\\t\\t 4.EXIT\");\n    do\n    {\n     cout<<(\"\\n ENTER YOUR CHOICE : \");\n     cin>>choice;\n     switch(choice)\n     {\n       case 1:\n       {\n           cout<<\"\\n ENTER THE ITEM TO BE PUSHED : \";\n           cin>>item;\n           enqueue(item);\n           break;\n       }\n       case 2:\n        {\n            dequeue();\n            break;\n        }\n       case 3:\n        {\n         display_CQ();\n         break;\n        }\n       case 4:\n        exit(100);\n     }\n    }while(choice!=4);\n    return 0;\n}\n\nvoid enqueue(int temp)\n{\n    if((front==0 && rear==size-1) || (front==rear+1))\n    {\n      cout<<\"\\n QUEUE OVERFLOW \";\n      return ;\n    }\n    if(front==-1)\n    {\n        front=rear=0;\n    }\n    else\n    {\n    if(rear==size-1)\n     {\n        rear=0;\n     }\n     else\n        rear++;\n    }\n    Cqueue[rear]=temp;\n}\n\nvoid dequeue()\n{\n    if(front==-1)\n    {\n        cout<<\"\\n QUEUE UNDERFLOW \";\n        return ;\n    }\n    cout<<\"\\n ELEMENT DELETED IS \"<<Cqueue[front];\n        if(front==rear)\n            front=rear=-1;\n        else\n        {\n            if(front==size-1)\n            front=0;\n        else\n            front++;\n        }\n}\n\nvoid display_CQ()\n{\nint front_pos = front,rear_pos = rear;\n    if(front == -1)\n    {\n    printf(\"QUEUE IS EMPTY\");\n    return;\n    }\n        printf(\"QUEUE IS :\");\n        if( front_pos <= rear_pos )\n            while(front_pos <= rear_pos)\n            {\n            printf(\"%d \",Cqueue[front_pos]);\n            front_pos++;\n            }\n        else\n        {\n                while(front_pos <= size-1)\n                {\n                printf(\"%d \",Cqueue[front_pos]);\n                front_pos++;\n                }\n            front_pos = 0;\n            while(front_pos <= rear_pos)\n            {\n            printf(\"%d \",Cqueue[front_pos]);\n            front_pos++;\n            }\n        }\n}\n\n"
  },
  {
    "path": "Data-Structures/Queue/Deque/Deque.cpp",
    "content": "#include <iostream>\n\nusing namespace std;\n\nstruct node\n{\n\tint value;\n\tnode * next;\n\tnode * prev;\n\n\tnode(int x, node * pr, node * nx){\n\t\tvalue = x;\n\t\tprev = pr;\n\t\tnext = nx;\n\t}\n};\n\nstruct myDeque\n{\n\tprivate:\n\t\tnode * head;\n\t\tnode * tail;\n\t\tint cnt;\n\t\t\n\t\tvoid push(int x) {\n\t\t\tnode * el = new node(x, NULL, NULL);\n\t\t\thead = el;\n\t\t\ttail = el;\n\t\t\tcnt++;\n\t\t}\n\n\tpublic:\n\t\tmyDeque()\n\t\t{\n\t\t\thead = NULL;\n\t\t\ttail = NULL;\n\t\t\tcnt = 0;\n\t\t}\n\t\t\n\t\tvoid push_back(int x) {\n\t\t\tif(empty()){\n\t\t\t\tpush(x);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\t\n\t\t\tnode * el = new node(x, tail, NULL);\n\n\t\t\ttail->next = el;\n\t\t\ttail = el;\n\t\t\tcnt++;\n\t\t}\n\n\t\tvoid push_front(int x) {\n\t\t\tif(empty()){\n\t\t\t\tpush(x);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\t\n\t\t\tnode * el = new node(x, NULL, head);\n\t\t\t\n\t\t\thead->prev = el;\n\t\t\thead = el;\n\t\t\tcnt++;\n\t\t}\n\t\t\n\t\tvoid pop_back() {\n\t\t\tif(!empty()) {\n\t\t\t\tint res = tail->value;\n\t\t\t\ttail = tail->prev;\n\t\t\t\tcnt--;\n\t\t\t\tcout << res;\n\t\t\t}\n\n\t\t\telse {\n\t\t\t\tcout << \"error\";\n\t\t\t}\n\t\t}\n\n\t\tvoid pop_front() {\n\t\t\tif(!empty()) {\n\t\t\t\tint res = head->value;\n\t\t\t\thead = head->next;\n\t\t\t\tcnt--;\n\t\t\t\tcout << res;\n\t\t\t}\n\n\t\t\telse {\n\t\t\t\tcout << \"error\";\n\t\t\t}\n\t\t}\n\t\tvoid front() {\n\t\t\tif(!empty())\n\t\t\t\tcout << head->value;\n\t\t\telse\n\t\t\t\tcout << \"error\";\n\t\t}\n\n\t\tvoid back() {\n\t\t\tif(!empty())\n\t\t\t\tcout << tail->value;\n\t\t\telse\n\t\t\t\tcout << \"error\";\n\t\t}\n\n\t\tint size() {\n\t\t\treturn cnt;\n\t\t}\n\t\tvoid clear() {\n\t\t\thead = NULL;\n\t\t\ttail = NULL;\n\t\t\tcnt = 0;\n\t\t}\n\t\tbool empty() {\n\t\t\treturn cnt == 0;\n\t\t}\n\t\t\n};\n\nint main()\n{\n\tstring q;\n\tint x;\n\tmyDeque md;\n\tdo\n    {\n        cin >> q;\n        if(q == \"push_back\"){\n            cin >> x;\n            md.push_back(x);\n            cout << \"ok\";\n        }\n        if(q == \"push_front\"){\n            cin >> x;\n            md.push_front(x);\n            cout << \"ok\";\n        }\n        if(q == \"pop_back\"){\n            md.pop_back();\n        }\n        if(q == \"pop_front\"){\n            md.pop_front();\n        }\n        if(q == \"front\"){\n            md.front();\n        }\n        if(q == \"back\"){\n            md.back();\n        }\n        if(q == \"size\"){\n            cout << md.size();\n        }\n        if(q == \"clear\"){\n            md.clear();\n            cout << \"ok\";\n        }\n        if(q == \"exit\"){\n            cout << \"bye\";\n        }\n        cout << endl;\n    }\n    while(q != \"exit\");\n\treturn 0;\n}\n"
  },
  {
    "path": "Data-Structures/Queue/Deque/Deque.java",
    "content": "import java.util.ArrayList;\nimport java.util.List;\n\npublic class Deque{\n    private List<Integer> deque = new ArrayList<Integer>();\n    \n    //add element at the beginning of the queue\n    public void insertFront(int item){\n        System.out.println(\"element added at front: \"+item);\n        deque.add(0,item);\n        System.out.println(deque);\n    }\n    \n    //add element at the end of the queue\n    public void insertRear(int item){\n        System.out.println(\"element added at rear: \"+item);\n        deque.add(item);\n        System.out.println(deque);\n    }\n\n    //remove an item from the beginning of the queue\n    public void removeFront(){\n        if(deque.isEmpty()){\n            System.out.println(\"Deque underflow, unable to remove.\");\n            return;\n        }\n        int rem = deque.remove(0);\n        System.out.println(\"element removed from front: \"+rem);\n        System.out.println(deque);\n    }\n \n    //remove an item from the beginning of the queue\n    public void removeRear(){\n        if(deque.isEmpty()){\n            System.out.println(\"Deque underflow, unable to remove.\");\n            return;\n        }\n        int rem = deque.remove(deque.size()-1);\n        System.out.println(\"element removed from front: \"+rem);\n        System.out.println(deque);\n    }\n \n    //gets the element from the front without removing it\n    public int peakFront(){\n        int item = deque.get(0);\n        System.out.println(\"Element at first: \"+item);\n        return item;\n    }\n     \n    //gets the element from the rear without removing it\n    public int peakRear(){\n        int item = deque.get(deque.size()-1);\n        System.out.println(\"Element at rear: \"+item);\n        return item;\n    }\n \n    public static void main(String a[]){\n        Deque deq = new Deque();\n        deq.insertFront(34);\n        deq.insertRear(45);\n        deq.removeFront();\n        deq.removeFront();\n        deq.removeFront();\n        deq.insertFront(21);\n        deq.insertFront(98);\n        deq.insertRear(5);\n        deq.insertFront(43);\n        deq.removeRear();\n    }\n}\n"
  },
  {
    "path": "Data-Structures/Queue/Deque/Deque.js",
    "content": "class Deque {\n  constructor() {\n    this.front = this.back = undefined;\n  }\n//   Adds a node to front of linked list\n  addFront(value) {\n    if (!this.front) this.front = this.back = { value };\n    else this.front = this.front.next = { value, prev: this.front };\n  }\n//   Remove a node from the front of linked list\n  removeFront() {\n    let value = this.peekFront();\n    if (this.front === this.back) this.front = this.back = undefined;\n    else (this.front = this.front.prev).next = undefined;\n    return value;\n  }\n//   Get the value from the first node \n  peekFront() {\n    return this.front && this.front.value;\n  }\n//   Adds a node to end of linked list\n  addBack(value) {\n    if (!this.front) this.front = this.back = { value };\n    else this.back = this.back.prev = { value, next: this.back };\n  }\n//   Removes a node from the back of linked list\n  removeBack() {\n    let value = this.peekBack();\n    if (this.front === this.back) this.front = this.back = undefined;\n    else (this.back = this.back.next).back = undefined;\n    return value;\n  }\n  //   Get the value from the first node \n  peekBack() {\n    return this.back && this.back.value;\n  }\n}\n\n// demo\nlet deque = new Deque;\nconsole.log(deque.peekFront()); // undefined\ndeque.addFront(1);\nconsole.log(deque.peekBack()); // 1\ndeque.addFront(2);\nconsole.log(deque.removeBack()); // 1\ndeque.addFront(3);\ndeque.addFront(4);\nconsole.log(deque.peekBack()); // 2\ndeque.addBack(5);\ndeque.addBack(6);\nconsole.log(deque.peekBack()); // 6\nconsole.log(deque.removeFront()); // 4\nconsole.log(deque.removeFront()); // 3\nconsole.log(deque.removeFront()); // 2\nconsole.log(deque.removeFront()); // 5\nconsole.log(deque.removeFront()); // 6\nconsole.log(deque.removeFront()); // undefined\n"
  },
  {
    "path": "Data-Structures/Queue/Deque/Deque.py",
    "content": "# Creating class deque\nclass Deque():\n    \n    # Initializing class\n    def __init__(self, data=None):\n        self.elements = []\n        if(data is not None):\n            self.elements = list(data)\n\n    # Appending an item\n    def append(self, item):\n        self.elements.append(item)\n\n    # Appending an item to the left\n    def appendleft(self, item):\n        self.elements = [item] + self.elements\n    \n    # Popping an item\n    def pop(self):\n        return self.elements.pop()\n    \n    # Popping item from the left\n    def popleft(self):\n        return self.elements.pop(0)\n    \n    # Searching for item in range\n    def index(self, item, start, stop):\n        for i in range(start, min(stop, len(self.elements))):\n            if(item == self.elements[i]):\n                return i\n    \n    # Inserting item at index\n    def insert(self,idx,item):\n        self.elements = self.elements[:idx] + [item] + self.elements[idx:]\n    \n    # Removing item\n    def remove(self, item):\n        self.elements.remove(item)\n\n    # Counting occurence of an item\n    def count(self, item):\n        counter = 0\n        for i in self.elements:\n            if(i == item):\n                counter+=1\n        return counter\n\n    # Extending\n    def extend(self, list_2):\n        list_2 = list(list_2)\n        self.elements += list_2\n        \n    # Extending to the left    \n    def extendleft(self, list_2):\n        list_2 = list(list_2)\n        self.elements = list_2[::-1] + self.elements\n    \n    # Rotating deque\n    def rotate(self,idx):\n        self.elements = self.elements[-idx:] + self.elements[:-idx]\n        \n    # Clearing the deque\n    def clear(self):\n        self.elements.clear()\n    \n    # Creating a copy\n    def copy(self):\n        return Deque(self.elements)\n\n    # Returning a string version\n    def __str__(self):\n        return str(self.elements)\n    \n    # Returning iterable\n    def __iter__(self):\n        for item in self.elements:\n            yield item\n\n\nif __name__ == \"__main__\":\n    x = Deque([2,3])\n    print(\"x:\", x)\n    x.appendleft(1)\n    print(\"Appending 1 to the left:\", x)\n    x.append(4)\n    print(\"Appending 4:\", x)\n    print(\"Popping element:\\n\", x.pop(), x)\n    print(\"Popping first element:\\n\", x.popleft(), x)\n    y = Deque([1,2,3,4,5,6,7,8,9])\n    print(\"y:\", y)\n    y.insert(0,0)\n    print(\"Inserting 0 at position 0:\", y)\n    y.insert(10,10)\n    print(\"Inserting 10 at position 10:\", y)\n    print(\"Index of 4:\", y.index(4,0,100))\n    y.remove(10)\n    print(\"After removing 10\",y)\n    y.extendleft(x)\n    print(\"Extending x to the left:\", y)\n    y.extend([4,4,4])\n    print(\"Extending [4,4,4]:\", y)\n    y.rotate(2)\n    print(\"Rotating by 2\", y)\n    y.rotate(-2)\n    print(\"Rotating by -2\", y)\n    y.clear()\n    print(\"Cleared y:\",y)\n    z = x.copy()\n    print(\"Creating copy of x:\",z)\n    z.append(12345)\n    print(\"After appending 12345 to z:\", z)\n    print(\"x:\",x,\"z:\",z)"
  },
  {
    "path": "Data-Structures/Queue/Deque/Deque.ts",
    "content": "// Node class \nclass DequeNode {\n  public data;\n  public prev: DequeNode | null;\n  public next: DequeNode | null;\n\n  // Constructor to initialize\n  // the node object\n  constructor(data: any) {\n      this.data = data;\n      this.prev = null;\n      this.next = null;\n  }\n}\n\n\nclass Deque {\n  public head: DequeNode | null;\n  public tail: DequeNode | null;\n\n  // Constructor to initialize LinkedList\n  constructor() {\n      this.head = null;\n      this.tail = null;\n  }\n\n  // Utility function just to see the results at a certain time\n  print() {\n      let a = []\n      let pointer: DequeNode | null = this.head;\n      while (pointer) {\n          a.push(pointer.data)\n          pointer = pointer.next\n      }\n      console.log(a)\n  }\n\n  // Function to see the beginning of the deque\n  peekFront() { \n      return this.head && this.head.data;\n  }\n\n\n  // Function to insert a new DequeNode at the beginning of the deque\n  // with the given value\n  appendFront(data: any) {\n      const newNode = new DequeNode(data)\n      if(!this.head) {\n          this.head = newNode;\n          this.tail = newNode;\n      } else {\n          this.head.prev = newNode;\n          newNode.next = this.head;\n          this.head = newNode;\n      }\n  }\n\n  // Function to remove a beginning at the end of the deque\n  removeFront() {\n      const value = this.peekFront();\n      if(value) {\n          if (this.head === this.tail) {\n              this.head = null;\n              this.tail = null;\n          } else {\n              this.head = this.head!.next;\n              this.head!.prev = null;\n          }\n      }\n      return value;\n  }\n\n  // Function to see the end the deque\n  peekBack() { \n      return this.tail && this.tail.data;\n  }\n\n  // Function to insert a new DequeNode at the beginning of the deque\n  // with the given value\n  appendBack(data: any) {\n      const newNode = new DequeNode(data)\n      if(!this.tail) {\n          this.head = newNode;\n          this.tail = newNode;\n      } else {\n          newNode.prev = this.tail;\n          this.tail.next = newNode;\n          this.tail = newNode;\n      }\n  }\n\n  // Function to remove a node at the end of the deque\n  removeBack() {\n      const value = this.peekBack();\n      if(value) {\n          if (this.head === this.tail) {\n              this.head = null;\n              this.tail = null;\n          } else {\n              this.tail = this.tail!.prev;\n              this.tail!.next = null;\n          }\n      }\n      return value;\n  }\n}\n\nconst deque = new Deque();\ndeque.appendFront(22);\ndeque.appendBack(4);\ndeque.appendBack(97);\ndeque.appendFront(1);\ndeque.appendBack(5);\ndeque.print()\ndeque.removeFront()\ndeque.removeBack()\ndeque.removeFront()\ndeque.print()\nconsole.log('Current front:', deque.peekFront());\nconsole.log('Current back:', deque.peekBack());\n"
  },
  {
    "path": "Data-Structures/Queue/Deque/README.md",
    "content": "# This folder is empty.\n"
  },
  {
    "path": "Data-Structures/Queue/Priority-Queue/Priority-Queue.cpp",
    "content": "#include<bits/stdc++.h>\r\nusing namespace std;\r\n\r\n// Node Declaration\r\nstruct node\r\n{\r\n\tint priority;\r\n\tint info; // info stands for the value or the item to be added\r\n\tstruct node *link;\r\n};\r\n// Class Priority Queue\r\nclass Priority_Queue\r\n{\r\n    private:\r\n        node *front; //front node of queue\r\n    public:\r\n        Priority_Queue()\r\n        {\r\n            front = NULL;\r\n        }\r\n        // Insert into Priority Queue\r\n        void insert(int item, int priority)\r\n        {\r\n            node *tmp, *q;\r\n            tmp = new node; // make a temprory node\r\n            tmp->info = item; //set the value\r\n            tmp->priority = priority; //set the priority\r\n            if (front == NULL || priority < front->priority) // if priority of current element less than front elemnt priority.\r\n            {\r\n                tmp->link = front;\r\n                front = tmp;\r\n            }\r\n            //else if greater priority\r\n            else\r\n            {\r\n                q = front;\r\n                while (q->link != NULL && q->link->priority <= priority)\r\n                    q=q->link;\r\n                tmp->link = q->link;\r\n                q->link = tmp;\r\n            }\r\n        }\r\n        // Delete from Priority Queue\r\n        void del()\r\n        {\r\n            node *tmp;\r\n            if(front == NULL)\r\n                cout<<\"Queue Underflow\\n\";\r\n            else\r\n            {\r\n                tmp = front;\r\n                cout<<\"Deleted item is: \"<<tmp->info<<endl;\r\n                front = front->link;\r\n                free(tmp);\r\n            }\r\n        }\r\n        //Print Priority Queue\r\n    \r\n        void display()\r\n        {\r\n            node *ptr;\r\n            ptr = front;\r\n            if (front == NULL)\r\n                cout<<\"Queue is empty\\n\";\r\n            else\r\n            {\tcout<<\"Queue is :\\n\";\r\n                cout<<\"Priority       Item\\n\";\r\n                while(ptr != NULL)\r\n                {\r\n                    cout<<ptr->priority<<\"                 \"<<ptr->info<<endl;\r\n                    ptr = ptr->link;\r\n                }\r\n            }\r\n        }\r\n};\r\n\r\n\r\nint main()\r\n{\r\n    int choice, item, priority;\r\n    Priority_Queue pq; \r\n    do\r\n    {\r\n        cout<<\"1.Insert\\n\";\r\n        cout<<\"2.Delete\\n\";\r\n        cout<<\"3.Display\\n\";\r\n        cout<<\"4.Quit\\n\";\r\n        cout<<\"Enter your choice : \"; \r\n        cin>>choice;\r\n        switch(choice)\r\n        {\r\n        case 1:\r\n            cout<<\"Input the item value to be added in the queue : \";\r\n            cin>>item;\r\n            cout<<\"Enter its priority : \";\r\n            cin>>priority;\r\n            pq.insert(item, priority);\r\n            break;\r\n        case 2:\r\n            pq.del();\r\n            break;\r\n        case 3:\r\n            pq.display();\r\n            break;\r\n        case 4:\r\n            break;\r\n        default :\r\n            cout<<\"Wrong choice\\n\";\r\n        }\r\n    }\r\n    while(choice != 4);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Data-Structures/Queue/Priority-Queue/PriorityQueue.php",
    "content": "\n<?php\n  \n  // Declare a class\n  class priorityQueue extends SplPriorityQueue {\n        \n      // Compare function to compare priority\n      // queue elements\n      public function compare($p1, $p2) {\n          if ($p1 === $p2) return 0;\n          return $p1 < $p2 ? -1 : 1;\n      }\n  }\n    \n  // Create an object of priority queue\n  $obj = new priorityQueue();\n    \n  // Insert elements into the queue\n  $obj->insert(\"p2\",2);\n  $obj->insert(\"p1\",1);\n  $obj->insert(\"p3\",3);\n  $obj->insert('p4',4);\n    \n  // Display the priority queue elements\n  // var_dump($obj);\n  echo\"Object  :\";\n  print_r($obj);\n  \n  // Display the extracted element\n  // from priority queue\n  echo\"Show extracted element according to priority  :\";\n  var_dump($obj->extract());\n  \n  // Display the number of elements\n  // in priority queue\n  echo\"Show the number of elements  :\";\n  var_dump($obj->count());\n  \n  // Use isCorrupted() function to check\n  // priority queue is in corrupted state\n  // or not\n  echo\"Show priority queue is in corrupted state or not  :\";\n  var_dump($obj->isCorrupted());\n  \n  // Use isEmpty() function to check\n  // priority queue is empty or not\n  echo\"Show priority queue is empty or not  :\";\n  var_dump($obj->isEmpty());\n  \n  ?>"
  },
  {
    "path": "Data-Structures/Queue/Priority-Queue/README.md",
    "content": "# This folder is empty.\n"
  },
  {
    "path": "Data-Structures/Queue/Priority-Queue/priorityQueue.js",
    "content": "class PriorityQueue {\n    constructor() {\n        this.queue = [];\n    }\n\n    // Insert an element into the queue\n    enqueue(element, priority) {\n        let node = [element, priority];\n\n        if(this.isEmpty()) {\n            this.queue.push(node);\n            return;\n        }\n\n        for(let i = 0; i < this.queue.length; i++) {\n            if(node[1] > this.queue[i][1]) {\n                this.queue.splice(i, 0, node);\n                return;\n            }\n        }\n\n        this.queue.push(node);\n    }\n\n    // Remove the element with the highest priority and return it\n    dequeue() {\n        return this.queue.shift();\n    }\n    \n    // Return the element with the highest priority\n    peek() {\n        return this.queue[0];\n    }\n\n    // Check if the queue is empty \n    isEmpty() {\n        return this.queue.length == 0;\n    }\n\n    // Return the number of elements in the queue\n    size() {\n        return this.queue.length;\n    }\n\n    // For debugging purposes\n    print() {\n        this.queue.forEach(element => {\n            console.log(element[0] + \"\\t\" + element[1]);\n        });\n    }\n}\n\n// Example\nqueue = new PriorityQueue();\nqueue.enqueue(5, 5);\nqueue.enqueue(\"Text\", 7);\nqueue.enqueue(true, 3);\nqueue.print();\n"
  },
  {
    "path": "Data-Structures/Queue/QueueUsingArray.c",
    "content": "#include<stdio.h>\n\nvoid enqueue(int[],int);\nvoid dequeue(int[]);\nvoid display_Queue(int[]);\n\nint Queue[],size,front=-1,rear=-1;\n\nvoid main()\n {\n     int item,choice;\n     char ch;\n     printf(\"\\n ENETR THE SIZE OF QUEUE :\");\n     scanf(\"%d\",&size);\n     printf(\"\\n AFTER DEQUEUE OPERATION\");\n                   dequeue(Queue);\n      printf(\"\\n ENTER THE ITEM :\");\n                    scanf(\"%d\",&item);\n                    enqueue(Queue,item);\n    display_Queue(Queue);\n }\n\n void enqueue(int Queue[],int temp)\n  {\n      if(rear==size-1)\n        printf(\"\\n QUEUE OVERFLOW\");\n      else\n        if(rear==-1)\n          {\n              front=rear=0;\n              Queue[rear]=temp;\n              display_Queue(Queue);\n          }\n        else\n        {\n            rear++;\n            Queue[rear]=temp;\n        }\n  }\n\n  void dequeue(int Queue[])\n   {\n       if(front==-1)\n        printf(\"\\n QUEUE UNDERFLOW\");\n       else\n       {\n         printf(\"\\n THE DELETED ITEM IS %d\",Queue[front]);\n         front++;\n        display_Queue(Queue);\n        if(front==rear)\n            front=rear=-1;\n        else\n          front++;\n       }\n   }\n\n void display_Queue(int Queue[])\n  {\n      if(front==-1)\n        return ;\n      for(int i=front;i<=rear;++i)\n          printf(Queue[i]);printf(\"<-\");\n      printf(\"%d\",Queue[rear]);\n\n  }\n"
  },
  {
    "path": "Data-Structures/Queue/QueueUsingArray.cpp",
    "content": "#include <iostream>\nusing namespace std;\nstruct node {\n   int data;\n   struct node *next;\n};\nstruct node* front = NULL;\nstruct node* rear = NULL;\nstruct node* temp;\nvoid Insert() {\n   int val;\n   cout<<\"Insert the element in queue : \"<<endl;\n   cin>>val;\n   if (rear == NULL) {\n      rear = (struct node *)malloc(sizeof(struct node));\n      rear->next = NULL;\n      rear->data = val;\n      front = rear;\n   } else {\n      temp=(struct node *)malloc(sizeof(struct node));\n      rear->next = temp;\n      temp->data = val;\n      temp->next = NULL;\n      rear = temp;\n   }\n}\nvoid Delete() {\n   temp = front;\n   if (front == NULL) {\n      cout<<\"Underflow\"<<endl;\n      return;\n   }\n   else\n   if (temp->next != NULL) {\n      temp = temp->next;\n      cout<<\"Element deleted from queue is : \"<<front->data<<endl;\n      free(front);\n      front = temp;\n   } else {\n      cout<<\"Element deleted from queue is : \"<<front->data<<endl;\n      free(front);\n      front = NULL;\n      rear = NULL;\n   }\n}\nvoid Display() {\n   temp = front;\n   if ((front == NULL) && (rear == NULL)) {\n      cout<<\"Queue is empty\"<<endl;\n      return;\n   }\n   cout<<\"Queue elements are: \";\n   while (temp != NULL) {\n      cout<<temp->data<<\" \";\n      temp = temp->next;\n   }\n   cout<<endl;\n}\nint main() {\n   int ch;\n   cout<<\"1) Insert element to queue\"<<endl;\n   cout<<\"2) Delete element from queue\"<<endl;\n   cout<<\"3) Display all the elements of queue\"<<endl;\n   cout<<\"4) Exit\"<<endl;\ndo {\n   cout<<\"Enter your choice : \"<<endl;\n   cin>>ch;\n   switch (ch) {\n      case 1: Insert();\n         break;\n      case 2: Delete();\n         break;\n      case 3: Display();\n         break;\n      case 4: cout<<\"Exit\"<<endl;\n         break;\n      default: cout<<\"Invalid choice\"<<endl;\n   }\n} while(ch!=4);\n   return 0;\n}\n"
  },
  {
    "path": "Data-Structures/Queue/QueueUsingArray.go",
    "content": "//https://play.golang.org/p/1RkOVLthUsD\n\npackage main\n\nimport (\n\t\"fmt\"\n)\n\nfunc enqueue(queue []int, ele int) []int {\n\tqueue = append(queue, ele)\n\treturn queue\n}\n\nfunc dequeue() int {\n\tdeleted_ele := queue[0]\n\tqueue = queue[1:]\n\treturn deleted_ele\n}\n\nvar queue []int\n\nfunc main() {\n\t//Enqueue\n\tqueue = enqueue(queue, 1)\n\tfmt.Println(queue)\n\tqueue = enqueue(queue, 2)\n\tfmt.Println(queue)\n\tqueue = enqueue(queue, 3)\n\tfmt.Println(queue)"
  },
  {
    "path": "Data-Structures/Queue/QueueUsingArray.java",
    "content": "package queueusingarray;\npublic class QueueUsingArray {\n   public static void main(String[] args) {\n        /* Create a queue of size 5 */\n        Queue q = new Queue(5);\n        /* Inserting elements in the queue */\n        q.queueEnque(1);\n        q.queueEnque(2);\n        q.queueEnque(3);\n        q.queueEnque(4);\n        q.queueEnque(5);\n        /* Print queue elements */\n        q.queueDisplay();\n        /* Delete elements */\n        q.queueDeque();\n        q.queueDeque();\n        /* Print queue elements */\n        q.queueDisplay();\n    }  \n}\nclass Queue{\n    private static int front,rear,size;\n    private static int queue[];\n    Queue(int c){\n        front=rear=0;\n        size=c;\n        queue = new int[size];\n    }\n    /* Function to insert an element at the rear of the queue */\n    static void queueEnque(int data){\n        /* Check whether queue is full or not */\n        if(size==rear){\n            System.out.println(\"Queue is Full\");\n        }\n        /* Insert an element at the rear */\n        else{\n            queue[rear]=data;\n            rear++;\n        }\n    }\n    /* Function to delete an element from the front of the queue */\n    static void queueDeque(){\n        /* Check if queue is empty */\n        if(front==rear){\n            System.out.println(\"Queue is Empty\");\n        }\n        /* Shift all the elements from index 2 till rear to the right by one */\n        else{\n            for(int i=0;i<rear-1;i++){\n                queue[i]=queue[i+1];\n            }\n        }\n        /* Decrement Rear */\n        rear--;\n    }\n    /* Print Queue elements */\n    static void queueDisplay(){\n        if(front==rear){\n            System.out.println(\"Queue is Empty\");\n        }\n        /* Traverse front to rear and print elements */\n        System.out.println ();\n        for(int i=front;i<rear;i++){\n            System.out.print(queue[i]+\" \");\n        }\n    }\n    /* Print front of the queue */\n    static void queuefront(){\n        if(front==rear){\n            System.out.println(\"Queue is Empty\");\n        }\n        System.out.println(\"Front Element\"+\" \"+queue[front]);\n        \n   }\n    \n}\n\nOutput: -\n1 2 3 4 5\n3 4 5\n"
  },
  {
    "path": "Data-Structures/Queue/QueueUsingArray.js",
    "content": "class Queue {\n\n  constructor(initial=[]) {\n    if (!Array.isArray(initial))\n      throw Error('You can only initialize with an array')\n    this.q = initial\n  }\n\n  put(element) {\n    this.q.push(element)\n  }\n\n  get() {\n    return this.q.shift()\n  }\n\n  print() {\n    console.log(this.q)\n  }\n\n}\n\n// Example work with Queue\nconst queue = new Queue([5, 8, 3])\n\nqueue.print()\nconsole.log(queue.get())\nqueue.print()\nqueue.put(8)\nqueue.put(0)\nqueue.print()\nqueue.get()\nqueue.get()\nqueue.print()\n"
  },
  {
    "path": "Data-Structures/Queue/QueueUsingArray.py",
    "content": "class FifoList:\n    def __init__(self):\n        self.data = {}\n        self.nextin = 0\n        self.nextout = 0\n    def append(self, data):\n        self.nextin += 1\n        self.data[self.nextin] = data\n    def pop(self):\n        self.nextout += 1\n        result = self.data[self.nextout]\n        del self.data[self.nextout]\n        return result\n    def display(self):\n        print(self.data.values())\n\n\nif __name__=='__main__':\n    f= FifoList()\n    loop= True\n    while(loop==True):\n        o=int(input('1. Insert, 2. Delete, 3. Display, 4. End '))\n        if(o==1):\n            a=int(input('Enter element: '))\n            f.append(a)\n        elif(o==2):\n            f.pop()\n            print('Element Deleted!')\n        elif(o==3):\n            f.display()\n        elif(o==4):\n            loop=False\n        else:\n            print('Invalid operation!')"
  },
  {
    "path": "Data-Structures/Queue/QueueUsingArray.rb",
    "content": "class Queue\n  include Enumerable\n  Node = Struct.new :element, :next\n  attr_reader :head, :tail, :size\n\n  def initialize(items = [])\n    @head = nil\n    @tail = nil\n    @size = 0\n\n    items.to_ary.each { |element| enqueue element }\n  end\n\n  def enqueue(element)\n    n = Node.new element, nil\n    if @tail\n      @tail.next = n\n      @tail = n\n    else\n      @head = @tail = n\n    end\n    @size += 1\n    element\n  end\n\n  def dequeue\n    return nil unless @head\n\n    n = @head\n    if @size == 1\n      clear\n      return n.element\n    end\n\n    @head = n.next\n    @size -= 1\n    n.element\n  end\n\n  def front\n    @head&.element\n  end\n\n  def back\n    @tail&.element\n  end\n\n  def empty?\n    @size.zero?\n  end\n\n  def clear\n    @head = nil\n    @tail = nil\n    @size = 0\n  end\n\n  def each\n    return unless @head\n\n    n = @head\n    while n\n      yield n.element\n      n = n.next\n    end\n  end\n\n  alias << enqueue\nend\n"
  },
  {
    "path": "Data-Structures/Queue/QueueUsingArray.swift",
    "content": "import Foundation\n\n// Generic Algorithm\nstruct Queue<Element> {\n    var array = [Element]()\n    \n    // ENQUEUE: Add an element at the end of the queue\n    mutating func enqueue(_ element: Element) {\n        array.append(element)\n    }\n   \n    // DEQUEUE: Remove the element from the beginning of the queue\n    mutating func dequeue() -> Element? {\n        return isEmpty ? nil : array.removeFirst()\n    }\n    \n    // PEEK: Returns the first element in the queue\n    func peek() -> Element? {\n        return array.first\n    }\n    \n    // Is queue empty?\n    var isEmpty: Bool {\n        return array.isEmpty\n    }\n    \n    // Number of elements in queue\n    var count: Int {\n        return array.count\n    }\n}\n\n// Use case - any type\nvar queue = Queue<String>()\nqueue.enqueue(\"Maria\")\nqueue.enqueue(\"Jim\")\nqueue.enqueue(\"Gloria\")\n\nqueue.peek()\nqueue.count\n"
  },
  {
    "path": "Data-Structures/Queue/QueueUsingLL.c",
    "content": "#include<stdio.h>\n#include<stdlib.h>\nstruct qlist\n{int info;\nstruct qlist *next;\n};\nstruct qlist *front=NULL,*rear=NULL;\nvoid enqueue(struct qlist **,struct qlist **,int );\nint dequeue(struct qlist **,struct qlist**);\nint main()\n{\nint ch,item;\nwhile(1)\n{\n\tprintf(\"\\n 1. Enqueue \\n2.Dequeue \\n3.exit\");\n\tscanf(\"%d\",&ch);\n\tswitch(ch)\n\t{\n\t\tcase 1:printf(\"\\n Enter item\");\n\t\t\tscanf(\"%d\",&item);\n\t\t\tenqueue(&front,&rear,item);\n\t\t\tbreak;\n\t\tcase 2:item=dequeue(&front ,&rear);\n\t\t\tprintf(\"\\n %d deleted\",item);\n\t\t\tbreak;\n\t\tcase 3:exit(0);\n\t\tdefault:printf(\"\\n invalid\");\n\t}\n}\n}\nvoid enqueue(struct qlist **pfront,struct qlist **prear,int item)\n{\n\t\n\tstruct qlist *newnode;\n\tnewnode=(struct qlist *)malloc(sizeof(struct qlist));\n\tnewnode->info=item;\n\tnewnode->next=NULL;\n\tif(*pfront==NULL)\n\t\t*pfront=newnode;\n\telse\n\t\t(*prear)->next=newnode;\n\t*prear=newnode;\n}\nint dequeue(struct qlist **pfront,struct qlist**prear)\n{\n\tstruct qlist *temp;\n\tint item;\n\tif(*pfront==NULL)\n\t{\n\t\tprintf(\"\\n underflow\");\n\t\treturn(-9999);\n\t}\n\ttemp=*pfront;\n\titem=(*pfront)->info;\n\tif(*pfront==*prear)\n\t{\n\t\t*pfront=NULL;\n\t\t*prear=NULL;\n\t}\n\telse\n\t\t*pfront=(*pfront)->next;\n\ttemp->next=NULL;\n\tfree(temp);\n\treturn(item);\n}\n"
  },
  {
    "path": "Data-Structures/Queue/QueueUsingLL.cpp",
    "content": "// FIFO Mechanism\n\n#include <iostream>\nusing namespace std;\n\nstruct node\n{\n    int data;\n    node *next;\n};\n\n// Function to insert values in the end in the Queue\nnode *add(node *rear, int val)\n{\n    node *x;\n    x = new node;\n    x->data = val;\n    x->next = NULL;\n    if (rear != NULL)\n        rear->next = x;\n    rear = x;\n    return rear;\n}\n\n// Function to delete values from the front in the Queue\nnode *del(node *front, int &val)\n{\n    if (front == NULL)\n    {\n        cout << \"Queue is Empty..!\" << endl; // Prints if the queue is empty\n        val = -9999;\n    }\n    else\n    {\n        node *x;\n        x = front;\n        front = front->next;\n        val = x->data; // Storing the deleted value in 'val'\n        delete x;\n    }\n    return front;\n}\n\n// Function to print values in the Queue\nvoid showqueue(node *front)\n{\n    node *ptr;\n    ptr = front;\n    if (ptr == NULL)\n    {\n        cout << \"Queue is empty..!\" << endl; // Prints if the queue is empty\n    }\n    else\n    {\n        cout << \"Queue is \" << endl;\n        while (ptr != NULL)\n        {\n            cout << ptr->data << \"\\t\";\n            ptr = ptr->next;\n        }\n        cout << endl;\n    }\n}\n\nint main()\n{\n    int choice, val;\n    node *front, *rear;\n    front = rear = NULL;\n\n    // Menu Driven Program\n    do\n    {\n        cout << \"\\nMain Menu\\n\"\n             << \"1. Insert\\n\"\n             << \"2. Delete\\n\"\n             << \"3. Show\\n\"\n             << \"4. Exit\\n\"\n             << \"Enter your choice: \";\n        cin >> choice;\n        switch (choice)\n        {\n        case 1:\n            cout << \"Enter value to be added: \";\n            cin >> val;\n            rear = add(rear, val);\n            if (front == NULL)\n                front = rear;\n            break;\n        case 2:\n            front = del(front, val);\n            if (val != -9999)\n                cout << \"The deleted value is: \" << val << endl;\n            if (front == NULL)\n                rear = front;\n            break;\n        case 3:\n            showqueue(front);\n            break;\n        default:\n            break;\n        }\n    } while (choice != 4); // Program exits whenever the user enters no. 4\n    return 0;\n}\n\n// Author - Ankit Goel"
  },
  {
    "path": "Data-Structures/Queue/QueueUsingLL.cs",
    "content": "using System;\nusing System.Collections;\nusing System.Collections.Generic;\n\nnamespace DataStructures\n{\n    class SimpleQueue\n    {\n        private LinkedList<int> queue = new LinkedList<int>();\n\n        public void Enqueue(int val) {\n            queue.AddLast(val);\n        }\n\n        public int Dequeue() {\n            int ret = queue.First.Value;\n            queue.RemoveFirst();\n            return ret;\n        }\n        public int Peek() {\n            return queue.First.Value;\n        }\n\n        public int Size() {\n            return queue.Count;\n        }\n\n        public bool IsEmpty() {\n            return queue.Count == 0;\n        }\n\n        public void Print()\n        {\n            foreach (int i in queue) Console.Write(i + \" \");\n        }\n\n        static void Main(string[] args)\n        {\n            SimpleQueue myQueue = new SimpleQueue();\n\n            myQueue.Enqueue(55);\n            myQueue.Enqueue(33);\n            myQueue.Enqueue(12);\n            myQueue.Enqueue(77);\n            myQueue.Enqueue(25);\n\n            Console.WriteLine(\"Current queue: \");\n            myQueue.Print();\n            Console.WriteLine();\n\n            int n = myQueue.Dequeue();\n            Console.WriteLine(\"The dequeued value: {0}\", n);\n            n = myQueue.Dequeue();\n            Console.WriteLine(\"The dequeued value: {0}\", n);\n            Console.WriteLine(\"Current queue: \");\n             myQueue.Print();\n            Console.WriteLine();\n        }\n    }\n}\n"
  },
  {
    "path": "Data-Structures/Queue/QueueUsingLL.php",
    "content": "\n<?php \n//Author KevinMathewTh\n\n//FIFO\nclass Node{\n    \n  public $value;\n  public $next;\n\n}\n\n//Queue class that store Node in queue\n\nclass Queue{\n    private $front = null;\n    private $back = null; \n\n    //Check if empty\n    public function isEmpty(){\n    return $this->front == null;\n    }\n\n    //Enqueue function\n\npublic function enqueue($value){\n    $oldBack = $this->back;\n    $this->back = new Node(); \n    $this->back->value = $value;\n    if($this->isEmpty()){\n    $this->front = $this->back; \n    }else{\n    $oldBack->next = $this->back;\n    }\n}\n\n// Dequeue Function\n\npublic function dequeue(){\nif($this->isEmpty()){\n    return null; \n    }\n    $removedValue = $this->front->value;\n    $this->front = $this->front->next;\n    return $removedValue;\n}\n\n\n// Show queue Function\n\npublic function show(){\n\n    $current = $this->front;\n    $print=\"\";\n    while($current != NULL)\n    {\n        $print .=$current->value.\",\";\n        $current = $current->next;\n    }\n    echo $print;\n    }\n}\n\n\n//Create a New Queue\n\n$queue = new Queue();\n\n\n//Inserting 1 , 2 , 3 , 4\n\n$queue->enqueue(1);\n$queue->enqueue(2);\n$queue->enqueue(3);\n$queue->enqueue(4);\n\n$queue->show();\n\necho \"<br>\";\n\n//DeQueue First Element\n\n$queue->dequeue().\"\\n\";\n\n//Show \n$queue->show();\n\n?>\n\n"
  },
  {
    "path": "Data-Structures/Queue/QueueUsingStacks.cpp",
    "content": "// Program to implement Queue using Stack in C.  \n#include<stdio.h>  \n#define N 5  \nint stack1[5], stack2[5]; // declaration of two stacks  \n// declaration of top variables.  \nint top1=-1, top2=-1;   \nint count=0;  \n// inserting the elements in stack1.  \nvoid push1(int data)  \n{  \n// Condition to check whether the stack1 is full or not.    \n if(top1==N-1)  \n{  \n   printf(\"\\n Stack is overflow...\");  \n}  \nelse  \n{  \n   top1++;   // Incrementing the value of top1  \n   stack1[top1]=data;  // pushing the data into stack1  \n}  \n}  \n// Removing the elements from the stack1.  \nint pop1()  \n{  \n// Condition to check whether the stack1 is empty or not.    \nif(top1==-1)  \n{  \n   printf(\"\\nStack is empty..\");  \n}  \nelse  \n{  \n   int a=stack1[top1];  // Assigning the topmost value of stack1 to 'a' variable.   \n   top1--;  // decrementing the value of top1.  \n   return a;   \n}  \n}   \n// pushing the data into the stack2.  \nvoid push2(int x)  \n{  \n//  Condition to check whether the stack2 is full or not  \nif(top2==N-1)  \n{  \n   printf(\"\\nStack is full..\");  \n}  \nelse  \n{  \n    top2++;   // incrementing the value of top2.  \n    stack2[top2]=x;  // assigning the 'x' value to the Stack2  \n  \n}  \n}   \n// Removing the elements from the Stack2  \nint pop2()  \n{  \n   int element = stack2[top2];  // assigning the topmost value to element  \n   top2--;  // decrement the value of top2  \n   return element;  \n}   \nvoid enqueue(int x)  \n{  \n    push1(x);  \n    count++;  \n}  \nvoid dequeue()  \n{  \n   if((top1==-1) && (top2==-1))  \n{  \n   printf(\"\\nQueue is empty\");  \n}  \nelse  \n{  \n  for(int i=0;i<count;i++)  \n  {  \n     int element = pop1();  \n     push2(element);  \n  }  \nint b= pop2();  \nprintf(\"\\nThe dequeued element is %d\", b);  \nprintf(\"\\n\");  \ncount--;  \nfor(int i=0;i<count;i++)  \n{  \n   int a = pop2();  \n   push1(a);   \n}  \n}}   \nvoid display()  \n{  \n   for(int i=0;i<=top1;i++)  \n  {  \n     printf(\"%d , \", stack1[i]);  \n  }  \n}  \nvoid main()  \n{  \n   enqueue(10);  \n   enqueue(20);  \n   enqueue(30);  \n   dequeue();  \n   enqueue(40);  \n   display();  \n}  "
  },
  {
    "path": "Data-Structures/Queue/README.md",
    "content": "# Queue\n* Queue is a linear data structure that follows the FIFO (First-In-First-Out) policy.Meaning, one end is always used to insert data and the other is used to remove data.\n\n# Sub-Topics\n* [Priority-Queue](Priority-Queue/)\n* [Deque](Deque/)\n* [Circular-Queue](Circular-Queue/)\n\n# Methods\n\n| Operation | Description \n|:--|:--\n|Enqueue | Add a new element  \n|Dequeue | Removes an element \n|Front | Get the fist element \n|Rear | Get the the last element \n|Size | Returns the total number of elements \n\n# Time Complexity\n\n| Operation | Complexity \n|:--|:--\n|Access | O(n) \n|Search | O(n) \n|Insertion | O(1) \n|Deletion | O(1) \n\n\n# Implementation\n\n## Using Linked List\n\n| Language | View | Code\n|:--: |:--: |:--:\n| c++ | [Github](https://github.com/ahampriyanshu/algo_ds_101/blob/main/Data-Structures/Queue/QueueUsingLL.cpp) | [Raw](QueueUsingLL.cpp)\n| c | [Github](https://github.com/ahampriyanshu/algo_ds_101/blob/main/Data-Structures/Queue/QueueUsingLL.c) | [Raw](QueueUsingLL.c)\n| cs | [Github](https://github.com/ahampriyanshu/algo_ds_101/blob/main/Data-Structures/Queue/QueueUsingLL.cs) | [Raw](QueueUsingLL.cs)\n| php | [Github](https://github.com/ahampriyanshu/algo_ds_101/blob/main/Data-Structures/Queue/QueueUsingLL.cpp) | [Raw](QueueUsingLL.php)\n\n## Using Array\n\n| Language |  | Code \n|:--: |:--: |:--:\n| c++ | [Github](https://github.com/ahampriyanshu/algo_ds_101/blob/main/Data-Structures/Queue/QueueUsingArray.cpp) | [Raw](QueueUsingArray.cpp)\n| c | [Github](https://github.com/ahampriyanshu/algo_ds_101/blob/main/Data-Structures/Queue/QueueUsingArray.c) | [Raw](QueueUsingArray.c)\n| java | [Github](https://github.com/ahampriyanshu/algo_ds_101/blob/main/Data-Structures/Queue/QueueUsingArray.java) | [Raw](QueueUsingArray.java)\n| js | [Github](https://github.com/ahampriyanshu/algo_ds_101/blob/main/Data-Structures/Queue/QueueUsingArray.js) | [Raw](QueueUsingArray.js)\n| py | [Github](https://github.com/ahampriyanshu/algo_ds_101/blob/main/Data-Structures/Queue/QueueUsingArray.py) | [Raw](QueueUsingArray.py)\n| cs | [Github](https://github.com/ahampriyanshu/algo_ds_101/blob/main/Data-Structures/Queue/QueueUsingArray.cs) | [Raw](QueueUsingArray.cs)\n| rb | [Github](https://github.com/ahampriyanshu/algo_ds_101/blob/main/Data-Structures/Queue/QueueUsingArray.rb) | [Raw](QueueUsingArray.rb)\n| php | [Github](https://github.com/ahampriyanshu/algo_ds_101/blob/main/Data-Structures/Queue/QueueUsingArray.php) | [Raw](QueueUsingArray.php)\n| go | [Github](https://github.com/ahampriyanshu/algo_ds_101/blob/main/Data-Structures/Queue/QueueUsingArray.go) | [Raw](QueueUsingArray.go)\n| scala | [Github](https://github.com/ahampriyanshu/algo_ds_101/blob/main/Data-Structures/Queue/QueueUsingArray.scala) | [Raw](QueueUsingArray.scala)\n| swift | [Github](https://github.com/ahampriyanshu/algo_ds_101/blob/main/Data-Structures/Queue/QueueUsingArray.swift) | [Raw](QueueUsingArray.swift)"
  },
  {
    "path": "Data-Structures/README.md",
    "content": "# Index\n\n* [Arrays](Arrays/)\n* [HashSet](HashSet/)   \n* [LinkedList](LinkedList/) \n* [HashMap](HashMap/) \n* [Queue](Queue/) \n* [Stacks](Stacks/) \n* [Graph](Graph/)\n* [Tree](Tree/)\n* [Heap](Heap/)"
  },
  {
    "path": "Data-Structures/Stack/Infix_to_prefix_postfix.cpp",
    "content": "/*\r\n\tAuthor: Sachin19k\r\n*/\r\n\r\n/*Problem Statement :\r\n\r\nImplement stack as an abstract data type using singly linked list and use this ADT for conversion of infix expression to postfix, prefix and evaluation of postfix and prefix expression.\r\n\r\nSample Input for Testing:\r\n1.\t(a+b)*c\r\n2.\t(a+b)/(c*d)\r\n3.\t(a+(b*c))/(c-(d*b))\r\n4.\ta*b/(c-d)+e*f\r\n5.\t(a-z)*(b+c-d*e)*f   */\r\n\r\n#include<iostream>\r\n#include<string.h>\r\n#include<ctype.h>\r\n\r\nusing namespace std;\r\n\r\nstruct node\r\n{\r\n\tchar data;\r\n\tnode *next;\r\n};\r\n\r\nstruct eval_node\r\n{\r\n\tint data;\r\n\teval_node *next;\r\n};\r\n\r\nclass stack\r\n{\r\n\tnode *top;\r\n\r\npublic:\r\n\tstack()\r\n\t{\r\n\t\ttop=NULL;\r\n\t}\r\n\tvoid push(char a);\r\n\tchar pop();\r\n};\r\n\r\nclass eval_stack\r\n{\r\n\teval_node *top;\r\n\r\npublic:\r\n\teval_stack()\r\n\t{\r\n\t\ttop=NULL;\r\n\t}\r\n\tvoid push(int a);\r\n\r\n\tint pop();\r\n};\r\n\r\nvoid stack::push(char a)\r\n{\r\n\tnode *newnode=new node;\r\n\tnewnode->data=a;\r\n\tnewnode->next=top;\r\n\ttop=newnode;\r\n}\r\n\r\nchar stack::pop()\r\n{\r\n\tif(top==NULL)\r\n\t{\r\n\t\tcout<<\"\\n UNDERFLOW!!\";\r\n\t\treturn '%';\r\n\t}\r\n\tchar a=top->data;\r\n\tnode *ptr=top;\r\n\ttop=top->next;\r\n\tdelete ptr;\r\n\treturn a;\r\n}\r\n\r\nvoid eval_stack::push(int a)\r\n{\r\n\teval_node *temp=new eval_node;\r\n\ttemp->data=a;\r\n\ttemp->next=top;\r\n\ttop=temp;\r\n}\r\n\r\nint eval_stack::pop()\r\n{\r\n\tif(top==NULL)\r\n\t{\r\n\t\tcout<<\"\\n UNDERFLOW!!\";\r\n\t\treturn '%';\r\n\t}\r\n\tint a=top->data;\r\n\teval_node *ptr=top;\r\n\ttop=top->next;\r\n\tdelete ptr;\r\n\treturn a;\r\n}\r\n\r\nvoid disp(char b[])\r\n{\r\n\tcout<<\"[\";\r\n\tfor(int i=0;b[i]!='\\0';i++)\r\n\t{\r\n\t\tcout<<b[i]<<\" \";\r\n\t}\r\n\tcout<<\"]\";\r\n}\r\n\r\nvoid rev(char a[],int n)\r\n{\r\n\tchar p;\r\n\tfor(int i=0;i<n/2;i++)\r\n\t{\r\n\t\tp=a[i];\r\n\t\ta[i]=a[n-1-i];\r\n\t\ta[n-i-1]=p;\r\n\t}\r\n\r\n\tfor(int i=0;i<n;i++)\r\n\t{\r\n\t\tif(a[i]=='(')\r\n\t\t{\r\n\t\t\ta[i]=')';\r\n\t\t}\r\n\t\telse if(a[i]==')')\r\n\t\t{\r\n\t\t\ta[i]='(';\r\n\t\t}\r\n\t}\r\n\r\n}\r\n\r\nint seq(char a)\r\n{\r\n\tif(a=='(')\r\n\t\treturn 0;\r\n\telse if(a=='-')\r\n\t\treturn 1;\r\n\telse if(a=='+')\r\n\t\treturn 2;\r\n\telse if(a=='/')\r\n\t\treturn 3;\r\n\telse\r\n\t\treturn 4;\r\n}\r\n\r\nint result(int a1,int a2,char op)\r\n{\r\n\tif(op=='+')\r\n\t\treturn (a1+a2);\r\n\telse if(op=='-')\r\n\t\treturn (a1-a2);\r\n\telse if(op=='*')\r\n\t\treturn (a1*a2);\r\n\telse\r\n\t\treturn (a1/a2);\r\n}\r\n\r\nvoid in_pos(char a[],char b[])\r\n{\r\n\tstack s;\r\n\tchar a1,a2;\r\n\tint b1,b2,top=-1,i=0,j=0;\r\n\twhile(a[i]!='\\0')\r\n\t{\r\n\t\tif(a[i]=='(')\r\n\t\t{\r\n\t\t\ts.push(a[i]);\r\n\t\t\ttop++;\r\n\t\t\ti++;\r\n\t\t}\r\n\r\n\t\telse if(isalnum(a[i]))\r\n\t\t{\r\n\t\t\tb[j]=a[i];\r\n\t\t\ti++;\r\n\t\t\tj++;\r\n\t\t}\r\n\r\n\t\telse if(a[i]=='-' || a[i]=='+' || a[i]=='/' || a[i]=='*')\r\n\t\t{\r\n\t\t\tif(top==-1)\r\n\t\t\t{\r\n\t\t\t\ts.push(a[i]);\r\n\t\t\t\ttop++;\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\ta1=s.pop();\r\n\t\t\t\ttop--;\r\n\r\n\t\t\t\tif(a1=='-' || a1=='+' || a1=='/' || a1=='*')\r\n\t\t\t\t{\r\n\t\t\t\t\ta2=a[i];\r\n\t\t\t\t\tb1=seq(a1);\r\n\t\t\t\t\tb2=seq(a2);\r\n\t\t\t\t\tif(b1>b2)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tb[j]=a1;\r\n\t\t\t\t\t\tj++;\r\n\t\t\t\t\t\ts.push(a2);\r\n\t\t\t\t\t\ttop++;\r\n\t\t\t\t\t}\r\n\t\t\t\t\telse\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\ts.push(a1);\r\n\t\t\t\t\t\ttop++;\r\n\t\t\t\t\t\ts.push(a2);\r\n\t\t\t\t\t\ttop++;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\ti++;\r\n\t\t}\r\n\t\telse if(a[i]==')')\r\n\t\t{\r\n\t\t\ta1=s.pop();\r\n\t\t\ttop--;\r\n\t\t\twhile(a1!='(')\r\n\t\t\t{\r\n\t\t\t\tb[j]=a1;\r\n\t\t\t\tj++;\r\n\t\t\t\ta1=s.pop();\r\n\t\t\t\ttop--;\r\n\t\t\t}\r\n\t\t\ti++;\r\n\t\t}\r\n\t}\r\n\r\n\twhile(top!=-1)\r\n\t{\r\n\t\ta1=s.pop();\r\n\t\ttop--;\r\n\t\tb[j]=a1;\r\n\t\tj++;\r\n\t}\r\n\tb[j]='\\0';\r\n}\r\n\r\nvoid in_pre(char a[],char b[])\r\n{\r\n\tint n=strlen(a);\r\n\trev(a,n);\r\n\tin_pos(a,b);\r\n\tn=strlen(b);\r\n\trev(b,n);\r\n}\r\n\r\nint eval_pos(char a[])\r\n{\r\n\teval_stack s;\r\n\tint op1,op2,top=-1,i=0,sol;\r\n\r\n\twhile(a[i]!='\\0')\r\n\t{\r\n\t\tif(isalnum(a[i]))\r\n\t\t{\r\n\t\t\ts.push(int(a[i])-48);\r\n\t\t\ttop++;\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\top2=s.pop();\r\n\t\t\ttop--;\r\n\t\t\top1=s.pop();\r\n\t\t\ttop--;\r\n\t\t\tsol=result(op1,op2,a[i]);\r\n\t\t\ts.push(sol);\r\n\t\t\ttop++;\r\n\t\t}\r\n\t\ti++;\r\n\t}\r\n\treturn sol;\r\n}\r\n\r\nint eval_pre(char a[])\r\n{\r\n\teval_stack s;\r\n\tint op1,op2,top=-1,sol;\r\n\tint i=strlen(a)-1;\r\n\twhile(i>=0)\r\n\t{\r\n\t\tif(isalnum(a[i]))\r\n\t\t{\r\n\t\t\ts.push(int(a[i])-48);\r\n\t\t\ttop++;\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\top1=s.pop();\r\n\t\t\ttop--;\r\n\t\t\top2=s.pop();\r\n\t\t\ttop--;\r\n\t\t\tsol=result(op1,op2,a[i]);\r\n\t\t\ts.push(sol);\r\n\t\t\ttop++;\r\n\t\t}\r\n\t\ti--;\r\n\t}\r\n\treturn sol;\r\n}\r\n int main()\r\n {\r\n \tchar ip[20],op[20];\r\n \tint in,ch;\r\n\r\n \tcout<<\"----MENU----\\n\";\r\n \tcout<<\"[1] INFIX TO POSTFIX\\n\";\r\n \tcout<<\"[2] INFIX TO PREFIX\\n\";\r\n \tcout<<\"[3] EVALUATION OF POSTFIX\\n\";\r\n \tcout<<\"[4] EVALUATION OF PREFIX\\n\\n\";\r\n\r\n \tdo\r\n \t{\r\n \t\tcout<<\"**** Enter your choice ****\\n\\n\";\r\n \t\tcin>>ch;\r\n \t\tif(ch==1)\r\n \t\t{\r\n \t\t\tcout<<\"Enter Infix expression: \\n\";\r\n \t\t\tcin>>ip;\r\n \t\t\tin_pos(ip,op);\r\n \t\t\tcout<<\"Hence, Postfix Expression is: \\n\";\r\n \t\t\tdisp(op);\r\n \t\t}\r\n \t\telse if(ch==2)\r\n \t\t{\r\n \t\t\tcout<<\"Enter Infix expression: \\n\";\r\n \t\t\tcin>>ip;\r\n \t\t\tin_pre(ip,op);\r\n \t\t\tcout<<\"Hence, Prefix Expression is: \\n\";\r\n \t\t\tdisp(op);\r\n \t\t}\r\n \t\telse if(ch==3)\r\n \t\t{\r\n \t\t\tcout<<\"Enter Postfix expression: \\n\";\r\n \t\t\tcin>>ip;\r\n \t\t\tint s1=eval_pos(ip);\r\n \t\t\tcout<<\"Evaluating Postfix Expression, we get \\n\";\r\n \t\t\tcout<<s1;\r\n \t\t}\r\n \t\telse if(ch==4)\r\n \t\t{\r\n \t\t\tcout<<\"Enter Prefix expression: \\n\";\r\n \t\t\tcin>>ip;\r\n \t\t\tint s2=eval_pre(ip);\r\n \t\t\tcout<<\"Evaluating Prefix Expression, we get \\n\";\r\n \t\t\tcout<<s2;\r\n \t\t}\r\n \t\telse\r\n \t\t{\r\n \t\t\tcout<<\"Please enter Valid input!!\\n\";\r\n \t\t}\r\n \t\tcout<<\"\\n Do you want to continue (Enter 1 if yes)\\n\";\r\n \t\tcin>>in;\r\n \t}\r\n \twhile(in==1);\r\n \t{\r\n \t\tcout<<\"\\n----Operation Completed!! ThankYou----\\n\";\r\n \t\treturn 0;\r\n \t}\r\n }\r\n\r\n/*\r\n---------------------------------------------------------------------------------------------------------------------------\r\nOUTPUT : \r\n\r\n----MENU----\r\n[1] INFIX TO POSTFIX\r\n[2] INFIX TO PREFIX\r\n[3] EVALUATION OF POSTFIX\r\n[4] EVALUATION OF PREFIX\r\n\r\n**** Enter your choice ****\r\n\r\n1\r\nEnter Infix expression: \r\n(a+(b*c))/(c-(d*b))\r\nHence, Postfix Expression is: \r\n[a b c * + c d b * - / ]\r\n----Operation Completed!! ThankYou----\r\n*/"
  },
  {
    "path": "Data-Structures/Stack/README.md",
    "content": "## Stack\n\nIn science of science, a pile is an ordered set of non-qualifying items that can be inserted and from which they can be disposed of at a single end - the top of the pile.\nDue to its form of operation, this data structure also has an alternative name - LIFO (Last-In, Fist-Out).The two changes that can be made to a stack are given special names.\n * When an item is added to a stack, it is \"stacked\" on top of the stack.\n * and when an item is removed, it is \"unstacked\".\n"
  },
  {
    "path": "Data-Structures/Stack/StackUsingArray.c",
    "content": "#include <stdio.h>\n\n#define max 100\nint st[100];\nint top = -1;\n\n// This function will add an element in the top of the stack.\nvoid push() {\n    int ele;\n    top++;\n    if(top >= max) {\n        printf(\"Stack is overflow\\n\");\n        return;\n    }\n    printf(\"Enter any one element to push in stack: \");\n    scanf(\"%d\", &ele);\n    st[top] = ele;\n    printf(\"%d pushed successfully in stack.\\n\", ele);\n}\n\n// This function will remove an element from the top of the stack.\nvoid pop() {\n    int ele;\n    if(top < 0) {\n        printf(\"Stack is underflow\\n\");\n        return;\n    }\n    ele = st[top];\n    top--;\n    printf(\"%d has been deleted from the stack.\\n\", ele);\n}\n\n// This function will remove all the elements from stack.\nvoid clear() {\n    top = -1;\n    printf(\"Stack is cleared.\\n\");\n}\n\n// This function will check if stack is empty or not.\nvoid isEmpty() {\n    if(top < 0) {\n        printf(\"Stack is empty.\\n\");\n    } else {\n        printf(\"Stack is not empty.\\n\");\n    }\n}\n\n// This function will show the top element in the stack.\nvoid topmost() {\n    if(top < 0) {\n        printf(\"Stack is underflow\\n\");\n        return;\n    }\n    printf(\"Topmost element in stack is %d\\n\", st[top]);\n}\n\n// This function will show the occurence of any element in the stack.\nvoid seek() {\n    int ele, count = 0;\n    if(top < 0) {\n        printf(\"Stack is underflow\\n\");\n        return;\n    }\n    printf(\"Enter any element to check the occurence in the stack: \");\n    scanf(\"%d\", &ele);\n    for(int i = 0; i <= top; ++i) {\n        if(st[i] == ele) {\n            count++;\n        }\n    }\n    printf(\"%d occurs %d times in the stack.\\n\", ele, count);\n}\n\n// This function will show all the elements in the stack.\nvoid display() {\n    if(top < 0) {\n        printf(\"Stack is underflow.\\n\");\n        return;\n    }\n    for(int i = 0; i <= top; ++i) {\n        printf(\"%d \", st[i]);\n    }\n    printf(\"\\n\");\n}\n\nvoid instructions() {\n    printf(\"You can add upto 100 elements in this Stack.\\n\");\n    printf(\"Enter 1 to push the element.\\n\");\n    printf(\"Enter 2 to pop the element.\\n\");\n    printf(\"Enter 3 to display all the elements.\\n\");\n    printf(\"Enter 4 to see the topmost element in stack.\\n\");\n    printf(\"Enter 5 to search the occurence of any element in the stack.\\n\");\n    printf(\"Enter 6 to check if stack is empty or not.\\n\");\n    printf(\"Enter 7 to clear the stack.\\n\");\n    printf(\"Enter 8 to exit.\\n\");\n}\n\nint main() {\n    int choice;\n    instructions();\n    do {\n        printf(\"\\nEnter your choice of operation: \");\n        scanf(\"%d\", &choice);\n        switch(choice) {\n            case 1: push();\n                break;\n            case 2: pop();\n                break;\n            case 3: display();\n                break;\n            case 4: topmost();\n                break;\n            case 5: seek();\n                break;\n            case 6: isEmpty();\n                break;\n            case 7: clear();\n                break;\n            case 8: return 0;\n            default:\n                printf(\"Wrong input. Read instructions to use stack efficiently.\\n\\n\");\n                instructions();\n        }\n    } while(1); // Program will run until user choose 8.\n    return 0;\n}\n"
  },
  {
    "path": "Data-Structures/Stack/StackUsingArray.cpp",
    "content": "#include<iostream>\nusing namespace std;\n\nclass stack{\n    private:\n        int top;\n        int j;\n        int arr[];\n\n    public:\n        stack(){\n            // int j;\n            top = -1;\n            cout << \"What stack size you want? \" << endl;\n            cin >> j;\n            for (int i = 0; i < j; i++)\n            {\n                arr[i] = 0;\n            }\n        }\n\n        bool isEmpty(){\n            if (top==-1)\n            {\n                return true;\n            }\n            else\n            {\n                return false;\n            }\n        } \n\n        bool isFull(){\n            if (top==(j-1))\n            {\n                return true;\n            }\n            else\n            {\n               return false;\n            }\n        }\n\n        void push(int i){\n            if (isFull())\n            {\n                cout<<\"Stack is Overflown\"<<endl;\n            }\n            else\n            {\n                top++;\n                arr[top] = i;\n            }\n        }\n\n        int pop(){\n            if (isEmpty())\n            {\n                cout << \"Stack is Underflown\" << endl;\n                return 0;\n            }\n            else\n            {\n                int a = arr[top];\n                arr[top] = 0;\n                top--;\n                return a;\n            }\n        }\n\n        int count(){\n            return top+1;\n        }\n\n        int peek(int i){\n            return arr[i];\n        }\n\n        void change(int val, int pos){\n            arr[pos] = val;\n            cout << \"Value changed at \" << pos << \" position to \" << val << endl;\n        }\n\n        void display(){\n            cout << \"All values in the stack are:\" << endl;\n            for (int i = (j-1); i >= 0; i--)\n            {\n                cout << i + 1 << \".  \" << arr[i]<<endl;\n            }\n        }\n\n};\n\nint main()\n{\n    stack s1;\n    int opt, pos, val;\n    system(\"clear\");\n    do\n    {\n        // system(\"clear\");\n        cout << \"Select Operation's number to perform\" << endl;\n        cout << \"0 EXIT\" << endl;\n        cout << \"1 PUSH\" << endl;\n        cout << \"2 POP\" << endl;\n        cout << \"3 CHECK EMPTY\" << endl;\n        cout << \"4 CHECK FULL\" << endl;\n        cout << \"5 PEEK at position\" << endl;\n        cout << \"6 COUNT\" << endl;\n        cout << \"7 CHANGE\" << endl;\n        cout << \"8 DISPLAY\" << endl;\n        cout << \"9 CLEAR SCREEN\" << endl<<endl;\n\n        cin >> opt;\n\n        switch (opt)\n        {\n        case 1:\n            system(\"clear\");\n            cout << \"Enter the number to push to the stack\" << endl;\n            cin >> val;\n            s1.push(val);\n            cout << endl<< endl<< endl;\n            break;\n        \n        case 2:\n            system(\"clear\");\n            cout << \"Pop done!\" << endl;\n            cout<< s1.pop()<<\" removed\"<<endl;\n            cout << endl<< endl<< endl;\n            break;\n\n        case 3:\n            system(\"clear\");\n            if (s1.isEmpty())\n            {\n                cout << \"Stack is underflown\" << endl;\n            }\n            else\n            {\n                cout << \"Stack is not empty\" << endl;\n            }\n            cout << endl<< endl<< endl;\n            break;\n\n        case 4:\n            system(\"clear\");\n             if (s1.isFull())\n            {\n                cout << \"Stack is overflown\" << endl;\n            }\n            else\n            {\n                cout << \"Stack is not full\" << endl;\n            }\n            cout << endl<< endl<< endl;\n            break;\n        \n        case 5:\n            system(\"clear\");\n            cout << \"Enter position number to peek at\" << endl;\n            cin >> pos;\n            cout << s1.peek(pos) << \" is at \" << pos<< endl;\n            cout << endl<< endl<< endl;\n            break;\n\n        case 6:\n            system(\"clear\");    \n            cout << s1.count() <<endl;\n            cout << endl<< endl<< endl;\n            break;\n\n        case 7:\n            system(\"clear\");\n            cout << \"Enter position number to make the change at\" << endl;\n            cin >> pos;\n            cout << \"Enter the number \" << endl;\n            cin >> val;\n            s1.change(val,pos) ;\n            cout << endl<< endl<< endl;\n            break;\n\n        case 8:\n            system(\"clear\");\n            s1.display();\n            cout << endl<< endl<< endl;\n            break;\n\n        case 9:\n            system(\"clear\");\n            break;\n\n        default:\n            system(\"clear\");\n            cout << \"Please enter a valid number \"<<endl;\n            break;\n        }\n\n        // system(\"clear\");\n    } while (opt != 0);\n\n    return 0;\n}\n"
  },
  {
    "path": "Data-Structures/Stack/StackUsingArray.cs",
    "content": "using System;\nusing System.Collections.Generic;\n\nnamespace Stack\n{\n  class Program\n  {\n    static void Main(string[] args)\n    {\n      Stack stack = new Stack();\n      Console.WriteLine(stack.isEmpty());\n      for (int i = 1; i < 6; i++)\n      {\n        stack.Push(i);\n      }\n      Console.WriteLine(stack.isEmpty());\n      stack.Peek();\n      for (int i = 1; i < 6; i++)\n      {\n        stack.Pop();\n      }\n      Console.WriteLine(stack.isEmpty());\n    }\n  }\n\n  class Stack\n  {\n    List<int> stack = new List<int>();\n    int top;\n\n    public Stack()\n    {\n      top = -1;\n    }\n\n    public void Push(int value)\n    {\n      stack.Add(value);\n      top++;\n    }\n\n    public void Pop()\n    {\n      if (isEmpty())\n      {\n        Console.WriteLine(\"Stack is empty!\");\n      }\n      int value = stack[top];\n      stack.RemoveAt(top);\n      top--;\n      Console.WriteLine($\"The value {value} was removed of stack\");\n    }\n\n    public void Peek()\n    {\n      if (isEmpty())\n      {\n        Console.WriteLine(\"Stack is empty!\");\n      }\n      Console.WriteLine($\"The topmost element of stack is {stack[top]}\");\n    }\n\n    public bool isEmpty()\n    {\n      return top == -1;\n    }\n  }\n}\n"
  },
  {
    "path": "Data-Structures/Stack/StackUsingArray.go",
    "content": "package main\nimport (\n\t\"fmt\"\n)\n\ntype stack []int\n\nfunc (s stack) push(v int) stack {\n    return append(s, v)\n}\n\nfunc (s stack) pop() (stack, int) {\n    l := len(s)\n   { return  s[:l-1], s[l-1]}\n}\n\nfunc (s stack) size() int {\n    return len(s)\n}\n\nfunc main(){\n    s := make(stack,0)\n    s = s.push(101)\n    s = s.push(203)\n    s = s.push(399)\n    s = s.push(501)\n    s, p := s.pop()\n    fmt.Println(p)\n    fmt.Println( s.size())\n\t\n\n}\n"
  },
  {
    "path": "Data-Structures/Stack/StackUsingArray.hs",
    "content": "module Stack where\n\nclass Stack s where\n  push :: a -> s a -> s a\n  pop :: s a -> (Maybe a, s a)\n  top :: s a -> Maybe a\n  size :: s a -> Int\n  isEmpty :: s a -> Bool\n  empty :: s a\n\nnewtype ListStack a = ListStack [a] deriving (Show)\n\ninstance Stack ListStack where\n  push x (ListStack st) = ListStack (x : st)\n\n  pop (ListStack []) = (Nothing, empty)\n  pop (ListStack (x:xs)) = (Just x, ListStack xs)\n\n  top (ListStack []) = Nothing\n  top (ListStack st) = Just (head st)\n\n  size (ListStack st) = length st\n\n  isEmpty (ListStack []) = True\n  isEmpty _ = False\n\n  empty = ListStack []\n"
  },
  {
    "path": "Data-Structures/Stack/StackUsingArray.java",
    "content": "import java.util.Scanner;  \nclass Stack   \n{  \n    int top;   \n    int maxsize = 10;  \n    int[] arr = new int[maxsize];  \n      \n      \n    boolean isEmpty()  \n    { \n        // If top is negative then stack is empty because  stack was intialized with top=-1 \n        return (top < 0);  \n    }  \n    Stack()  \n    {  \n        top = -1;  \n    }  \n    boolean push (Scanner sc)  \n    {  \n        if(top == maxsize-1)  \n        {  \n            // if top element index becomes equal to size of array -1 then it becomes overflow\n            System.out.println(\"Overflow !!\");  \n            return false;  \n        }  \n        else   \n        {  \n            System.out.println(\"Enter Value\");  \n            int v = sc.nextInt();  \n            top++;  \n            arr[top]=v;  \n            System.out.println(\"Item pushed\");  \n            return true;  \n        }  \n    }  \n    boolean pop ()  \n    {  \n        if (top == -1)  \n        {  \n            // If top=-1 that means no element is present in the array \n            System.out.println(\"Underflow !!\");  \n            return false;  \n        }  \n        else   \n        {  \n            top --;   \n            System.out.println(\"Element popped\");  \n            return true;  \n        }  \n    }  \n    void display ()  \n    {  \n        System.out.println(\"Printing stack elements .....\");  \n        // Iterating over the array from top element to 0 index element because it is stack \n        for(int i = top; i>=0;i--)  \n        {  \n            System.out.println(arr[i]);  \n        }  \n    }  \n}  \npublic class Stack_Operations {  \npublic static void main(String[] args) {  \n    int ch=0;  \n    Scanner sc = new Scanner(System.in);  \n    Stack s = new Stack();  \n    System.out.println(\"*********Stack using array*********\\n\");  \n    while(ch != 4)  \n    {  \n        System.out.println(\"\\nChose one from the below options...\\n\");  \n        System.out.println(\"\\n1.Push\\n2.Pop\\n3.Show\\n4.Exit\");  \n        System.out.println(\"\\n Enter your choice \\n\");        \n        ch = sc.nextInt();  \n        switch(ch)  \n        {  \n            case 1:  \n            {   \n                s.push(sc);  \n                break;  \n            }  \n            case 2:  \n            {  \n                s.pop();  \n                break;  \n            }  \n            case 3:  \n            {  \n                s.display();  \n                break;  \n            }  \n            case 4:   \n            {  \n                System.out.println(\"Exiting....\");  \n                System.exit(0);  \n                break;   \n            }  \n            default:  \n            {  \n                System.out.println(\"Please Enter valid choice \");  \n            }   \n        };  \n    }  \n}  \n}  "
  },
  {
    "path": "Data-Structures/Stack/StackUsingArray.js",
    "content": "class Stack {\n  constructor() {\n    this.stack = [];\n    this.top = -1;\n  }\n  push(value) {\n    this.top++;\n    this.stack[this.top] = value;\n  }\n  pop() {\n    if (this.top == -1) {\n      return \"Stack is empty\";\n    }\n    var ret_val = this.stack[this.top];\n    this.top--;\n    return ret_val;\n  }\n\n  peek() {\n    if (this.top == -1) {\n      return \"Stack is empty\";\n    }\n    var ret_val = this.stack[this.top];\n    return ret_val;\n  }\n\n  isEmpty() {\n    return this.top == -1;\n  }\n}\n\nstk = new Stack();\nconsole.log(stk.isEmpty());\nstk.push(1);\nstk.push(2);\nconsole.log(stk.peek());\nconsole.log(stk.isEmpty());\nstk.push(3);\nstk.push(4);\nconsole.log(stk.pop());\nconsole.log(stk.pop());\nconsole.log(stk.pop());\nconsole.log(stk.pop());\nconsole.log(stk.isEmpty());\n"
  },
  {
    "path": "Data-Structures/Stack/StackUsingArray.php",
    "content": "\n<?php \nclass Stack\n{\n    protected $stack;\n    protected $size;\n    public function __construct($size = 50) {\n        //declare stack\n        $this->stack = array();\n        //declare stack size\n        $this->size  = $size;\n    }\n    public function push($data) {//push element into stack\n        if(count($this->stack) < $this->size) {//check if stack is overflow       \n            // array_unshift() prepends passed elements to the front of the array.\n            array_unshift($this->stack, $data);//insert an element at the beginning      \n        } else {\n            throw new RuntimeException(\"Stack overflow\");//show error is stack overflow\n        }\n    }\n    \n\n    public function pop() {//pop element from stack\n        if (empty($this->stack)) {//check if stack is empty          \n            throw new RuntimeException(\"Stack underflow\");//throw error if empty\n        } else {\n            // array_shift() shifts the first value of the array off and returns it\n            return array_shift($this->stack);//pop element\n        }\n    }\n    \n   \n}\n \n$stack = new Stack();//create obbject of class\n \n$stack->push(4);//add 4 to stack\n$stack->push(5);//add 5 to stack \n \necho $stack->pop();  // Pop 5 and echo the element popped\n \n$stack->push(7);//add 7 to stack\n$stack->push(9);//add 9 to stack\n$stack->push(8);//add 8 to stack\n \necho $stack->pop();  // Pop 8 and echo the element popped\necho $stack->pop();  // Pop 9 and echo the element poppedv\n?>"
  },
  {
    "path": "Data-Structures/Stack/StackUsingArray.rb",
    "content": "class DynamicStack\n  def initialize\n    @stack = []\n  end\n\n  def is_empty?\n    @stack.empty?\n  end\n\n  def push(value)\n    @stack << value\n  end\n\n  def pop\n    is_empty? ? nil : @stack.pop\n  end\n\n  def peek\n    @stack.last\n  end\nend\n\nclass StaticStack\n  # @param [Integer] capacity\n  def initialize(capacity)\n    @stack = Array.new(capacity)\n    @top = -1\n    @capacity = capacity\n  end\n\n  def is_empty?\n    @top == -1\n  end\n\n  def push(value)\n    raise \"Stack full\" if is_full?\n    @top += 1\n    @stack[@top] = value\n  end\n\n  def pop\n    return nil if is_empty?\n    value = @stack[top]\n    @top -= 1\n    value\n  end\n\n  def peek\n    is_empty? ? nil : @stack[@top]\n  end\n\n  private\n\n  def is_full?\n    @top >= @capacity - 1\n  end\nend\n\nstack_kinds = [DynamicStack, StaticStack]\nparams = [[], [4]]\n\nstack_kinds.zip(params).each do |klass, param|\n  puts \"Create new stack: #{klass}\"\n  stack = klass.new(*param)\n  puts \"Is stack empty? #{stack.is_empty?}\"\n  (1..5).each do |num|\n    puts \"Push to stack: #{num}\"\n    stack.push(num)\n  end\n  puts \"Element at top is #{stack.peek}\"\n  loop do\n    break if stack.is_empty?\n    puts \"Pop Element: #{stack.pop}\"\n  end\nend\n"
  },
  {
    "path": "Data-Structures/Stack/StackUsingArray.swift",
    "content": "import Foundation\n\nstruct Stack<T> {\n    private var items: [T] = []\n    \n    mutating func push(element: T) {\n        items.append(element)\n    }\n    \n    mutating func pop() -> T? {\n        items.popLast()\n    }\n    \n    func peek() -> T? {\n        return items.last\n    }\n    \n    var isEmpty: Bool {\n        return items.isEmpty\n    }\n}\n\nextension Stack: CustomStringConvertible {\n    var description: String {\n        return items.description\n    }\n}\n\nvar intStack = Stack<Int>()\n\nprint(intStack.isEmpty)\n\nintStack.push(element: 1)\nintStack.push(element: 2)\nintStack.push(element: 3)\n\nprint(intStack.description)\nprint(intStack.isEmpty)\n\nintStack.pop()\nprint(intStack.peek())\n\nprint(intStack.description)\n\nvar stringStack = Stack<String>()\n\nprint(intStack.isEmpty)\n\nstringStack.push(element: \"Hi\")\nstringStack.push(element: \"Person\")\n\nprint(intStack.isEmpty)\nprint(stringStack.description)\n\nstringStack.pop()\nprint(stringStack.peek())\n\nprint(stringStack.description)\n"
  },
  {
    "path": "Data-Structures/Stack/StackUsingLL.cpp",
    "content": "#include <iostream>\n\nusing namespace std;\n\nstruct node\n{\n\tint value;\n\tnode * prev;\n\n\tnode(int x, node * pr){\n\t\tvalue = x;\n\t\tprev = pr;\n\t}\n};\n\nstruct myStack\n{\n\tprivate:\n\t\tnode * top;\n\t\tint cnt;\n\n\n\n\tpublic:\n\t\tmyStack()\n\t\t{\n\t\t\ttop = NULL;\n\t\t\tcnt = 0;\n\t\t}\n\n\t\tvoid push(int x) {\n\t\t\tnode * el = new node(x, top);\n\t\t\ttop = el;\n\t\t\tcnt++;\n\t\t}\n\t\t\n\t\tvoid pop() {\n\t\t\tif(!empty()) {\n\t\t\t\tint res = top->value;\n\t\t\t\ttop = top->prev;\n\t\t\t\tcnt--;\n\t\t\t\tcout << res;\n\t\t\t}\n\t\t\t\n\t\t\telse {\n\t\t\t\tcout << \"error\";\n\t\t\t}\n\t\t}\n\t\tvoid back() {\n\t\t\tif(!empty())\n\t\t\t\tcout << top->value;\n\t\t\telse\n\t\t\t\tcout << \"error\";\n\t\t}\n\n\t\tint size() {\n\t\t\treturn cnt;\n\t\t}\n\t\tvoid clear() {\n\t\t\ttop = NULL;\n\t\t\tcnt = 0;\n\t\t}\n\t\tbool empty() {\n\t\t\treturn cnt == 0;\n\t\t}\n\t\t\n};\n\nint main()\n{\n\tstring q;\n\tint x;\n\tmyStack st;\n\tdo\n    \t{\n        cin >> q;\n        if(q == \"push\"){\n            cin >> x;\n            st.push(x);\n            cout << \"ok\";\n        }\n        if(q == \"pop\"){\n            st.pop();\n        }\n        if(q == \"back\"){\n            st.back();\n        }\n        if(q == \"size\"){\n            cout << st.size();\n        }\n        if(q == \"clear\"){\n            st.clear();\n            cout << \"ok\";\n        }\n        if(q == \"exit\"){\n            cout << \"bye\";\n        }\n        cout << endl;\n    }\n    while(q != \"exit\");\n\treturn 0;\n}\n"
  },
  {
    "path": "Data-Structures/Stack/StackUsingLL.go",
    "content": "package main\r\n\r\nimport (\r\n\t\"errors\"\r\n\t\"fmt\"\r\n)\r\n\r\n// Stack of String values\r\ntype Stack []string\r\n\r\nfunc main() {\r\n\tvar stack Stack\r\n\r\n\tstack.Push(\"First\")\r\n\tstack.Push(\"Second\")\r\n\tstack.Push(\"Third\")\r\n\r\n\tfor !stack.IsEmpty() {\r\n\t\tvalue, _ := stack.Peek()\r\n\t\tfmt.Printf(\"Peek - First item is: %s\\n\", value)\r\n\r\n\t\tvalue, _ = stack.Pop()\r\n\t\tfmt.Printf(\"Pop - popped item: %s\\n\", value)\r\n\t}\r\n}\r\n\r\n// IsEmpty returns true if there are no items in the Stack.\r\nfunc (s *Stack) IsEmpty() bool {\r\n\treturn len(*s) == 0\r\n}\r\n\r\n// Push appends a new value to the Stack.\r\nfunc (s *Stack) Push(value string) {\r\n\t*s = append(*s, value)\r\n}\r\n\r\n// Pop returns and removes the top value in the Stack.\r\n// Returns an error if trying to pop an empty Stack\r\nfunc (s *Stack) Pop() (string, error) {\r\n\tif s.IsEmpty() {\r\n\t\treturn \"\", errors.New(\"stack is empty\")\r\n\t}\r\n\r\n\ti := len(*s) - 1\r\n\tvalue := (*s)[i]\r\n\t*s = (*s)[:i]\r\n\treturn value, nil\r\n}\r\n\r\n// Peek returns first value in the Stack without removing\r\n// Returns an error if the Stack is empty\r\nfunc (s *Stack) Peek() (string, error) {\r\n\tif s.IsEmpty() {\r\n\t\treturn \"\", errors.New(\"stack is empty\")\r\n\t}\r\n\r\n\ti := len(*s) - 1\r\n\tvalue := (*s)[i]\r\n\treturn value, nil\r\n}\r\n"
  },
  {
    "path": "Data-Structures/Stack/StackUsingLL.java",
    "content": "import java.util.Scanner;\n\npublic class StackUsingLL {\n    Node head;\n    class Node {\n        int val;\n        Node next;\n        int min;\n\n    public Node(int val, int min) {\n        this.val = val;\n        this.min = min;\n        next = null;\n        }\n    }\n\n    public void push(int x) { // O(1)\n        if(head == null){\n            head = new Node(x, x);\n        }\n        else {\n            Node node = new Node(x, Math.min(head.min,x));\n            node.next = head;\n            head = node;\n            }\n        }\n\n        public void pop() {\n        if(head!=null){\n            head = head.next;\n            }\n        }\n\n        public int peek() {\n        if(head!=null) {\n            return head.val;\n            }\n        return -1;\n        }\n\n        public int getMin() {\n        if(head!=null){\n            return head.min;\n        }\n        return -1;\n        }\n\n        public void display() {\n\n            // check for stack underflow\n            if (head == null) {\n                System.out.printf(\"\\nStack Underflow\");\n            }\n            else {\n                Node temp = head;\n                while (temp != null) {\n                    System.out.print(temp.val+\" \");\n                    temp = temp.next;\n                }\n                System.out.println(\"\");\n            }\n        }\n        \n    public static void operation(StackUsingLL stack) {\n    \t System.out.println(\"Enter the operation\");\n         System.out.println(\"1. \"+\"push\");\n         System.out.println(\"2. pop\");\n         System.out.println(\"3. peek\");\n         System.out.println(\"4. display\");\n         \n         Scanner sc = new Scanner(System.in);\n         int input = sc.nextInt();\n         \n         switch(input) {\n         // push into stack\n         case 1:\n             System.out.println(\"Enter the number of elements to be pushed\");\n             int number = sc.nextInt();\n             \n             System.out.println(\"Enter the elements\");\n             while(number-->0) {\n             \tint element = sc.nextInt();\n             \tstack.push(element);\n             }\n             stack.operation(stack);\n          // Delete top element of Stack\n           case 2:\n         \tstack.pop();\n         \tstack.operation(stack);\n             \n          // print Top element of Stack  \n           case 3:\n         \t  System.out.printf(\"\\nTop element is %d\\n\", stack.peek());\n         \t stack.operation(stack);\n             \n           //print Stack elements  \n           case 4:\n         \tstack.display();\n         \tstack.operation(stack);\n         \t\n           case 5:\n        \tSystem.out.println(\"EXIT\");\n        \tSystem.exit(0);\n         \t\n           default: System.exit(0);\n         }\n    }\n\n    public static void main(String[] args) {\n        //object of class\n    \tStackUsingLL stack = new StackUsingLL();\n        stack.operation(stack);\n    }\n}\n"
  },
  {
    "path": "Data-Structures/Stack/StackUsingLL.js",
    "content": "class Node {\n    constructor(data) {\n      this.data = data;\n      this.next = null;\n    }\n}\n\nclass Stack {\n    constructor() {\n        this.head = null;\n    }\n\n    isEmpty() {\n        return this.head === null;\n    }\n\n    push(data) {\n        if (this.head) {\n            const newNode = new Node(data);\n            newNode.next = this.head;\n            this.head = newNode;\n        } else {\n            this.head = new Node(data);\n        }\n    }\n\n    pop() {\n        if (this.head) {\n            const data = this.head.data;\n            this.head = this.head.next;\n            return data;\n        } else {\n            throw \"Stack underflow\";\n        }\n    }\n\n    peek() {\n        if (this.head) {\n            return this.head.data;\n        } else {\n            throw \"Stack underflow\";\n        }\n    }\n}\n\nconst stack = new Stack();\nconsole.log(stack.isEmpty());\nstack.push(5);\nstack.push(9);\nstack.push(6);\nconsole.log(stack.pop());\nconsole.log(stack.peek());\nstack.push(5);\nconsole.log(stack.isEmpty());\n\n//OUTPUT(TEST CASE)\n//true\n//6\n//9\n//false\n"
  },
  {
    "path": "Data-Structures/Stack/StackUsingLL.py",
    "content": "class Node:\n    def __init__(self,data):\n        self.data = data\n        self.next = None\n     \nclass Stack:\n\n    def __init__(self):\n        self.head = None\n     \n    def isempty(self):\n        if self.head == None:\n            return True\n        else:\n            return False\n     \n    def push(self,data):\n         \n        if self.head == None:\n            self.head=Node(data)\n             \n        else:\n            new_node = Node(data)\n            new_node.next = self.head\n            self.head = new_node\n\n    def pop(self):\n         \n        if self.isempty():\n            print(\"Stack Underflow!\")\n            return None\n             \n        else:\n            pop_node = self.head\n            self.head = self.head.next\n            pop_node.next = None\n            return pop_node.data\n     \n    def peek(self):\n         \n        if self.isempty():\n            return None\n             \n        else:\n            return self.head.data\n        \n    def display(self):\n         \n        iter_node = self.head\n        if self.isempty():\n            print(\"Stack Underflow!\")\n         \n        else:\n             \n            while(iter_node != None):\n                 \n                print(iter_node.data,\"->\",end = \" \")\n                iter_node = iter_node.next\n            return\n         \n# Driver code\nMyStack = Stack()\n \nMyStack.push(1)\nMyStack.push(2)\nMyStack.push(3)\nMyStack.push(4)\n \n# Display stack elements\nMyStack.display()\n \n# Print top element of stack\nprint(\"\\nStack Top: \",MyStack.peek())\n \n# Delete top elements of stack\nMyStack.pop()\nMyStack.pop()\n \n# Display stack elements\nMyStack.display()\n \nprint(\"\\nStack Top: \", MyStack.peek())\n\n# Output:\n#     4 -> 3 -> 2 -> 1 -> \n#     Stack Top:  4\n#     2 -> 1 ->\n#     Stack Top:  2\n"
  },
  {
    "path": "Data-Structures/Stack/stackUsingLinkedList.c",
    "content": "#include <stdio.h>\n#include <stdlib.h>\nstruct node\n{\n    int val;\n    struct node *next;\n};\nstruct node *head;\nvoid push()\n{\n    int val;\n    struct node *ptr = (struct node *)malloc(sizeof(struct node));\n\n    if (ptr == NULL)\n        printf(\"not able to push the element\");\n\n    else\n    {\n        printf(\"Enter the value\");\n        scanf(\"%d\", &val);\n        if (head == NULL)\n        {\n            ptr->val = val;\n            ptr->next = NULL;\n            head = ptr;\n        }\n        else\n        {\n            ptr->val = val;\n            ptr->next = head;\n            head = ptr;\n        }\n        printf(\"Item pushed\");\n    }\n}\n\nvoid pop()\n{\n    int item;\n    struct node *ptr;\n    if (head == NULL)\n        printf(\"Underflow\");\n\n    else\n    {\n        item = head->val;\n        ptr = head;\n        head = head->next;\n        free(ptr);\n        printf(\"Item popped\");\n    }\n}\nvoid display()\n{\n    int i;\n    struct node *ptr;\n    ptr = head;\n    if (ptr == NULL)\n        printf(\"Stack is empty\\n\");\n\n    else\n    {\n        printf(\"Printing Stack elements \\n\");\n        while (ptr != NULL)\n        {\n            printf(\"%d\\n\", ptr->val);\n            ptr = ptr->next;\n        }\n    }\n}\nint main()\n{\n    int choice = 0;\n    while (choice != 4)\n    {\n        printf(\"\\n\\nChose one from the below options...\\n\");\n        printf(\"\\n1.Push\\n2.Pop\\n3.Show\\n4.Exit\");\n        printf(\"\\n Enter your choice \\n\");\n        scanf(\"%d\", &choice);\n        switch (choice)\n        {\n        case 1:\n        {\n            push();\n            break;\n        }\n        case 2:\n        {\n            pop();\n            break;\n        }\n        case 3:\n        {\n            display();\n            break;\n        }\n        case 4:\n        {\n            printf(\"Exiting....\");\n            break;\n        }\n        default:\n            printf(\"Please Enter valid choice \");\n            \n        };\n    }\n}\n"
  },
  {
    "path": "Data-Structures/Stack/stackusingLL.c",
    "content": "#include <stdio.h>\n#include <stdlib.h>\nstruct node{\n  int data;\n  struct node *next;\n};\nstruct stack{\n  int top;\n  struct node *list;//head of list\n};\nstruct node *newNode(){\n  struct node *newnode=(struct node*)malloc(sizeof(struct node));\n  printf(\"\\nEnter the number to be inserted\\n\");\n  scanf(\"%d\",&newnode->data);\n  newnode->next=NULL;\n  return newnode;\n}\nstruct stack *create_stack(){\n  struct stack *st=(struct stack*)malloc(sizeof(struct stack));\n  st->list=NULL;\n  st->top=-1;\n  return st;\n}\nvoid push(struct node **head){\n  struct node *n=newNode();\n  if(*head==NULL){\n    *head=n;\n  }\n  else{\n    struct node *p=*head;\n    n->next=p;\n    *head=n;\n  }\n}\nvoid pop(struct node **head){\n  if(*head==NULL){\n    printf(\"\\nUNDERFLOW\\n\");\n  }\n  else{\n    struct node *temp=*head;\n    *head=temp->next;\n    printf(\"\\nDeleted %d\\n\",temp->data);\n    free(temp);\n  }\n}\nvoid top_element(struct node *head){\n  printf(\"\\nTop element is %d\\n\",head->data);\n}\nvoid print_stack(struct node *head){\n  printf(\"\\n\");\n  struct node *p=head;\n  while(p!=NULL){\n    printf(\"%d \",p->data);\n    p=p->next;\n  }\n  printf(\"\\n\");\n}\nint main(){\n  struct stack *st=create_stack();\n  char ch;\n  printf(\"a->push\\nd->pop\\np->find top element\\nk->print stack\\nq->quit\\n\");\n  do{\n    printf(\"\\nEnter a character from the given menu to perform the operations on stack\\n\");\n    ch=getche();\n    switch(ch){\n      case 'a': ;\n      push(&st->list);\n      break;\n      case 'd': ;\n      pop(&st->list);\n      break;\n      case 'p': ;\n      top_element(st->list);\n      break;\n      case 'q': ;\n      break;\n      case 'k': ;\n      print_stack(st->list);\n      break;\n      default:\n      printf(\"\\nIllegal Character entered\\n\");\n      break;\n    }\n  }while(ch!='q');\n}\n"
  },
  {
    "path": "Data-Structures/Tree/23-Tree/23Tree.cpp",
    "content": "#include<iostream>\n#include<algorithm>\n#define INT_MAX 2147483647\nusing namespace std;\n\nstruct TreeNode{\n    //stores data - represents left, right, middle\n    int keys[3];\n    // 4 pointers which refer to child, also stores parent node pointer\n    struct TreeNode* p1, *p2, *p3, *p4, *parent;\n    //maintains numbers of keys in keys array\n    int keyCount;\n};\n\nTreeNode* root = NULL;\n\n//prints inorder traversal of 2-3 tree\nvoid printInorder(TreeNode* root){\n    if(!root)\n        return;\n    printInorder(root->p1);\n    cout<<root->keys[0]<<\" \";\n    printInorder(root->p2);\n    if(root->keyCount==2)\n        cout<<root->keys[1]<<\" \";\n    printInorder(root->p3);\n}\n\n//prints preorder traversal of 2-3 tree\nvoid printPreorder(TreeNode* root){\n    if(!root)\n        return;\n    cout<<root->keys[0]<<\" \";\n    printPreorder(root->p1);\n    if(root->keyCount==2)\n        cout<<root->keys[1]<<\" \";\n    printPreorder(root->p2);\n    printPreorder(root->p3);\n}\n\n//prints postorder traversal of 2-3 tree\nvoid printPostorder(TreeNode* root){\n    if(!root)\n        return;\n    printPostorder(root->p1);\n    printPostorder(root->p2);\n    printPostorder(root->p3);\n    if(root->keyCount==2)\n        cout<<root->keys[1]<<\" \";\n    cout<<root->keys[0]<<\" \";\n}\n\n//creates and initializes a new node\nTreeNode* newNode(int key){\n    TreeNode* node = new TreeNode;\n    node->keys[0] = key;\n    node->keys[1] = node->keys[2] = INT_MAX;\n    node->p1 = node->p2 = node->p3 = node->p4 = node->parent = NULL;\n    node->keyCount = 1;\n    return node;\n}\n\n//searches the 2-3 tree and returns the node containing the key, returns NUlL when not found\nTreeNode* search(TreeNode* root, int key){\n    if(!root)\n        return NULL;\n    if(key<root->keys[0])\n        return search(root->p1, key);\n    if(key>root->keys[0] && key < root->keys[1])\n        return search(root->p2, key);\n    if(key > root->keys[1])\n        return search(root->p3, key);\n    return root;\n}\n\n// checks if node is in overflow condition \nbool isOverflow(TreeNode* node){\n    return node && node->keyCount == 3;\n}\n\n// fixes the overflow condition, splits the overflowing node and shifts its middle to the parent\nvoid fixOverflow(TreeNode *node) {\n    cout<<\"Fix Overflow Start\\n\";\n\twhile (isOverflow(node)) { \n\t\tint median = node->keys[1];\n\t\tTreeNode *temp = newNode(node->keys[2]);\n\t\ttemp->p2 = node->p4;\n\t\ttemp->p1 = node->p3;\n\t\tif (temp->p2)\n\t\t\ttemp->p2->parent = temp;\n\t\tif (temp->p1)\n\t\t\ttemp->p1->parent = temp;\n\t\tnode->keys[1] = node->keys[2] = INT_MAX;\n\t\tnode->p3 = node->p4 = NULL;\n\t\tnode->keyCount = 1;\n\t\tTreeNode *p = node->parent;\n\t\tif (!p) {\n\t\t\troot = newNode(median);\n\t\t\tnode->parent = temp->parent = root;\n\t\t\troot->p2 = temp;\n\t\t\troot->p1 = node;\n\t\t\tbreak;\n\t\t} else {\n\t\t\ttemp->parent = p;\n\t\t\tif (node == p->p1) { \n\t\t\t\tp->keys[2] = p->keys[1];\n\t\t\t\tp->keys[1] = p->keys[0];\n\t\t\t\tp->keys[0] = median;\n\t\t\t\tp->keyCount++;\n\t\t\t\tp->p4 = p->p3;\n\t\t\t\tp->p3 = p->p2;\n\t\t\t\tp->p2 = temp;\n\t\t\t} else if (node == p->p2) { \n\t\t\t\tp->keys[2] = p->keys[1];\n\t\t\t\tp->keys[1] = median;\n\t\t\t\tp->keyCount++;\n\t\t\t\tp->p4 = p->p3;\n\t\t\t\tp->p3 = temp;\n\t\t\t} else { \n\t\t\t\tp->keys[2] = median;\n\t\t\t\tp->keyCount++;\n\t\t\t\tp->p4 = temp;\n\t\t\t}\n\t\t\tnode = p;\n\t\t}\n\t}\n    cout<<\"Fix Overflow End\\n\";\n}\n\n// utility function to insert in a 2-3 tree, in case the overflow condition occur, fixOverflow is called\nvoid insert(int key) {\n    cout<<\"Insert Start\\n\";\n\tTreeNode *node = NULL;\n\tTreeNode *temp = root;\n\twhile(temp){\n\t\tnode = temp; \n\t\tif (key < temp->keys[0])\n\t\t\ttemp = temp->p1;\n\t\telse if (temp->keyCount == 1)\n\t\t\ttemp = temp->p2;\n\t\telse\n\t\t\ttemp = temp->p3;\n\t}\n\tif (!node){\n        cout<<\"ok\\n\";\n\t\troot = newNode(key);\n    }\n\telse {\n\t\tif (key < node->keys[0]){\n\t\t\tnode->keys[2] = node->keys[1];\n\t\t\tnode->keys[1] = node->keys[0]; \n\t\t\tnode->keys[0] = key;\n\t\t} else if (key > node->keys[0] && key < node->keys[1]){\n\t\t\tnode->keys[2] = node->keys[1];\n\t\t\tnode->keys[1] = key;\n\t\t} else\n\t\t\tnode->keys[2] = key;\n\n\t\tnode->keyCount++;\n\t\tif (isOverflow(node)) \n\t\t\tfixOverflow(node);\n\t}\n    cout<<\"Insert End\\n\";\n}\n\n// checks underflow condition\nbool isUnderflow(TreeNode* node){\n    return node && node->keyCount<1;\n}\n\n// checks if a node can donate one of its keys\nbool canDonate(TreeNode* node){\n    return node && node->keyCount>1;\n}\n\nbool isEmpty(TreeNode* node){\n    return node->keyCount==0;\n}\n\nbool isRoot(TreeNode* node){\n    return node == root;\n}\n\n// fixes the underflow condition, redistribution and merging operations are done to overcome underflow\nvoid fixUnderflow(TreeNode *node) {\n\twhile (isUnderflow(node)){ \n\t\tTreeNode *p = node->parent;\n\t\tTreeNode *x = NULL; \n\t\tTreeNode *z = NULL; \n\t\tif (node == p->p1){ \n\t\t\tz = p->p2;\n\t\t} else if (node == p->p2) { \n\t\t\tx = p->p1;\n\t\t\tz = p->p3;\n\t\t} else { \n\t\t\tx = p->p2;\n\t\t}\n\t\tif (canDonate(z)) { \n\t\t\tif(node == p->p1) {\n\t\t\t\tnode->keys[0] = p->keys[0];\n\t\t\t\tp->keys[0] = z->keys[0]; \n\t\t\t} else {\n\t\t\t\tnode->keys[0] = p->keys[1];\n\t\t\t\tp->keys[1] = z->keys[0]; \n\t\t\t}\n\t\t\tnode->p2 = z->p1;\n\t\t\tif (node->p2)\n\t\t\t\tnode->p2->parent = node;\n\t\t\tnode->keyCount++;\n\t\t\tz->keys[0] = z->keys[1];\n\t\t\tz->keys[1] = INT_MAX;\n\t\t\tz->p1 = z->p2;\n\t\t\tz->p2 = z->p3;\n\t\t\tz->p3 = NULL;\n\t\t\tz->keyCount--;\n\n\t\t} else if (canDonate(x)) { \n\t\t\tif(x == p->p1) {\n\t\t\t\tnode->keys[0] = p->keys[0];\n\t\t\t\tp->keys[0] = x->keys[1]; \n\t\t\t} else {\n\t\t\t\tnode->keys[0] = p->keys[1];\n\t\t\t\tp->keys[1] = x->keys[1]; \n\t\t\t}\n\t\t\tnode->p1 = x->p3;\n\t\t\tif (node->p1)\n\t\t\t\tnode->p1->parent = node;\n\t\t\tnode->keyCount++;\n\t\t\tx->keys[1] = INT_MAX;\n\t\t\tx->p3 = NULL;\n\t\t\tx->keyCount--;\n\t\t} else {\n\t\t\tif (z){\n\t\t\t\tif (node == p->p1)\n\t\t\t\t\tnode->keys[0] = p->keys[0];\n\t\t\t\telse\n\t\t\t\t\tnode->keys[0] = p->keys[1];\n\t\t\t\tnode->keys[1] = z->keys[0];\n\t\t\t\tnode->p2 = z->p1;\n\t\t\t\tnode->p3 = z->p2;\n\t\t\t\tif (node->p2)\n\t\t\t\t\tnode->p2->parent = node;\n\t\t\t\tif (node->p3)\n\t\t\t\t\tnode->p3->parent = node;\n\t\t\t\tnode->keyCount += 2;\n\t\t\t\tif (node == p->p1) {\n\t\t\t\t\tp->p2 = p->p3;\n\t\t\t\t\tp->keys[0] = p->keys[1];\n\t\t\t\t}\n\t\t\t\tp->p3 = NULL;\n\t\t\t\tp->keys[1] = INT_MAX;\n\t\t\t\tp->keyCount--;\n\t\t\t\tif (isEmpty(p) && isRoot(p)) {\n\t\t\t\t\tfree(p);\n\t\t\t\t\tnode->parent = p = NULL;\n\t\t\t\t\troot = node;\n\t\t\t\t}\n\t\t\t\tfree(z);\n\t\t\t} else {\n\t\t\t\tif (x == p->p1)\n\t\t\t\t\tx->keys[1] = p->keys[0];\n\t\t\t\telse\n\t\t\t\t\tx->keys[1] = p->keys[1];\n\t\t\t\tx->p3 = node->p1;\n\t\t\t\tif (x->p3)\n\t\t\t\t\tx->p3->parent = x;\n\t\t\t\tx->keyCount++;\n\t\t\t\tif (x == p->p1) {\n\t\t\t\t\tp->p2 = p->p3;\n\t\t\t\t\tp->keys[0] = p->keys[1];\n\t\t\t\t}\n\t\t\t\tp->p3 = NULL;\n\t\t\t\tp->keys[1] = INT_MAX;\n\t\t\t\tp->keyCount--;\n\t\t\t\tif (isEmpty(p) && isRoot(p)) {\n\t\t\t\t\tfree(p);\n\t\t\t\t\tx->parent = p = NULL;\n\t\t\t\t\troot = x;\n\t\t\t\t}\n\t\t\t\tfree(node);\n\t\t\t}\n\t\t}\n\t\tnode = p;\n\t}\n}\n\n// gets the inorder successor to the given node\nTreeNode* getMin(TreeNode* root){\n    if(root->p1)\n        getMin(root->p1);\n    return root;\n}\n\nTreeNode* getMax(TreeNode* root){\n    if(root->p3)\n        getMax(root->p3);\n    if(root->p2)\n        getMax(root->p2);\n    return root;\n}\n\nbool isLeaf(TreeNode* node){\n    return !node->p1 && !node->p2;\n}\n\n// delete helper function, performs simple deletion and checks if there is underflow or not, if yes, then calls, fixUnderflow\nvoid deleteNode(int key) {\n\tTreeNode *node = search(root, key);\n\tif (isLeaf(node)) {\n\t\tif (key == node->keys[0]) {\n\t\t\tnode->keys[0] = node->keys[1];\n\t\t\tnode->keys[1] = INT_MAX;\n\t\t} else\n\t\t\tnode->keys[1] = INT_MAX;\n\t\tnode->keyCount--;\n\t\tif (isUnderflow(node)) { \n\t\t\tif (isRoot(node)) {\n\t\t\t\tfree(root);\n\t\t\t\troot = NULL;\n\t\t\t} else\n\t\t\t\tfixUnderflow(node);\n\t\t}\n\t} else {\n\t\tTreeNode *y = NULL;\n\t\tif (key == node->keys[0])\n\t\t\ty = getMin(node->p2);\n\t\telse\n\t\t\ty = getMin(node->p3);\n\t\tif (key == node->keys[0])\n\t\t\tnode->keys[0] = y->keys[0];\n\t\telse\n\t\t\tnode->keys[1] = y->keys[0];\n\t\ty->keys[0] = y->keys[1];\n\t\ty->keys[1] = INT_MAX;\n\t\ty->keyCount--;\n\n\t\tif (isUnderflow(y))\n\t\t\tfixUnderflow(y);\n\t}\n}\n\nint main(){\n    while(1){\n        cout<<\"++++++++++++++++++++++++++++++++++\\n\";\n        cout<<\"Select an Operation\\n\";\n        cout<<\" 1. Insert\\n 2. Delete \\n 3. Search \\n 4. Inorder Traverse\\n 5. Preorder Traverse\\n 6. Postorder Traverse\\n 7. Exit \\n\";\n        cout<<\"++++++++++++++++++++++++++++++++++\\n\";\n        int selection;\n        cin>>selection;\n        if(selection == 1){\n            cout<<\"Enter Number to Insert\\n\";\n            int key;\n            cin>>key;\n            insert(key);\n        } else if(selection==2){\n            cout<<\"Enter Number to Delete\\n\";\n            int num;\n            cin>>num;\n            deleteNode(num);\n        } else if(selection==3){\n            cout<<\"Enter Number to Search\\n\";\n            int num;\n            cin>>num;\n            TreeNode* temp = search(root,num);\n            if(temp)\n                cout<<\"Found\\n\";\n            else\n                cout<<\"Not Found\\n\";\n        } else if(selection==4){\n            printInorder(root);\n            cout<<\"\\n\";\n        } else if(selection==5){\n            printPreorder(root);\n            cout<<\"\\n\";\n        } else if(selection==6){\n            printPostorder(root);\n            cout<<\"\\n\";\n        } else if(selection==7){\n            break;\n        }\n    }\n}\n\n"
  },
  {
    "path": "Data-Structures/Tree/23-Tree/23Tree.py",
    "content": "class Node(object):\n    \n    path = []\n\n    def __init__(self, data, parent=None):\n        self.childs = {}\n        self.data = [data]\n        self.parent = parent        \n\n    def insert(self, value):\n        Node.path = []\n        insert_node = self.search(value)\n        insert_node.add(value)\n\n    def split(self):\n        if self.parent is None and self.childs:\n            branch = Node.path.pop()\n            newNodeLeft = Node(self.data.pop(0), self)\n            newNodeRight = Node(self.data.pop(1), self)                      \n            if branch == \"left\":\n               newNodeLeft.childs[\"left\"] = self.childs[\"left\"]\n               newNodeLeft.childs[\"right\"] = self.childs[\"overflow\"]\n               newNodeRight.childs[\"left\"] = self.childs[\"mid\"]\n               newNodeRight.childs[\"right\"] = self.childs[\"right\"]\n            elif branch == \"mid\":\n               newNodeLeft.childs[\"left\"] = self.childs[\"left\"]\n               newNodeLeft.childs[\"right\"] = self.childs[\"mid\"]\n               newNodeRight.childs[\"left\"] = self.childs[\"overflow\"]\n               newNodeRight.childs[\"right\"] = self.childs[\"right\"]\n            elif branch == \"right\":\n               newNodeLeft.childs[\"left\"] = self.childs[\"left\"]\n               newNodeLeft.childs[\"right\"] = self.childs[\"mid\"]\n               newNodeRight.childs[\"left\"] = self.childs[\"right\"]\n               newNodeRight.childs[\"right\"] = self.childs[\"overflow\"]\n            newNodeLeft.childs[\"left\"].parent = newNodeLeft\n            newNodeLeft.childs[\"right\"].parent = newNodeLeft\n            newNodeRight.childs[\"left\"].parent = newNodeRight\n            newNodeRight.childs[\"right\"].parent = newNodeRight\n            self.childs[\"left\"] = newNodeLeft\n            self.childs[\"right\"] = newNodeRight\n            del self.childs[\"mid\"]\n\n        elif self.parent is not None and self.childs:\n            branch = Node.path.pop()\n            newNode = Node(self.data.pop(), self.parent)\n            self.parent.childs[\"overflow\"] = newNode\n            if branch == \"left\":  \n                newNode.childs[\"left\"] = self.childs[\"mid\"]\n                newNode.childs[\"right\"] = self.childs[\"right\"]\n                self.childs[\"right\"] = self.childs[\"overflow\"]\n            elif branch == \"mid\":\n                newNode.childs[\"left\"] = self.childs[\"overflow\"]\n                newNode.childs[\"right\"] = self.childs[\"right\"]\n                self.childs[\"right\"] = self.childs[\"mid\"]\n            elif branch == \"right\":\n                newNode.childs[\"left\"] = self.childs[\"right\"]\n                newNode.childs[\"right\"] = self.childs[\"overflow\"]\n                self.childs[\"right\"] = self.childs[\"mid\"]\n            newNode.childs[\"left\"].parent = newNode\n            newNode.childs[\"right\"].parent = newNode\n            del self.childs[\"mid\"]\n\n        elif self.parent is None and not self.childs:\n            self.childs[\"left\"] = Node(self.data.pop(0), self)\n            self.childs[\"right\"] = Node(self.data.pop(1), self)   \n\n        elif self.parent is not None and not self.childs:\n            self.parent.childs[\"overflow\"] = Node(self.data.pop(), self.parent) \n            \n                \n    def add(self, value):\n        if value not in self.data:\n            self.data.append(value)\n            self.data.sort()\n            if len(self.data) == 3:\n                self.split()\n                if self.parent is not None:\n                    self.parent.add(self.data.pop())\n            else:\n                if \"overflow\" in self.childs:\n                    branch = Node.path.pop()\n                    if branch == \"left\":\n                        self.childs[\"mid\"] = self.childs[\"overflow\"]\n                    elif branch == \"right\":\n                        self.childs[\"mid\"] = self.childs[\"right\"]\n                        self.childs[\"right\"] = self.childs[\"overflow\"]\n                    del self.childs[\"overflow\"]\n\n    def search(self, value):   \n        if self.childs:\n            boundLeft = min(self.data)\n            boundRight = max(self.data)\n            if value < boundLeft:\n                Node.path.append(\"left\")\n                return self.childs[\"left\"].search(value)\n            elif value > boundRight:\n                Node.path.append(\"right\")\n                return self.childs[\"right\"].search(value)\n            else:\n                Node.path.append(\"mid\")\n                return self.childs[\"mid\"].search(value)\n        else:\n             return self \n\n    def element(self, value):\n        if value in self.data:\n            return True\n        elif self.childs:\n            boundLeft = min(self.data)\n            boundRight = max(self.data)\n            if value < boundLeft:\n                return self.childs[\"left\"].element(value)\n            elif value > boundRight:\n                return self.childs[\"right\"].element(value)\n            else:\n                return self.childs[\"mid\"].element(value)\n        else:\n            return False\n"
  },
  {
    "path": "Data-Structures/Tree/AVL-Tree/AVL_Tree.java",
    "content": "/*\n *  Java Program to Implement AVL Tree\n */\n \n import java.util.Scanner;\n \n /* Class AVLNode */\n class AVLNode\n {    \n     AVLNode left, right;\n     int data;\n     int height;\n \n     /* Constructor */\n     public AVLNode()\n     {\n         left = null;\n         right = null;\n         data = 0;\n         height = 0;\n     }\n     /* Constructor */\n     public AVLNode(int n)\n     {\n         left = null;\n         right = null;\n         data = n;\n         height = 0;\n     }     \n }\n \n /* Class AVLTree */\n class AVLTree\n {\n     private AVLNode root;     \n \n     /* Constructor */\n     public AVLTree()\n     {\n         root = null;\n     }\n     /* Function to check if tree is empty */\n     public boolean isEmpty()\n     {\n         return root == null;\n     }\n     /* Make the tree logically empty */\n     public void makeEmpty()\n     {\n         root = null;\n     }\n     /* Function to insert data */\n     public void insert(int data)\n     {\n         root = insert(data, root);\n     }\n     /* Function to get height of node */\n     private int height(AVLNode t )\n     {\n         return t == null ? -1 : t.height;\n     }\n     /* Function to max of left/right node */\n     private int max(int lhs, int rhs)\n     {\n         return lhs > rhs ? lhs : rhs;\n     }\n     /* Function to insert data recursively */\n     private AVLNode insert(int x, AVLNode t)\n     {\n         if (t == null)\n             t = new AVLNode(x);\n         else if (x < t.data)\n         {\n             t.left = insert( x, t.left );\n             if( height( t.left ) - height( t.right ) == 2 )\n                 if( x < t.left.data )\n                     t = rotateWithLeftChild( t );\n                 else\n                     t = doubleWithLeftChild( t );\n         }\n         else if( x > t.data )\n         {\n             t.right = insert( x, t.right );\n             if( height( t.right ) - height( t.left ) == 2 )\n                 if( x > t.right.data)\n                     t = rotateWithRightChild( t );\n                 else\n                     t = doubleWithRightChild( t );\n         }\n         else\n           ;  // Duplicate; do nothing\n         t.height = max( height( t.left ), height( t.right ) ) + 1;\n         return t;\n     }\n     /* Rotate binary tree node with left child */     \n     private AVLNode rotateWithLeftChild(AVLNode k2)\n     {\n         AVLNode k1 = k2.left;\n         k2.left = k1.right;\n         k1.right = k2;\n         k2.height = max( height( k2.left ), height( k2.right ) ) + 1;\n         k1.height = max( height( k1.left ), k2.height ) + 1;\n         return k1;\n     }\n \n     /* Rotate binary tree node with right child */\n     private AVLNode rotateWithRightChild(AVLNode k1)\n     {\n         AVLNode k2 = k1.right;\n         k1.right = k2.left;\n         k2.left = k1;\n         k1.height = max( height( k1.left ), height( k1.right ) ) + 1;\n         k2.height = max( height( k2.right ), k1.height ) + 1;\n         return k2;\n     }\n     /**\n      * Double rotate binary tree node: first left child\n      * with its right child; then node k3 with new left child */\n     private AVLNode doubleWithLeftChild(AVLNode k3)\n     {\n         k3.left = rotateWithRightChild( k3.left );\n         return rotateWithLeftChild( k3 );\n     }\n     /**\n      * Double rotate binary tree node: first right child\n      * with its left child; then node k1 with new right child */      \n     private AVLNode doubleWithRightChild(AVLNode k1)\n     {\n         k1.right = rotateWithLeftChild( k1.right );\n         return rotateWithRightChild( k1 );\n     }    \n     /* Functions to count number of nodes */\n     public int countNodes()\n     {\n         return countNodes(root);\n     }\n     private int countNodes(AVLNode r)\n     {\n         if (r == null)\n             return 0;\n         else\n         {\n             int l = 1;\n             l += countNodes(r.left);\n             l += countNodes(r.right);\n             return l;\n         }\n     }\n     /* Functions to search for an element */\n     public boolean search(int val)\n     {\n         return search(root, val);\n     }\n     private boolean search(AVLNode r, int val)\n     {\n         boolean found = false;\n         while ((r != null) && !found)\n         {\n             int rval = r.data;\n             if (val < rval)\n                 r = r.left;\n             else if (val > rval)\n                 r = r.right;\n             else\n             {\n                 found = true;\n                 break;\n             }\n             found = search(r, val);\n         }\n         return found;\n     }\n     /* Function for inorder traversal */\n     public void inorder()\n     {\n         inorder(root);\n     }\n     private void inorder(AVLNode r)\n     {\n         if (r != null)\n         {\n             inorder(r.left);\n             System.out.print(r.data +\" \");\n             inorder(r.right);\n         }\n     }\n     /* Function for preorder traversal */\n     public void preorder()\n     {\n         preorder(root);\n     }\n     private void preorder(AVLNode r)\n     {\n         if (r != null)\n         {\n             System.out.print(r.data +\" \");\n             preorder(r.left);             \n             preorder(r.right);\n         }\n     }\n     /* Function for postorder traversal */\n     public void postorder()\n     {\n         postorder(root);\n     }\n     private void postorder(AVLNode r)\n     {\n         if (r != null)\n         {\n             postorder(r.left);             \n             postorder(r.right);\n             System.out.print(r.data +\" \");\n         }\n     }     \n }\n \n /* Class AVL Tree Test */\n public class AVLTreeTest\n {\n     public static void main(String[] args)\n    {            \n        Scanner scan = new Scanner(System.in);\n        /* Creating object of AVLTree */\n        AVLTree avlt = new AVLTree(); \n \n        System.out.println(\"AVLTree Tree Test\\n\");          \n        char ch;\n        /*  Perform tree operations  */\n        do    \n        {\n            System.out.println(\"\\nAVLTree Operations\\n\");\n            System.out.println(\"1. insert \");\n            System.out.println(\"2. search\");\n            System.out.println(\"3. count nodes\");\n            System.out.println(\"4. check empty\");\n            System.out.println(\"5. clear tree\");\n \n            int choice = scan.nextInt();            \n            switch (choice)\n            {\n            case 1 : \n                System.out.println(\"Enter integer element to insert\");\n                avlt.insert( scan.nextInt() );                     \n                break;                          \n            case 2 : \n                System.out.println(\"Enter integer element to search\");\n                System.out.println(\"Search result : \"+ avlt.search( scan.nextInt() ));\n                break;                                          \n            case 3 : \n                System.out.println(\"Nodes = \"+ avlt.countNodes());\n                break;     \n            case 4 : \n                System.out.println(\"Empty status = \"+ avlt.isEmpty());\n                break;     \n            case 5 : \n                System.out.println(\"\\nTree Cleared\");\n                avlt.makeEmpty();\n                break;         \n            default : \n                System.out.println(\"Wrong Entry \\n \");\n                break;   \n            }\n            /*  Display tree  */ \n            System.out.print(\"\\nPost order : \");\n            avlt.postorder();\n            System.out.print(\"\\nPre order : \");\n            avlt.preorder();\n            System.out.print(\"\\nIn order : \");\n            avlt.inorder();\n \n            System.out.println(\"\\nDo you want to continue (Type y or n) \\n\");\n            ch = scan.next().charAt(0);                        \n        } while (ch == 'Y'|| ch == 'y');               \n    }\n }\n"
  },
  {
    "path": "Data-Structures/Tree/AVL-Tree/AVL_Tree.py",
    "content": "import sys\n\nclass TreeNode(object):\n    def __init__(self, key):\n        self.key = key\n        self.left = None\n        self.right = None\n        self.height = 1\n\n\nclass AVLTree(object):\n    def insert_node(self, root, key):\n\n        # Find the correct location and insert the node\n        if not root:\n            return TreeNode(key)\n        elif key < root.key:\n            root.left = self.insert_node(root.left, key)\n        else:\n            root.right = self.insert_node(root.right, key)\n\n        root.height = 1 + max(self.getHeight(root.left),\n                              self.getHeight(root.right))\n        balanceFactor = self.getBalance(root)\n        if balanceFactor > 1:\n            if key < root.left.key:\n                return self.rightRotate(root)\n            else:\n                root.left = self.leftRotate(root.left)\n                return self.rightRotate(root)\n\n        if balanceFactor < -1:\n            if key > root.right.key:\n                return self.leftRotate(root)\n            else:\n                root.right = self.rightRotate(root.right)\n                return self.leftRotate(root)\n\n        return root\n\n    def delete_node(self, root, key):\n        if not root:\n            return root\n        elif key < root.key:\n            root.left = self.delete_node(root.left, key)\n        elif key > root.key:\n            root.right = self.delete_node(root.right, key)\n        else:\n            if root.left is None:\n                temp = root.right\n                root = None\n                return temp\n            elif root.right is None:\n                temp = root.left\n                root = None\n                return temp\n            temp = self.getMinValueNode(root.right)\n            root.key = temp.key\n            root.right = self.delete_node(root.right,\n                                          temp.key)\n        if root is None:\n            return root\n        root.height = 1 + max(self.getHeight(root.left),\n                              self.getHeight(root.right))\n\n        balanceFactor = self.getBalance(root)\n        if balanceFactor > 1:\n            if self.getBalance(root.left) >= 0:\n                return self.rightRotate(root)\n            else:\n                root.left = self.leftRotate(root.left)\n                return self.rightRotate(root)\n        if balanceFactor < -1:\n            if self.getBalance(root.right) <= 0:\n                return self.leftRotate(root)\n            else:\n                root.right = self.rightRotate(root.right)\n                return self.leftRotate(root)\n        return root\n    def leftRotate(self, z):\n        y = z.right\n        T2 = y.left\n        y.left = z\n        z.right = T2\n        z.height = 1 + max(self.getHeight(z.left),\n                           self.getHeight(z.right))\n        y.height = 1 + max(self.getHeight(y.left),\n                           self.getHeight(y.right))\n        return y\n    def rightRotate(self, z):\n        y = z.left\n        T3 = y.right\n        y.right = z\n        z.left = T3\n        z.height = 1 + max(self.getHeight(z.left),\n                           self.getHeight(z.right))\n        y.height = 1 + max(self.getHeight(y.left),\n                           self.getHeight(y.right))\n        return y\n\n    \n    def getHeight(self, root):\n        if not root:\n            return 0\n        return root.height\n\n    def getBalance(self, root):\n        if not root:\n            return 0\n        return self.getHeight(root.left) - self.getHeight(root.right)\n\n    def getMinValueNode(self, root):\n        if root is None or root.left is None:\n            return root\n        return self.getMinValueNode(root.left)\n\n    def preOrder(self, root):\n        if not root:\n            return\n        print(\"{0} \".format(root.key), end=\"\")\n        self.preOrder(root.left)\n        self.preOrder(root.right)\n\n \n    def printHelper(self, currPtr, indent, last):\n        if currPtr != None:\n            sys.stdout.write(indent)\n            if last:\n                sys.stdout.write(\"R----\")\n                indent += \"     \"\n            else:\n                sys.stdout.write(\"L----\")\n                indent += \"|    \"\n            print(currPtr.key)\n            self.printHelper(currPtr.left, indent, False)\n            self.printHelper(currPtr.right, indent, True)\n\n\nmyTree = AVLTree()\nroot = None\nnums = [33, 13, 52, 9, 21, 61, 8, 11]\nfor num in nums:\n    root = myTree.insert_node(root, num)\nmyTree.printHelper(root, \"\", True)\nkey = 13\nroot = myTree.delete_node(root, key)\nprint(\"After Deletion: \")\nmyTree.printHelper(root, \"\", True)\n"
  },
  {
    "path": "Data-Structures/Tree/AVL-Tree/AVLtree.c",
    "content": "// AVL tree implementation in C\r\n\r\n#include <stdio.h>\r\n#include <stdlib.h>\r\n\r\n// Create Node\r\nstruct Node {\r\n  int key;\r\n  struct Node *left;\r\n  struct Node *right;\r\n  int height;\r\n};\r\n\r\nint max(int a, int b);\r\n\r\n// Calculate height\r\nint height(struct Node *N) {\r\n  if (N == NULL)\r\n    return 0;\r\n  return N->height;\r\n}\r\n\r\nint max(int a, int b) {\r\n  return (a > b) ? a : b;\r\n}\r\n\r\n// Create a node\r\nstruct Node *newNode(int key) {\r\n  struct Node *node = (struct Node *)\r\n    malloc(sizeof(struct Node));\r\n  node->key = key;\r\n  node->left = NULL;\r\n  node->right = NULL;\r\n  node->height = 1;\r\n  return (node);\r\n}\r\n\r\n// Right rotate\r\nstruct Node *rightRotate(struct Node *y) {\r\n  struct Node *x = y->left;\r\n  struct Node *T2 = x->right;\r\n\r\n  x->right = y;\r\n  y->left = T2;\r\n\r\n  y->height = max(height(y->left), height(y->right)) + 1;\r\n  x->height = max(height(x->left), height(x->right)) + 1;\r\n\r\n  return x;\r\n}\r\n\r\n// Left rotate\r\nstruct Node *leftRotate(struct Node *x) {\r\n  struct Node *y = x->right;\r\n  struct Node *T2 = y->left;\r\n\r\n  y->left = x;\r\n  x->right = T2;\r\n\r\n  x->height = max(height(x->left), height(x->right)) + 1;\r\n  y->height = max(height(y->left), height(y->right)) + 1;\r\n\r\n  return y;\r\n}\r\n\r\n// Get the balance factor\r\nint getBalance(struct Node *N) {\r\n  if (N == NULL)\r\n    return 0;\r\n  return height(N->left) - height(N->right);\r\n}\r\n\r\n// Insert node\r\nstruct Node *insertNode(struct Node *node, int key) {\r\n  // Find the correct position to insertNode the node and insertNode it\r\n  if (node == NULL)\r\n    return (newNode(key));\r\n\r\n  if (key < node->key)\r\n    node->left = insertNode(node->left, key);\r\n  else if (key > node->key)\r\n    node->right = insertNode(node->right, key);\r\n  else\r\n    return node;\r\n\r\n  // Update the balance factor of each node and\r\n  // Balance the tree\r\n  node->height = 1 + max(height(node->left),\r\n               height(node->right));\r\n\r\n  int balance = getBalance(node);\r\n  if (balance > 1 && key < node->left->key)\r\n    return rightRotate(node);\r\n\r\n  if (balance < -1 && key > node->right->key)\r\n    return leftRotate(node);\r\n\r\n  if (balance > 1 && key > node->left->key) {\r\n    node->left = leftRotate(node->left);\r\n    return rightRotate(node);\r\n  }\r\n\r\n  if (balance < -1 && key < node->right->key) {\r\n    node->right = rightRotate(node->right);\r\n    return leftRotate(node);\r\n  }\r\n\r\n  return node;\r\n}\r\n\r\nstruct Node *minValueNode(struct Node *node) {\r\n  struct Node *current = node;\r\n\r\n  while (current->left != NULL)\r\n    current = current->left;\r\n\r\n  return current;\r\n}\r\n\r\n// Delete a nodes\r\nstruct Node *deleteNode(struct Node *root, int key) {\r\n  // Find the node and delete it\r\n  if (root == NULL)\r\n    return root;\r\n\r\n  if (key < root->key)\r\n    root->left = deleteNode(root->left, key);\r\n\r\n  else if (key > root->key)\r\n    root->right = deleteNode(root->right, key);\r\n\r\n  else {\r\n    if ((root->left == NULL) || (root->right == NULL)) {\r\n      struct Node *temp = root->left ? root->left : root->right;\r\n\r\n      if (temp == NULL) {\r\n        temp = root;\r\n        root = NULL;\r\n      } else\r\n        *root = *temp;\r\n      free(temp);\r\n    } else {\r\n      struct Node *temp = minValueNode(root->right);\r\n\r\n      root->key = temp->key;\r\n\r\n      root->right = deleteNode(root->right, temp->key);\r\n    }\r\n  }\r\n\r\n  if (root == NULL)\r\n    return root;\r\n\r\n  // Update the balance factor of each node and\r\n  // balance the tree\r\n  root->height = 1 + max(height(root->left),\r\n               height(root->right));\r\n\r\n  int balance = getBalance(root);\r\n  if (balance > 1 && getBalance(root->left) >= 0)\r\n    return rightRotate(root);\r\n\r\n  if (balance > 1 && getBalance(root->left) < 0) {\r\n    root->left = leftRotate(root->left);\r\n    return rightRotate(root);\r\n  }\r\n\r\n  if (balance < -1 && getBalance(root->right) <= 0)\r\n    return leftRotate(root);\r\n\r\n  if (balance < -1 && getBalance(root->right) > 0) {\r\n    root->right = rightRotate(root->right);\r\n    return leftRotate(root);\r\n  }\r\n\r\n  return root;\r\n}\r\n\r\n// Print the Preorder tree\r\nvoid printPreOrder(struct Node *root) {\r\n  if (root != NULL) {\r\n    printf(\"%d \", root->key);\r\n    printPreOrder(root->left);\r\n    printPreOrder(root->right);\r\n  }\r\n}\r\n\r\n// Print the Inorder tree\r\nvoid InOrder(struct Node *root) {\r\n  if (root != NULL) {\r\n    InOrder(root->left);\r\n    printf(\"%d \", root->key);\r\n    InOrder(root->right);\r\n  }\r\n}\r\n\r\n// Print the Postorder tree\r\nvoid PostOrder(struct Node *root) {\r\n  if (root != NULL) {\r\n    PostOrder(root->left);\r\n    PostOrder(root->right);\r\n    printf(\"%d \", root->key);\r\n  }\r\n}\r\n\r\nint main() {\r\n  struct Node *root = NULL;\r\n\r\n  root = insertNode(root, 2);\r\n  root = insertNode(root, 1);\r\n  root = insertNode(root, 7);\r\n  root = insertNode(root, 4);\r\n  root = insertNode(root, 5);\r\n  root = insertNode(root, 3);\r\n  root = insertNode(root, 8);\r\n\r\n  printPreOrder(root);\r\n\r\n  root = deleteNode(root, 3);\r\n\r\n  printf(\"\\nAfter deletion: \");\r\n  printf(\"\\nPreorder: \");\r\n  printPreOrder(root);\r\n  printf(\"\\nInorder: \");\r\n  InOrder(root);\r\n  printf(\"\\nPostorder: \");\r\n  PostOrder(root);\r\n\r\n\r\n\r\n  return 0;\r\n}\r\n\r\n/* Output:\r\n4 2 1 3 7 5 8\r\nAfter deletion:\r\nPreorder: 4 2 1 7 5 8\r\nInorder: 1 2 4 5 7 8\r\nPostorder: 1 2 5 8 7 4 */\r\n\r\n\r\n"
  },
  {
    "path": "Data-Structures/Tree/AVL-Tree/README.md",
    "content": "## This folder is empty.\n"
  },
  {
    "path": "Data-Structures/Tree/AVL-Tree/avl_tree.py",
    "content": "'''\nPython Code for AVL Tree\n@ Author - Sandip Dutta\n------------------------------------------------------------------------\n$ AVL Tree:\n\nAVL Tree is a special kind of Binary Search Tree. Each node in the\ntree, stores a variable called 'BalanceFactor'. Balance Factor\nis equal to the difference between the height of the left \nsubtree and the right subtree of the node.\n\n    BalanceFactor = (height(left_Subtree) - height(right_Subtree))\n\nIn AVL Trees, it is always maintained that the Balance Factor of each \nnode is {-1, 0, 1}. This causes the tree to be balanced, that is not \nskewed in one direction or the other.\n\n$ Example of AVL Tree:\n\n           10\n           / \\\n          8  12\n         /  /  \\\n        2  11  15\n\nIf we calculate the balance factor for each node, it comes \nout to be {0, 1, -1}.\n\n$ Usefulness:\n\nAVL trees have common operations such as min, max, search all in \nO(log(n)) time complexity.\n\n$ How to maintain balance\n\nAVL achieve balance by using rotations. For more details, see Wikipedia.\n'''\n\nclass Node(object):\n    '''Implement node of a tree.'''\n\n    def __init__(\n    self, \n    value, \n    left = None, \n    right = None,    \n    height = 1):\n        '''Implements the node of the tree.\n        @ Args:\n        > value - (int) Value of the node\n        > left - (int, def - None) left node\n        > right - (int, def - None) right node\n        > height - (int, def - 1) height of the tree upto the node.\n                    Since we need to check height multiple times\n                    we store it\n        '''\n        self.value = value\n        self.left = left\n        self.right = right\n        self.height = height\n\nclass AVL_Tree(object):\n    '''Implements AVL Tree.'''\n\n    # Helper/utility functions\n    def getHeight(self, node):\n        '''Returns the height of the node of AVL Tree.\n        @ Args:\n        > node - (Node) node of a tree. If empty tree, is None\n        '''\n        if not node:\n            return 0\n        return node.height\n    \n    def getBalanceFactor(self, node):\n        '''Returns the balance factor of the AVL Tree.\n        @ Args:\n        > node - (Node) node of a tree. If empty tree, is None\n        '''\n        if not node:\n            return 0\n        return self.getHeight(node.left) - self.getHeight(node.right)\n\n    def leftRotate(self, node):\n        ''' Performs left rotation on subtree of a node\n        rooted at @argument: node.\n        @ Args:\n        > node - (Node) node of AVL Tree. Empty == None\n        @ Return:\n        > finalNode - (Node) final Node after left rotation\n        '''\n        finalNode = node.right # final parent node after rotation\n        tempNode = finalNode.left\n\n        # Rotate\n        finalNode.left = node\n        node.right = tempNode\n\n        # update heights\n        node.height = 1 + max(\n            self.getHeight(node.left),\n            self.getHeight(node.right)\n        )\n        finalNode.height = 1 + max(\n            self.getHeight(finalNode.left),\n            self.getHeight(finalNode.right)\n        )\n\n        # return finalNode so that parent of 'node' knows \n        # what to point to\n        return finalNode\n\n    def rightRotate(self, node):\n        ''' Performs right rotation on subtree of a node\n        rooted at @argument: node.\n        @ Args:\n        > node - (Node) node of AVL Tree. Empty == None\n        @ Return:\n        > finalNode - (Node) final Node after right rotation\n        '''\n        finalNode = node.left\n        tempNode = finalNode.right\n\n        # Rotate right\n        finalNode.left = node\n        node.right = tempNode\n\n        # Update heights\n        node.height = 1 + max(\n            self.getHeight(node.left),\n            self.getHeight(node.right)\n        )\n\n        finalNode.height = 1 + max(\n            self.getHeight(finalNode.left),\n            self.getHeight(finalNode.right)\n        )\n\n        # return finalNode so that parent of 'node' what to \n        # point to\n        return finalNode\n\n    def insertNode(self, rootNode, value):\n        '''Inserts node in AVL tree as per standard BST rules\n        and performs necessary rotations to balance the tree.\n        @ Args:\n        > rootNode = (Node) The root node of the tree,\n                        Empty tree === None\n        > value = (int) The value to be inserted\n        @ Return:\n        > rootNode = (Node) The root node of the tree with value\n                    in it's final position\n        '''\n        if not rootNode: return Node(value) # Empty tree\n\n        # Insert as per BST rules\n        if value < rootNode.value:\n            rootNode.left = self.insertNode(rootNode.left, value)\n        else:\n            rootNode.right = self.insertNode(rootNode.right, value)\n\n        # Get balance factor\n        balanceFactor = self.getBalanceFactor(rootNode)\n\n        # Perform rotations after insertion\n        if balanceFactor > 1:            \n            # if below condition is true, we know\n            # as per BST rules, value is in left subtree\n            # of left subtree of rootNode.\n            # As insertion of value caused change in balance\n            # We will adjust that subtree so that balance is\n            # restored. \n            if value < rootNode.left.value:\n                return self.rightRotate(rootNode)\n            else:\n                # Left skewed tree after insertion\n                # but value is greater than value of rootNode\n                # Thus, value is the left node of the tree\n                # After rotation, update parent node with \n                # new left node.\n                rootNode.left = self.leftRotate(root.left)\n                return self.rightRotate(root)\n\n        if balanceFactor < -1:\n            if value > rootNode.right.value:\n                # Adjust right sub tree\n                return self.leftRotate(rootNode)\n            else:\n                # Update parent node\n                rootNode.right = self.rightRotate(root.right)\n                return self.leftRotate(rootNode)\n\n        return rootNode"
  },
  {
    "path": "Data-Structures/Tree/Binary-Indexed-Tree/Binary-Indexed-Tree.c",
    "content": "/**\n Binary Index Tree or Fenwick Tree\n It is a data structure that can efficiently update\n elements and calculate prefix sums in a table of numbers.\n\n There are two types of query that the user can input in this program\n\n 1. Get sum upto ith position\n    Format - 1 i\n    Ex - 1 5\n\n 2. Update the element at ith position to k\n    Format - 2 i k\n    Ex - 1 5 2\n\n    SAMPLE INPUT :-\n        12\n        2 1 1 3 2 3 4 5 6 7 8 9\n        3\n        1 5\n        2 2 6\n        1 5\n\n    EXPECTED OUTPUT :-\n        9\n        14\n*/\n#include <stdio.h>\n\n//Create BIT in O(n) time\nvoid createBIT(int ftree[], int n) {\n\n    for(int i=1; i<=n; i++) {\n        int j = i + (i & (-1*i));\n        if(j <= n)\n            ftree[j] += ftree[i];\n    }\n}\n\n//Update the value in the required nodes in Tree in O(log n)\nvoid update(int ftree[], int n, int val, int i) {\n    while(i <= n) {\n        ftree[i] += val;\n        i += (i & (-1*i));\n    }\n}\n\n//Gives the sum of elements upto ith position in O(log n)\nint getSum(int ftree[], int n, int i) {\n    int sum = 0;\n    while(i != 0) {\n        sum += ftree[i];\n        i -= (i & (-1*i));\n    }\n    return sum;\n}\n\nint main() {\n    int n, query;\n    int val, i, type;\n    printf(\"Enter size of Array: \");\n    scanf(\"%d\", &n);\n\n    int ftree[n+1];\n    int arr[n+1];\n    ftree[0] = arr[0] = 0;\n    printf(\"Enter %d elements in array: \", n);\n    for(i=1; i<=n; i++) {\n        scanf(\"%d\", &arr[i]);\n        ftree[i] = arr[i];\n    }\n\n    printf(\"Enter no. of Queries: \");\n    scanf(\"%d\", &query);\n\n    createBIT(ftree, n);\n    while(query--) {\n        printf(\"Enter Query: \");\n        scanf(\"%d\", &type);\n\n        if(type == 1) {\n            scanf(\"%d\", &i);\n            printf(\"Sum: %d\\n\", getSum(ftree, n, i));\n        }\n        else {\n            scanf(\"%d %d\", &i, &val);\n            update(ftree, n, val - arr[i], i);\n        }\n    }\n}\n"
  },
  {
    "path": "Data-Structures/Tree/Binary-Indexed-Tree/Binary-Indexed-Tree.go",
    "content": "package main\r\n\r\nimport (\r\n\t\"bufio\"\r\n\t\"fmt\"\r\n\t\"os\"\r\n\t\"strconv\"\r\n\t\"strings\"\r\n)\r\n\r\n// BITree is a binary indexed tree, great for getting the sum from index 1 to n\r\ntype BITree []int\r\n\r\n// NewBITree builds a BITree from an array\r\nfunc NewBITree(array []int) BITree {\r\n\toutput := make(BITree, len(array)+1)\r\n\tfor i := 1; i < len(output); i++ {\r\n\t\toutput.Update(i, array[i-1])\r\n\t}\r\n\treturn output\r\n}\r\n\r\n// Update can be used to manually add values in the BITree\r\nfunc (b BITree) Update(i, val int) {\r\n\tfor i < len(b) {\r\n\t\tb[i] += val\r\n\t\t// The line below makes i to move to the parent node\r\n\t\ti += i & (-i)\r\n\t}\r\n}\r\n\r\n// GetSum computes the sum from 1 to i in O(log n) time\r\nfunc (b BITree) GetSum(i int) (sum int) {\r\n\tfor i > 0 {\r\n\t\tsum += b[i]\r\n\t\t// The line below makes i to move to the parent node\r\n\t\ti -= i & (-i)\r\n\t}\r\n\treturn\r\n}\r\n\r\nfunc main() {\r\n\t// Get the array\r\n\treader := bufio.NewReader(os.Stdin)\r\n\tfmt.Print(\"Values separated by commas: \")\r\n\ttext, _ := reader.ReadString('\\n')\r\n\ttext = strings.ReplaceAll(text, \" \", \"\")\r\n\r\n\t// Convert the text array to an actual []int\r\n\ta := make([]int, strings.Count(text, \",\")+1)\r\n\tvar err error\r\n\tfor i, val := range strings.Split(text[:len(text)-2], \",\") {\r\n\t\ta[i], err = strconv.Atoi(val)\r\n\t\tif err != nil {\r\n\t\t\tpanic(err)\r\n\t\t}\r\n\t}\r\n\r\n\tBIT := NewBITree(a)\r\n\r\n\tfmt.Println(\"Binary Indexed Tree array:\")\r\n\tfmt.Println(BIT)\r\n\r\n\tfmt.Println(\"Press Ctrl+c to exit the loop...\")\r\n\tfor {\r\n\t\tindex := 0\r\n\t\tfmt.Print(\"Get the sum from 1 to: \")\r\n\t\tfmt.Scan(&index)\r\n\t\tfmt.Println(BIT.GetSum(index))\r\n\t}\r\n}\r\n"
  },
  {
    "path": "Data-Structures/Tree/Binary-Indexed-Tree/Binary-Indexed-Tree.java",
    "content": "/**\n Binary Index Tree or Fenwick Tree\n It is a data structure that can efficiently update\n elements and calculate prefix sums in a table of numbers.\n\n\n There are two types of query that the user can input in this program\n 1. Get sum upto ith position\n    Format - 1 i\n    Ex - 1 5\n\n 2. Update the element at ith position to k\n    Format - 2 i k\n    Ex - 1 5 2\n\n\n    SAMPLE INPUT :-\n        12\n        2 1 1 3 2 3 4 5 6 7 8 9\n        3\n        1 5\n        2 2 6\n        1 5\n\n    EXPECTED OUTPUT :-\n        9\n        14\n*/\nimport java.io.*;\nimport java.util.StringTokenizer;\n\nclass Binary_Index_Tree {\n\t\n\tstatic BufferedReader br = new BufferedReader(new InputStreamReader(System.in));\n\tstatic StringTokenizer st;\n\t\n\t//Create BIT in O(n) time\n\tstatic void createBIT(int[] ftree, int n) {\n\t\tint i, j;\n\t\tfor(i=1; i<=n; i++) {\n\t\t\tj = i + (i & (-1*i));\n\t\t\tif(j <= n)\n\t\t\t\tftree[j] += ftree[i];\n\t\t}\n\t}\n\n\t//Update the value in the required nodes in Tree in O(log n)\n\tstatic void update(int[] ftree, int n, int val, int i) {\n\t\twhile(i <= n) {\n\t\t\tftree[i] += val;\n\t\t\ti += (i & (-1*i));\n\t\t}\n\t}\n\n\t//Gives the sum of elements upto ith position in O(log n)\n\tstatic int getSum(int[] ftree, int n, int i) {\n\t\tint sum = 0;\n\t\twhile(i != 0) {\n\t\t\tsum += ftree[i];\n\t\t\ti -= (i & (-1*i));\n\t\t}\n\t\treturn sum;\n\t}\n\n\tpublic static void main(String[] args) throws IOException{\n\t\tint n, query;\n\t\tint val, i, type;\n\t\tSystem.out.print(\"Enter size of Array: \");\n\t\tn = Integer.parseInt(br.readLine());\n\n\t\tint[] ftree = new int[n+1];\n\t\tint[] arr = new int[n+1];\n\t\t\n\t\tftree[0] = arr[0] = 0;\n\t\tSystem.out.print(\"Enter \" + n + \" elements in array: \");\n\t\tst = new StringTokenizer(br.readLine());\n\t\tfor(i=1; i<=n; i++) {\n\t\t\tftree[i] = arr[i] = Integer.parseInt(st.nextToken());\n\t\t}\n\n\t\tSystem.out.print(\"Enter no. of Queries: \");\n\t\tquery = Integer.parseInt(br.readLine()); \n\n\t\tcreateBIT(ftree, n);\n\t\twhile(query != 0) {\n\t\t\tSystem.out.print(\"Enter Query: \");\n\t\t\tst = new StringTokenizer(br.readLine());\n\t\t\t\n\t\t\ttype = Integer.parseInt(st.nextToken());\n\t\t\tif(type == 1) {\n\t\t\t\ti = Integer.parseInt(st.nextToken());\n\t\t\t\tSystem.out.println(\"Sum: \" + getSum(ftree, n, i));\n\t\t\t}\n\t\t\telse {\n\t\t\t\ti = Integer.parseInt(st.nextToken());\n\t\t\t\tval = Integer.parseInt(st.nextToken());\n\t\t\t\tupdate(ftree, n, val - arr[i], i);\n\t\t\t}\n\t\t\tquery--;\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "Data-Structures/Tree/Binary-Indexed-Tree/Binary-Indexed-Tree.py",
    "content": "# BUILD, UPDATE ,QUERY BINARY INDEXED TREE OR FENWICK TREE\r\n\r\n\r\nclass BITree:\r\n    # Construction of a Binary Indexed Tree\r\n    def __init__(self, a: list):\r\n        n = len(a) + 1\r\n        self.__BIT = [0] * n\r\n        for i in range(1, n):\r\n            self.update(i, a[i - 1])\r\n\r\n    def __getitem__(self, i):\r\n        return self.__BIT[i]\r\n\r\n    # Always pass by this method to update the BITree\r\n    def update(self, i: int, val: int):\r\n        while i < len(self.__BIT):\r\n            self.__BIT[i] += val\r\n            # The line below makes i to move to the parent node\r\n            i += i & (-i)\r\n\r\n    def getSum(self, i: int):\r\n        total = 0\r\n        while i > 0:\r\n            total += self.__BIT[i]\r\n            i -= i & (-i)\r\n\r\n        return total\r\n\r\n\r\nif __name__ == \"__main__\":\r\n    a = [\r\n        int(i)\r\n        for i in input(\"Values of separated by commas: \").replace(\" \", \"\").split(\",\")\r\n    ]\r\n    BIT = BITree(a)\r\n\r\n    print(\"Binary Indexed Tree array:\")\r\n    print(\", \".join(str(i) for i in BIT))\r\n\r\n    print(\"Press Ctrl+c to exit the loop...\")\r\n    while True:\r\n        index = int(input(\"Get the sum from 1 to : \"))\r\n        print(BIT.getSum(index))\r\n"
  },
  {
    "path": "Data-Structures/Tree/Binary-Search-Tree/BST.cs",
    "content": "using System;\n// http://csharpexamples.com/c-binary-search-tree-implementation/\n\nclass Node\n{\n    public Node LeftNode { get; set; }\n    public Node RightNode { get; set; }\n    public int Data { get; set; }\n}\n\nclass BinaryTree\n{\n    public Node Root { get; set; }\n \n    public bool Add(int value)\n    {\n        Node before = null, after = this.Root;\n \n        while (after != null)\n        {\n            before = after;\n            if (value < after.Data) //Is new node in left tree? \n                  after = after.LeftNode; \n            else if (value > after.Data) //Is new node in right tree?\n                after = after.RightNode;\n            else\n            {\n                //Exist same value\n                return false;\n            }\n        }\n \n        Node newNode = new Node();\n        newNode.Data = value;\n \n        if (this.Root == null)//Tree ise empty\n            this.Root = newNode;\n        else\n        {\n            if (value < before.Data)\n                before.LeftNode = newNode;\n            else\n                before.RightNode = newNode;\n        }\n \n        return true;\n    }\n \n    public Node Find(int value)\n    {\n        return this.Find(value, this.Root);            \n    }\n \n    public void Remove(int value)\n    {\n        this.Root = Remove(this.Root, value);\n    }\n \n    private Node Remove(Node parent, int key)\n    {\n        if (parent == null) return parent;\n \n        if (key < parent.Data) parent.LeftNode = Remove(parent.LeftNode, key); else if (key > parent.Data)\n            parent.RightNode = Remove(parent.RightNode, key);\n \n        // if value is same as parent's value, then this is the node to be deleted  \n        else\n        {\n            // node with only one child or no child  \n            if (parent.LeftNode == null)\n                return parent.RightNode;\n            else if (parent.RightNode == null)\n                return parent.LeftNode;\n \n            // node with two children: Get the inorder successor (smallest in the right subtree)  \n            parent.Data = MinValue(parent.RightNode);\n \n            // Delete the inorder successor  \n            parent.RightNode = Remove(parent.RightNode, parent.Data);\n        }\n \n        return parent;\n    }\n \n    private int MinValue(Node node)\n    {\n        int minv = node.Data;\n \n        while (node.LeftNode != null)\n        {\n            minv = node.LeftNode.Data;\n            node = node.LeftNode;\n        }\n \n        return minv;\n    }\n \n    private Node Find(int value, Node parent)\n    {\n        if (parent != null)\n        {\n            if (value == parent.Data) return parent;\n            if (value < parent.Data)\n                return Find(value, parent.LeftNode);\n            else\n                return Find(value, parent.RightNode);\n        }\n \n        return null;\n    }\n \n    public int GetTreeDepth()\n    {\n        return this.GetTreeDepth(this.Root);\n    }\n \n    private int GetTreeDepth(Node parent)\n    {\n        return parent == null ? 0 : Math.Max(GetTreeDepth(parent.LeftNode), GetTreeDepth(parent.RightNode)) + 1;\n    }\n \n    public void TraversePreOrder(Node parent)\n    {\n        if (parent != null)\n        {\n            Console.Write(parent.Data + \" \");\n            TraversePreOrder(parent.LeftNode);\n            TraversePreOrder(parent.RightNode);\n        }\n    }\n \n    public void TraverseInOrder(Node parent)\n    {\n        if (parent != null)\n        {\n            TraverseInOrder(parent.LeftNode);\n            Console.Write(parent.Data + \" \");\n            TraverseInOrder(parent.RightNode);\n        }\n    }\n \n    public void TraversePostOrder(Node parent)\n    {\n        if (parent != null)\n        {\n            TraversePostOrder(parent.LeftNode);\n            TraversePostOrder(parent.RightNode);\n            Console.Write(parent.Data + \" \");\n        }\n    }\n\n    static void Main(string[] args) {\n        BinaryTree binaryTree = new BinaryTree();\n        \n        binaryTree.Add(1);\n        binaryTree.Add(2);\n        binaryTree.Add(7);\n        binaryTree.Add(3);\n        binaryTree.Add(10);\n        binaryTree.Add(5);\n        binaryTree.Add(8);\n        \n        Node node = binaryTree.Find(5);\n        int depth = binaryTree.GetTreeDepth();\n        \n        Console.WriteLine(\"PreOrder Traversal:\");\n        binaryTree.TraversePreOrder(binaryTree.Root);\n        Console.WriteLine();\n        \n        Console.WriteLine(\"InOrder Traversal:\");\n        binaryTree.TraverseInOrder(binaryTree.Root);\n        Console.WriteLine();\n        \n        Console.WriteLine(\"PostOrder Traversal:\");\n        binaryTree.TraversePostOrder(binaryTree.Root);\n        Console.WriteLine();\n        \n        binaryTree.Remove(7);\n        binaryTree.Remove(8);\n        \n        Console.WriteLine(\"PreOrder Traversal After Removing Operation:\");\n        binaryTree.TraversePreOrder(binaryTree.Root);\n        Console.WriteLine();\n    }\n}\n\n"
  },
  {
    "path": "Data-Structures/Tree/Binary-Search-Tree/BST_balanced.cpp",
    "content": "#include <iostream>\n#include <cmath>\n \nusing namespace std;\nint mx = -1e9-10, mn = 1e9+10, c = 0;\nstruct node\n{\n    int key;\n    node * left;\n    node * right;\n \tbool isBalancedNode;\n    node(int k) {\n        key = k;\n        left = right = NULL;\n        isBalancedNode = true;\n    }\n};\n \nstruct BST\n{\n    node * root;\n    int cnt;\n \n    BST() {\n        cnt = 0;\n        root = NULL;\n    }\n \n    node * add(node * root, int x) {\n       \n        if(root == NULL)\n        {\n            node * n = new node(x);\n            root = n;\n            cnt++;\n        }\n        else if(x < root->key)\n        {\n            root->left = add(root->left, x);\n        }\n        else if(x > root->key)\n        {\n            root->right = add(root->right, x);\n        }\n        return root;\n    }\n\n\n\n    void inorder(node * x) {\n        if(x != NULL) {\n            inorder(x->left);\n            cout << x->key << ' ' << x->isBalancedNode << '\\n';\n            inorder(x->right);\n        }\n    }\n\n    int balance(node * root, int h) {\n    \tif(root == NULL) return h;\n    \tint l = balance(root->left, h+1);\n    \tint r = balance(root->right, h+1);\n    \troot->isBalancedNode = (abs(l - r) < 2);\n    \treturn max(l, r);\n    }\n\n    bool isBalanced(node * x) {\n    \tif(x == NULL) return true;\n    \treturn x->isBalancedNode && isBalanced(x->right) && isBalanced(x->left);\n    }\n};\nint main() {\n    BST myTree;\n    int x, cnt=0;\n    while(cin>>x && x!=0)\n    {\n        myTree.root = myTree.add(myTree.root, x);\n    }\n    myTree.balance(myTree.root, 0);\n    \n    cout <<(myTree.isBalanced(myTree.root) ? \"YES\" : \"NO\");\n\n    return 0;\n}\n"
  },
  {
    "path": "Data-Structures/Tree/Binary-Search-Tree/BinarySearchTree.go",
    "content": "package main\n\nimport \"fmt\"\n\ntype treeNode struct {\n\tvalue     int\n\tleftNode  *treeNode\n\trightNode *treeNode\n}\n\ntype tree struct {\n\troot *treeNode\n}\n\nfunc (binaryTree *tree) reset() {\n\tbinaryTree.root = nil\n}\n\nfunc (binaryTree *tree) insert(value int) {\n\tbinaryTree.insertRec(binaryTree.root, value)\n}\n\nfunc (binaryTree *tree) insertRec(node *treeNode, value int) *treeNode {\n\tif binaryTree.root == nil {\n\t\tbinaryTree.root = &treeNode{\n\t\t\tvalue: value,\n\t\t}\n\t\treturn binaryTree.root\n\t}\n\tif node == nil {\n\t\treturn &treeNode{value: value}\n\t}\n\tif value <= node.value {\n\t\tnode.leftNode = binaryTree.insertRec(node.leftNode, value)\n\t}\n\tif value > node.value {\n\t\tnode.rightNode = binaryTree.insertRec(node.rightNode, value)\n\t}\n\treturn node\n}\n\nfunc (binaryTree *tree) find(value int) error {\n\tnode := binaryTree.findRec(binaryTree.root, value)\n\tif node == nil {\n\t\treturn fmt.Errorf(\"value: %d not present\", value)\n\t}\n\treturn nil\n}\n\nfunc (binaryTree *tree) findRec(node *treeNode, value int) *treeNode {\n\tif node == nil {\n\t\treturn nil\n\t}\n\tif node.value == value {\n\t\treturn binaryTree.root\n\t}\n\tif value < node.value {\n\t\treturn binaryTree.findRec(node.leftNode, value)\n\t}\n\treturn binaryTree.findRec(node.rightNode, value)\n}\n\nfunc (binaryTree *tree) inorder() {\n\tbinaryTree.inorderRec(binaryTree.root)\n}\n\nfunc (binaryTree *tree) inorderRec(node *treeNode) {\n\tif node != nil {\n\t\tbinaryTree.inorderRec(node.leftNode)\n\t\tfmt.Println(node.value)\n\t\tbinaryTree.inorderRec(node.rightNode)\n\t}\n}\n\nfunc main() {\n\tbinaryTree := &tree{}\n\telements := []int{32, 48, 17, -8, 13, 21, 19}\n\tfor _, val := range elements {\n\t\tbinaryTree.insert(val)\n\t}\n\n\tfmt.Printf(\"Traversing the tree: Inorder:\\n\")\n\tbinaryTree.inorder()\n\tbinaryTree.reset()\n\telements = []int{-13, -8, 15, 12, 0, 63, 21}\n\tfor _, val := range elements {\n\t\tbinaryTree.insert(val)\n\t}\n\n\tfmt.Printf(\"\\nTraversing the tree: Inorder:\\n\")\n\tbinaryTree.inorder()\n\tfmt.Printf(\"\\nFinding Values:\\n\")\n\n\ttoFind := 48\n\terr := binaryTree.find(toFind)\n\tif err != nil {\n\t\tfmt.Printf(\"Value %d Not Found\\n\", toFind)\n\t} else {\n\t\tfmt.Printf(\"Value %d Found\\n\", toFind)\n\t}\n\n\ttoFind = -33\n\terr = binaryTree.find(toFind)\n\tif err != nil {\n\t\tfmt.Printf(\"Value %d Not Found\\n\", toFind)\n\t} else {\n\t\tfmt.Printf(\"Value %d Found\\n\", toFind)\n\t}\n\n\ttoFind = 21\n\terr = binaryTree.find(toFind)\n\tif err != nil {\n\t\tfmt.Printf(\"Value %d Not Found\\n\", toFind)\n\t} else {\n\t\tfmt.Printf(\"Value %d Found\\n\", toFind)\n\t}\n\n\ttoFind = 0\n\terr = binaryTree.find(toFind)\n\tif err != nil {\n\t\tfmt.Printf(\"Value %d Not Found\\n\", toFind)\n\t} else {\n\t\tfmt.Printf(\"Value %d Found\\n\", toFind)\n\t}\n}\n"
  },
  {
    "path": "Data-Structures/Tree/Binary-Search-Tree/BinarySearchTree.java",
    "content": "import java.util.LinkedList;\nimport java.util.Queue;\nimport java.util.Stack;\npublic class BinarySearchTree {\n    TreeNode root;\n    public BinarySearchTree(){\n        this.root = null;\n    }\n    public boolean isEmpty(){\n        return root==null;\n    }\n    public void deleteByCopying(int deletevalue){\n        TreeNode p = this.root,prev=null;\n        while(p!=null && p.info != deletevalue){\n            prev = p;\n            if(deletevalue >= p.info){\n                p = p.right;\n            }\n            else{\n                p=p.left;\n            }\n        }\n        TreeNode node = p;\n        if(p!=null && p.info==deletevalue){\n            if(node.right == null){\n                node = node.left;\n            }\n            else if(node.left == null){\n                node = node.right;\n            }\n            else{\n                TreeNode tmp = node.left;\n                TreeNode prev2 = node;\n                while(tmp.right!=null){\n                    prev2 = tmp;\n                    tmp = tmp.right;\n                }\n                node.info = tmp.info;\n                if(prev2==node){\n                    prev2.left = tmp.left;\n                }\n                else{\n                    prev2.right = tmp.left;\n                }\n            }\n        }\n    }\n    public void deleteByMerging(int deleteValue){\n        TreeNode p=this.root,prev=null;\n        while(p!=null && p.info!=deleteValue){ // Search for delete node\n            prev=  p;\n            if(deleteValue >= p.info){\n                p = p.right;\n            }\n            else{\n                p = p.left;\n            }\n        }\n        TreeNode nodeForPrevToPointTo = p;\n        if(p!=null && p.info == deleteValue){\n            if(p.right ==null){\n                nodeForPrevToPointTo = p.left;\n            }\n            else if(p.left == null){\n                nodeForPrevToPointTo = p.right;\n            }\n            else{\n                TreeNode temp = nodeForPrevToPointTo.left;\n                while(temp.right!=null){\n                    temp = temp.right;\n                }\n                temp.right = p.right;\n                nodeForPrevToPointTo = p.left;\n                if(p == root){\n                    root = nodeForPrevToPointTo;\n                }\n                else if(prev.left == p){\n                    prev.left = nodeForPrevToPointTo;\n                }\n                else{\n                    prev.right = nodeForPrevToPointTo;\n                }\n            }\n        }\n        else if(root!=null){\n            System.out.println(\"Key \" + deleteValue + \"is not in the tree\");\n        }\n        else{\n            System.out.println(\"The tree is empty\");\n        }\n    }\n    public void preorderTravelsal(){\n        TreeNode p = root;\n        Stack stack = new Stack();\n        if(p!=null){\n            stack.push(p);\n            while(!stack.isEmpty()){\n                p= (TreeNode)stack.pop();\n                System.out.print(p.info+\" \");\n                if(p.right!=null){\n                    stack.push(p.right);\n                }\n                if(p.left!=null){\n                    stack.push(p.left);\n                }\n            }\n        }\n    }\n    public void breadthFirstTraversal(){\n        TreeNode p  = root;\n        Queue<TreeNode> q = new LinkedList<>();\n        if(p!=null){\n            q.add(p);\n            while(!q.isEmpty()){\n                p = q.remove();\n                System.out.print(p.info + \" \");\n                if(p.left !=null){\n                    q.add(p.left);\n                }\n                if(p.right!=null){\n                    q.add(p.right);\n                }\n            }\n        }\n    }\n    public void inorderTraversalRecursion(TreeNode p){\n        if(p!=null){\n            inorderTraversalRecursion(p.left);\n            System.out.print(p.info + \" \"); //visit node p\n            inorderTraversalRecursion(p.right);\n        }\n    }\n    public void preorderTraversalRecursion(TreeNode p){\n        if(p!=null){\n            System.out.print(p.info + \" \"); //visit node p\n            preorderTraversalRecursion(p.left);\n            preorderTraversalRecursion(p.right);\n        }\n    }\n    public void postorderTraversalRecursion(TreeNode p){\n        if(p!=null){\n            postorderTraversalRecursion(p.left);\n            postorderTraversalRecursion(p.right);\n            System.out.print(p.info + \" \"); //visit node p\n        }\n    }\n    public void insert(int newInfo){\n        if(isEmpty()){\n            this.root = new TreeNode(newInfo);\n        }\n        else{\n            TreeNode p = root;\n            while(p!=null){\n                if(newInfo<p.info){\n                    if(p.left != null){\n                        p = p.left;\n                    }\n                    else{\n                        p.left = new TreeNode(newInfo);\n                        break;\n                    }\n                }\n                else{\n                    if(p.right != null){\n                        p = p.right;\n                    }\n                    else{\n                        p.right = new TreeNode(newInfo);\n                        break;\n                    }\n                }\n            }\n        }\n    }\n    public TreeNode search(int info){\n        if(isEmpty()){\n            System.out.println(\"Cannot find : \"+info);\n            return null;\n        }\n        else{\n            TreeNode p = root;\n            while(p!=null){\n                if(p.info == info){\n                    System.out.println(\"Found : \"+info);\n                    return p;\n                }\n                else if(info < p.info){\n                    p = p.left;\n                }\n                else{\n                    p = p.right;\n                }\n            }\n            System.out.println(\"Cannot find : \"+info);\n            return null;\n        }\n    }  \n    public int countNode(TreeNode t){\n        if(t !=null){\n            return 1+countNode(t.left)+countNode(t.right);\n        }\n        else{\n            return 0;\n        }\n    }\n    public int countLeaves(TreeNode t){\n        if(t==null){\n            return 0;\n        }\n        else if(t.left ==null && t.right == null){\n            return 1;\n        }\n        else{\n            return countLeaves(t.left)+countLeaves(t.right);\n        }\n    }\n    public int countRightChildren(TreeNode t){\n        if(t.right !=null){\n            if(t.left!=null){\n                return 1 + countRightChildren(t.left) + countRightChildren(t.right);\n            }\n            else{\n                return 1 + countRightChildren(t.right);\n            }\n        }\n        else{\n            if(t.left!=null){\n                return countRightChildren(t.left);\n            }\n            return 0;\n        }\n    }\n    public int getHeight(TreeNode t){\n        if(t != null){\n            return 1 + Math.max(getHeight(t.left),getHeight(t.right));\n        }\n        else{\n            return 0;\n        }\n\n    }\n    public void deleteLeaves(TreeNode t){\n        if(t==null){ return; }\n        else if(t.left!=null || t.right != null){\n            if(t.left!=null && t.right != null){\n                if(t.left.left==null&&t.left.right==null){\n                    t.left = null;\n                }\n                if(t.right.left==null&&t.right.right==null){\n                    t.right = null;\n                }\n            }\n            else if(t.left!=null){\n                if(t.left.left==null&&t.left.right==null){\n                    t.left = null;\n                }\n            }\n            else{\n                if(t.right.left==null&&t.right.right==null){\n                    t.right = null;\n                }\n            }\n        }\n        deleteLeaves(t.left);       deleteLeaves(t.right);\n    }\n    public void breadthFirst(){\n        TreeNode p  = root;\n        Queue<TreeNode> queue = new LinkedList<TreeNode>();\n        if(p!=null){\n            queue.add(p);\n            while(!queue.isEmpty()){\n                p = queue.poll();\n                System.out.print(p.info + \" \");\n                if(p.left !=null){\n                    queue.add(p.left);\n                }\n                if(p.right!=null){\n                    queue.add(p.right);\n                }\n            }\n        }\n    }\n    public void preorder(TreeNode p){\n        if(p!=null){\n            System.out.print(p.info + \" \");\n            preorder(p.left);\n            preorder(p.right);\n        }\n    }\n    public void inorder(TreeNode p){\n        if(p!=null){\n            inorder(p.left);\n            System.out.print(p.info + \" \");\n            inorder(p.right);\n        }\n    }\n    public void postorder(TreeNode p){\n        if(p!=null){\n            postorder(p.left);\n            postorder(p.right);\n            System.out.print(p.info+ \" \");\n        }\n    }\n    public void iterativePreorder(){\n        TreeNode p = root;\n        Stack travStack = new Stack();\n        if(p!=null){\n            travStack.push(p);\n            while(!travStack.isEmpty()){\n                p= (TreeNode)travStack.pop();\n                System.out.print(p.info+\" \");\n                if(p.right!=null){\n                    travStack.push(p.right);\n                }\n                if(p.left!=null){\n                    travStack.push(p.left);\n                }\n            }\n        }\n    }\n    public void iterativeInorder(){\n        TreeNode p = root;\n        Stack travStack = new Stack();\n        while(p!=null){\n            while(p!=null){\n            if(p.right!=null){\n                travStack.push(p.right);\n            }\n            travStack.push(p);\n            p = p.left;\n            }\n            p = (TreeNode) travStack.pop();\n            while(!travStack.isEmpty() && p.right == null){\n                System.out.print(p.info+\" \");\n                p = (TreeNode) travStack.pop();\n            }\n            System.out.print(p.info+\" \");\n            if(!travStack.isEmpty()){\n                p= (TreeNode) travStack.pop();\n            }\n            else{\n                p = null;\n            }\n        }\n    }\n    public void iterativeLastorder(){\n        TreeNode p = root,q=root;\n        Stack travStack = new Stack();\n        while(p!=null){\n            for(;p.left!=null;p=p.left){\n                travStack.push(p);\n            }\n            while(p!=null && (p.right==null||p.right==q)){\n                System.out.print(p.info+\" \");\n                q = p;\n                if(travStack.isEmpty())return;\n                p = (TreeNode) travStack.pop();\n            }\n            travStack.push(p);\n            p=p.right;\n        }\n    }\n}\nclass TreeNode {\n    int info;\n    TreeNode left,right;\n    public TreeNode(int info){\n        this(info,null,null);\n    }\n    public TreeNode(int info,TreeNode left,TreeNode right){\n        this.info = info;\n        this.left = left;\n        this.right = right;\n    }\n}"
  },
  {
    "path": "Data-Structures/Tree/Binary-Search-Tree/Binary_Search_Tree.cpp",
    "content": "// Author : Sachin19k\r\n// Topic: Binary Search Tree \r\n\r\n/* Problem Statement : \r\nImplement binary search tree and perform following operations:\r\na) Insert (Handle insertion of duplicate entry)\r\nb) Delete\r\nc) Search\r\nd) Display tree Traversal (Recursive & Non-recursive)\r\ne) Display - Depth of tree\r\nf) Display - Mirror image\r\ng) Create a copy\r\nh) Display all parent nodes with their child nodes\r\ni) Display leaf nodes\r\nj) Display tree level wise  */\r\n\r\n#include<iostream> \r\n#include<queue> \r\n#include<stack> \r\nusing namespace std; \r\n\r\n\r\n// Structure of the node of Binary Search Tree\r\nstruct dll \r\n{ \r\n   int data; \r\n   dll *left; \r\n   dll *right; \r\n};\r\n\r\ndll *BSTinsert(dll *root,int x) //Inserting node in BST\r\n{ \r\n   dll *p, *prev, *r; \r\n   r=new dll; \r\n   r->data=x; \r\n   r->left=NULL; \r\n   r->right=NULL; \r\n   if(root==NULL) \r\n   { \r\n       return r; \r\n   } \r\n\r\n   p=root; \r\n   while(p!=NULL) \r\n   { \r\n       prev=p; \r\n       if(x>p->data) \r\n           p=p->right; \r\n       else if(x<p->data) \r\n           p=p->left; \r\n       else \r\n       { \r\n cout<<\"DUPLICATE ELEMENTS ARRIVED :(\\n\"; //duplicate entry \r\n return (root); \r\n} \r\n} \r\nif(x>prev->data) \r\n   prev->right=r; \r\nelse \r\n   prev->left=r; \r\nreturn (root); \r\n} \r\n\r\nvoid levelorder(dll *root) //Print the node in levelorder form\r\n{ \r\n   if(root==NULL) \r\n       return; \r\n   queue <dll *> p; \r\n   p.push(root); \r\n   int count=1; \r\n   while(!p.empty()) \r\n   { \r\n       if(count==0) \r\n       { \r\n           cout<<\"\\n\"; \r\n           count=p.size(); \r\n       } \r\n\r\n       dll *q = p.front(); \r\n       cout<<q->data<<\"\\t\"; \r\n       if(q->left!=NULL) \r\n           p.push(q->left); \r\n       if(q->right!=NULL) \r\n           p.push(q->right); \r\n       p.pop(); \r\n       count--; \r\n\r\n   } \r\n} \r\n\r\nvoid Rpreorder(dll *root) //Recursive Postorder\r\n{ \r\n   if(root!=NULL) \r\n   { \r\n       cout<<root->data<<\"\\t\"; \r\n       Rpreorder(root->left); \r\n       Rpreorder(root->right); \r\n   } \r\n} \r\n\r\nvoid NRpreorder(dll *root) //Iterative Preorder\r\n{ \r\n   stack <dll *> s; \r\n   while(!s.empty() || root!=NULL) \r\n   { \r\n       while(root!=NULL) \r\n       { \r\n           cout<<root->data<<\"\\t\"; \r\n           s.push(root); \r\n           root=root->left; \r\n       } \r\n       root=s.top(); \r\n       s.pop(); \r\n       root=root->right; \r\n\r\n   } \r\n} \r\n\r\nvoid Rinorder(dll *root) //Recursive Inorder\r\n{ \r\n   if(root!=NULL) \r\n   { \r\n       Rinorder(root->left); \r\n       cout<<root->data<<\"\\t\"; \r\n       Rinorder(root->right); \r\n   } \r\n} \r\n\r\nvoid NRinorder(dll *root) //Iterative Inorder\r\n{ \r\n   stack <dll *> s; \r\n   while(!s.empty() || root!=NULL) \r\n   { \r\n       while(root!=NULL) \r\n       { \r\n           s.push(root); \r\n           root=root->left; \r\n       } \r\n       root=s.top(); \r\n       s.pop(); \r\n       cout<<root->data<<\"\\t\"; \r\n       root=root->right; \r\n   } \r\n} \r\n\r\nvoid Rpostorder(dll *root) //Recursive Postorder\r\n{ \r\n   if(root==NULL) \r\n   { \r\n       return; \r\n   } \r\n   Rpostorder(root->left); \r\n\r\n   Rpostorder(root->right); \r\n\r\n   cout<<root->data<<\"\\t\"; \r\n} \r\n\r\nvoid NRpostorder(dll *root) //Iterative Postorder\r\n{ \r\n   stack <dll*> s1; \r\n   stack <int> s2; \r\n   while(root!=NULL) \r\n   { \r\n       s1.push(root); \r\n       s2.push(0); \r\n       root=root->left; \r\n   } \r\n   while(!s1.empty()) \r\n   { \r\n       root=s1.top(); \r\n       if(s2.top()==1) \r\n       { \r\n           s1.pop(); \r\n           s2.pop(); \r\n           cout<<root->data<<\"\\t\"; \r\n       } \r\n       else \r\n       { \r\n           s2.top()=1; \r\n           root=root->right; \r\n           while(root!=NULL) \r\n           { \r\n               s1.push(root); \r\n               s2.push(0); \r\n               root=root->left; \r\n           } \r\n       } \r\n   } \r\n} \r\n\r\nint BSTheight(dll *root) //Height of BST\r\n{ \r\n   if(root==NULL) \r\n       return -1; \r\n   queue <dll *> p; \r\n   p.push(root); \r\n   int ht=-1,count; \r\n   while(1) \r\n   { \r\n       count=p.size(); \r\n       if(count==0) \r\n           return ht; \r\n       ht++; \r\n       while(count--) \r\n       { \r\n           dll *q=p.front(); \r\n           p.pop(); \r\n           if(q->left!=NULL) \r\n               p.push(q->left); \r\n           if(q->right!=NULL) \r\n               p.push(q->right); \r\n       } \r\n   } \r\n} \r\n\r\ndll* f_min(dll *root) //Find Minimum element from root\r\n{ \r\n   dll*p=root; \r\n   while(p->left!=NULL) \r\n   { \r\n       p=p->left; \r\n   } \r\n   return (p); \r\n} \r\n\r\ndll *f_max(dll *root) //Find Maximum element from root\r\n{ \r\n   dll *p=root; \r\n   while(p->right!=NULL) \r\n   { \r\n       p=p->right; \r\n   } \r\n   return (p); \r\n} \r\n\r\nbool search(dll *root,int x) //Search an element in BST\r\n{ \r\n   while(root!=NULL) \r\n   { \r\n       if(x==root->data) \r\n       { \r\n           cout<<\"ELEMENT FOUND :)\\n\" ; \r\n           return true; \r\n       } \r\n       else if(x>root->data) \r\n       { \r\n           root=root->right; \r\n       } \r\n       else \r\n       { \r\n           root=root->left; \r\n       } \r\n   } \r\n   cout<<\"ELEMENT NOT FOUND :( \\n\" ; \r\n   return false; \r\n\r\n} \r\n\r\ndll *bstdelete(dll *root, int x) //Delete the node from BST\r\n{ \r\n   dll *m; \r\n   if(root==NULL) \r\n   { \r\n       cout<<\"NOT FOUND!!\"; \r\n       return root; \r\n   } \r\n   if(x < root->data) \r\n   { \r\n       root->left=bstdelete(root->left,x); \r\n       return root; \r\n   } \r\n   if(x>root->data) \r\n   { \r\n       root->right=bstdelete(root->right,x); \r\n       return root; \r\n   } \r\n   if(root->left==NULL && root->right==NULL) \r\n   { \r\n       m=root; \r\n       delete m; \r\n       return (NULL); \r\n   } \r\n   else if(root->left==NULL) \r\n   { \r\n       m=root; \r\n       root=root->right; \r\n       delete m; \r\n       return (root); \r\n   } \r\n   else if(root->right==NULL) \r\n   { \r\n       m=root; \r\n       root=root->left; \r\n       delete m; \r\n       return (root); \r\n   } \r\n   m=f_min(root->right); \r\n   root->data=m->data; \r\n   root->right=bstdelete(root->right, m->data); \r\n   return (root); \r\n} \r\n\r\ndll *mirr(dll *root) //Mirror image of the BST\r\n{ \r\n   if(root==NULL) \r\n       return NULL; \r\n   dll *p=root; \r\n   queue <dll *> q; \r\n   q.push(root); \r\n   while(!q.empty()) \r\n   { \r\n       dll *curr=q.front(); \r\n       q.pop(); \r\n       swap(curr->left, curr->right); \r\n       if(curr->left) \r\n           q.push(curr->left); \r\n       if(curr->right) \r\n           q.push(curr->right); \r\n   } \r\n   return (p); \r\n} \r\n\r\ndll *nd_copy(dll *root) \r\n{ \r\n   if(root==NULL) \r\n   { \r\n       return root; \r\n   } \r\n   dll *p = new dll; \r\n   p->data=root->data; \r\n   p->left=nd_copy(root->left); \r\n   p->right=nd_copy(root->right); \r\n   return p; \r\n} \r\n\r\nvoid par_chld(dll *root) //Print all parents and their Children\r\n{ \r\n   if(root==NULL) \r\n       return; \r\n   queue <dll *> p; \r\n   p.push(root); \r\n   int count=1,x; \r\n   while(!p.empty()) \r\n   { \r\n       x=0; \r\n       dll *q = p.front(); \r\n       cout<<q->data<<\"\\t\"; \r\n       if(q->left!=NULL) \r\n       { \r\n           x++; \r\n           p.push(q->left); \r\n           cout<<(q->left)->data<<\"\\t\"; \r\n       } \r\n       if(q->right!=NULL) \r\n       { \r\n           x++; \r\n           p.push(q->right); \r\n           cout<<(q->right)->data<<\"\\t\"; \r\n       } \r\n       if(x==0) \r\n       { \r\n           cout<<\"\\t\\t(node has no child)\"; \r\n       } \r\n       else if(x==1) \r\n       { \r\n           cout<<\"\\t(node has one child)\"; \r\n       } \r\n       else if(x==2) \r\n       { \r\n           cout<<\"(node has two children)\"; \r\n       } \r\n       p.pop(); \r\n       cout<<\"\\n\"; \r\n\r\n   } \r\n} \r\n\r\nvoid leaf_nd(dll *root) //Print all leafnode in BST\r\n{ \r\n   if (!root) \r\n       return; \r\n\r\n   if (root->left==NULL && root->right==NULL) \r\n   { \r\n       cout << root->data << \"\\t\"; \r\n       return; \r\n   } \r\n\r\n   if (root->left) \r\n       leaf_nd(root->left); \r\n\r\n   if (root->right) \r\n       leaf_nd(root->right); \r\n} \r\n\r\nint main() //main function\r\n{ \r\n   dll *root=NULL,*z=NULL; \r\n   bool b; \r\n   int n,p,x; \r\n   \r\n   cout<<\"[1] BST INSERT\\n\"; \r\n   cout<<\"[2] DELETE \\n\"; \r\n   cout<<\"[3] SEARCH AN ELEMENT'S PRESENCE \\n\"; \r\n   cout<<\"[4] RECURSIVE PREORDER\\n\"; \r\n   cout<<\"[5] NON RECURSIVE PREORDER\\n\"; \r\n   cout<<\"[6] RECURSIVE INORDER\\n\"; \r\n   cout<<\"[7] NON RECURSIVE INORDER\\n\"; \r\n   cout<<\"[8] RECURSIVE POSTORDER\\n\"; \r\n   cout<<\"[9] NON RECURSIVE POSTORDER\\n\"; \r\n   cout<<\"[10] HEIGHT OF TREE \\n\"; \r\n   cout<<\"[11] MIRROR IMAGE \\n\"; \r\n   cout<<\"[12] CREATE A COPY \\n\"; \r\n   cout<<\"[13] DISPLAY ALL PARENT NODES WITH CHILD NODES \\n\"; \r\n   cout<<\"[14] DISPLAY LEAF NODES \\n\"; \r\n   cout<<\"[15] LEVEL ORDER DISPLAY\\n\"; \r\n   cout<<\"[16] FIND MINIMUM \\n\"; \r\n   cout<<\"[17] FIND MAXIMUM \\n\";\r\n   \r\n   do \r\n   { \r\n       cout<<\"\\nEnter your choice: \"; \r\n       cin>>n; \r\n       switch(n) \r\n       { \r\n           case 1: \r\n           do \r\n           { \r\n               cout<<\"enter the data \\n\"; \r\n               cin>>x; \r\n               root = BSTinsert(root,x); \r\n               cout<<\"want to enter more?\\n\"; \r\n               cin>>p; \r\n           } \r\n           while(p!=0); \r\n           break; \r\n           case 2: \r\n           cout<<\"enter the element to be deleted?\\n\"; \r\n           cin>>x; \r\n           if(search(root,x)) \r\n           { \r\n               root = bstdelete(root,x); \r\n               levelorder(root); \r\n           } \r\n           else \r\n           { \r\n               cout<<\"CAN'T DELETE!! \\n\"; \r\n           } \r\n           break; \r\n           case 3: \r\n           cout<<\"ENTER THE ELEMENT TO BE SEARCHED??\\n\"; \r\n           cin>>x; \r\n           b = search(root,x); \r\n           break; \r\n           case 4: Rpreorder(root); \r\n           break; \r\n           case 5: NRpreorder(root); \r\n           break; \r\n           case 6: Rinorder(root); \r\n           break; \r\n           case 7: NRinorder(root); \r\n           break; \r\n           case 8: Rpostorder(root); \r\n           break; \r\n           case 9: NRpostorder(root); \r\n           break; \r\n           case 10: \r\n           x = BSTheight(root); \r\n           cout<<x; \r\n           break; \r\n           case 11: \r\n           cout<<\"MIRROR IMAGE IS:\\n\"; \r\n           z = mirr (root); \r\n           levelorder(root); \r\n           break; \r\n           case 12: \r\n           z = nd_copy(root); \r\n           cout<<\"Created copy is:\\n\"; \r\n           levelorder(z); \r\n           break; \r\n           case 13: \r\n           par_chld(root); \r\n           break; \r\n           case 14: \r\n           leaf_nd(root); \r\n           break; \r\n           case 15: \r\n           levelorder(root); \r\n           break; \r\n           case 16: z=f_min(root); \r\n           cout<<z->data; \r\n           break; \r\n           case 17: z = f_max(root); \r\n           cout<<z->data; \r\n           break; \r\n       } \r\n   } \r\n   \r\n   while(n<18); \r\n   \r\n   cout<<\"\\nOPERATION COMPLETED!! THANK YOU\"; \r\n   \r\n   return 0; \r\n}\r\n\r\n\r\n/*\r\n-----------------------------------------------------------------------------------------------------------------------------\r\n\r\nOUTPUT :\r\n\r\n[1] BST INSERT\r\n[2] DELETE \r\n[3] SEARCH AN ELEMENT'S PRESENCE \r\n[4] RECURSIVE PREORDER\r\n[5] NON RECURSIVE PREORDER\r\n[6] RECURSIVE INORDER\r\n[7] NON RECURSIVE INORDER\r\n[8] RECURSIVE POSTORDER\r\n[9] NON RECURSIVE POSTORDER\r\n[10] HEIGHT OF TREE \r\n[11] MIRROR IMAGE \r\n[12] CREATE A COPY \r\n[13] DISPLAY ALL PARENT NODES WITH CHILD NODES \r\n[14] DISPLAY LEAF NODES \r\n[15] LEVEL ORDER DISPLAY\r\n[16] FIND MINIMUM \r\n[17] FIND MAXIMUM \r\nEnter your choice: 1\r\nenter the data \r\n8\r\nwant to enter more?\r\n1\r\nenter the data \r\n3\r\nwant to enter more?\r\n1\r\nenter the data \r\n10\r\nwant to enter more?\r\n1\r\nenter the data \r\n1\r\nwant to enter more?\r\n1\r\nenter the data \r\n6\r\nwant to enter more?\r\n1\r\nenter the data \r\n14\r\nwant to enter more?\r\n1\r\nenter the data \r\n4\r\nwant to enter more?\r\n1\r\nenter the data \r\n7\r\nwant to enter more?\r\n1\r\nenter the data \r\n13\r\nwant to enter more?\r\n0\r\nEnter your choice: 3\r\nENTER THE ELEMENT TO BE SEARCHED??\r\n7\r\nELEMENT FOUND :)\r\nEnter your choice: 5\r\n8       3       1       6       4       7       10      14      13\r\nEnter your choice: 7\r\n1       3       4       6       7       8       10      13      14\r\nEnter your choice: 9\r\n1       4       7       6       3       13      14      10      8\r\nEnter your choice: 10\r\n3\r\nEnter your choice: 15\r\n8\r\n3       10\r\n1       6       14\r\n4       7       13\r\nEnter your choice: 13\r\n8       3       10      (node has two children)\r\n3       1       6       (node has two children)\r\n10      14              (node has one child)\r\n1                       (node has no child)\r\n6       4       7       (node has two children)\r\n14      13              (node has one child)\r\n4                       (node has no child)\r\n7                       (node has no child)\r\n13                      (node has no child)\r\nEnter your choice: 11\r\nMIRROR IMAGE IS:\r\n8\r\n10      3\r\n14      6       1\r\n13      7       4\r\nEnter your choice: 16\r\n14\r\nEnter your choice: 15\r\n8\r\n10      3\r\n14      6       1\r\n13      7       4\r\nEnter your choice: 18\r\nOPERATION COMPLETED!! THANK YOU\r\n...Program finished with exit code 0\r\nPress ENTER to exit console.\r\n*/\r\n"
  },
  {
    "path": "Data-Structures/Tree/Binary-Search-Tree/Binary_Search_Tree.py",
    "content": "# Binary Search Tree (BST) Implementation\n\nclass BSTNode:\n    def __init__(selfNode, nodeData):  # Node Structure\n        selfNode.nodeData = nodeData\n        selfNode.left = None\n        selfNode.right = None\n        selfNode.parent = None\n\n# Insertion Operation\n\n    def insert(selfNode, node):\n        if selfNode.nodeData > node.nodeData:\n            if selfNode.left is None:\n                selfNode.left = node\n                node.parent = selfNode\n            else:\n                selfNode.left.insert(node)\n        elif selfNode.nodeData < node.nodeData:\n            if selfNode.right is None:\n                selfNode.right = node\n                node.parent = selfNode\n            else:\n                selfNode.right.insert(node)\n\n# Removal Operation Functions\n\n    def replace_node_of_parent(selfNode, new_node):\n        if selfNode.parent is not None:\n            if new_node is not None:\n                new_node.parent = selfNode.parent\n            if selfNode.parent.left == selfNode:\n                selfNode.parent.left = new_node\n            elif selfNode.parent.right == selfNode:\n                selfNode.parent.right = new_node\n        else:\n            selfNode.nodeData = new_node.nodeData\n            selfNode.left = new_node.left\n            selfNode.right = new_node.right\n            if new_node.left is not None:\n                new_node.left.parent = selfNode\n            if new_node.right is not None:\n                new_node.right.parent = selfNode\n\n    def find_min(selfNode):\n        current = selfNode\n        while current.left is not None:\n            current = current.left\n        return current\n\n    def remove(selfNode):\n        if (selfNode.left is not None and selfNode.right is not None):\n            successor = selfNode.right.find_min()\n            selfNode.nodeData = successor.nodeData\n            successor.remove()\n        elif selfNode.left is not None:\n            selfNode.replace_node_of_parent(selfNode.left)\n        elif selfNode.right is not None:\n            selfNode.replace_node_of_parent(selfNode.right)\n        else:\n            selfNode.replace_node_of_parent(None)\n\n# Search required data within BST\n\n    def search(selfNode, nodeData):\n        if selfNode.nodeData > nodeData:\n            if selfNode.left is not None:\n                return selfNode.left.search(nodeData)\n            else:\n                return None\n        elif selfNode.nodeData < nodeData:\n            if selfNode.right is not None:\n                return selfNode.right.search(nodeData)\n            else:\n                return None\n        return selfNode\n\n# InOrder Traversal Operation\n\n    def inorder(selfNode):\n        if selfNode.left is not None:\n            selfNode.left.inorder()\n        print(selfNode.nodeData, end=' ')\n        if selfNode.right is not None:\n            selfNode.right.inorder()\n\n# PostOrder Traversal Operation\n\n    def postorder(selfNode):\n        if selfNode.left is not None:\n            selfNode.left.inorder()\n        if selfNode.right is not None:\n            selfNode.right.inorder()\n        print(selfNode.nodeData, end=' ')\n\n# PreOrder Traversal Operation\n\n    def preorder(selfNode):\n        print(selfNode.nodeData, end=' ')\n        if selfNode.left is not None:\n            selfNode.left.inorder()\n        if selfNode.right is not None:\n            selfNode.right.inorder()\n\n\nclass BSTree:  # Structure of Binary Search Tree\n    def __init__(selfNode):\n        selfNode.root = None\n\n    def inorder(selfNode):\n        if selfNode.root is not None:\n            selfNode.root.inorder()\n\n    def preorder(selfNode):\n        if selfNode.root is not None:\n            selfNode.root.preorder()\n\n    def postorder(selfNode):\n        if selfNode.root is not None:\n            selfNode.root.postorder()\n\n    def add(selfNode, nodeData):\n        new_node = BSTNode(nodeData)\n        if selfNode.root is None:\n            selfNode.root = new_node\n        else:\n            selfNode.root.insert(new_node)\n\n    def remove(selfNode, nodeData):\n        to_remove = selfNode.search(nodeData)\n        if (selfNode.root == to_remove and selfNode.root.left is None\n                and selfNode.root.right is None):\n            selfNode.root = None\n        else:\n            to_remove.remove()\n\n    def search(selfNode, nodeData):\n        if selfNode.root is not None:\n            return selfNode.root.search(nodeData)\n\n\nbstree = BSTree()  # Object of class BSTree\n\n# Menu of Operations on BST Tree\n\nprint('BST Tree Operation Menu')\nprint('Add <data>')\nprint('Remove <data>')\nprint('Inorder')\nprint('Preorder')\nprint('Postorder')\nprint('Quit')\n\nwhile True:\n    do = input('Enter your action => ').split()\n\n    operation = do[0].strip().lower()\n    if operation == 'add':\n        nodeData = int(do[1])\n        bstree.add(nodeData)\n    elif operation == 'remove':\n        nodeData = int(do[1])\n        bstree.remove(nodeData)\n    elif operation == 'inorder':\n        print('Inorder Traversal: ', end='')\n        bstree.inorder()\n        print()\n    elif operation == 'postorder':\n        print('Postorder Traversal: ', end='')\n        bstree.postorder()\n        print()\n    elif operation == 'preorder':\n        print('Preorder Traversal: ', end='')\n        bstree.preorder()\n        print()\n    elif operation == 'quit':\n        print(\"BST Tree Implementation finished.\")\n        break\n"
  },
  {
    "path": "Data-Structures/Tree/Binary-Search-Tree/Binary_Search_Tree_operations.cpp",
    "content": "// Author : Sachin19k\r\n// Topic: Binary Search Tree \r\n\r\n/* Problem Statement : \r\nImplement binary search tree and perform following operations:\r\na) Insert (Handle insertion of duplicate entry)\r\nb) Delete\r\nc) Search\r\nd) Display tree Traversal (Recursive & Non-recursive)\r\ne) Display - Depth of tree\r\nf) Display - Mirror image\r\ng) Create a copy\r\nh) Display all parent nodes with their child nodes\r\ni) Display leaf nodes\r\nj) Display tree level wise  */\r\n\r\n#include<iostream> \r\n#include<queue> \r\n#include<stack> \r\nusing namespace std; \r\n\r\n\r\n// Structure of the node of Binary Search Tree\r\nstruct dll \r\n{ \r\n   int data; \r\n   dll *left; \r\n   dll *right; \r\n};\r\n\r\ndll *BSTinsert(dll *root,int x) //Inserting node in BST\r\n{ \r\n   dll *p, *prev, *r; \r\n   r=new dll; \r\n   r->data=x; \r\n   r->left=NULL; \r\n   r->right=NULL; \r\n   if(root==NULL) \r\n   { \r\n       return r; \r\n   } \r\n\r\n   p=root; \r\n   while(p!=NULL) \r\n   { \r\n       prev=p; \r\n       if(x>p->data) \r\n           p=p->right; \r\n       else if(x<p->data) \r\n           p=p->left; \r\n       else \r\n       { \r\n cout<<\"DUPLICATE ELEMENTS ARRIVED :(\\n\"; //duplicate entry \r\n return (root); \r\n} \r\n} \r\nif(x>prev->data) \r\n   prev->right=r; \r\nelse \r\n   prev->left=r; \r\nreturn (root); \r\n} \r\n\r\nvoid levelorder(dll *root) //Print the node in levelorder form\r\n{ \r\n   if(root==NULL) \r\n       return; \r\n   queue <dll *> p; \r\n   p.push(root); \r\n   int count=1; \r\n   while(!p.empty()) \r\n   { \r\n       if(count==0) \r\n       { \r\n           cout<<\"\\n\"; \r\n           count=p.size(); \r\n       } \r\n\r\n       dll *q = p.front(); \r\n       cout<<q->data<<\"\\t\"; \r\n       if(q->left!=NULL) \r\n           p.push(q->left); \r\n       if(q->right!=NULL) \r\n           p.push(q->right); \r\n       p.pop(); \r\n       count--; \r\n\r\n   } \r\n} \r\n\r\nvoid Rpreorder(dll *root) //Recursive Postorder\r\n{ \r\n   if(root!=NULL) \r\n   { \r\n       cout<<root->data<<\"\\t\"; \r\n       Rpreorder(root->left); \r\n       Rpreorder(root->right); \r\n   } \r\n} \r\n\r\nvoid NRpreorder(dll *root) //Iterative Preorder\r\n{ \r\n   stack <dll *> s; \r\n   while(!s.empty() || root!=NULL) \r\n   { \r\n       while(root!=NULL) \r\n       { \r\n           cout<<root->data<<\"\\t\"; \r\n           s.push(root); \r\n           root=root->left; \r\n       } \r\n       root=s.top(); \r\n       s.pop(); \r\n       root=root->right; \r\n\r\n   } \r\n} \r\n\r\nvoid Rinorder(dll *root) //Recursive Inorder\r\n{ \r\n   if(root!=NULL) \r\n   { \r\n       Rinorder(root->left); \r\n       cout<<root->data<<\"\\t\"; \r\n       Rinorder(root->right); \r\n   } \r\n} \r\n\r\nvoid NRinorder(dll *root) //Iterative Inorder\r\n{ \r\n   stack <dll *> s; \r\n   while(!s.empty() || root!=NULL) \r\n   { \r\n       while(root!=NULL) \r\n       { \r\n           s.push(root); \r\n           root=root->left; \r\n       } \r\n       root=s.top(); \r\n       s.pop(); \r\n       cout<<root->data<<\"\\t\"; \r\n       root=root->right; \r\n   } \r\n} \r\n\r\nvoid Rpostorder(dll *root) //Recursive Postorder\r\n{ \r\n   if(root==NULL) \r\n   { \r\n       return; \r\n   } \r\n   Rpostorder(root->left); \r\n\r\n   Rpostorder(root->right); \r\n\r\n   cout<<root->data<<\"\\t\"; \r\n} \r\n\r\nvoid NRpostorder(dll *root) //Iterative Postorder\r\n{ \r\n   stack <dll*> s1; \r\n   stack <int> s2; \r\n   while(root!=NULL) \r\n   { \r\n       s1.push(root); \r\n       s2.push(0); \r\n       root=root->left; \r\n   } \r\n   while(!s1.empty()) \r\n   { \r\n       root=s1.top(); \r\n       if(s2.top()==1) \r\n       { \r\n           s1.pop(); \r\n           s2.pop(); \r\n           cout<<root->data<<\"\\t\"; \r\n       } \r\n       else \r\n       { \r\n           s2.top()=1; \r\n           root=root->right; \r\n           while(root!=NULL) \r\n           { \r\n               s1.push(root); \r\n               s2.push(0); \r\n               root=root->left; \r\n           } \r\n       } \r\n   } \r\n} \r\n\r\nint BSTheight(dll *root) //Height of BST\r\n{ \r\n   if(root==NULL) \r\n       return -1; \r\n   queue <dll *> p; \r\n   p.push(root); \r\n   int ht=-1,count; \r\n   while(1) \r\n   { \r\n       count=p.size(); \r\n       if(count==0) \r\n           return ht; \r\n       ht++; \r\n       while(count--) \r\n       { \r\n           dll *q=p.front(); \r\n           p.pop(); \r\n           if(q->left!=NULL) \r\n               p.push(q->left); \r\n           if(q->right!=NULL) \r\n               p.push(q->right); \r\n       } \r\n   } \r\n} \r\n\r\ndll* f_min(dll *root) //Find Minimum element from root\r\n{ \r\n   dll*p=root; \r\n   while(p->left!=NULL) \r\n   { \r\n       p=p->left; \r\n   } \r\n   return (p); \r\n} \r\n\r\ndll *f_max(dll *root) //Find Maximum element from root\r\n{ \r\n   dll *p=root; \r\n   while(p->right!=NULL) \r\n   { \r\n       p=p->right; \r\n   } \r\n   return (p); \r\n} \r\n\r\nbool search(dll *root,int x) //Search an element in BST\r\n{ \r\n   while(root!=NULL) \r\n   { \r\n       if(x==root->data) \r\n       { \r\n           cout<<\"ELEMENT FOUND :)\\n\" ; \r\n           return true; \r\n       } \r\n       else if(x>root->data) \r\n       { \r\n           root=root->right; \r\n       } \r\n       else \r\n       { \r\n           root=root->left; \r\n       } \r\n   } \r\n   cout<<\"ELEMENT NOT FOUND :( \\n\" ; \r\n   return false; \r\n\r\n} \r\n\r\ndll *bstdelete(dll *root, int x) //Delete the node from BST\r\n{ \r\n   dll *m; \r\n   if(root==NULL) \r\n   { \r\n       cout<<\"NOT FOUND!!\"; \r\n       return root; \r\n   } \r\n   if(x < root->data) \r\n   { \r\n       root->left=bstdelete(root->left,x); \r\n       return root; \r\n   } \r\n   if(x>root->data) \r\n   { \r\n       root->right=bstdelete(root->right,x); \r\n       return root; \r\n   } \r\n   if(root->left==NULL && root->right==NULL) \r\n   { \r\n       m=root; \r\n       delete m; \r\n       return (NULL); \r\n   } \r\n   else if(root->left==NULL) \r\n   { \r\n       m=root; \r\n       root=root->right; \r\n       delete m; \r\n       return (root); \r\n   } \r\n   else if(root->right==NULL) \r\n   { \r\n       m=root; \r\n       root=root->left; \r\n       delete m; \r\n       return (root); \r\n   } \r\n   m=f_min(root->right); \r\n   root->data=m->data; \r\n   root->right=bstdelete(root->right, m->data); \r\n   return (root); \r\n} \r\n\r\ndll *mirr(dll *root) //Mirror image of the BST\r\n{ \r\n   if(root==NULL) \r\n       return NULL; \r\n   dll *p=root; \r\n   queue <dll *> q; \r\n   q.push(root); \r\n   while(!q.empty()) \r\n   { \r\n       dll *curr=q.front(); \r\n       q.pop(); \r\n       swap(curr->left, curr->right); \r\n       if(curr->left) \r\n           q.push(curr->left); \r\n       if(curr->right) \r\n           q.push(curr->right); \r\n   } \r\n   return (p); \r\n} \r\n\r\ndll *nd_copy(dll *root) \r\n{ \r\n   if(root==NULL) \r\n   { \r\n       return root; \r\n   } \r\n   dll *p = new dll; \r\n   p->data=root->data; \r\n   p->left=nd_copy(root->left); \r\n   p->right=nd_copy(root->right); \r\n   return p; \r\n} \r\n\r\nvoid par_chld(dll *root) //Print all parents and their Children\r\n{ \r\n   if(root==NULL) \r\n       return; \r\n   queue <dll *> p; \r\n   p.push(root); \r\n   int count=1,x; \r\n   while(!p.empty()) \r\n   { \r\n       x=0; \r\n       dll *q = p.front(); \r\n       cout<<q->data<<\"\\t\"; \r\n       if(q->left!=NULL) \r\n       { \r\n           x++; \r\n           p.push(q->left); \r\n           cout<<(q->left)->data<<\"\\t\"; \r\n       } \r\n       if(q->right!=NULL) \r\n       { \r\n           x++; \r\n           p.push(q->right); \r\n           cout<<(q->right)->data<<\"\\t\"; \r\n       } \r\n       if(x==0) \r\n       { \r\n           cout<<\"\\t\\t(node has no child)\"; \r\n       } \r\n       else if(x==1) \r\n       { \r\n           cout<<\"\\t(node has one child)\"; \r\n       } \r\n       else if(x==2) \r\n       { \r\n           cout<<\"(node has two children)\"; \r\n       } \r\n       p.pop(); \r\n       cout<<\"\\n\"; \r\n\r\n   } \r\n} \r\n\r\nvoid leaf_nd(dll *root) //Print all leafnode in BST\r\n{ \r\n   if (!root) \r\n       return; \r\n\r\n   if (root->left==NULL && root->right==NULL) \r\n   { \r\n       cout << root->data << \"\\t\"; \r\n       return; \r\n   } \r\n\r\n   if (root->left) \r\n       leaf_nd(root->left); \r\n\r\n   if (root->right) \r\n       leaf_nd(root->right); \r\n} \r\n\r\nint main() //main function\r\n{ \r\n   dll *root=NULL,*z=NULL; \r\n   bool b; \r\n   int n,p,x; \r\n   cout<<\"[1] BST INSERT\\n\"; \r\n   cout<<\"[2] DELETE \\n\"; \r\n   cout<<\"[3] SEARCH AN ELEMENT'S PRESENCE \\n\"; \r\n   cout<<\"[4] RECURSIVE PREORDER\\n\"; \r\n   cout<<\"[5] NON RECURSIVE PREORDER\\n\"; \r\n   cout<<\"[6] RECURSIVE INORDER\\n\"; \r\n   cout<<\"[7] NON RECURSIVE INORDER\\n\"; \r\n   cout<<\"[8] RECURSIVE POSTORDER\\n\"; \r\n   cout<<\"[9] NON RECURSIVE POSTORDER\\n\"; \r\n   cout<<\"[10] HEIGHT OF TREE \\n\"; \r\n   cout<<\"[11] MIRROR IMAGE \\n\"; \r\n   cout<<\"[12] CREATE A COPY \\n\"; \r\n   cout<<\"[13] DISPLAY ALL PARENT NODES WITH CHILD NODES \\n\"; \r\n   cout<<\"[14] DISPLAY LEAF NODES \\n\"; \r\n   cout<<\"[15] LEVEL ORDER DISPLAY\\n\"; \r\n   cout<<\"[16] FIND MINIMUM \\n\"; \r\n   cout<<\"[17] FIND MAXIMUM \\n\"; \r\n   do \r\n   { \r\n       cout<<\"\\nEnter your choice: \"; \r\n       cin>>n; \r\n       switch(n) \r\n       { \r\n           case 1: \r\n           do \r\n           { \r\n               cout<<\"enter the data \\n\"; \r\n               cin>>x; \r\n               root = BSTinsert(root,x); \r\n               cout<<\"want to enter more?\\n\"; \r\n               cin>>p; \r\n           } \r\n           while(p!=0); \r\n           break; \r\n           case 2: \r\n           cout<<\"enter the element to be deleted?\\n\"; \r\n           cin>>x; \r\n           if(search(root,x)) \r\n           { \r\n               root = bstdelete(root,x); \r\n               levelorder(root); \r\n           } \r\n           else \r\n           { \r\n               cout<<\"CAN'T DELETE!! \\n\"; \r\n           } \r\n           break; \r\n           case 3: \r\n           cout<<\"ENTER THE ELEMENT TO BE SEARCHED??\\n\"; \r\n           cin>>x; \r\n           b = search(root,x); \r\n           break; \r\n           case 4: Rpreorder(root); \r\n           break; \r\n           case 5: NRpreorder(root); \r\n           break; \r\n           case 6: Rinorder(root); \r\n           break; \r\n           case 7: NRinorder(root); \r\n           break; \r\n           case 8: Rpostorder(root); \r\n           break; \r\n           case 9: NRpostorder(root); \r\n           break; \r\n           case 10: \r\n           x = BSTheight(root); \r\n           cout<<x; \r\n           break; \r\n           case 11: \r\n           cout<<\"MIRROR IMAGE IS:\\n\"; \r\n           z = mirr (root); \r\n           levelorder(root); \r\n           break; \r\n           case 12: \r\n           z = nd_copy(root); \r\n           cout<<\"Created copy is:\\n\"; \r\n           levelorder(z); \r\n           break; \r\n           case 13: \r\n           par_chld(root); \r\n           break; \r\n           case 14: \r\n           leaf_nd(root); \r\n           break; \r\n           case 15: \r\n           levelorder(root); \r\n           break; \r\n           case 16: z=f_min(root); \r\n           cout<<z->data; \r\n           break; \r\n           case 17: z = f_max(root); \r\n           cout<<z->data; \r\n           break; \r\n       } \r\n   } \r\n   while(n<18); \r\n   cout<<\"\\nOPERATION COMPLETED!! THANK YOU\"; \r\n   return 0; \r\n}\r\n\r\n\r\n/*\r\n-----------------------------------------------------------------------------------------------------------------------------\r\n\r\nOUTPUT :\r\n\r\n[1] BST INSERT\r\n[2] DELETE \r\n[3] SEARCH AN ELEMENT'S PRESENCE \r\n[4] RECURSIVE PREORDER\r\n[5] NON RECURSIVE PREORDER\r\n[6] RECURSIVE INORDER\r\n[7] NON RECURSIVE INORDER\r\n[8] RECURSIVE POSTORDER\r\n[9] NON RECURSIVE POSTORDER\r\n[10] HEIGHT OF TREE \r\n[11] MIRROR IMAGE \r\n[12] CREATE A COPY \r\n[13] DISPLAY ALL PARENT NODES WITH CHILD NODES \r\n[14] DISPLAY LEAF NODES \r\n[15] LEVEL ORDER DISPLAY\r\n[16] FIND MINIMUM \r\n[17] FIND MAXIMUM \r\nEnter your choice: 1\r\nenter the data \r\n8\r\nwant to enter more?\r\n1\r\nenter the data \r\n3\r\nwant to enter more?\r\n1\r\nenter the data \r\n10\r\nwant to enter more?\r\n1\r\nenter the data \r\n1\r\nwant to enter more?\r\n1\r\nenter the data \r\n6\r\nwant to enter more?\r\n1\r\nenter the data \r\n14\r\nwant to enter more?\r\n1\r\nenter the data \r\n4\r\nwant to enter more?\r\n1\r\nenter the data \r\n7\r\nwant to enter more?\r\n1\r\nenter the data \r\n13\r\nwant to enter more?\r\n0\r\nEnter your choice: 3\r\nENTER THE ELEMENT TO BE SEARCHED??\r\n7\r\nELEMENT FOUND :)\r\nEnter your choice: 5\r\n8       3       1       6       4       7       10      14      13\r\nEnter your choice: 7\r\n1       3       4       6       7       8       10      13      14\r\nEnter your choice: 9\r\n1       4       7       6       3       13      14      10      8\r\nEnter your choice: 10\r\n3\r\nEnter your choice: 15\r\n8\r\n3       10\r\n1       6       14\r\n4       7       13\r\nEnter your choice: 13\r\n8       3       10      (node has two children)\r\n3       1       6       (node has two children)\r\n10      14              (node has one child)\r\n1                       (node has no child)\r\n6       4       7       (node has two children)\r\n14      13              (node has one child)\r\n4                       (node has no child)\r\n7                       (node has no child)\r\n13                      (node has no child)\r\nEnter your choice: 11\r\nMIRROR IMAGE IS:\r\n8\r\n10      3\r\n14      6       1\r\n13      7       4\r\nEnter your choice: 16\r\n14\r\nEnter your choice: 15\r\n8\r\n10      3\r\n14      6       1\r\n13      7       4\r\nEnter your choice: 18\r\nOPERATION COMPLETED!! THANK YOU\r\n...Program finished with exit code 0\r\nPress ENTER to exit console.\r\n*/"
  },
  {
    "path": "Data-Structures/Tree/Binary-Search-Tree/LCA.py",
    "content": "#Code to get the inorder traversal and to find the lowest common ansester of two given node in binary search tree by user in python\n\n\nclass new_node:\n    def __init__(self,data):\n        self.data=data\n        self.left=None\n        self.right=None\n\ndef insert(root,data):\n    if root==None:\n        return new_node(data)\n    else:\n        if root.data==data:\n            return root\n        elif root.data>data:\n            root.right=insert(root.right,data)\n        elif data>root.data:\n            root.left=insert(root.left,data)\n\n    return root\n\n\ndef inorder(root):\n    if root:\n        inorder(root.left)\n        print(root.data,end=\" \")\n        inorder(root.right)\n\ndef find_LCA(root,n1,n2):\n\n    if root is None:\n        return\n    left_data=find_LCA(root.left,n1,n2)\n    right_data=find_LCA(root.right,n1,n2)\n\n    if root.data==n1 or root.data==n2:\n        return root\n\n    return left_data if left_data is not None else right_data\n\n\nif __name__=='__main__':\n    n = int(input('Enter number of node u want in this BST: '))\n    x=int(input('Enter data you want to insert in root node: '))\n    root=new_node(x)\n\n    for i in range(n-1):\n        v=int(input('Data: '))\n        insert(root,v)\n    choice=0\n    while(choice!=3):\n        choice=int(input('''\n        1. Inorder Traversal of BST\n        2. LCA of two node\n        3. Quit\n        '''))\n        if choice==1:\n            inorder(root)\n        elif choice==2:\n            print('Give two node whose LCA you want to find: ')\n            m1,m2=map(int,input().split())\n            print(find_LCA(root,m1,m2).data)\n\n    print('Have a nice day!')\n"
  },
  {
    "path": "Data-Structures/Tree/Binary-Search-Tree/README.md",
    "content": "## This folder is empty.\n"
  },
  {
    "path": "Data-Structures/Tree/Binary-Search-Tree/Validate_BST.py",
    "content": "#!/usr/env/python\n\nclass BSTNode:\n    def __init__(self, data):  # Node Structure\n        self.data = data\n        self.left = None\n        self.right = None\n\n    \"\"\" The data from the nodes should be ordered as left.data <= self.data <= right.data \"\"\"\n    def isValid(self):\n        return self is None or (\n            (self.left is None or (self.left.data <= self.data and self.left.isValid()))\n            and\n            (self.right is None or (self.data <= self.right.data and self.right.isValid())))\n\nif __name__ == \"__main__\":\n    bst = BSTNode(5)\n    bst.left = BSTNode(3)\n    bst.right = BSTNode(8)\n    bst.left.left = BSTNode(1)\n    bst.left.right = BSTNode(4)\n\n    print(bst.isValid())\n    \n    nonbst = BSTNode(5)\n    nonbst.left = BSTNode(6)\n    print(nonbst.isValid())\n\n"
  },
  {
    "path": "Data-Structures/Tree/Binary-Search-Tree/Vertcal_order_traversal.py",
    "content": "#Code for inorder as well as vertical order traversal of BST in python\n\nclass new_node:\n    def __init__(self,data):\n        self.data=data\n        self.left=None\n        self.right=None\n\ndef insert(root,data):\n    if root==None:\n        return new_node(data)\n    else:\n        if root.data==data:\n            return root\n        elif root.data>data:\n            root.right=insert(root.right,data)\n        elif data>root.data:\n            root.left=insert(root.left,data)\n\n    return root\n\ndef vertical_line(root,hd,m):\n    if root is None:\n        return\n    try:\n        m[hd].append(root.data)\n    except:\n        m[hd]=[root.data]\n\n    vertical_line(root.left,hd-1,m)\n    vertical_line(root.right,hd+1,m)\n\ndef print_vertical_order(root):\n    m=dict()\n    h=0\n    vertical_line(root,h,m)\n    for ind,val in enumerate(sorted(m)):\n        for i in m[val]:\n            print(i)\n        print()\n\ndef inorder(root):\n    if root:\n        inorder(root.left)\n        print(root.data)\n        inorder(root.right)\n\n\nif __name__=='__main__':\n    n = int(input('Enter number of node u want in this BST: '))\n    x=int(input('Enter data you want to insert in root node: '))\n    root=new_node(x)\n\n    for i in range(n-1):\n        v=int(input('Data: '))\n        insert(root,v)\n    choice=0\n    while(choice!=3):\n        choice=int(input('''\n        1. Inorder Traversal of BST\n        2. Vertical-order-traversal of BST\n        3. Quit\n        '''))\n        if choice==1:\n            inorder(root)\n        elif choice==2:\n            print_vertical_order(root)\n\n    print('Have a nice day!')\n"
  },
  {
    "path": "Data-Structures/Tree/Binary-Search-Tree/inorder_transversal.c",
    "content": "#include <stdio.h> \n#include <stdlib.h> \nstruct node \n{ \n\tint data; \n\tstruct node* left; \n\tstruct node* right; \n}; \n\nstruct node* newNode(int data) \n{ \n\tstruct node* node = (struct node*) \n\tmalloc(sizeof(struct node)); \n\tnode->data = data; \n\tnode->left = NULL; \n\tnode->right = NULL; \n              return(node); \n} \nvoid printInorder(struct node* node) \n{ \n     if (node == NULL) \n          return; \n \n     printInorder(node->left); \n  \n     printf(\"%d \", node->data);   \n \n     printInorder(node->right); \n} \n \n\nint main() \n{ \n\tstruct node *root = newNode(1); \n\troot->left = newNode(2); \n\troot->right= newNode(3); \n\troot->left->left= newNode(4); \n\troot->left->right = newNode(5); \n\n\tprintf(\"\\nInorder traversal of binary tree is \\n\"); \n\tprintInorder(root);  \n              getchar(); \n\treturn 0; \n}\n"
  },
  {
    "path": "Data-Structures/Tree/Binary-Search-Tree/operationBST.cpp",
    "content": "#include<iostream>\n#include<stdlib.h>\nusing namespace std;\nstruct Node\n{\nint info;\nNode *left;\nNode *right;\n};\nNode* FindMin(Node *node)\n{\nif(node==NULL)\n{\nreturn NULL;\n}\nif(node->left)\nreturn FindMin(node->left);\nelse\nreturn node;\n}\nNode* FindMax(Node *node)\n{\nif(node==NULL)\n{\nreturn NULL;\n}\nif(node->right)\nreturn(FindMax(node->right));\nelse\nreturn node;\n}\nNode *Insert(Node *node,int info)\n{\nif(node==NULL)\n{\nNode *temp;\ntemp=new Node;\ntemp -> info = info;\ntemp -> left = temp -> right = NULL;\nreturn temp;\n}\nif(info >(node->info))\n{\nnode->right = Insert(node->right,info);\n}\nelse if(info < (node->info))\n{\nnode->left = Insert(node->left,info);\n}\nreturn node;\n}\nNode * Delet(Node *node, int info)\n{\nNode *temp;\nif(node==NULL)\n{\ncout<<\"Element Not Found\";\n}\nelse if(info < node->info)\n{\nnode->left = Delet(node->left, info);\n}\nelse if(info > node->info)\n{\nnode->right = Delet(node->right, info);\n}\nelse\n{\nif(node->right && node->left)\n{\ntemp = FindMin(node->right);\nnode -> info = temp->info;\nnode -> right = Delet(node->right,temp->info);\n}\nelse\n{\ntemp = node;\nif(node->left == NULL)\nnode = node->right;\nelse if(node->right == NULL)\nnode = node->left;\nfree(temp);\n}\n}\nreturn node;\n}\nNode * Find(Node *node, int info)\n{\nif(node==NULL)\n{\nreturn NULL;\n}\nif(info > node->info)\n{\nreturn Find(node->right,info);\n}\nelse if(info < node->info)\n{\nreturn Find(node->left,info);\n}\nelse\n{\nreturn node;\n}\n}\nvoid Inorder(Node *node)\n{\nif(node==NULL)\n{\nreturn;\n}\nInorder(node->left);\ncout<<node->info<<\" \";\nInorder(node->right);\n}\nvoid Preorder(Node *node)\n{\nif(node==NULL)\n{\nreturn;\n}\ncout<<node->info<<\" \";\nPreorder(node->left);\nPreorder(node->right);\n}\nvoid Postorder(Node *node)\n{\nif(node==NULL)\n{\nreturn;\n}\nPostorder(node->left);\nPostorder(node->right);\ncout<<node->info<<\" \";\n}\n\nint n=1;\n\nint CountNodes(Node*root)\n{\n\tif(root==NULL)\n\t\treturn 0;\n\tif(root->left!=NULL)\n\t{\n\t\tn=n+1;\n\t\tn=CountNodes(root->left);\n\t}\n\tif(root->right!=NULL)\n\t{\n\t\tn=n+1;\n\t\tn=CountNodes(root->right);\n\t}\n\treturn n;\n}\n\n\n\nmain()\n{\nNode *root = NULL,*temp;\nint ch;\nwhile(1)\n{\ncout<<\"\\n\\t\\t OPERATION MENU \";\ncout<<\"\\n\\t 1.Insert\\n\\t 2.Delete\\n\\t 3.Inorder\\n\\t 4.Preorder\\n\\t 5.Postorder\\n\\t 6.\";\ncout<<\"FindMin\\n\\t 7.FindMax\\n\\t 8.Search\\n\\t 9.Count NO. of Nodes\\n\\t 10.Exit\\n\";\ncout<<\"Enter your choice:\";\ncin>>ch;\nswitch(ch)\n{\ncase 1:\ncout<<\"\\nEnter element to be insert:\";\ncin>>ch;\nroot = Insert(root, ch);\ncout<<\"\\nElements in BST are:\";\nInorder(root);\nbreak;\ncase 2:\ncout<<\"\\nEnter element to be deleted:\";\ncin>>ch;\nroot = Delet(root,ch);\ncout<<\"\\nAfter deletion elements in BST are:\";\nInorder(root);\nbreak;\ncase 3:\ncout<<\"\\nInorder Travesals is:\";\nInorder(root);\nbreak;\ncase 4:\ncout<<\"\\nPreorder Traversals is:\";\nPreorder(root);\nbreak;\ncase 5:\ncout<<\"\\nPostorder Traversals is:\";\nPostorder(root);\nbreak;\ncase 6:\ntemp = FindMin(root);\ncout<<\"\\nMinimum element is :\"<<temp->info;\nbreak;\ncase 7:\ntemp = FindMax(root);\ncout<<\"\\nMaximum element is :\"<<temp->info;\nbreak;\ncase 8:\ncout<<\"\\nEnter element to be searched:\";\ncin>>ch;\ntemp = Find(root,ch);\nif(temp==NULL)\n{\ncout<<\"Element is not found\\n\";\n}\nelse\n{\ncout<<\"Element \"<<temp->info<<\" is Found\\n\";\n}\nbreak;\ncase 9:\n    {\n        cout<<\"\\n Total No. of Nodes is: \"<<CountNodes(root);\n        break;\n    }\n    case 10:\nexit(0);\n\ndefault:\ncout<<\"\\nEnter correct choice:\";\nbreak;\n}\n}\n}\n"
  },
  {
    "path": "Data-Structures/Tree/Binary-Search-Tree/postorder_transversal.c",
    "content": "#include <stdio.h> \n#include <stdlib.h> \nstruct node \n{ \n\tint data; \n\tstruct node* left; \n\tstruct node* right; \n}; \n\nstruct node* newNode(int data) \n{ \n\tstruct node* node = (struct node*) \n\tmalloc(sizeof(struct node)); \n\tnode->data = data; \n\tnode->left = NULL; \n\tnode->right = NULL; \n              return(node); \n} \nvoid printPostorder(struct node* node) \n{ \n     if (node == NULL) \n        return; \n   \n     printPostorder(node->left); \n \n     printPostorder(node->right); \n  \n     printf(\"%d \", node->data); \n} \n\nint main() \n{ \n\tstruct node *root = newNode(1); \n\troot->left = newNode(2); \n\troot->right= newNode(3); \n\troot->left->left= newNode(4); \n\troot->left->right = newNode(5); \n\n\tprintf(\"\\nPostorder traversal of binary tree is \\n\"); \n\tprintPostorder(root);  \n              getchar(); \n\treturn 0; \n}\n"
  },
  {
    "path": "Data-Structures/Tree/Binary-Search-Tree/valid BST",
    "content": "#include <bits/stdc++.h> \nusing namespace std; \n\n\nstruct Node \n{ \n\tint data; \n\tstruct Node* left, *right; \n\t\n\tNode(int data) \n\t{ \n\t\tthis->data = data; \n\t\tleft = right = NULL; \n\t} \n}; \n\n\nbool isBSTUtil(struct Node* root, Node *&prev) \n{ \n\tif (root) \n\t{ \n\t\tif (!isBSTUtil(root->left, prev)) \n\t\treturn false; \n \n\t\tif (prev != NULL && root->data <= prev->data) \n\t\treturn false; \n\n\t\tprev = root; \n\n\t\treturn isBSTUtil(root->right, prev); \n\t} \n\n\treturn true; \n} \n\nbool isBST(Node *root) \n{ \nNode *prev = NULL; \nreturn isBSTUtil(root, prev); \n} \n\nint main() \n{ \n\tstruct Node *root = new Node(3); \n\troot->left\t = new Node(2); \n\troot->right\t = new Node(5); \n\troot->left->left = new Node(1); \n\troot->left->right = new Node(4); \n\n\tif (isBST(root)) \n\t\tcout << \"Is BST\"; \n\telse\n\t\tcout << \"Not a BST\"; \n\n\treturn 0; \n} \n"
  },
  {
    "path": "Data-Structures/Tree/Binary-Tree/BTree.cpp",
    "content": "#include<iostream>\n#include<algorithm>\nusing namespace std;\n\n//implementing BTree of Order 6\n\nstruct BTreeNode\n{\n    //Array containing keys in a node\n    int *vals;\n    //Array containing pointer to children in a node\n    BTreeNode **children;\n    //Checks if node is a leaf node or not\n    bool isLeaf;\n    //Maintains number of keys present in vals array\n    int numberOfKeys;\n};\n\n// Pointer to root of tree and a temporary pointer\nBTreeNode* root = NULL, *x = NULL;\n\n//Creates a new empty node\nBTreeNode * newNode(){\n    BTreeNode* newptr = new BTreeNode;\n    newptr->vals = new int[5];\n    newptr->children = new BTreeNode *[6];\n    newptr->isLeaf = true;\n    newptr->numberOfKeys = 0;\n    for (int i=0;i<6;i++){\n        newptr->children[i] = NULL;\n    }\n    return newptr;\n}\n\n//Performs DFS Traversal on the tree, inorder traversal to be precise\nvoid traverseBTree(BTreeNode* node){\n    int i;\n    for(i=0; i< node->numberOfKeys; i++){\n        if(!node->isLeaf)\n            traverseBTree(node->children[i]);\n        cout<<\" \"<<node->vals[i];\n    } \n    if(!node->isLeaf){\n        traverseBTree(node->children[i]);\n    }\n    cout<<\"\\n\";\n}\n\n//Handles the splitting of child when the tree is full to prevent overflow\nint splitChild(BTreeNode *node, int index){\n    int mid;\n    BTreeNode* temp1 = newNode();\n    temp1->isLeaf = true;\n    if (index==-1){\n        mid = node->vals[2];\n        node->vals[2] = 0;\n        node->numberOfKeys-=1;\n        BTreeNode* temp = newNode();\n        temp->isLeaf = false;\n        node->isLeaf = true;\n        for(int i=3;i<5;i++){\n            temp1->vals[i-3] = node->vals[i];\n            temp1->children[i-3] = node->children[i];\n            temp1->numberOfKeys+=1;\n            node->vals[i] = 0;\n            node->numberOfKeys-=1;\n        }\n        for(int i=0;i<6;i++){\n            node->children[i] = NULL;\n        }\n        temp->vals[0] = mid;\n        temp->children[temp->numberOfKeys] = node;\n        temp->children[temp->numberOfKeys+1] = temp1;\n        temp->numberOfKeys++;\n        root = temp;\n    } else {\n        BTreeNode *temp2 = node->children[index];\n        mid = temp2->vals[2];\n        temp2->vals[2] = 0;\n        temp2->numberOfKeys-=1;\n        for(int i=3;i<5;i++)\n        {\n            temp1->vals[i-3] = temp2->vals[i];\n            temp1->numberOfKeys+=1;\n            temp2->vals[i] = 0;\n            temp2->numberOfKeys-=1;\n        }\n        x->children[index+1] = temp2;\n        x->children[index+1] = temp1; \n    }\n    return mid;\n}\n\n//Handles the cases related to insertion of node in the tree and calls appropriate functions when needed\nvoid insertNode(int val){\n    int i, temp;\n    x = root;\n    if(!x){\n        root = newNode();\n        x = root;\n    } else {\n        if(x->isLeaf && x->numberOfKeys==5){\n            temp = splitChild(x, -1);\n            x = root;\n            for(i=0; i<(x->numberOfKeys);i++){\n                if((val>x->vals[i]) && (val<x->vals[i + 1])){\n                    i++;\n                    break;\n                } else if (val < x->vals[0]){\n                    break;\n                } else {\n                    continue;\n                }\n            }\n            x = x->children[i];\n        } else {\n            while (!x->isLeaf){\n                for(i=0;i<(x->numberOfKeys);i++){\n                    if((val>x->vals[i]) && (val<x->vals[i + 1])){\n                        i++;\n                        break;\n                    } else if (val < x->vals[0]){\n                        break;\n                    } else {\n                        continue;\n                    }\n                }\n                if((x->children[i])->numberOfKeys==5){\n                    temp = splitChild(x, i);\n                    x->vals[x->numberOfKeys] = temp;\n                    x->numberOfKeys+=1;\n                    continue;\n                } else {\n                    x = x->children[i];\n                }\n            }\n        }\n    }\n    x->vals[x->numberOfKeys] = val;\n    sort(x->vals, x->vals + x->numberOfKeys);\n    x->numberOfKeys+=1;\n}\n\n//Implementing Deletion in a class as there is circular dependency between removeFromSubtree and removeFromGeneral\n//Such a case is very difficult to handle with sequential programming, hence using a class\nclass Deletion{\n    public:\n    //Returns the index of predecessor of the current node\n    //Predecessor is the just smaller value, which means last element of the rightmost leaf to the left\n    int getPredecessor(BTreeNode* node, int i){\n        BTreeNode* temp = node->children[i];\n        while(!temp->isLeaf)\n            temp = temp->children[temp->numberOfKeys];\n        return temp->vals[temp->numberOfKeys-1];\n    }\n\n    //Returns the index of successor of the current node\n    //Successor is the just larger value, which means the first element of the leftmost leaf to the right\n    int getSuccessor(BTreeNode* node, int i){\n        BTreeNode* temp = node->children[i+1];\n        while(!temp->isLeaf)\n            temp = temp->children[0];\n        return temp->vals[0];\n    }\n\n    //Borrows the value from the just previous child and copies it to the current one\n    //Used when filling values in case there are less than 2 child\n    void borrowFromPrevious(BTreeNode* node, int i){\n        BTreeNode* c = node->children[i];\n        BTreeNode* s = node->children[i-1];\n        for(int j = c->numberOfKeys-1;j>=0;j--)\n            c->vals[i+1] = c->vals[i];\n        if(!c->isLeaf)\n            for(int j = c->numberOfKeys;j>=0;j--)\n                c->children[j+1] = c->children[j];\n\n        c->vals[0] = node->vals[i-1];\n        if(!c->isLeaf)\n            c->children[0] = s->children[s->numberOfKeys];\n        node->vals[i-1] = s->vals[s->numberOfKeys-1];\n        c->numberOfKeys+=1;\n        s->numberOfKeys-=1;\n    }\n\n    //Borrows the value from the just next child and copies it to the current one\n    //Used when filling values in case of there are less than 2 child\n    void borrowFromNext(BTreeNode* node, int i){\n        BTreeNode* c = node->children[i];\n        BTreeNode* s = node->children[i+1];\n        c->vals[c->numberOfKeys] = node->vals[i];\n        if(!c->isLeaf)\n            c->children[c->numberOfKeys+1] = s->children[0];\n        node->vals[i] = s->vals[0];\n        for(int j=1;j<s->numberOfKeys;j++)\n            s->vals[j-1] = s->vals[j];\n        if(!s->isLeaf)\n            for(int j=1;j<=s->numberOfKeys;j++)\n                s->children[j-1] = s->children[j];\n        c->numberOfKeys+=1;\n        s->numberOfKeys-=1; \n    }\n\n    //Merges the current child with the next child and frees the memory of unused pointer\n    void merge(BTreeNode* node, int i){\n        BTreeNode* c = node->children[i];\n        BTreeNode* s = node->children[i+1];\n        c->vals[2] = node->vals[i];\n        for(int j=0;j<s->numberOfKeys;j++)\n            c->vals[j+3] = s->vals[j];\n        if(!c->isLeaf)\n            for(int j=0;j<=s->numberOfKeys;j++)\n                c->children[j+3] = s->children[j];\n        for(int j=i+1;j<node->numberOfKeys;j++)\n            node->vals[j-1] = node->vals[j];\n        for(int j=i+2;j<=node->numberOfKeys;j++)\n            node->children[j-1] = node->children[j];\n        c->numberOfKeys+=(s->numberOfKeys+1);\n        node->numberOfKeys-=1;\n        delete(s);\n    }\n\n    // Return the value the just >= the given key\n    int findClosestKey(BTreeNode* node, int key){\n        int i=0;\n        while(i<node->numberOfKeys && node->vals[i]<key)\n            ++i;\n        return i;\n    }\n\n    //Removes the value from given leaf node, copies the successive values\n    void removeFromLeaf(BTreeNode* node, int i){\n        for(int j=i+1;j<node->numberOfKeys;j++)\n            node->vals[j-1] = node->vals[j];\n        node->numberOfKeys-=1;\n    }\n\n    //Removes the value from given non leaf node\n    //Checks number of keys in children and calls appropriate function\n    void removeFromGeneral(BTreeNode* node, int i){\n        int key = node->vals[i];\n        if(node->children[i]->numberOfKeys >= 3){\n            int pre = getPredecessor(node, i);\n            node->vals[i] = pre;\n            removeFromSubtree(node->children[i], pre);\n        } else if(node->children[i+1]->numberOfKeys>=3){\n            int suc = getSuccessor(node, i);\n            node->vals[i] = suc;\n            removeFromSubtree(node->children[i+1], suc);\n        } else {\n            merge(node, i);\n            removeFromSubtree(node, i);\n        }\n    }\n\n    //Handles the node which has less than 2 keys and fill values accordingly\n    void fill(BTreeNode* node, int i){ \n        if(i!=0 && node->children[i-1]->numberOfKeys>=3)\n            borrowFromPrevious(node,i);\n        else if(i!=node->numberOfKeys && node->children[i+1]->numberOfKeys>=3)\n            borrowFromNext(node,i);\n        else{\n            if(i!=node->numberOfKeys)\n                merge(node,i);\n            else\n                merge(node,i-1);\n        }\n    } \n\n    //Removes values from the subtree rooted with given key\n    void removeFromSubtree(BTreeNode* node, int key){\n        int i = findClosestKey(node,key);\n        if(i<node->numberOfKeys && node->vals[i]==key){\n            if(node->isLeaf)\n                removeFromLeaf(node, i);\n            else\n                removeFromGeneral(node,i);\n        } else {\n            if(node->isLeaf){\n                cout<<\"Key not found in tree\\n\";\n                return;\n            }\n            bool flag = (i==node->numberOfKeys) ? true : false;\n            if(node->children[i]->numberOfKeys<3)\n                fill(node, i);\n            if(flag && i>node->numberOfKeys)\n                removeFromSubtree(node->children[i-1], key);\n            else\n                removeFromSubtree(node->children[i], key);\n        }\n    }\n\n    //The utility function to be called by main\n    void deleteNode(BTreeNode* root, int val){\n        if(!root){\n            cout<<\"Tree is Empty\\n\";\n            return;\n        }\n        removeFromSubtree(root, val);\n        if(root->numberOfKeys==0){\n            BTreeNode* temp = root;\n            if(root->isLeaf)    \n                root=NULL;\n            else\n                root = root->children[0];\n            delete(temp);\n        }\n    }\n};\n\n// Searches the value in the given tree and returns a pointer to the node\nBTreeNode* search(BTreeNode* root, int val){\n    int i=0;\n    while(i<root->numberOfKeys && val>root->vals[i])\n        ++i;\n    if(root->vals[i]==val)\n        return root;\n    if(root->isLeaf)\n        return NULL;\n    return search(root->children[i], val);\n}\n\nint main(){\n    while(1){\n        cout<<\"++++++++++++++++++++++++++++++++++\\n\";\n        cout<<\"Select an Operation\\n\";\n        cout<<\" 1. Insert\\n 2. Delete \\n 3. Search \\n 4.Traverse\\n5. Exit \\n\";\n        cout<<\"++++++++++++++++++++++++++++++++++\\n\";\n        int selection;\n        cin>>selection;\n        if(selection == 1){\n            cout<<\"Enter Number to Insert\\n\";\n            int key;\n            cin>>key;\n            insertNode(key);\n        } else if(selection == 2){\n            cout<<\"Enter Number to Delete\\n\";\n            int num;\n            cin>>num;\n            BTreeNode* temp = search(root,num);\n            Deletion d;\n            if(temp)\n                d.deleteNode(root,num);\n            else\n                cout<<\"Value doesn't exist\\n\";\n        } else if(selection==3){\n            cout<<\"Enter Number to Search\\n\";\n            int num;\n            cin>>num;\n            BTreeNode* temp = search(root,num);\n            if(temp)\n                cout<<\"Found\\n\";\n            else\n                cout<<\"Not Found\\n\";\n        } else if(selection == 4){\n            cout<<\"Traversal: \";\n            traverseBTree(root);\n            cout<<\"\\n\";\n        } else if(selection == 5){\n            break;\n        }\n    }\n}\n"
  },
  {
    "path": "Data-Structures/Tree/Binary-Tree/Binary tree using C.c",
    "content": "#include<stdlib.h>\n#include<stdio.h>\n\nstruct bin_tree {\nint data;\nstruct bin_tree * right, * left;\n};\ntypedef struct bin_tree node;\n\nvoid insert(node ** tree, int val)\n{\n    node *temp = NULL;\n    if(!(*tree))\n    {\n        temp = (node *)malloc(sizeof(node));\n        temp->left = temp->right = NULL;\n        temp->data = val;\n        *tree = temp;\n        return;\n    }\n\n    if(val < (*tree)->data)\n    {\n        insert(&(*tree)->left, val);\n    }\n    else if(val > (*tree)->data)\n    {\n        insert(&(*tree)->right, val);\n    }\n\n}\n\nvoid print_preorder(node * tree)\n{\n    if (tree)\n    {\n        printf(\"%d\\n\",tree->data);\n        print_preorder(tree->left);\n        print_preorder(tree->right);\n    }\n\n}\n\nvoid print_inorder(node * tree)\n{\n    if (tree)\n    {\n        print_inorder(tree->left);\n        printf(\"%d\\n\",tree->data);\n        print_inorder(tree->right);\n    }\n}\n\nvoid print_postorder(node * tree)\n{\n    if (tree)\n    {\n        print_postorder(tree->left);\n        print_postorder(tree->right);\n        printf(\"%d\\n\",tree->data);\n    }\n}\n\nvoid deltree(node * tree)\n{\n    if (tree)\n    {\n        deltree(tree->left);\n        deltree(tree->right);\n        free(tree);\n    }\n}\n\nnode* search(node ** tree, int val)\n{\n    if(!(*tree))\n    {\n        return NULL;\n    }\n\n    if(val < (*tree)->data)\n    {\n        search(&((*tree)->left), val);\n    }\n    else if(val > (*tree)->data)\n    {\n        search(&((*tree)->right), val);\n    }\n    else if(val == (*tree)->data)\n    {\n        return *tree;\n    }\n}\n\nvoid main()\n{\n    node *root;\n    node *tmp;\n    //int i;\n\n    root = NULL;\n    /* Inserting nodes into tree */\n    insert(&root, 9);\n    insert(&root, 4);\n    insert(&root, 15);\n    insert(&root, 6);\n    insert(&root, 12);\n    insert(&root, 17);\n    insert(&root, 2);\n\n    /* Printing nodes of tree */\n    printf(\"Pre Order Display\\n\");\n    print_preorder(root);\n\n    printf(\"In Order Display\\n\");\n    print_inorder(root);\n\n    printf(\"Post Order Display\\n\");\n    print_postorder(root);\n\n    /* Search node into tree */\n    tmp = search(&root, 4);\n    if (tmp)\n    {\n        printf(\"Searched node=%d\\n\", tmp->data);\n    }\n    else\n    {\n        printf(\"Data Not found in tree.\\n\");\n    }\n\n    /* Deleting all nodes of tree */\n    deltree(root);\n}\n"
  },
  {
    "path": "Data-Structures/Tree/Binary-Tree/Btree.java",
    "content": "/****************************************************\r\n*  Author - Ayush Sharma (belphegor-s)\r\n*  File Name - B-Tree.java\r\n*  \r\n*  Short Note about B-Tree -\r\n*\r\n*  B Tree is a specialized m-way tree that can\r\n*  be widely used for disk access. \r\n*  A B-Tree of order m can have at most m-1 keys\r\n*  and m children. One of the main reason of using \r\n*  B tree is its capability to store large number \r\n*  of keys in a single node and large key values by \r\n*  keeping the height of the tree relatively small.\r\n*\r\n******************************************************/\r\n\r\n// Java program to illustrate the sum of two numbers\r\n\r\n// A BTree \r\nclass Btree {\r\n\tpublic BTreeNode root; // Pointer to root node\r\n\tpublic int t; // Minimum degree\r\n\r\n\t// Constructor (Initializes tree as empty)\r\n\tBtree(int t) {\r\n\t\tthis.root = null;\r\n\t\tthis.t = t;\r\n\t}\r\n\r\n\t// function to traverse the tree\r\n\tpublic void traverse() {\r\n\t\tif (this.root != null)\r\n\t\t\tthis.root.traverse();\r\n\t\tSystem.out.println();\r\n\t}\r\n\r\n\t// function to search a key in this tree\r\n\tpublic BTreeNode search(int k) {\r\n\t\tif (this.root == null)\r\n\t\t\treturn null;\r\n\t\telse\r\n\t\t\treturn this.root.search(k);\r\n\t}\r\n}\r\n\r\n// A BTree node \r\nclass BTreeNode {\r\n\tint[] keys; // An array of keys\r\n\tint t; // Minimum degree (defines the range for number of keys)\r\n\tBTreeNode[] C; // An array of child pointers\r\n\tint n; // Current number of keys\r\n\tboolean leaf; // Is true when node is leaf. Otherwise false\r\n\r\n\t// Constructor\r\n\tBTreeNode(int t, boolean leaf) {\r\n\t\tthis.t = t;\r\n\t\tthis.leaf = leaf;\r\n\t\tthis.keys = new int[2 * t - 1];\r\n\t\tthis.C = new BTreeNode[2 * t];\r\n\t\tthis.n = 0;\r\n\t}\r\n\r\n\t// A function to traverse all nodes in a subtree rooted with this node\r\n\tpublic void traverse() {\r\n\r\n\t\t// There are n keys and n+1 children, travers through n keys\r\n\t\t// and first n children\r\n\t\tint i = 0;\r\n\t\tfor (i = 0; i < this.n; i++) {\r\n\r\n\t\t\t// If this is not leaf, then before printing key[i],\r\n\t\t\t// traverse the subtree rooted with child C[i].\r\n\t\t\tif (this.leaf == false) {\r\n\t\t\t\tC[i].traverse();\r\n\t\t\t}\r\n\t\t\tSystem.out.print(keys[i] + \" \");\r\n\t\t}\r\n\r\n\t\t// Print the subtree rooted with last child\r\n\t\tif (leaf == false)\r\n\t\t\tC[i].traverse();\r\n\t}\r\n\r\n\t// A function to search a key in the subtree rooted with this node.\r\n\tBTreeNode search(int k) { // returns NULL if k is not present.\r\n\r\n\t\t// Find the first key greater than or equal to k\r\n\t\tint i = 0;\r\n\t\twhile (i < n && k > keys[i])\r\n\t\t\ti++;\r\n\r\n\t\t// If the found key is equal to k, return this node\r\n\t\tif (keys[i] == k)\r\n\t\t\treturn this;\r\n\r\n\t\t// If the key is not found here and this is a leaf node\r\n\t\tif (leaf == true)\r\n\t\t\treturn null;\r\n\r\n\t\t// Go to the appropriate child\r\n\t\treturn C[i].search(k);\r\n\r\n\t}\r\n}\r\n"
  },
  {
    "path": "Data-Structures/Tree/Binary-Tree/Check_duplicates_in _BTree.java",
    "content": "import java.util.HashSet; \npublic class CheckDuplicateValues { \n   \n    public static boolean checkDupUtil(Node root, HashSet<Integer> s)  \n    {  \n        if (root == null)  \n            return false;  \n        if (s.contains(root.data))  \n            return true;  \n        s.add(root.data);  \n        \n        return checkDupUtil(root.left, s) || checkDupUtil(root.right, s);  \n    }  \n    \n    public static boolean checkDup(Node root)  \n    {  \n        HashSet<Integer> s=new HashSet<>(); \n        return checkDupUtil(root, s);  \n    }  \n  \n    public static void main(String args[]) { \n        Node root = new Node(1);  \n        root.left = new Node(2);  \n        root.right = new Node(2);\n        root.left.left = new Node(3);\n        root.left.right = new Node(4);\n        if (checkDup(root))  \n            System.out.print(\"Yes This tree contains Duplicates value.\");  \n        else\n            System.out.print(\"No duplicates values exist\");  \n    } \n} \nclass Node {  \n    int data;  \n    Node left;\n    Node right;\n    Node(int data) \n    { \n        this.data=data; \n    } \n}; \n"
  },
  {
    "path": "Data-Structures/Tree/Binary-Tree/Density/DensityBtree.c",
    "content": "/* Density of Binary Tree = Size / Height */\n\n#include<stdio.h> \t\t//For standard input / output operations\n#include<stdlib.h>\t\t//For dynamic declaration of Node using malloc\n\nstruct Node { \t//Struct for a Node in the tree\n    int data; \t//Data stored in this node\n    struct Node *left, *right; \t\t//Pointer to left and right child\n}; \n\nstruct Node* newNode(int data) {\t//Function for defining a New Node\n    struct Node* node = malloc(sizeof(struct Node)); \n    node->data = data; \n    node->left = node->right = NULL; \t//Initialize left and right child as 0\n    return node; \n} \n\nint heightAndSize(struct Node* node, int *size) { \n    if (node==NULL)\t//Left node \n        return 0; \n\n    int left_child_height = heightAndSize(node->left, size); \t//Recursively calls of the function for its left child\n    int right_child_height = heightAndSize(node->right, size); \t//Recursively calls of the function for its right child\n\n    *size=*size+1; \t//Increments size by 1 on traversal of each node\n    return (left_child_height > right_child_height) ? left_child_height + 1 : right_child_height + 1; //Returns the larger height among it's left and right child and adds 1 to account for itself\n} \n\nfloat density(struct Node* root){ \t//Function to calculate density by passing root of tree\n    if (root == NULL) \t//Incase root is Null , tree will be empty and hence density is 0\n        return 0; \n\n    int size, tree_height;\n    size = 0; \t//Initialize size of the tree as 0\n    tree_height = heightAndSize(root, &size); //Calls function to find height and size of the tree (returns height and increments size by address of parameter)\n    return (float)size/tree_height; \n} \n\nint main(){ \n    struct Node* root = newNode(1); \t//Root of tree \n    root->left = newNode(2); \t\t\t//Child Node\n    root->right = newNode(3); \t\t\t//Child Node\n    root->right->left = newNode(4);\t\t//Child Node\n\n    // For current example, height = 3 and size = 4 hence density should be 1.3333\n    printf(\"Density of given binary tree is %f\", density(root)); \t//Prints density\n    return 0; \n} "
  },
  {
    "path": "Data-Structures/Tree/Binary-Tree/Density/DensityBtree.cpp",
    "content": "/*Density of Binary Tree = Size / Height */\n\n#include<bits/stdc++.h> \n   \nstruct Node \n{ \n    int data; \n    Node *left, *right; \n}; \n   \nNode* newNode(int data) \n{ \n    Node* node = new Node; \n    node->data = data; \n    node->left = node->right = NULL; \n    return node; \n} \n  \nint heighAndSize(Node* node, int &size) \n{ \n    if (node==NULL) \n        return 0; \n  \n    int l = heighAndSize(node->left, size); \n    int r = heighAndSize(node->right, size); \n  \n    size++; \n    return (l > r) ? l + 1 : r + 1; \n} \n  \nfloat density(Node* root) \n{ \n    if (root == NULL) \n        return 0; \n  \n    int size = 0; // To store size \n  \n    int _height = heighAndSize(root, size); \n  \n    return (float)size/_height; \n} \n  \nint main() \n{ \n    Node* root = newNode(1); \n    root->left = newNode(2); \n    root->right = newNode(3); \n  \n    printf(\"Density of given binary tree is %f\", \n           density(root)); \n  \n    return 0; \n} \n"
  },
  {
    "path": "Data-Structures/Tree/Binary-Tree/Deserialize/Deserialize.rb",
    "content": "# created : 13/10/2020\n# author  : baniksudipto\n\nclass TreeNode\n    attr_accessor :value, :left, :right\n\n    def initialize(value = nil)\n        @value = value\n        @left = nil\n        @right = nil\n    end\nend\n\nclass Codec\n    def initialize(empty_leaf_marker, separator)\n      @index = 0\n      @marker = empty_leaf_marker\n      @separator = separator\n    end\n  \n    def serialize(root)\n      # Encodes a tree to a single string.\n      if root\n        [root.value , serialize(root.left), serialize(root.right)].join(@separator)\n      else\n        @marker.to_s\n      end\n    end\n  \n    def deserialize(data)\n        # Decodes a string to a tree\n        @index = 0\n        data = data.split(@separator)\n        build_tree(data)\n    end\n  \n    private\n  \n    def build_tree(data)\n      value = data[@index]\n      @index += 1\n      if value.nil? or value == @marker\n        nil\n      else\n        node = TreeNode.new(value)\n        node.left = build_tree(data)\n        node.right = build_tree(data)\n        node\n      end\n    end\n  end\n\n# test \nserialized_string = \"1,2,4,#,#,5,#,#,3,6,#,#,7,#,#\"\n\n#       1\n#    2     3\n#  4  5   6  7\n\ncodec = Codec.new('#',',')\n\nraise \"This is not working\" unless codec.serialize(codec.deserialize(serialized_string)) == serialized_string\n"
  },
  {
    "path": "Data-Structures/Tree/Binary-Tree/Duplicate_values.cs",
    "content": "using System; \nusing System.Collections; \nusing System.Collections.Generic; \n\nclass CheckDuplicateValues \n{ \n\n\t//Function that used HashSet to \n\t// find presence of duplicate nodes \n\tpublic static Boolean checkDupUtil(Node root, HashSet<int> s) \n\t{ \n\t\t// If tree is empty, there are no \n\t\t// duplicates. \n\t\tif (root == null) \n\t\t\treturn false; \n\t\n\t\t// If current node's data is already present. \n\t\tif (s.Contains(root.data)) \n\t\t\treturn true; \n\t\n\t\t// Insert current node \n\t\ts.Add(root.data); \n\t\t\n\t\t// Recursively check in left and right \n\t\t// subtrees. \n\t\treturn checkDupUtil(root.left, s) || \n\t\t\t\tcheckDupUtil(root.right, s); \n\t} \n\t\n\tpublic static Boolean checkDup(Node root) \n\t{ \n\t\tHashSet<int> s = new HashSet<int>(); \n\t\treturn checkDupUtil(root, s); \n\t} \n\n\tpublic static void Main(String []args) \n\t{ \n\t\tNode root = new Node(1); \n\t\troot.left = new Node(2); \n\t\troot.right = new Node(2); \n\t\troot.left.left = new Node(3); \n\t\tif (checkDup(root)) \n\t\t\tConsole.Write(\"Yes\"); \n\t\telse\n\t\t\tConsole.Write(\"No\"); \n\t} \n} \npublic class Node \n{ \n\tpublic int data; \n\tpublic Node left, right; \n\tpublic Node(int data) \n\t{ \n\t\tthis.data = data; \n\t} \n}; \n"
  },
  {
    "path": "Data-Structures/Tree/Binary-Tree/Invert_Binary_Tree/Invert_Binary_Tree.py",
    "content": "\"\"\"Invert Binary Tree - Write a function that takes in a Binary Tree and inverts it. In other words, the function should swap every left node in the tree for its corresponding right node. \nEach Binary Tree node has an integer value, a left child node, and a right child node. Children nodes can either be Bina ry Tree nodes themselves or None / null.\n\"\"\"\n\n# ITERATIVE\n# O(N)T | O(N)S\n\ndef invertBinaryTree(tree):\n    queue = [tree]\n    while len(queue) != 0:\n        currNode = queue.pop(0)\n        if currNode is None:\n            continue\n        swap(currNode)\n        queue.append(currNode.left)\n        queue.append(currNode.right)\n\n\ndef swap(tree):\n    tree.left, tree.right = tree.right, tree.left\n\n\nclass BinaryTree:\n    def __init__(self, value):\n        self.value = value\n        self.left = None\n        self.right = None\n\n# RECURSIVE\n# O(N)T | O(d)S\n\n\ndef invertBinaryTree(tree):\n    if tree is not None:\n        swap(tree)\n        invertBinaryTree(tree.left)\n        invertBinaryTree(tree.right)\n    return\n\n\ndef swap(tree):\n    tree.left, tree.right = tree.right, tree.left\n\n\n# This is the class of the input binary tree.\nclass BinaryTree:\n    def __init__(self, value):\n        self.value = value\n        self.left = None\n        self.right = None\n"
  },
  {
    "path": "Data-Structures/Tree/Binary-Tree/Invert_Binary_Tree/invertBinTree.rb",
    "content": "# simple bst implementation\nclass BST\n    attr_accessor :head\n    # simple bst node implementation\n    class Node\n       attr_accessor :left\n       attr_accessor :right\n       attr_accessor :value\n       \n       def initialize(val)\n            @value = val\n       end\n    end\n\n    # bst constructor\n    def initialize(val)\n        @head = Node.new(val)\n    end\n\n    # method for inserting new values into a given bst\n    def self.insert(val, tree)\n        if not tree then\n            return Node.new(val)\n        else\n            if val > tree.value then\n                tree.right = insert(val, tree.right)\n            else \n                tree.left = insert(val, tree.left)\n            end\n        end\n        tree\n    end\n\n    # tree inversion method\n    def self.invert(tree)\n        # base case, null leaf reached\n        if not tree then\n            return\n        end\n        # otherwise, recurse and swap left and right nodes of tree\n        temp = tree.right\n        tree.right = invert(tree.left)\n        tree.left = invert(temp)\n        # return inverted result\n        tree\n    end\n\n    # simple bst print method for printing\n    def self.printTree(tree, level = 0)\n        if not tree then\n            return\n        else\n            if level == 0 then\n                puts tree.value\n            elsif level == 1 then\n                print tree.value\n            else\n                puts \" #{tree.value}\"\n            end\n            printTree(tree.left, 1)\n            printTree(tree.right, 2)\n        end\n    end\nend\n\n# simple integer input example, takes three int inputs\nputs \"Please input three integers for an example.\"\nb = BST.new((gets).to_i)\nBST.insert((gets).to_i, b.head)\nBST.insert((gets).to_i, b.head)\nputs \"Example tree~\"\nBST.printTree(b.head)\n# then inverts tree\nputs \"Inverted result~\"\nBST.invert(b.head)\nBST.printTree(b.head)"
  },
  {
    "path": "Data-Structures/Tree/Binary-Tree/Invert_Binary_Tree/invert_binary_tree.cpp",
    "content": "#include<bits/stdc++.h> \nusing namespace std; \n//Definition for binary tree-\nstruct TreeNode {\n   int val;\n   TreeNode *left;\n   TreeNode *right;\n};\n//Utility function-\nstruct TreeNode* newNode(int val) { \n    struct TreeNode* node = (struct TreeNode*)malloc(sizeof(struct TreeNode)); \n    node->val = val; \n    node->left = NULL; \n    node->right = NULL;\n    return(node); \n} \n//Inverting Binary Tree using recursion-\nvoid invert(TreeNode* A){\n    if(A==NULL) return;\n    invert(A->left);\n    TreeNode* t1=A->left;\n    invert(A->right);\n    TreeNode* t2=A->right;\n    A->left=t2;\n    A->right=t1;\n}\nTreeNode* invertTree(TreeNode* root) {\n    invert(root);\n    return root;\n}\nint main() { \n    struct TreeNode *root = newNode(1); \n    root->left = newNode(2); \n    root->right = newNode(3); \n    root->left->left = newNode(4); \n    root->left->right = newNode(5);\n    //Convert tree to its mirror-\n    root = invertTree(root); \n    return 0;  \n} \n"
  },
  {
    "path": "Data-Structures/Tree/Binary-Tree/Invert_Binary_tree/invert_btree.swift",
    "content": "class TreeNode {\n    var left: TreeNode?\n    var right: TreeNode?\n    var value: Int\n\n    init(val: Int) {\n        self.value = val\n    }\n\n}\n\nclass Tree{\n    var root: TreeNode\n    init(val: TreeNode){\n        self.root = val\n    }\n    func invertTree(){\n        invert(node: self.root)\n    }\n    func invert(node: TreeNode){\n        if(node.left == nil&&node.right == nil){\n            return\n        }\n        let temp = node.left\n        node.left = node.right\n        node.right = temp\n        if(node.left != nil ){\n            invert(node: node.left!)\n        }\n        if(node.right != nil){\n            invert(node: node.right!)\n        }\n    }\n\n}\nvar root = TreeNode(val: 1)\nvar o = TreeNode(val: 3)\nvar b = TreeNode(val: 7)\nvar h = TreeNode(val: 4)\nvar g = TreeNode(val: 2)\n\nroot.left = o\nroot.right = b\nroot.right?.right = h\nroot.right?.left = g\nvar myTree = Tree(val: root)\n\nmyTree.invertTree()\n"
  },
  {
    "path": "Data-Structures/Tree/Binary-Tree/Right_View/RightViewBTree.java",
    "content": "class Node { \n  \n    int data; \n    Node left, right; \n  \n    Node(int item) { \n        data = item; \n        left = right = null; \n    } \n} \n  \n\nclass Max_level { \n  \n    int max_level; \n} \n  \nclass BinaryTree { \n  \n    Node root; \n    Max_level max = new Max_level(); \n  \n    // Recursive function to print right view of a binary tree. \n    void rightViewUtil(Node node, int level, Max_level max_level) { \n  \n        if (node == null)  \n            return; \n  \n        // If this is the last Node of its level \n        if (max_level.max_level < level) { \n            System.out.print(node.data + \" \"); \n            max_level.max_level = level; \n        } \n  \n        // Recur for right subtree first, then left subtree \n        rightViewUtil(node.right, level + 1, max_level); \n        rightViewUtil(node.left, level + 1, max_level); \n    } \n  \n    void rightView() \n    { \n        rightView(root); \n    } \n  \n    void rightView(Node node) { \n  \n        rightViewUtil(node, 1, max); \n    } \n  \n    public static void main(String args[]) { \n        BinaryTree tree = new BinaryTree(); \n        tree.root = new Node(1); \n        tree.root.left = new Node(2); \n        tree.root.right = new Node(3); \n        tree.root.left.left = new Node(4); \n        tree.root.left.right = new Node(5); \n        tree.root.right.left = new Node(6); \n        tree.root.right.right = new Node(7); \n        tree.root.right.left.right = new Node(8); \n          \n        tree.rightView(); \n  \n        } \n} \n"
  },
  {
    "path": "Data-Structures/Tree/Binary-Tree/Right_View/rightViewBinTree.rb",
    "content": "# simple bst implementation\nclass BST\n    attr_accessor :head\n    # simple bst node implementation\n    class Node\n       attr_accessor :left\n       attr_accessor :right\n       attr_accessor :value\n       \n       def initialize(val)\n            @value = val\n       end\n    end\n\n    # bst constructor\n    def initialize(val)\n        @head = Node.new(val)\n    end\n\n    # method for inserting new values into a given bst\n    def self.insert(val, tree)\n        if not tree then\n            return Node.new(val)\n        else\n            if val > tree.value then\n                tree.right = insert(val, tree.right)\n            else \n                tree.left = insert(val, tree.left)\n            end\n        end\n        tree\n    end\n\n    # right side view method\n    def self.rightSideView(tree)\n        rightView = []\n        while tree \n            rightView << tree.value\n            tree = tree.right\n        end\n        rightView\n    end\n\n    # simple bst print method for printing\n    def self.printTree(tree, level = 0)\n        if not tree then\n            return\n        else\n            if level == 0 then\n                puts tree.value\n            elsif level == 1 then\n                print tree.value\n            else\n                puts \" #{tree.value}\"\n            end\n            printTree(tree.left, 1)\n            printTree(tree.right, 2)\n        end\n    end\nend\n\n# simple integer input example, takes three int inputs\nb = BST.new((gets).to_i)\nBST.insert((gets).to_i, b.head)\nBST.insert((gets).to_i, b.head)\nBST.printTree(b.head)\nputs BST.rightSideView(b.head).inspect\n"
  },
  {
    "path": "Data-Structures/Tree/Binary-Tree/Right_View/right_view.py",
    "content": "class Node: \n\t# A constructor to create a new Binary tree Node \n\tdef __init__(self, item): \n\t\tself.data = item \n\t\tself.left = None\n\t\tself.right = None\n\t\n\ndef rightViewUtil(root, level, max_level): \n\t\n\t# Base Case \n\tif root is None: \n\t\treturn\n\n\tif (max_level[0] < level): \n\t\tprint \"%d \" %(root.data), \n\t\tmax_level[0] = level \n\n\trightViewUtil(root.right, level+1, max_level) \n\trightViewUtil(root.left, level+1, max_level) \n\ndef rightView(root): \n\tmax_level = [0] \n\trightViewUtil(root, 1, max_level) \n\n\n# Driver program to test above function \nroot = Node(1) \nroot.left = Node(2) \nroot.right = Node(3) \nroot.left.left = Node(4) \nroot.left.right = Node(5) \nroot.right.left = Node(6) \nroot.right.right = Node(7) \nroot.right.left.right = Node(8) \n\nrightView(root) \n\n"
  },
  {
    "path": "Data-Structures/Tree/Binary-Tree/Right_View/right_view.swift",
    "content": "class TreeNode {\n    var left: TreeNode?\n    var right: TreeNode?\n    var value: Int\n\n    init(val: Int) {\n        self.value = val\n    }\n\n}\n\nclass Tree{\n    var root: TreeNode\n    init(val: TreeNode){\n        self.root = val\n    }\n    func rightView()-> [TreeNode]{\n\n        var rightView = [TreeNode]()\n        var curretNode: TreeNode?\n        curretNode = self.root\n        while(curretNode?.right != nil){\n            rightView.append(curretNode!)\n            curretNode = curretNode!.right\n        }\n        rightView.append(curretNode!)\n        return rightView\n    }\n\n}\nvar root = TreeNode(val: 1)\nvar o = TreeNode(val: 3)\nvar b = TreeNode(val: 7)\nvar h = TreeNode(val: 4)\nvar g = TreeNode(val: 2)\n\nroot.left = o\nroot.right = b\nroot.right?.right = h\nroot.right?.left = g\nvar myTree = Tree(val: root)\n\nfor node in myTree.rightView() {\n    print(node.value, \" \")\n}\n"
  },
  {
    "path": "Data-Structures/Tree/Binary-Tree/Right_View/right_view_of_binary_tree.cpp",
    "content": "#include<bits/stdc++.h> \nusing namespace std;\n//Definition for binary tree\nstruct TreeNode {\n    int val;\n    TreeNode *left;\n    TreeNode *right;\n};\n//Utility function to create Tree nodes\nTreeNode* newNode(int val) { \n    TreeNode *temp = new TreeNode; \n    temp->val = val; \n    temp->left = temp->right = NULL; \n    return temp; \n} \n//The task is equivalent to returning the last value in each level of the tree, ie. similar to Breadth First Traversal\nvector<int> getRightView(TreeNode* root) {\n    vector<int>answer;\n    queue<TreeNode*>Q;          \n    TreeNode* temp;\n    Q.push(root);\n    //NULL node is used to demarkate separate levels of the tree-\n    Q.push(NULL);              \n    //BFS type approach using queue-\n    while(!Q.empty()){         \n        temp=Q.front();\n        Q.pop();\n        if(temp!=NULL){\n           if(temp->left!=NULL) \n              Q.push(temp->left);\n           if(temp->right!=NULL) \n              Q.push(temp->right);\n           if(Q.front()==NULL){             //we are at the end of the current level, ie. current node's value is required in the answer\n              answer.push_back(temp->val);\n              Q.pop();\n              Q.push(NULL);\n           }\n       }\n    }\n    return answer;\n}\nint main() { \n    //constructing the tree-\n    TreeNode* root = newNode(10); \n    root->left = newNode(2); \n    root->right = newNode(3); \n    root->left->left = newNode(7); \n    root->left->right = newNode(8); \n    root->right->right = newNode(15); \n    root->right->left = newNode(12); \n    root->right->right->left = newNode(14); \n    vector<int> RightViewOfBTree = getRightView(root);\n    //printing the vector containing right view of this tree-\n    for(int i=0; i<RightViewOfBTree.size(); i++)\n        cout<<RightViewOfBTree[i]<<\" \";\n    cout<<\"\\n\";\n} \n"
  },
  {
    "path": "Data-Structures/Tree/Binary-Tree/Serialize/Serialize.cpp",
    "content": "#include <stdio.h> \n#define MARKER -1 \n\nstruct Node \n{ \n    int key; \n    struct Node* left, *right; \n}; \n\nNode* newNode(int key) \n{ \n    Node* temp = new Node; \n    temp->key = key; \n    temp->left = temp->right = NULL; \n    return (temp); \n} \n  \nvoid serialize(Node *root, FILE *fp) \n{ \n    if (root == NULL) \n    { \n        fprintf(fp, \"%d \", MARKER); \n        return; \n    } \n  \n    fprintf(fp, \"%d \", root->key); \n    serialize(root->left, fp); \n    serialize(root->right, fp); \n} \n\nint main() \n{ \n    struct Node *root        = newNode(32); \n    root->left               = newNode(12); \n    root->right              = newNode(23); \n    root->left->left         = newNode(40); \n    root->left->right        = newNode(33); \n    root->left->right->left  = newNode(50); \n    root->left->right->right = newNode(45); \n  \n    FILE *fp = fopen(\"tree.txt\", \"w\"); \n    if (fp == NULL) \n    { \n        puts(\"Error: Could not open file!\"); \n        return 0; \n    } \n    serialize(root, fp); \n    fclose(fp);   \n    return 0; \n} \n"
  },
  {
    "path": "Data-Structures/Tree/Binary-Tree/Serialize/Serialize.py",
    "content": "class Node:\r\n    def __init__(self, key, left=None, right=None):\r\n        self.key = key\r\n        self.left = left\r\n        self.right = right\r\n\r\n    def __repr__(self):\r\n        left = f\" left={self.left}\" if self.left is not None else \"\"\r\n        right = f\" right={self.right}\" if self.right is not None else \"\"\r\n        return f\"<Node object key={self.key}{left+right}>\"\r\n\r\n\r\ndef serialize(root):\r\n    if root is None:\r\n        return \"-1\"\r\n\r\n    # for each branch, return the key, the left then the right node\r\n    output = (str(root.key), serialize(root.left), serialize(root.right))\r\n    return \" \".join(output)\r\n\r\n\r\nif __name__ == \"__main__\":\r\n    #     1\r\n    #    / \\\r\n    #   2   3\r\n    #  / \\ / \\\r\n    # 4 -1 6  7\r\n    root = Node(1, Node(2, Node(4)), Node(3, Node(6), Node(7)))\r\n    print(root)\r\n\r\n    with open(\"tree.txt\", \"w\") as fp:\r\n        fp.write(serialize(root))"
  },
  {
    "path": "Data-Structures/Tree/Binary-Tree/Subtree_check/Subtree_check.cpp",
    "content": "#include<cstring>\r\n#include<iostream>\r\n\r\nusing namespace std;\r\n#define MAX 100\r\n \r\n// Structure of a tree node\r\nstruct Node {\r\n    char key;\r\n    struct Node *left, *right;\r\n};\r\n \r\n// A utility function to create a new BST node\r\nNode* newNode(char item)\r\n{\r\n    Node* temp = new Node;\r\n    temp->key = item;\r\n    temp->left = temp->right = NULL;\r\n    return temp;\r\n}\r\n \r\n// A utility function to store inorder traversal of tree rooted\r\n// with root in an array arr[]. Note that i is passed as reference\r\nvoid storeInorder(Node* root, char arr[], int& i)\r\n{\r\n    if (root == NULL) {\r\n        arr[i++] = '$';\r\n        return;\r\n    }\r\n    storeInorder(root->left, arr, i);\r\n    arr[i++] = root->key;\r\n    storeInorder(root->right, arr, i);\r\n}\r\n \r\n// A utility function to store preorder traversal of tree rooted\r\n// with root in an array arr[]. Note that i is passed as reference\r\nvoid storePreOrder(Node* root, char arr[], int& i)\r\n{\r\n    if (root == NULL) {\r\n        arr[i++] = '$';\r\n        return;\r\n    }\r\n    arr[i++] = root->key;\r\n    storePreOrder(root->left, arr, i);\r\n    storePreOrder(root->right, arr, i);\r\n}\r\n \r\n/* This function returns true if S is a subtree of T, otherwise false */\r\nbool isSubtree(Node* T, Node* S)\r\n{\r\n    /* base cases */\r\n    if (S == NULL)\r\n        return true;\r\n    if (T == NULL)\r\n        return false;\r\n \r\n    // Store Inorder traversals of T and S in inT[0..m-1]\r\n    // and inS[0..n-1] respectively\r\n    int m = 0, n = 0;\r\n    char inT[MAX], inS[MAX];\r\n    storeInorder(T, inT, m);\r\n    storeInorder(S, inS, n);\r\n    inT[m] = '\\0', inS[n] = '\\0';\r\n \r\n    // If inS[] is not a substring of inT[], return false\r\n    if (strstr(inT, inS) == NULL)\r\n        return false;\r\n \r\n    // Store Preorder traversals of T and S in preT[0..m-1]\r\n    // and preS[0..n-1] respectively\r\n    m = 0, n = 0;\r\n    char preT[MAX], preS[MAX];\r\n    storePreOrder(T, preT, m);\r\n    storePreOrder(S, preS, n);\r\n    preT[m] = '\\0', preS[n] = '\\0';\r\n \r\n    // If preS[] is not a substring of preT[], return false\r\n    // Else return true\r\n    return (strstr(preT, preS) != NULL);\r\n}\r\n \r\n// Driver program to test above function\r\nint main()\r\n{\r\n    Node* T = newNode('a');\r\n    T->left = newNode('b');\r\n    T->right = newNode('d');\r\n    T->left->left = newNode('c');\r\n    T->right->right = newNode('e');\r\n \r\n    Node* S = newNode('a');\r\n    S->left = newNode('b');\r\n    S->left->left = newNode('c');\r\n    S->right = newNode('d');\r\n \r\n    if (isSubtree(T, S))\r\n        cout << \"Yes: S is a subtree of T\";\r\n    else\r\n        cout << \"No: S is NOT a subtree of T\";\r\n \r\n    return 0;\r\n}\r\nO\r\n\r\n\r\n"
  },
  {
    "path": "Data-Structures/Tree/Binary-Tree/SymmetricBTree.java",
    "content": "class Node  \n{ \n    int key; \n    Node left, right; \n   \n    Node(int item)  \n    { \n        key = item; \n        left = right = null; \n    } \n} \n   \nclass BinaryTree  \n{ \n    Node root; \n   \n    boolean isMirror(Node node1, Node node2)  \n    { \n        if (node1 == null && node2 == null) \n            return true; \n        if (node1 != null && node2 != null && node1.key == node2.key) \n            return (isMirror(node1.left, node2.right) \n                    && isMirror(node1.right, node2.left)); \n        return false; \n    } \n   \n    boolean isSymmetric(Node node)  \n    { \n        return isMirror(root, root); \n    } \n   \n     \n    public static void main(String args[])  \n    { \n        BinaryTree tree = new BinaryTree(); \n        tree.root = new Node(1); \n        tree.root.left = new Node(2); \n        tree.root.right = new Node(2); \n        tree.root.left.left = new Node(3); \n        tree.root.left.right = new Node(4); \n        tree.root.right.left = new Node(4); \n        tree.root.right.right = new Node(3); \n        boolean output = tree.isSymmetric(tree.root); \n        if (output == true) \n            System.out.println(\"Tree is Symmetric \"); \n        else\n            System.out.println(\"Tree is not Symmetric\"); \n    } \n} \n"
  },
  {
    "path": "Data-Structures/Tree/Binary-Tree/SymmetryBTree/SymmetryBTree.rb",
    "content": "# Question: \n# Given a binary tree, check whether it is a mirror of itself\n#\n# Solution: \n# \n# structure of TreeNode\n\nclass TreeNode\n  attr_accessor :val, :left, :right\n\n  def initialize(val = 0, left = nil, right = nil)\n    @val = val\n    @left = left\n    @right = right\n  end\nend\n\n# method to check if Tree is symmetric\ndef symmetric?(root)\n  check_symmetry(root, root)\nend\n\n# utility method of symmetric?\ndef check_symmetry(actual, mirror)\n  return true if actual.nil? && mirror.nil?\n  return false if actual.nil? || mirror.nil?\n\n  (actual.val == mirror.val) && check_symmetry(actual.left, mirror.right) &&\n    check_symmetry(actual.right, mirror.left)\nend\n\n\n\n#  ===============  Test Cases ============\n\n\n# sample tree 1   ==> symmetric? => true\n#      5\n#   4     4\n# 1         1\n\n\nsymmetric_tree = TreeNode.new(5)\nsymmetric_tree.left = TreeNode.new(4)\nsymmetric_tree.left.left = TreeNode.new(1)\nsymmetric_tree.right = TreeNode.new(4)\nsymmetric_tree.right.right = TreeNode.new(1)\n\nsymmetric?(symmetric_tree) ? puts('working as expected') : puts('not working as expected')\n\n# sample tree 2   ==> symmetric? => false\n#      5\n#   3     3\n# 2     2\n\n\nasymmetric_tree = TreeNode.new(5)\nasymmetric_tree.left = TreeNode.new(3)\nasymmetric_tree.right = TreeNode.new(3)\nasymmetric_tree.left.left = TreeNode.new(2)\nasymmetric_tree.right.left = TreeNode.new(2)\n\n!symmetric?(asymmetric_tree) ? puts('working as expected') : puts('not working as expected')\n\n\n# sample tree 3   ==> symmetric? => false\n#      5\n#   3     4\n# 2         1\n\n\nasymmetric_tree = TreeNode.new(5)\nasymmetric_tree.left = TreeNode.new(3)\nasymmetric_tree.right = TreeNode.new(4)\nasymmetric_tree.left.left = TreeNode.new(2)\nasymmetric_tree.right.right = TreeNode.new(1)\n\n!symmetric?(asymmetric_tree) ? puts('working as expected') : puts('not working as expected')\n\n\n\n\n\n"
  },
  {
    "path": "Data-Structures/Tree/Binary-Tree/SymmetryBTree.cs",
    "content": "// C# program to check is binary  \n// tree is symmetric or not  \nusing System;  \n  \nclass Node  \n{  \n    public int key;  \n    public Node left, right;  \n      \n    public Node(int item)  \n    {  \n        key = item;  \n        left = right = null;  \n    }  \n}  \n      \nclass GFG  \n{  \n    Node root;  \n      \n    // returns true if trees with roots \n    // as root1 and root2 are mirror  \n    Boolean isMirror(Node node1,  \n                     Node node2)  \n    {  \n        // if both trees are empty,  \n        // then they are mirror image  \n        if (node1 == null && node2 == null)  \n            return true;  \n      \n        // For two trees to be mirror images,  \n        // the following three conditions must be true  \n        // 1 - Their root node's key must be same  \n        // 2 - left subtree of left tree and right subtree  \n        //       of right tree have to be mirror images  \n        // 3 - right subtree of left tree and left subtree  \n        //       of right tree have to be mirror images  \n        if (node1 != null && node2 != null &&  \n            node1.key == node2.key)  \n            return (isMirror(node1.left, node2.right) &&  \n                    isMirror(node1.right, node2.left));  \n      \n        // if neither of the above conditions  \n        // is true then root1 and root2 are \n        // mirror images  \n        return false;  \n    }  \n      \n    // returns true if the tree is symmetric  \n    // i.e mirror image of itself  \n    Boolean isSymmetric(Node node)  \n    {  \n        // check if tree is mirror of itself  \n        return isMirror(root, root);  \n    }  \n      \n    // Driver Code  \n    static public void Main(String[] args)  \n    {  \n        GFG tree = new GFG();  \n        tree.root = new Node(1);  \n        tree.root.left = new Node(2);  \n        tree.root.right = new Node(2);  \n        tree.root.left.left = new Node(3);  \n        tree.root.left.right = new Node(4);  \n        tree.root.right.left = new Node(4);  \n        tree.root.right.right = new Node(3);  \n        Boolean output = tree.isSymmetric(tree.root);  \n        if (output == true)  \n            Console.WriteLine(\"1\");  \n        else\n            Console.WriteLine(\"0\");  \n    }  \n}  \n"
  },
  {
    "path": "Data-Structures/Tree/Binary-Tree/SymmetryBTree.py",
    "content": "# Node structure \nclass TreeNode:\n\n    def __init__(self, val=0, left=None, right=None):\n        \"\"\"\"\n        Creates a new tree node\n        :param val: Value of the node\n        :param left: Node on the left\n        :param right: Node on the right\n        \"\"\"\n        self.val = val\n        self.left = left\n        self.right = right\n    \n\ndef isMirror(root1, root2):\n    \"\"\"\"\n    Returns True if trees with roots as root1 and root 2  are mirror \n    :param root1: TreeNode\n    :param root2: TreeNode\n    \"\"\"\n    # If both trees are empty, then they are mirror images \n    if root1 is None and root2 is None: \n        return True\n\n    \"\"\" For two trees to be mirror images, the following three \n        conditions must be true \n        1 - Their root node's key must be same \n        2 - left subtree of left tree and right subtree \n        of the right tree have to be mirror images \n        3 - right subtree of left tree and left subtree \n        of right tree have to be mirror images \n    \"\"\"\n    if (root1 is not None and root2 is not None): \n            if root1.val == root2.val: \n                return (isMirror(root1.left, root2.right)and\n                isMirror(root1.right, root2.left)) \n\n    # If neither of the above conditions is true then root1 \n    # and root2 are not mirror images \n    return False\n\ndef isSymmetric(root: TreeNode):\n    \"\"\"\n    Checks if the tree is mirror of itself\n    :param root: Tree Node\n    \"\"\"\n    # Check if tree is mirror of itself \n    return isMirror(root, root)\n\n\n# Driver Program \n# Let's construct the tree show in the above figure \nroot = TreeNode(1) \nroot.left = TreeNode(2) \nroot.right = TreeNode(2) \nroot.left.left = TreeNode(3) \nroot.left.right = TreeNode(4) \nroot.right.left = TreeNode(4) \nroot.right.right = TreeNode(3) \nprint(\"1\" if isSymmetric(root) == True else \"0\")\n\n# This code is contributed by Nikhil Kumar Singh(nickzuck_007) \n"
  },
  {
    "path": "Data-Structures/Tree/Binary-Tree/Two_level_Node/two_level_Node.cpp",
    "content": "#include <bits/stdc++.h> \nusing namespace std; \n  \n/* A binary tree Node has key, pointer to left and right children */\nstruct Node \n{ \n    int key; \n    struct Node* left, *right; \n}; \n  \n/* Given a binary tree, print nodes from level number 'low' to level \n   number 'high'*/\nvoid printLevels(Node* root, int low, int high) \n{ \n    queue <Node *> Q; \n  \n    Node *marker = new Node; // Marker node to indicate end of level \n  \n    int level = 1;   // Initialize level number \n  \n    // Enqueue the only first level node and marker node for end of level \n    Q.push(root); \n    Q.push(marker); \n  \n    // Simple level order traversal loop \n    while (Q.empty() == false) \n    { \n        // Remove the front item from queue \n        Node *n = Q.front(); \n        Q.pop(); \n  \n        // Check if end of level is reached \n        if (n == marker) \n        { \n            // print a new line and increment level number \n            cout << endl; \n            level++; \n  \n            // Check if marker node was last node in queue or \n            // level number is beyond the given upper limit \n            if (Q.empty() == true || level > high) break; \n  \n            // Enqueue the marker for end of next level \n            Q.push(marker); \n  \n            // If this is marker, then we don't need print it \n            // and enqueue its children \n            continue; \n        } \n  \n        // If level is equal to or greater than given lower level, \n        // print it \n        if (level >= low) \n            cout << n->key << \" \"; \n  \n        // Enqueue children of non-marker node \n        if (n->left != NULL)  Q.push(n->left); \n        if (n->right != NULL) Q.push(n->right); \n    } \n} \n  \n/* Helper function that allocates a new Node with the \n   given key and NULL left and right pointers. */\nNode* newNode(int key) \n{ \n    Node* temp = new Node; \n    temp->key = key; \n    temp->left = temp->right = NULL; \n    return (temp); \n} \n  \n/* Driver program to test above functions*/\nint main() \n{ \n    // Let us construct the BST shown in the above figure \n    struct Node *root        = newNode(20); \n    root->left               = newNode(8); \n    root->right              = newNode(22); \n    root->left->left         = newNode(4); \n    root->left->right        = newNode(12); \n    root->left->right->left  = newNode(10); \n    root->left->right->right = newNode(14); \n  \n    cout << \"Level Order traversal between given two levels is\"; \n    printLevels(root, 2, 3); \n  \n    return 0; \n} \n"
  },
  {
    "path": "Data-Structures/Tree/Binary-Tree/Two_level_Node.java",
    "content": "// Java program to print Nodes level by level between given two levels \nimport java.util.LinkedList; \nimport java.util.Queue; \n   \n/* A binary tree Node has key, pointer to left and right children */\nclass Node  \n{ \n    int data; \n    Node left, right; \n   \n    public Node(int item)  \n    { \n        data = item; \n        left = right = null; \n    } \n} \n   \nclass BinaryTree  \n{ \n    Node root; \n   \n    /* Given a binary tree, print nodes from level number 'low' to level \n       number 'high'*/\n    void printLevels(Node node, int low, int high)  \n    { \n        Queue<Node> Q = new LinkedList<>(); \n   \n        Node  marker = new Node(4); // Marker node to indicate end of level \n   \n        int level = 1;   // Initialize level number \n   \n        // Enqueue the only first level node and marker node for end of level \n        Q.add(node); \n        Q.add(marker); \n   \n        // Simple level order traversal loop \n        while (Q.isEmpty() == false)  \n        { \n            // Remove the front item from queue \n            Node  n = Q.peek(); \n            Q.remove(); \n   \n            // Check if end of level is reached \n            if (n == marker)  \n            { \n                // print a new line and increment level number \n                System.out.println(\"\"); \n                level++; \n   \n                // Check if marker node was last node in queue or \n                // level number is beyond the given upper limit \n                if (Q.isEmpty() == true || level > high) \n                    break; \n   \n                // Enqueue the marker for end of next level \n                Q.add(marker); \n                   \n                // If this is marker, then we don't need print it \n                // and enqueue its children \n                continue; \n            } \n   \n            // If level is equal to or greater than given lower level, \n            // print it \n            if (level >= low) \n                System.out.print( n.data + \" \"); \n  \n            // Enqueue children of non-marker node \n            if (n.left != null) \n                Q.add(n.left); \n              \n            if (n.right != null)  \n                Q.add(n.right); \n              \n        } \n    } \n   \n    // Driver program to test for above functions \n    public static void main(String args[])  \n    { \n        BinaryTree tree = new BinaryTree(); \n        tree.root = new Node(20); \n        tree.root.left = new Node(8); \n        tree.root.right = new Node(22); \n   \n        tree.root.left.left = new Node(4); \n        tree.root.left.right = new Node(12); \n        tree.root.left.right.left = new Node(10); \n        tree.root.left.right.right = new Node(14); \n   \n        System.out.print(\"Level Order traversal between given two levels is \"); \n        tree.printLevels(tree.root, 2, 3); \n   \n    } \n} \n"
  },
  {
    "path": "Data-Structures/Tree/Binary-Tree/VerticalOrderTraversal.java",
    "content": "/**\n * Definition for a binary tree node.\n * public class TreeNode {\n *     int val;\n *     TreeNode left;\n *     TreeNode right;\n *     TreeNode() {}\n *     TreeNode(int val) { this.val = val; }\n *     TreeNode(int val, TreeNode left, TreeNode right) {\n *         this.val = val;\n *         this.left = left;\n *         this.right = right;\n *     }\n * }\n */\n \nclass Solution {\n    public List<List<Integer>> verticalTraversal(TreeNode root) {\n        TreeMap<Integer,TreeMap<Integer,TreeSet<Integer>>> xCoord = new TreeMap();\n        view(root, 0, 0, xCoord);\n        List<List<Integer>> list = new ArrayList<List<Integer>>();\n        for(Integer i: xCoord.keySet()){\n            TreeMap<Integer, TreeSet<Integer>> yCoord = xCoord.get(i);\n            List<Integer> arr = new ArrayList<Integer>();\n            for(Integer j: yCoord.keySet()){\n                TreeSet<Integer> keys = yCoord.get(j);\n                for(Integer k: keys)\n                    arr.add(k);\n            }\n            list.add(arr);\n        }\n        return list;\n    }\n    public void view(TreeNode root, int x, int y, TreeMap<Integer,TreeMap<Integer,TreeSet<Integer>>> xCoord){\n        if(root==null) return;\n        \n        TreeMap<Integer,TreeSet<Integer>> yCoord = xCoord.getOrDefault(x, new TreeMap<Integer,TreeSet<Integer>>());\n        TreeSet<Integer> keys = yCoord.getOrDefault(y, new TreeSet<Integer>());\n        keys.add(root.val);\n        yCoord.put(y, keys);\n        xCoord.put(x, yCoord);\n        view(root.left, x-1, y+1, xCoord);\n        view(root.right, x+1, y+1, xCoord);\n    }\n}\n"
  },
  {
    "path": "Data-Structures/Tree/Binary-Tree/VerticalOrderTraversal.py",
    "content": "# submission by liamm91\n\nclass TreeNode:\n    def __init__(self, val=None, left=None, right=None):\n        self._val = val\n        self._left = left\n        self._right = right\n\n        # determining coords\n        self._x = self._y = 0\n\n    def insertNode(self, node):\n        if node.val: # if there is a value\n            if self.val < node.val: # insert to the right\n                if self.right: # node exists\n                    self.right.insertNode(node)\n                else: # node doesn't exist\n                    self.right = node\n                    self.right.x = self.x + 1\n                    self.right.y = self.y - 1\n            else: # insert to the left\n                if self.left: # node exists\n                    self.left.insertNode(node)\n                else: # node doesn't exist\n                    self.left = node\n                    self.left.x = self.x - 1\n                    self.left.y = self.y - 1\n\n    # properties\n\n    @property\n    def y(self):\n        return self._y\n\n    @y.setter\n    def y(self, new_y):\n        self._y = new_y\n\n    @property\n    def x(self):\n        return self._x\n\n    @x.setter\n    def x(self, new_x):\n        self._x = new_x\n\n    @property\n    def left(self):\n        return self._left\n\n    @left.setter\n    def left(self, left_node):\n        self._left = left_node\n\n    @property\n    def right(self):\n        return self._right\n\n    @right.setter\n    def right(self, right_node):\n        self._right = right_node\n    \n    @property\n    def val(self):\n        return self._val\n\n    @val.setter\n    def val(self, new_val):\n        self._val = new_val\n\n    def traverse(self):\n        if self.left:\n            self.left.traverse()\n        print(self)\n        if self.right:\n            self.right.traverse()\n\n    def __str__(self):\n        return \"Node at x: %d, y: %d with value %d\" % (self.x, self.y, self.val)\n\n\nclass BinaryTree:\n    def __init__(self, head: TreeNode=None):\n        self.head = head\n        self.vot = [self.head]\n\n    def insertNode(self, node: TreeNode):\n        if not self.head: # if head doesn't exist\n            self.head = node\n            self.head.x = self.head.y = 0\n        else: # head exists\n            self.head.insertNode(node)\n\n    def vertical_order_traverse(self):\n        self.vot = [self.head] # reinitializing the list incase self.head is None\n        def __group_nodes(arr_nodes):\n            r = t = [] # init vars\n            for node in arr_nodes: # looping thru the array\n                if t: # if there are nodes in the temp list\n                    if t[0].x == node.x: # if the x pos of the node \n                        t.append(node) # add the node to the temp list\n                    else: # if the x pos between the node and list differ\n                        for n in t:\n                            t[t.index(n)] = n.val # converting nodes into their values\n                        r.append((t[0], t)[len(t) > 1]) # adding the temp list to the return array\n                        t = [node] # putting the temp list to the new node\n                else:\n                    t = [node] # putting the temp list to thte new node\n\n            if t: r.append(t[0].val) # if there are left over nodes, convert and add\n\n            return r\n\n        def __getsides(self, node): # recusive function to return all node in the tree\n            l, r = node.left, node.right\n            if l:\n                self.vot.append(l) # appending node to the master list\n                __getsides(self, l)\n            if r:\n                self.vot.append(r) # appending node to the master list\n                __getsides(self, r)\n\n        __getsides(self, self.head) # starting recursive function\n\n        # sorting all the nodes\n        self.vot.sort(key=lambda node: node.x)\n        self.vot = __group_nodes(self.vot)\n\n        # returning vertical traverse order\n        return self.vot\n\ndef main():\n    nums = []\n    print(\"Input numbers in to the array, the first number you put in will be the root of the tree. \\nIf you input a non integer value, the Vertical Order Traversal will start.\")\n    while True:\n        to_input = input(\">: \")\n        try:\n            nums.append(float(to_input))\n        except Exception as e:\n            print(\"Bad value\")\n            break\n    tree = BinaryTree()\n    for num in nums:\n        tree.insertNode(TreeNode(num))\n\n\t#tree.head.traverse()\n\n    print(tree.vertical_order_traverse())\n\nif __name__ == \"__main__\":\n    main()\n"
  },
  {
    "path": "Data-Structures/Tree/Binary-Tree/Vertical_Sum/Verticle_sum_of_BinaryTree.java",
    "content": "import java.util.TreeMap; \n   \n// Class for a tree node \nclass TreeNode { \n   \n    // data members \n    private int key; \n    private TreeNode left; \n    private TreeNode right; \n   \n    // Accessor methods \n    public int key()        { return key; } \n    public TreeNode left()  { return left; } \n    public TreeNode right() { return right; } \n   \n    // Constructor \n    public TreeNode(int key) \n   { this.key = key; left = null; right = null; } \n   \n    // Methods to set left and right subtrees \n    public void setLeft(TreeNode left)   { this.left = left; } \n    public void setRight(TreeNode right) { this.right = right; } \n} \n   \n// Class for a Binary Tree \nclass Tree { \n   \n    private TreeNode root; \n   \n    // Constructors \n    public Tree() { root = null; } \n    public Tree(TreeNode n) { root = n; } \n   \n    // Method to be called by the consumer classes  \n    // like Main class \n    public void VerticalSumMain() { VerticalSum(root); } \n   \n    // A wrapper over VerticalSumUtil() \n    private void VerticalSum(TreeNode root) { \n   \n        // base case \n        if (root == null) { return; } \n   \n        // Creates an empty TreeMap hM \n        TreeMap<Integer, Integer> hM = \n                   new TreeMap<Integer, Integer>(); \n   \n        // Calls the VerticalSumUtil() to store the  \n        // vertical sum values in hM \n        VerticalSumUtil(root, 0, hM); \n   \n        // Prints the values stored by VerticalSumUtil() \n        if (hM != null) { \n            System.out.println(hM.entrySet()); \n        } \n    } \n   \n    // Traverses the tree in in-order form and builds \n    // a hashMap hM that contains the vertical sum \n    private void VerticalSumUtil(TreeNode root, int hD, \n                         TreeMap<Integer, Integer> hM) { \n   \n        // base case \n        if (root == null) {  return; } \n   \n        // Store the values in hM for left subtree \n        VerticalSumUtil(root.left(), hD - 1, hM); \n   \n        // Update vertical sum for hD of this node \n        int prevSum = (hM.get(hD) == null) ? 0 : hM.get(hD); \n        hM.put(hD, prevSum + root.key()); \n   \n        // Store the values in hM for right subtree \n        VerticalSumUtil(root.right(), hD + 1, hM); \n    } \n} \n   \n// Driver class to test the verticalSum methods \npublic class Main { \n   \n    public static void main(String[] args) { \n        /* Create any Binary Tree for eg-\n              1 \n            /    \\ \n          2        3 \n         / \\      / \\ \n        4   5    6   7 \n   \n        */\n        TreeNode root = new TreeNode(1); \n        root.setLeft(new TreeNode(2)); \n        root.setRight(new TreeNode(3)); \n        root.left().setLeft(new TreeNode(4)); \n        root.left().setRight(new TreeNode(5)); \n        root.right().setLeft(new TreeNode(6)); \n        root.right().setRight(new TreeNode(7)); \n        Tree t = new Tree(root); \n   \n        System.out.println(\"Following are the values of\" +  \n                           \" vertical sums with the positions\" + \n                        \" of the columns with respect to root \"); \n        t.VerticalSumMain(); \n    } \n} \n"
  },
  {
    "path": "Data-Structures/Tree/Binary-Tree/Vertical_Sum/Verticle_sum_of_Binary_Tree.cpp",
    "content": "#include <bits/stdc++.h> \n  \nusing namespace std; \n  \n\nstruct TNode{ \n    int key; \n    struct TNode *left, *right; \n}; \n  \n \nTNode* newTNode(int key) \n{ \n    TNode* temp = new TNode; \n    temp->key = key; \n    temp->left = temp->right = NULL; \n    return temp; \n} \n  \n \nstruct LLNode{ \n    int key; \n    struct LLNode *prev, *next; \n}; \n  \n \nLLNode* newLLNode(int key) \n{ \n    LLNode* temp = new LLNode; \n    temp->key = key; \n    temp->prev = temp->next = NULL; \n    return temp; \n} \n  \n \nvoid verticalSumDLLUtil(TNode *root, LLNode *sumNode) \n{ \n    \n\n    sumNode->key = sumNode->key + root->key; \n  \n     \n    if(root->left) \n    { \n        if(sumNode->prev == NULL) \n        { \n            sumNode->prev = newLLNode(0); \n            sumNode->prev->next = sumNode; \n        } \n        verticalSumDLLUtil(root->left, sumNode->prev); \n    } \n  \n    \n    if(root->right) \n    { \n        if(sumNode->next == NULL) \n        { \n            sumNode->next = newLLNode(0); \n            sumNode->next->prev = sumNode; \n        } \n        verticalSumDLLUtil(root->right, sumNode->next); \n    } \n} \n  \n\n\nvoid verticalSumDLL(TNode* root) \n{ \n    \n    LLNode* sumNode = newLLNode(0); \n  \n     \n    verticalSumDLLUtil(root, sumNode); \n  \n    \n    while(sumNode->prev != NULL){ \n        sumNode = sumNode->prev; \n    } \n  \n    while(sumNode != NULL){ \n        cout << sumNode->key <<\" \"; \n        sumNode = sumNode->next; \n    } \n} \n  \nint main() \n{ \n    \n    TNode *root = newTNode(1); \n    root->left = newTNode(2); \n    root->right = newTNode(3); \n    root->left->left = newTNode(4); \n    root->left->right = newTNode(5); \n    root->right->left = newTNode(6); \n    root->right->right = newTNode(7); \n  \n    cout << \"Vertical Sums are\\n\"; \n    verticalSumDLL(root); \n    return 0; \n} \n  \n"
  },
  {
    "path": "Data-Structures/Tree/Binary-Tree/b_tree.cpp",
    "content": "// Searching a key on a B-tree in C++\n\n#include <iostream>\nusing namespace std;\n\nclass TreeNode {\n  int *keys;\n  int t;\n  TreeNode **C;\n  int n;\n  bool leaf;\n\n   public:\n  TreeNode(int temp, bool bool_leaf);\n\n  void insertNonFull(int k);\n  void splitChild(int i, TreeNode *y);\n  void traverse();\n\n  TreeNode *search(int k);\n\n  friend class BTree;\n};\n\nclass BTree {\n  TreeNode *root;\n  int t;\n\n   public:\n  BTree(int temp) {\n    root = NULL;\n    t = temp;\n  }\n\n  void traverse() {\n    if (root != NULL)\n      root->traverse();\n  }\n\n  TreeNode *search(int k) {\n    return (root == NULL) ? NULL : root->search(k);\n  }\n\n  void insert(int k);\n};\n\nTreeNode::TreeNode(int t1, bool leaf1) {\n  t = t1;\n  leaf = leaf1;\n\n  keys = new int[2 * t - 1];\n  C = new TreeNode *[2 * t];\n\n  n = 0;\n}\n\nvoid TreeNode::traverse() {\n  int i;\n  for (i = 0; i < n; i++) {\n    if (leaf == false)\n      C[i]->traverse();\n    cout << \" \" << keys[i];\n  }\n\n  if (leaf == false)\n    C[i]->traverse();\n}\n\nTreeNode *TreeNode::search(int k) {\n  int i = 0;\n  while (i < n && k > keys[i])\n    i++;\n\n  if (keys[i] == k)\n    return this;\n\n  if (leaf == true)\n    return NULL;\n\n  return C[i]->search(k);\n}\n\nvoid BTree::insert(int k) {\n  if (root == NULL) {\n    root = new TreeNode(t, true);\n    root->keys[0] = k;\n    root->n = 1;\n  } else {\n    if (root->n == 2 * t - 1) {\n      TreeNode *s = new TreeNode(t, false);\n\n      s->C[0] = root;\n\n      s->splitChild(0, root);\n\n      int i = 0;\n      if (s->keys[0] < k)\n        i++;\n      s->C[i]->insertNonFull(k);\n\n      root = s;\n    } else\n      root->insertNonFull(k);\n  }\n}\n\nvoid TreeNode::insertNonFull(int k) {\n  int i = n - 1;\n\n  if (leaf == true) {\n    while (i >= 0 && keys[i] > k) {\n      keys[i + 1] = keys[i];\n      i--;\n    }\n\n    keys[i + 1] = k;\n    n = n + 1;\n  } else {\n    while (i >= 0 && keys[i] > k)\n      i--;\n\n    if (C[i + 1]->n == 2 * t - 1) {\n      splitChild(i + 1, C[i + 1]);\n\n      if (keys[i + 1] < k)\n        i++;\n    }\n    C[i + 1]->insertNonFull(k);\n  }\n}\n\nvoid TreeNode::splitChild(int i, TreeNode *y) {\n  TreeNode *z = new TreeNode(y->t, y->leaf);\n  z->n = t - 1;\n\n  for (int j = 0; j < t - 1; j++)\n    z->keys[j] = y->keys[j + t];\n\n  if (y->leaf == false) {\n    for (int j = 0; j < t; j++)\n      z->C[j] = y->C[j + t];\n  }\n\n  y->n = t - 1;\n  for (int j = n; j >= i + 1; j--)\n    C[j + 1] = C[j];\n\n  C[i + 1] = z;\n\n  for (int j = n - 1; j >= i; j--)\n    keys[j + 1] = keys[j];\n\n  keys[i] = y->keys[t - 1];\n  n = n + 1;\n}\n\nint main() {\n  BTree t(3);\n  t.insert(8);\n  t.insert(9);\n  t.insert(10);\n  t.insert(11);\n  t.insert(15);\n  t.insert(16);\n  t.insert(17);\n  t.insert(18);\n  t.insert(20);\n  t.insert(23);\n\n  cout << \"The B-tree is: \";\n  t.traverse();\n\n  int k = 10;\n  (t.search(k) != NULL) ? cout << endl\n                 << k << \" is found\"\n              : cout << endl\n                 << k << \" is not Found\";\n\n  k = 2;\n  (t.search(k) != NULL) ? cout << endl\n                 << k << \" is found\"\n              : cout << endl\n                 << k << \" is not Found\\n\";\n}\n"
  },
  {
    "path": "Data-Structures/Tree/Binary-Tree/b_tree.java",
    "content": "\npublic class BTree {\n\n  private int T;\n\n  // Node creation\n  public class Node {\n    int n;\n    int key[] = new int[2 * T - 1];\n    Node child[] = new Node[2 * T];\n    boolean leaf = true;\n\n    public int Find(int k) {\n      for (int i = 0; i < this.n; i++) {\n        if (this.key[i] == k) {\n          return i;\n        }\n      }\n      return -1;\n    };\n  }\n\n  public BTree(int t) {\n    T = t;\n    root = new Node();\n    root.n = 0;\n    root.leaf = true;\n  }\n\n  private Node root;\n\n  // Search key\n  private Node Search(Node x, int key) {\n    int i = 0;\n    if (x == null)\n      return x;\n    for (i = 0; i < x.n; i++) {\n      if (key < x.key[i]) {\n        break;\n      }\n      if (key == x.key[i]) {\n        return x;\n      }\n    }\n    if (x.leaf) {\n      return null;\n    } else {\n      return Search(x.child[i], key);\n    }\n  }\n\n  // Splitting the node\n  private void Split(Node x, int pos, Node y) {\n    Node z = new Node();\n    z.leaf = y.leaf;\n    z.n = T - 1;\n    for (int j = 0; j < T - 1; j++) {\n      z.key[j] = y.key[j + T];\n    }\n    if (!y.leaf) {\n      for (int j = 0; j < T; j++) {\n        z.child[j] = y.child[j + T];\n      }\n    }\n    y.n = T - 1;\n    for (int j = x.n; j >= pos + 1; j--) {\n      x.child[j + 1] = x.child[j];\n    }\n    x.child[pos + 1] = z;\n\n    for (int j = x.n - 1; j >= pos; j--) {\n      x.key[j + 1] = x.key[j];\n    }\n    x.key[pos] = y.key[T - 1];\n    x.n = x.n + 1;\n  }\n\n  // Inserting a value\n  public void Insert(final int key) {\n    Node r = root;\n    if (r.n == 2 * T - 1) {\n      Node s = new Node();\n      root = s;\n      s.leaf = false;\n      s.n = 0;\n      s.child[0] = r;\n      Split(s, 0, r);\n      insertValue(s, key);\n    } else {\n      insertValue(r, key);\n    }\n  }\n\n  // Insert the node\n  final private void insertValue(Node x, int k) {\n\n    if (x.leaf) {\n      int i = 0;\n      for (i = x.n - 1; i >= 0 && k < x.key[i]; i--) {\n        x.key[i + 1] = x.key[i];\n      }\n      x.key[i + 1] = k;\n      x.n = x.n + 1;\n    } else {\n      int i = 0;\n      for (i = x.n - 1; i >= 0 && k < x.key[i]; i--) {\n      }\n      ;\n      i++;\n      Node tmp = x.child[i];\n      if (tmp.n == 2 * T - 1) {\n        Split(x, i, tmp);\n        if (k > x.key[i]) {\n          i++;\n        }\n      }\n      insertValue(x.child[i], k);\n    }\n\n  }\n\n  public void Show() {\n    Show(root);\n  }\n\n  // Display\n  private void Show(Node x) {\n    assert (x == null);\n    for (int i = 0; i < x.n; i++) {\n      System.out.print(x.key[i] + \" \");\n    }\n    if (!x.leaf) {\n      for (int i = 0; i < x.n + 1; i++) {\n        Show(x.child[i]);\n      }\n    }\n  }\n\n  // Check if present\n  public boolean Contain(int k) {\n    if (this.Search(root, k) != null) {\n      return true;\n    } else {\n      return false;\n    }\n  }\n\n  public static void main(String[] args) {\n    BTree b = new BTree(3);\n    b.Insert(8);\n    b.Insert(9);\n    b.Insert(10);\n    b.Insert(11);\n    b.Insert(15);\n    b.Insert(20);\n    b.Insert(17);\n\n    b.Show();\n\n    if (b.Contain(12)) {\n      System.out.println(\"\\nfound\");\n    } else {\n      System.out.println(\"\\nnot found\");\n    }\n    ;\n  }\n}\n"
  },
  {
    "path": "Data-Structures/Tree/Binary-Tree/b_tree.js",
    "content": "'use strict';\n\n/*  \n *  JavaScript Implementation of a B tree, multi-way tree\n *  m - order of tree ≈ max number of children\n * \n * nodes are split with left-bias, \n *  - nodes that don't split evenly in two (after removing middle key)\n *  - the left side will have one more key than the right side\n *\n * */\n\nfunction btree(order) {\n  let maxKeys = order-1;\n  let root = null;\n  return {\n\n    root() { \n      return root; \n    },\n    setRoot(newRoot) {\n       root = newRoot; return this\n    },\n    maxKeys() {\n       return maxKeys; \n    },\n    isEmpty(){\n      return (root === null)\n    },\n    exists(item, node = root){\n      if (root === null) return false;\n      if (node.contains(item)) return true;\n      if (node.isLeaf) return false; \n      return (this.exists(item, node.child[node.subTree(item)]));\n    },\n    \n    find(item, node){\n      // return node that contains item or \n      //   the leaf node where item will be inserted\n      if (root === null) return false;\n      if ((node.isLeaf) || (node.contains(item))) {\n        return node;\n      } else {\n        let pos = node.subTree(item);\n        return this.find(item, node.child[pos]);\n      }\n    },\n\n    insert(item){\n      // insert item into tree\n      if(this.root() === null) {\n        this.setRoot(makeNode());\n        this.root().keys.push(item);\n      } else {\n        // get leaf to insert item into, unless already in tree\n        let node = this.find(item, this.root());  \n        if (!node.contains(item)) {\n          node.leafInsert(item);\n          // balance(tree, node);\n          this.balance(node);\n        } else {\n          console.log(`${item} already in tree`);\n          return false;\n        }\n      }\n      return true;\n    },\n\n    insertPoint(node, key) {\n      let index = node.keys.findIndex((e) => e > key);\n      let pos = (index === -1) ? node.keyCount() : index;\n      return pos;\n    },\n\n    merge(key, parent, left, right) {\n      let pos = this.insertPoint(parent, key);\n      parent.keys.splice(pos, 0, key);\n      parent.child[pos] = left;\n      parent.child.splice(pos+1, 0, right);\n      right.parent = parent;\n      return parent;\n    },\n\n    split(node) {\n      let [left, midKey, right] = this.getParts(node);\n\n      let parent = left.parent;\n      // did we split the root?\n      if (parent === null) { \n        parent = this.increaseHeight(left, right, midKey);\n      } else {\n        // merge midKey into parent node, update links\n        parent = this.merge(midKey, parent, left, right);\n      }\n      return parent;\n    },\n\n    getParts(node) {\n      // newNode will hold right half of node \n      let middle = node.midPoint();\n      let newNode = makeNode();\n      newNode.keys = node.keys.splice(middle+1);\n      let midKey = node.keys.pop()\n\n      if (!node.isLeaf) {\n        newNode.isLeaf = false;\n        newNode.child = node.child.splice(middle + 1);\n        newNode.child.forEach((e) => {\n          e.parent = newNode;\n        })\n      }\n      return [node, midKey, newNode];\n    },\n\n    balance (node) {\n      if (node.keyCount() > this.maxKeys()) {\n        this.balance(this.split(node));\n      } \n    },\n\n    increaseHeight(left, right, key) {\n      let newRoot = makeNode();\n      newRoot.parent === null;\n      newRoot.isLeaf = false;\n      this.setRoot(newRoot);\n      newRoot.keys.push(key);\n      newRoot.child[0] = left;\n      newRoot.child[1] = right;\n      // parent of the just split nodes ≈≈ new root\n      left.parent = newRoot;\n      right.parent = newRoot;\n      return newRoot;\n    },\n\n    // tree.traverse().inOrder().toArray();\n    traverse() {\n      let items = [];\n      let list = '';\n      let root = this.root();\n      return {\n        inOrder : function(node = root){\n          if (node.isLeaf) {\n            node.keys.forEach((k) => { items.push(k) } );\n            node.keys.forEach((k) => { list += k + ', ' } );\n            return this;\n          }\n          else {\n            // visit left child, then root, then recurse\n            for(let i = 0; i < node.keyCount(); i++) {\n              this.inOrder(node.child[i])\n              items.push(node.keys[i]);\n              list += node.keys[i] + ', ';\n            }\n            // print last right child\n            this.inOrder(node.child[node.keyCount()]);\n          }\n          return this; \n        }, \n        toArray : function() {\n          return items;\n        },\n        toList : function() {\n          // remove trailing whitespace & comma\n          return list.trim().slice(0,-1);\n        }\n      }\n    }\n  }\n}\n\nfunction makeNode() {\n  return {\n    isLeaf: true,\n    parent: null, \n    keys: [],   // max: m-1\n    child: [],  // max: m\n\n    keyCount() { \n      return this.keys.length; \n    },\n    midPoint() {\n      return Math.floor(this.keys.length/2);\n    },\n    contains(item) { \n      return (this.keys.includes(item))\n    },\n\n    // returns index of child[] ≈≈ the subTree to search for item\n    subTree(item){\n      if(item < this.keys[0]) {\n         return 0;\n      } else {\n        let index = this.keys.findIndex((e) => e > item);\n        return (index === -1) ? this.keyCount() : index;\n      } \n    },\n    \n    // insert item into leaf node, then sort\n    leafInsert(item) {\n      this.keys.push(item); \n      this.keys.sort((a,b) => ((a<b) ? -1 : ((a>b) ? 1: 0)));\n    },\n  }\n}\n\n// sample test\n/*\nconst tree = btree(3);\n\nlet a1 = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,20];\nlet a2 = [100,90,80,70,60,50,40,30,20,10,15,25,35,45,55,65,75,85,95];\nlet a3 = [4,2,7,1,5,3,8];\n\nlet a = a2;\n\na.forEach((e) => {\n    tree.insert(e);\n    console.log(tree.traverse().inOrder().toList());\n});\nconsole.log(tree.traverse().inOrder().toArray());\n*/\n\n// Interactive sample run\nconst readline = require(\"readline\");\nconst rl = readline.createInterface({\n    input: process.stdin,\n    output: process.stdout\n});\nconsole.log();\nconsole.log(\"Enter order of tree on first line.\");\nconsole.log(\"Enter numbers to insert, one per line.\");\nconsole.log(\"^c to end input\");\nconsole.log();\nlet input = [];\nrl.on('line', function (line) {\n  input.push(parseInt(line, 10));\n});\n\nrl.on('close', function (l) {\n  let order = input.shift();\n  const tree = btree(order);\n  input.forEach((e) => {\n    tree.insert(e);\n  });\n  console.log(`Tree order: ${order}`)\n  console.log(`In order traversal:`)\n  console.log(tree.traverse().inOrder().toList()); \n  process.exit(0);\n});\n\n\n\nmodule.exports.btree = btree;\n"
  },
  {
    "path": "Data-Structures/Tree/Binary-Tree/b_tree.py",
    "content": "class BTreeNode:\n    def __init__(self, leaf=False):\n        self.leaf = leaf\n        self.keys = []\n        self.child = []\n\n\nclass BTree:\n    def __init__(self, t):\n        self.root = BTreeNode(True)\n        self.t = t\n\n    # Print the tree\n    def print_tree(self, x, l=0):\n        print(\"Level \", l, \" \", len(x.keys), end=\":\")\n        for i in x.keys:\n            print(i, end=\" \")\n        print()\n        l += 1\n        if len(x.child) > 0:\n            for i in x.child:\n                self.print_tree(i, l)\n\n    # Search key\n    def search_key(self, k, x=None):\n        if x is not None:\n            i = 0\n            while i < len(x.keys) and k > x.keys[i][0]:\n                i += 1\n            if i < len(x.keys) and k == x.keys[i][0]:\n                return (x, i)\n            elif x.leaf:\n                return None\n            else:\n                return self.search_key(k, x.child[i])\n        else:\n            return self.search_key(k, self.root)\n\n    # Insert the key\n    def insert_key(self, k):\n        root = self.root\n        if len(root.keys) == (2 * self.t) - 1:\n            temp = BTreeNode()\n            self.root = temp\n            temp.child.insert_key(0, root)\n            self.split(temp, 0)\n            self.insert_non_full(temp, k)\n        else:\n            self.insert_non_full(root, k)\n\n    # Insert non full condition\n    def insert_non_full(self, x, k):\n        i = len(x.keys) - 1\n        if x.leaf:\n            x.keys.append((None, None))\n            while i >= 0 and k[0] < x.keys[i][0]:\n                x.keys[i + 1] = x.keys[i]\n                i -= 1\n            x.keys[i + 1] = k\n        else:\n            while i >= 0 and k[0] < x.keys[i][0]:\n                i -= 1\n            i += 1\n            if len(x.child[i].keys) == (2 * self.t) - 1:\n                self.split(x, i)\n                if k[0] > x.keys[i][0]:\n                    i += 1\n            self.insert_non_full(x.child[i], k)\n\n    # Split\n    def split(self, x, i):\n        t = self.t\n        y = x.child[i]\n        z = BTreeNode(y.leaf)\n        x.child.insert_key(i + 1, z)\n        x.keys.insert_key(i, y.keys[t - 1])\n        z.keys = y.keys[t: (2 * t) - 1]\n        y.keys = y.keys[0: t - 1]\n        if not y.leaf:\n            z.child = y.child[t: 2 * t]\n            y.child = y.child[0: t - 1]\n\n\ndef main():\n    B = BTree(3)\n\n    for i in range(10):\n        B.insert_key((i, 2 * i))\n\n    B.print_tree(B.root)\n\n    if B.search_key(8) is not None:\n        print(\"\\nFound\")\n    else:\n        print(\"\\nNot found\")\n\n\nif __name__ == '__main__':\n    main()\n"
  },
  {
    "path": "Data-Structures/Tree/Binary-Tree/binary_tree_trans.cpp",
    "content": "#include <bits/stdc++.h>\r\nusing namespace std;\r\nstruct Node {\r\n   struct Node* left;\r\n   struct Node* right;\r\n   int data;\r\n   Node(int data) {\r\n      this->data = data;\r\n      this->left = NULL;\r\n      this->right = NULL;\r\n   }\r\n};\r\nint height(struct Node* root) {\r\n   if (root == NULL)\r\n      return 0;\r\n   int lheight = height(root->left);\r\n   int rheight = height(root->right);\r\n   return max(1 + lheight, 1 + rheight);\r\n}\r\nvoid leftToRight(struct Node* root, int level) {\r\n   if (root == NULL)\r\n      return;\r\n   if (level == 1)\r\n      cout << root->data << \" \";\r\n   else if (level > 1) {\r\n      leftToRight(root->left, level - 1);\r\n      leftToRight(root->right, level - 1);\r\n   }\r\n}\r\nvoid rightToLeft(struct Node* root, int level) {\r\n   if (root == NULL)\r\n      return;\r\n   if (level == 1)\r\n      cout << root->data << \" \";\r\n   else if (level > 1) {\r\n      rightToLeft(root->right, level - 1);\r\n      rightToLeft(root->left, level - 1);\r\n   }\r\n}\r\nint main() {\r\n   struct Node* root = new Node(1);\r\n   root->left = new Node(2);\r\n   root->right = new Node(3);\r\n   root->left->left = new Node(4);\r\n   root->right->left = new Node(5);\r\n   root->right->right = new Node(7);\r\n   root->left->left->left = new Node(10);\r\n   root->left->left->right = new Node(11);\r\n   root->right->right->left = new Node(8);\r\n   int i = 1;\r\n   int j = height(root);\r\n   int flag = 0;\r\n   while (i <= j) {\r\n      if (flag == 0) {\r\n         rightToLeft(root, i);\r\n         flag = 1;\r\n         i++;\r\n      } else {\r\n         leftToRight(root, j);\r\n         flag = 0;\r\n         j--;\r\n      }\r\n   }\r\n   return 0;\r\n}\r\n"
  },
  {
    "path": "Data-Structures/Tree/Binary-Tree/duplicate_values.cpp",
    "content": "#include <bits/stdc++.h> \nusing namespace std; \n//Definition of Binary Tree node-\nstruct TreeNode { \n    int val; \n    struct TreeNode* left; \n    struct TreeNode* right; \n}; \n//Utility function-\nstruct TreeNode* newNode(int val) { \n    struct TreeNode* node = new TreeNode; \n    node->val = val; \n    node->left = node->right = NULL; \n    return (node); \n} \n\nbool find(TreeNode* root, unordered_set<int> &s) { \n    // If tree is empty, there are no duplicates \n    if (root == NULL) \n       return false; \n    // If current node's data is already present, ie. duplicate found-\n    if (s.find(root->val) != s.end()) \n       return true; \n    // If not found, insert current node- \n    s.insert(root->data); \n    // Recursively check in left and right subtrees-\n    return find(root->left, s)||find(root->right, s); \n} \n\nbool isDup(struct TreeNode* root) { \n    unordered_set<int> s; \n    return find(root, s); \n}\n\nint main() { \n    struct TreeNode* root = newNode(1); \n    root->left = newNode(2); \n    root->right = newNode(2); \n    root->left->left = newNode(3); \n    if (isDup(root)) \n        return 1;\n    return 0; \n} \n"
  },
  {
    "path": "Data-Structures/Tree/Binary-Tree/duplicate_values.py",
    "content": "\t\t\t\t\t \nclass newNode: \n\n\t# Construct to create a new node \n\tdef __init__(self, key): \n\t\tself.data = key \n\t\tself.left = None\n\t\tself.right = None\n\ndef checkDupUtil( root, s) : \n\n\t# If tree is empty, there are no \n\t# duplicates. \n\tif (root == None) : \n\t\treturn False\n\n\t# If current node's data is already present. \n\tif root.data in s: \n\t\treturn True\n\n\t# Insert current node \n\ts.add(root.data) \n\t\n\t# Recursively check in left and right \n\t# subtrees. \n\treturn checkDupUtil(root.left, s) or checkDupUtil(root.right, s) \n\n\n# To check if tree has duplicates \ndef checkDup( root) : \n\n\ts=set() \n\treturn checkDupUtil(root, s) \n\n\n# Driver Code \nif __name__ == '__main__': \n\troot = newNode(10) \n\troot.left = newNode(5) \n\troot.right = newNode(20) \n\troot.left.left = newNode(20) \n\tif (checkDup(root)): \n\t\tprint(\"Yes\") \n\telse: \n\t\tprint(\"No\") \n\n"
  },
  {
    "path": "Data-Structures/Tree/Binary-Tree/duplicate_values.rb",
    "content": "# simple bst implementation\nclass BST\n    attr_accessor :head\n    # simple bst node implementation\n    class Node\n       attr_accessor :left\n       attr_accessor :right\n       attr_accessor :value\n       \n       def initialize(val)\n            @value = val\n       end\n    end\n\n    # bst constructor\n    def initialize(val)\n        @head = Node.new(val)\n    end\n\n    # method for inserting new values into a given bst\n    def self.insert(val, tree)\n        if not tree then\n            return Node.new(val)\n        else\n            if val > tree.value then\n                tree.right = insert(val, tree.right)\n            else \n                tree.left = insert(val, tree.left)\n            end\n        end\n        tree\n    end\n\n    # method to check for duplicates\n    def self.duplicates?(tree, prev_vals = [])\n        # base case, if null leaf reached this path had no duplicates\n        if not tree then\n            return true\n        # otherwise, check if current value is a duplicate\n        elsif prev_vals.include? tree.value then\n            return false\n        end\n        # if curr value is unique, add it to prev values tracker\n        prev_vals << tree.value\n        # then recurse\n        duplicates?(tree.left) && duplicates?(tree.right)\n    end\n\n    # simple bst print method for printing (unbalanced trees may look odd)\n    def self.printTree(tree, level = 0)\n        if not tree then\n            return\n        else\n            if level == 0 then\n                puts tree.value\n            elsif level == 1 then\n                print \"#{tree.value} \"\n            else\n                puts \" #{tree.value}\"\n            end\n            printTree(tree.left, 1)\n            printTree(tree.right, 2)\n        end\n    end\nend\n\n# simple integer input example, takes three int inputs\nputs \"Please input three integers for an example.\"\nb = BST.new((gets).to_i)\nBST.insert((gets).to_i, b.head)\nBST.insert((gets).to_i, b.head)\nputs \"Example tree~\"\nBST.printTree(b.head)\n# then checks for duplicates\nputs \"Duplicates? ~\"\nputs BST.duplicates?(b.head)"
  },
  {
    "path": "Data-Structures/Tree/Binary-Tree/subtree_check.cpp",
    "content": "#include<bits/stdc++.h> \nusing namespace std; \n\n// Basic node structure of a binary tree\nclass node \n{ \n\tpublic: \n\tint data; \n\tnode* left; \n\tnode* right; \n}; \n\n// Helper function to grow the tree\nnode* newNode(int data) \n{ \n    // allocate memory and assign data\n\tnode* Node = new node(); \n\tNode->data = data; \n\t\n\t// point left and right Node pointers to NULL\n\tNode->left = NULL; \n\tNode->right = NULL; \n\t\n\treturn(Node); \n} \n\n// Recursive Function to check whether trees \n// with roots as root1 and root2 \n// are identical or not \nbool areIdentical(node * root1, node *root2) \n{ \n\t// if both trees are null then they are \n\t// identical trivially\n\tif (root1 == NULL && root2 == NULL) \n\t\treturn true; \n\n    // if either tree is identical then they \n    // non identical\n\tif (root1 == NULL || root2 == NULL) \n\t\treturn false; \n\n    // check if data of both roots is same\n    if (root1->data == root2->data) {\n        \n        // recursive definition to traverse through\n        // both trees\n        return (areIdentical(root1->left, root2->left) && areIdentical(root1->right, root2->right));\n    }\n    \n    // if data is not same then return false\n    else {\n        return false;\n    }\n} \n\n\n// Recursive Main function which returns true if S \n// is a subtree of T, otherwise false \nbool isSubtree(node *T, node *S) \n{ \n\t// base cases \n\tif (S == NULL) \n\t\treturn true; \n\n\tif (T == NULL) \n\t\treturn false; \n\n\t// Check the tree with root as current node \n\tif (areIdentical(T, S)) \n\t\treturn true; \n\n\t// recursive definition to traverse through\n\t// the main tree to find identical subtree\n\treturn isSubtree(T->left, S) || isSubtree(T->right, S); \n} \n\nint main() \n{ \n    // Driver code taken from GFG\n    \n\t// TREE 1 \n\t/* Construct the following tree \n\t\t26 \n\t\t/ \\ \n\t      10   3 \n\t      / \\    \\ \n\t    4    6    3 \n\t     \\ \n\t      30 \n\t*/\n\tnode *T = newNode(26); \n\tT->right\t\t = newNode(3); \n\tT->right->right = newNode(3); \n\tT->left\t\t = newNode(10); \n\tT->left->left\t = newNode(4); \n\tT->left->left->right = newNode(30); \n\tT->left->right\t = newNode(6); \n\n\t// TREE 2 \n\t/* Construct the following tree \n\t\t10 \n\t\t/ \\ \n\t       4   6 \n\t       \\ \n\t\t30 \n\t*/\n\tnode *S = newNode(10); \n\tS->right\t = newNode(6); \n\tS->left\t = newNode(4); \n\tS->left->right = newNode(30); \n\n\n\tif (isSubtree(T, S)) \n\t\tcout << \"Tree 2 is subtree of Tree 1\"; \n\telse\n\t\tcout << \"Tree 2 is not a subtree of Tree 1\"; \n\n\treturn 0; \n} \n\n"
  },
  {
    "path": "Data-Structures/Tree/Binary-Tree/symmetry_bTree.cpp",
    "content": "//Definition for binary tree-\nstruct TreeNode {\n    int val;\n    TreeNode *left;\n    TreeNode *right;\n\n};\n//Utility function-\nTreeNode *newNode(int val) { \n    TreeNode *temp = new Node; \n    temp->val  = val; \n    temp->left  = temp->right = NULL; \n    return (temp); \n} \n\nint check(TreeNode* A, TreeNode* B){\n    if(A==NULL && B==NULL)\n       return 1;\n    //one is NULL, other is not, ie. Asymmetric-\n    if(A==NULL || B==NULL)\n       return 0;\n    //unequal values, ie. Asymmetric-\n    if(A->val != B->val)   \n       return 0;\n    //checking all subtrees using recursion-\n    if(check(A->left, B->right) && check(A->right, B->left))\n       return 1;\n    //Asymmetric-\n    return 0;              \n}\nint isSymmetric(TreeNode* A) {\n    //null tree is considered symmetric-\n    if(A==NULL)\n       return 1;\n    return check(A->left, A->right);\n}\n\nint main() { \n    TreeNode *root = newNode(1); \n    root->left = newNode(2); \n    root->right = newNode(2); \n    root->left->left = newNode(3); \n    root->left->right = newNode(4); \n    root->right->left = newNode(4); \n    root->right->right = newNode(3); \n  \n    return isSymmetric(root);\n} \n"
  },
  {
    "path": "Data-Structures/Tree/Binary-Tree/two_level_node.py",
    "content": "class Node: \n\t# Constructor tor create a new node \n\tdef __init__(self, key): \n\t\tself.key = key \n\t\tself.left = None\n\t\tself.right = None\n\t\n\n\ndef printLevels(root, low, high): \n\tQ = [] \n\t\n\tmarker = Node(11114) # Marker node to indicate end of level \n\t\n\tlevel = 1 # Initialize level number \n\n\t# Enqueue the only first level node and marker node for \n\t# end of level \n\tQ.append(root) \n\tQ.append(marker) \n\t\n\t#print Q \n\t# Simple level order traversal loop \n\twhile(len(Q) >0): \n\t\t# Remove the front item from queue \n\t\tn = Q[0] \n\t\tQ.pop(0) \n\t\t#print Q \n\t\t# Check if end of level is reached \n\t\tif n == marker: \n\t\t\t# print a new line and increment level number \n\t\t\tprint\n\t\t\tlevel += 1\n\t\t\n\t\t\t# Check if marker node was last node in queue \n\t\t\t# or level nubmer is beyond the given upper limit \n\t\t\tif len(Q) == 0 or level > high: \n\t\t\t\tbreak\n\t\t\t\n\t\t\t# Enqueue the marker for end of next level \n\t\t\tQ.append(marker) \n\t\t\t\n\t\t\t# If this is marker, then we don't need print it \n\t\t\t# and enqueue its children \n\t\t\tcontinue\n\t\tif level >= low: \n\t\t\t\tprint n.key, \n\t\t\t\n\t\t# Enqueue children of non-marker node \n\t\tif n.left is not None: \n\t\t\tQ.append(n.left) \n\t\t\tQ.append(n.right) \n\n# Driver program to test the above function \nroot = Node(20) \nroot.left = Node(8) \nroot.right = Node(22) \nroot.left.left = Node(4) \nroot.left.right = Node(12) \nroot.left.right.left = Node(10) \nroot.left.right.right = Node(14) \n\nprint \"Level Order Traversal between given two levels is\", \nprintLevels(root,2,3) \n\n\n"
  },
  {
    "path": "Data-Structures/Tree/Expression Tree/Expression_Tree.cpp",
    "content": "/*\n\tAuthor: adi1212 \n*/\n\n/*Problem Statement : \nConstruct an Expression Tree from postfix and prefix expression. Perform recursive and nonrecursive In-order, pre-order and post-order traversals. */\n\n#include<bits/stdc++.h> \nusing namespace std; \n\nstruct dll \n{ \n   char data; \n   dll *left; \n   dll *right; \n}; \n\nvoid levelorder(dll *root) \n{ \n   if(root==NULL) \n       return; \n   queue <dll *> p; \n   p.push(root); \n   int count=1; \n   while(!p.empty()) \n   { \n       if(count==0) \n       { \n           cout<<\"\\n\"; \n           count=p.size(); \n       } \n\n       dll *q = p.front(); \n       cout<<q->data<<\"\\t\"; \n       if(q->left!=NULL) \n           p.push(q->left); \n       if(q->right!=NULL) \n           p.push(q->right); \n       p.pop(); \n       count--; \n\n   } \n} \n\nvoid Rpreorder(dll *root) //Recursive preorder \n{ \n   if(root!=NULL) \n   { \n       cout<<root->data<<\"\\t\"; \n       Rpreorder(root->left); \n       Rpreorder(root->right); \n   } \n}\n\nvoid NRpreorder(dll *root) //non-Recursive preorder \n{ \n   stack <dll *> s; \n   while(!s.empty() || root!=NULL) \n   { \n       while(root!=NULL) \n       { \n           cout<<root->data<<\"\\t\"; \n           s.push(root); \n           root=root->left; \n       } \n       root=s.top(); \n       s.pop(); \n       root=root->right; \n\n   } \n} \n\nvoid Rinorder(dll *root) //Recursive inorder \n{ \n   if(root!=NULL) \n   { \n       Rinorder(root->left); \n       cout<<root->data<<\"\\t\"; \n       Rinorder(root->right); \n   } \n} \n\nvoid NRinorder(dll *root) //non-Recursive inorder \n{ \n   stack <dll *> s; \n   while(!s.empty() || root!=NULL) \n   { \n       while(root!=NULL) \n       { \n           s.push(root); \n           root=root->left; \n       } \n       root=s.top(); \n       s.pop(); \n       cout<<root->data<<\"\\t\"; \n       root=root->right; \n   } \n} \n\nvoid Rpostorder(dll *root) //Recursive postorder \n{ \n   if(root==NULL) \n   { \n       return; \n   } \n   Rpostorder(root->left); \n\n   Rpostorder(root->right); \n\n   cout<<root->data<<\"\\t\"; \n}\n\nvoid NRpostorder(dll *root) //non-Recursive postorder \n{ \n   stack <dll*> s1; \n   stack <int> s2; \n   while(root!=NULL) \n   { \n       s1.push(root); \n       s2.push(0); \n       root=root->left; \n   } \n   while(!s1.empty()) \n   { \n       root=s1.top(); \n       if(s2.top()==1) \n       { \n           s1.pop(); \n           s2.pop(); \n           cout<<root->data<<\"\\t\"; \n       } \n       else \n       { \n           s2.top()=1; \n           root=root->right; \n           while(root!=NULL) \n           { \n               s1.push(root); \n               s2.push(0); \n               root=root->left; \n           } \n       } \n   } \n} \n\nbool isOperator(char c) //checking whether operator \n{ \n   if (c == '+' || c == '-' || c == '*' || c == '/' || c == '^') \n   { \n       return true; \n   } \n   return false; \n} \n\nvoid trav(dll *root) //tree traversal \n{ \n   int ch; \n   cout<<\"\\n[1] RECURSIVE PREORDER\\n\"; \n   cout<<\"[2] NON RECURSIVE PREORDER\\n\"; \n   cout<<\"[3] RECURSIVE INORDER\\n\"; \n   cout<<\"[4] NON RECURSIVE INORDER\\n\"; \n   cout<<\"[5] RECURSIVE POSTORDER\\n\"; \n   cout<<\"[6] NON RECURSIVE POSTORDER\\n\"; \n   do \n   { \n       cout<<\"\\nEnter your choice: (enter -1 to exit)\"; \n       cin>>ch; \n       switch(ch) \n       { \n           case 1: Rpreorder(root); \n           break; \n           case 2: NRpreorder(root); \n           break; \n           case 3: Rinorder(root); \n           break; \n           case 4: NRinorder(root); \n           break; \n           case 5: Rpostorder(root); \n           break; \n           case 6: NRpostorder(root); \n           break; \n       } \n   } \n   while(ch!=-1); \n}\n\nvoid call1(char s[]) //postfix expression \n{ \n   stack <dll*> s1; \n   dll *p,*op1,*op2; \n   int i=0; \n   int n=strlen(s); \n   char c; \n   while(i<n) \n   { \n       p=new dll; \n       p->data=s[i]; \n       if(isOperator(s[i])) \n       { \n           op1=s1.top(); \n           s1.pop(); \n           op2=s1.top(); \n           s1.pop(); \n\n           p->left=op2; \n           p->right=op1; \n           s1.push(p); \n       } \n       else \n       { \n           p->left=NULL; \n           p->right=NULL; \n           s1.push(p); \n       } \n       i++; \n   } \n   p=s1.top(); \n   s1.pop(); \n   cout<<\"\\nwant to see level order? (TYPE Y if YES)\\n\"; \n   cin>>c; \n   if(c=='Y' || c=='y') \n   { \n       levelorder(p); \n   } \n   trav(p); \n} \n\nvoid call2(char s[]) //prefix expression \n{ \n   int i=strlen(s)-1; \n   stack <dll*> s1; \n   dll *p,*op1,*op2; \n   char c; \n   while(i>=0) \n   { \n       p=new dll; \n       p->data=s[i]; \n       if(isOperator(s[i])) \n       { \n           op2=s1.top(); \n           s1.pop(); \n           op1=s1.top(); \n           s1.pop(); \n           p->left=op2; \n           p->right=op1; \n           s1.push(p); \n       } \n       else \n       { \n           p->left=NULL; \n           p->right=NULL; \n           s1.push(p); \n       } \n       i--; \n   } \n   p=s1.top(); \n   s1.pop(); \n   cout<<\"\\nwant to see level order? (TYPE Y if YES)\\n\"; \n   cin>>c; \n   if(c=='Y' || c=='y') \n   { \n       levelorder(p); \n   } \n   trav(p); \n} \n\nint main() \n{ \n   dll *root=NULL; \n   char s[20],n; \n   int ch; \n   do \n   { \n       cout<<\"Construct a EXPRESSION TREE from?\\n\"; \n       cout<<\"[1] POSTFIX EXPRESSION\\n\"; \n       cout<<\"[2] PREFIX EXPRESSION\\n\"; \n       cout<<\"\\nEnter your choice: (enter 0 to exit)\"; \n       cin>>n; \n       if(n=='1') \n       { \n           cout<<\"Enter postfix expression: \\n\"; \n           cin>>s; \n           call1(s); \n       } \n       else if(n=='2') \n       { \n           cout<<\"Enter prefix expression: \\n\"; \n           cin>>s; \n           call2(s); \n       } \n   } \n   while(n!='0'); \n   cout<<\"\\nOPERATION COMPLETED!! THANK YOU\"; \n   return 0; \n}\n\n/*\n---------------------------------------------------------------------------------------------------------------------------\n\nOUTPUT :\n \nConstruct a EXPRESSION TREE from?\n[1] POSTFIX EXPRESSION\n[2] PREFIX EXPRESSION\n\nEnter your choice: (enter 0 to exit)1\nEnter postfix expression: \nAB*CD*+\n\nwant to see level order? (TYPE Y if YES)\ny\n+\n*       *\nA       B       C       D\n[1] RECURSIVE PREORDER\n[2] NON RECURSIVE PREORDER\n[3] RECURSIVE INORDER\n[4] NON RECURSIVE INORDER\n[5] RECURSIVE POSTORDER\n[6] NON RECURSIVE POSTORDER\n\nEnter your choice: (enter -1 to exit)3\nA       *       B       +       C       *       D\nEnter your choice: (enter -1 to exit)-1\nConstruct a EXPRESSION TREE from?\n[1] POSTFIX EXPRESSION\n[2] PREFIX EXPRESSION\n\nEnter your choice: (enter 0 to exit)0 \n\nOPERATION COMPLETED!! THANK YOU\n\n...Program finished with exit code 0\nPress ENTER to exit console.\n*/\n"
  },
  {
    "path": "Data-Structures/Tree/Fibonacci-Heap/Fibonacci-Heap.c",
    "content": "// Operations on a Fibonacci heap in C\n\n#include <math.h>\n#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n\ntypedef struct _NODE {\n  int key;\n  int degree;\n  struct _NODE *left_sibling;\n  struct _NODE *right_sibling;\n  struct _NODE *parent;\n  struct _NODE *child;\n  bool mark;\n  bool visited;\n} NODE;\n\ntypedef struct fibanocci_heap {\n  int n;\n  NODE *min;\n  int phi;\n  int degree;\n} FIB_HEAP;\n\nFIB_HEAP *make_fib_heap();\nvoid insertion(FIB_HEAP *H, NODE *new, int val);\nNODE *extract_min(FIB_HEAP *H);\nvoid consolidate(FIB_HEAP *H);\nvoid fib_heap_link(FIB_HEAP *H, NODE *y, NODE *x);\nNODE *find_min_node(FIB_HEAP *H);\nvoid decrease_key(FIB_HEAP *H, NODE *node, int key);\nvoid cut(FIB_HEAP *H, NODE *node_to_be_decrease, NODE *parent_node);\nvoid cascading_cut(FIB_HEAP *H, NODE *parent_node);\nvoid Delete_Node(FIB_HEAP *H, int dec_key);\n\nFIB_HEAP *make_fib_heap() {\n  FIB_HEAP *H;\n  H = (FIB_HEAP *)malloc(sizeof(FIB_HEAP));\n  H->n = 0;\n  H->min = NULL;\n  H->phi = 0;\n  H->degree = 0;\n  return H;\n}\n\n// Printing the heap\nvoid print_heap(NODE *n) {\n  NODE *x;\n  for (x = n;; x = x->right_sibling) {\n    if (x->child == NULL) {\n      printf(\"node with no child (%d) \\n\", x->key);\n    } else {\n      printf(\"NODE(%d) with child (%d)\\n\", x->key, x->child->key);\n      print_heap(x->child);\n    }\n    if (x->right_sibling == n) {\n      break;\n    }\n  }\n}\n\n// Inserting nodes\nvoid insertion(FIB_HEAP *H, NODE *new, int val) {\n  new = (NODE *)malloc(sizeof(NODE));\n  new->key = val;\n  new->degree = 0;\n  new->mark = false;\n  new->parent = NULL;\n  new->child = NULL;\n  new->visited = false;\n  new->left_sibling = new;\n  new->right_sibling = new;\n  if (H->min == NULL) {\n    H->min = new;\n  } else {\n    H->min->left_sibling->right_sibling = new;\n    new->right_sibling = H->min;\n    new->left_sibling = H->min->left_sibling;\n    H->min->left_sibling = new;\n    if (new->key < H->min->key) {\n      H->min = new;\n    }\n  }\n  (H->n)++;\n}\n\n// Find min node\nNODE *find_min_node(FIB_HEAP *H) {\n  if (H == NULL) {\n    printf(\" \\n Fibonacci heap not yet created \\n\");\n    return NULL;\n  } else\n    return H->min;\n}\n\n// Union operation\nFIB_HEAP *unionHeap(FIB_HEAP *H1, FIB_HEAP *H2) {\n  FIB_HEAP *Hnew;\n  Hnew = make_fib_heap();\n  Hnew->min = H1->min;\n\n  NODE *temp1, *temp2;\n  temp1 = Hnew->min->right_sibling;\n  temp2 = H2->min->left_sibling;\n\n  Hnew->min->right_sibling->left_sibling = H2->min->left_sibling;\n  Hnew->min->right_sibling = H2->min;\n  H2->min->left_sibling = Hnew->min;\n  temp2->right_sibling = temp1;\n\n  if ((H1->min == NULL) || (H2->min != NULL && H2->min->key < H1->min->key))\n    Hnew->min = H2->min;\n  Hnew->n = H1->n + H2->n;\n  return Hnew;\n}\n\n// Calculate the degree\nint cal_degree(int n) {\n  int count = 0;\n  while (n > 0) {\n    n = n / 2;\n    count++;\n  }\n  return count;\n}\n\n// Consolidate function\nvoid consolidate(FIB_HEAP *H) {\n  int degree, i, d;\n  degree = cal_degree(H->n);\n  NODE *A[degree], *x, *y, *z;\n  for (i = 0; i <= degree; i++) {\n    A[i] = NULL;\n  }\n  x = H->min;\n  do {\n    d = x->degree;\n    while (A[d] != NULL) {\n      y = A[d];\n      if (x->key > y->key) {\n        NODE *exchange_help;\n        exchange_help = x;\n        x = y;\n        y = exchange_help;\n      }\n      if (y == H->min)\n        H->min = x;\n      fib_heap_link(H, y, x);\n      if (y->right_sibling == x)\n        H->min = x;\n      A[d] = NULL;\n      d++;\n    }\n    A[d] = x;\n    x = x->right_sibling;\n  } while (x != H->min);\n\n  H->min = NULL;\n  for (i = 0; i < degree; i++) {\n    if (A[i] != NULL) {\n      A[i]->left_sibling = A[i];\n      A[i]->right_sibling = A[i];\n      if (H->min == NULL) {\n        H->min = A[i];\n      } else {\n        H->min->left_sibling->right_sibling = A[i];\n        A[i]->right_sibling = H->min;\n        A[i]->left_sibling = H->min->left_sibling;\n        H->min->left_sibling = A[i];\n        if (A[i]->key < H->min->key) {\n          H->min = A[i];\n        }\n      }\n      if (H->min == NULL) {\n        H->min = A[i];\n      } else if (A[i]->key < H->min->key) {\n        H->min = A[i];\n      }\n    }\n  }\n}\n\n// Linking\nvoid fib_heap_link(FIB_HEAP *H, NODE *y, NODE *x) {\n  y->right_sibling->left_sibling = y->left_sibling;\n  y->left_sibling->right_sibling = y->right_sibling;\n\n  if (x->right_sibling == x)\n    H->min = x;\n\n  y->left_sibling = y;\n  y->right_sibling = y;\n  y->parent = x;\n\n  if (x->child == NULL) {\n    x->child = y;\n  }\n  y->right_sibling = x->child;\n  y->left_sibling = x->child->left_sibling;\n  x->child->left_sibling->right_sibling = y;\n  x->child->left_sibling = y;\n  if ((y->key) < (x->child->key))\n    x->child = y;\n\n  (x->degree)++;\n}\n\n// Extract min\nNODE *extract_min(FIB_HEAP *H) {\n  if (H->min == NULL)\n    printf(\"\\n The heap is empty\");\n  else {\n    NODE *temp = H->min;\n    NODE *pntr;\n    pntr = temp;\n    NODE *x = NULL;\n    if (temp->child != NULL) {\n      x = temp->child;\n      do {\n        pntr = x->right_sibling;\n        (H->min->left_sibling)->right_sibling = x;\n        x->right_sibling = H->min;\n        x->left_sibling = H->min->left_sibling;\n        H->min->left_sibling = x;\n        if (x->key < H->min->key)\n          H->min = x;\n        x->parent = NULL;\n        x = pntr;\n      } while (pntr != temp->child);\n    }\n\n    (temp->left_sibling)->right_sibling = temp->right_sibling;\n    (temp->right_sibling)->left_sibling = temp->left_sibling;\n    H->min = temp->right_sibling;\n\n    if (temp == temp->right_sibling && temp->child == NULL)\n      H->min = NULL;\n    else {\n      H->min = temp->right_sibling;\n      consolidate(H);\n    }\n    H->n = H->n - 1;\n    return temp;\n  }\n  return H->min;\n}\n\nvoid cut(FIB_HEAP *H, NODE *node_to_be_decrease, NODE *parent_node) {\n  NODE *temp_parent_check;\n\n  if (node_to_be_decrease == node_to_be_decrease->right_sibling)\n    parent_node->child = NULL;\n\n  node_to_be_decrease->left_sibling->right_sibling = node_to_be_decrease->right_sibling;\n  node_to_be_decrease->right_sibling->left_sibling = node_to_be_decrease->left_sibling;\n  if (node_to_be_decrease == parent_node->child)\n    parent_node->child = node_to_be_decrease->right_sibling;\n  (parent_node->degree)--;\n\n  node_to_be_decrease->left_sibling = node_to_be_decrease;\n  node_to_be_decrease->right_sibling = node_to_be_decrease;\n  H->min->left_sibling->right_sibling = node_to_be_decrease;\n  node_to_be_decrease->right_sibling = H->min;\n  node_to_be_decrease->left_sibling = H->min->left_sibling;\n  H->min->left_sibling = node_to_be_decrease;\n\n  node_to_be_decrease->parent = NULL;\n  node_to_be_decrease->mark = false;\n}\n\nvoid cascading_cut(FIB_HEAP *H, NODE *parent_node) {\n  NODE *aux;\n  aux = parent_node->parent;\n  if (aux != NULL) {\n    if (parent_node->mark == false) {\n      parent_node->mark = true;\n    } else {\n      cut(H, parent_node, aux);\n      cascading_cut(H, aux);\n    }\n  }\n}\n\nvoid decrease_key(FIB_HEAP *H, NODE *node_to_be_decrease, int new_key) {\n  NODE *parent_node;\n  if (H == NULL) {\n    printf(\"\\n FIbonacci heap not created \");\n    return;\n  }\n  if (node_to_be_decrease == NULL) {\n    printf(\"Node is not in the heap\");\n  }\n\n  else {\n    if (node_to_be_decrease->key < new_key) {\n      printf(\"\\n Invalid new key for decrease key operation \\n \");\n    } else {\n      node_to_be_decrease->key = new_key;\n      parent_node = node_to_be_decrease->parent;\n      if ((parent_node != NULL) && (node_to_be_decrease->key < parent_node->key)) {\n        printf(\"\\n cut called\");\n        cut(H, node_to_be_decrease, parent_node);\n        printf(\"\\n cascading cut called\");\n        cascading_cut(H, parent_node);\n      }\n      if (node_to_be_decrease->key < H->min->key) {\n        H->min = node_to_be_decrease;\n      }\n    }\n  }\n}\n\nvoid *find_node(FIB_HEAP *H, NODE *n, int key, int new_key) {\n  NODE *find_use = n;\n  NODE *f = NULL;\n  find_use->visited = true;\n  if (find_use->key == key) {\n    find_use->visited = false;\n    f = find_use;\n    decrease_key(H, f, new_key);\n  }\n  if (find_use->child != NULL) {\n    find_node(H, find_use->child, key, new_key);\n  }\n  if ((find_use->right_sibling->visited != true)) {\n    find_node(H, find_use->right_sibling, key, new_key);\n  }\n\n  find_use->visited = false;\n}\n\nFIB_HEAP *insertion_procedure() {\n  FIB_HEAP *temp;\n  int no_of_nodes, ele, i;\n  NODE *new_node;\n  temp = (FIB_HEAP *)malloc(sizeof(FIB_HEAP));\n  temp = NULL;\n  if (temp == NULL) {\n    temp = make_fib_heap();\n  }\n  printf(\" \\n enter number of nodes to be insert = \");\n  scanf(\"%d\", &no_of_nodes);\n  for (i = 1; i <= no_of_nodes; i++) {\n    printf(\"\\n node %d and its key value = \", i);\n    scanf(\"%d\", &ele);\n    insertion(temp, new_node, ele);\n  }\n  return temp;\n}\nvoid Delete_Node(FIB_HEAP *H, int dec_key) {\n  NODE *p = NULL;\n  find_node(H, H->min, dec_key, -5000);\n  p = extract_min(H);\n  if (p != NULL)\n    printf(\"\\n Node deleted\");\n  else\n    printf(\"\\n Node not deleted:some error\");\n}\n\nint main(int argc, char **argv) {\n  NODE *new_node, *min_node, *extracted_min, *node_to_be_decrease, *find_use;\n  FIB_HEAP *heap, *h1, *h2;\n  int operation_no, new_key, dec_key, ele, i, no_of_nodes;\n  heap = (FIB_HEAP *)malloc(sizeof(FIB_HEAP));\n  heap = NULL;\n  while (1) {\n    printf(\" \\n Operations \\n 1. Create Fibonacci heap \\n 2. Insert nodes into fibonacci heap \\n 3. Find min \\n 4. Union \\n 5. Extract min \\n 6. Decrease key \\n 7.Delete node \\n 8. print heap \\n 9. exit \\n enter operation_no = \");\n    scanf(\"%d\", &operation_no);\n\n    switch (operation_no) {\n      case 1:\n        heap = make_fib_heap();\n        break;\n\n      case 2:\n        if (heap == NULL) {\n          heap = make_fib_heap();\n        }\n        printf(\" enter number of nodes to be insert = \");\n        scanf(\"%d\", &no_of_nodes);\n        for (i = 1; i <= no_of_nodes; i++) {\n          printf(\"\\n node %d and its key value = \", i);\n          scanf(\"%d\", &ele);\n          insertion(heap, new_node, ele);\n        }\n        break;\n\n      case 3:\n        min_node = find_min_node(heap);\n        if (min_node == NULL)\n          printf(\"No minimum value\");\n        else\n          printf(\"\\n min value = %d\", min_node->key);\n        break;\n\n      case 4:\n        if (heap == NULL) {\n          printf(\"\\n no FIbonacci heap created \\n \");\n          break;\n        }\n        h1 = insertion_procedure();\n        heap = unionHeap(heap, h1);\n        printf(\"Unified Heap:\\n\");\n        print_heap(heap->min);\n        break;\n\n      case 5:\n        if (heap == NULL)\n          printf(\"Empty Fibonacci heap\");\n        else {\n          extracted_min = extract_min(heap);\n          printf(\"\\n min value = %d\", extracted_min->key);\n          printf(\"\\n Updated heap: \\n\");\n          print_heap(heap->min);\n        }\n        break;\n\n      case 6:\n        if (heap == NULL)\n          printf(\"Fibonacci heap is empty\");\n        else {\n          printf(\" \\n node to be decreased = \");\n          scanf(\"%d\", &dec_key);\n          printf(\" \\n enter the new key = \");\n          scanf(\"%d\", &new_key);\n          find_use = heap->min;\n          find_node(heap, find_use, dec_key, new_key);\n          printf(\"\\n Key decreased- Corresponding heap:\\n\");\n          print_heap(heap->min);\n        }\n        break;\n      case 7:\n        if (heap == NULL)\n          printf(\"Fibonacci heap is empty\");\n        else {\n          printf(\" \\n Enter node key to be deleted = \");\n          scanf(\"%d\", &dec_key);\n          Delete_Node(heap, dec_key);\n          printf(\"\\n Node Deleted- Corresponding heap:\\n\");\n          print_heap(heap->min);\n          break;\n        }\n      case 8:\n        print_heap(heap->min);\n        break;\n\n      case 9:\n        free(new_node);\n        free(heap);\n        exit(0);\n\n      default:\n        printf(\"Invalid choice \");\n    }\n  }\n}"
  },
  {
    "path": "Data-Structures/Tree/Generic Tree/GenericTree.cpp",
    "content": "#include<iostream>\n#include <deque>\n#include<climits>\n#include<bits/stdc++.h>\nusing namespace std;\n#define INF 1e18\nstruct Node\n{\n    int key;\n    vector<Node*> children;//reference to child nodes\n    Node(int x)\n   {\n      key=x;\n   }\n};\n\nint main()\n{\n  ios_base::sync_with_stdio(0); cin.tie(0); //for fast IO\n       Node *root = new Node(10);\n       int n;\n       //enter n numbers that will be children of root\n       cin>>n;\n       for(int i=0;i<n;i++)\n       {\n           int x;\n           cin>>x;\n           root->children.push_back(new Node(x));\n       }\n       //enter x1 numbers that will children of first child\n       int x1;\n       cin>>x1;\n       for(int i=0;i<x1;i++)\n       {\n\n           int x;\n           cin>>x;\n           Node* k=new Node(x);\n           root->children[0]->children.push_back(k);\n\n       }\n       int x2;\n       cin>>x2;\n        //enter x2 numbers that will children of first child\n       for(int i=0;i<x2;i++)\n       {\n            \n           int x;\n           cin>>x;\n           root->children[1]->children.push_back(new Node(x));\n\n       }\n      // dynamically we can more children \n   \n       cout<<root->children[1]->key;\n\n       }\n"
  },
  {
    "path": "Data-Structures/Tree/README.md",
    "content": "# This folder is empty.\n"
  },
  {
    "path": "Data-Structures/Tree/Red-Black-Tree/Red-Black-Tree.c",
    "content": "#include <stdio.h>\n#include <stdlib.h>\n\nenum nodeColor {\n  RED,\n  BLACK\n};\n\nstruct rbNode {\n  int data, color;\n  struct rbNode *link[2];\n};\n\nstruct rbNode *root = NULL;\n\n// Create a red-black tree\nstruct rbNode *createNode(int data) {\n  struct rbNode *newnode;\n  newnode = (struct rbNode *)malloc(sizeof(struct rbNode));\n  newnode->data = data;\n  newnode->color = RED;\n  newnode->link[0] = newnode->link[1] = NULL;\n  return newnode;\n}\n\n// Insert an node\nvoid insertion(int data) {\n  struct rbNode *stack[98], *ptr, *newnode, *xPtr, *yPtr;\n  int dir[98], ht = 0, index;\n  ptr = root;\n  if (!root) {\n    root = createNode(data);\n    return;\n  }\n\n  stack[ht] = root;\n  dir[ht++] = 0;\n  while (ptr != NULL) {\n    if (ptr->data == data) {\n      printf(\"Duplicates Not Allowed!!\\n\");\n      return;\n    }\n    index = (data - ptr->data) > 0 ? 1 : 0;\n    stack[ht] = ptr;\n    ptr = ptr->link[index];\n    dir[ht++] = index;\n  }\n  stack[ht - 1]->link[index] = newnode = createNode(data);\n  while ((ht >= 3) && (stack[ht - 1]->color == RED)) {\n    if (dir[ht - 2] == 0) {\n      yPtr = stack[ht - 2]->link[1];\n      if (yPtr != NULL && yPtr->color == RED) {\n        stack[ht - 2]->color = RED;\n        stack[ht - 1]->color = yPtr->color = BLACK;\n        ht = ht - 2;\n      } else {\n        if (dir[ht - 1] == 0) {\n          yPtr = stack[ht - 1];\n        } else {\n          xPtr = stack[ht - 1];\n          yPtr = xPtr->link[1];\n          xPtr->link[1] = yPtr->link[0];\n          yPtr->link[0] = xPtr;\n          stack[ht - 2]->link[0] = yPtr;\n        }\n        xPtr = stack[ht - 2];\n        xPtr->color = RED;\n        yPtr->color = BLACK;\n        xPtr->link[0] = yPtr->link[1];\n        yPtr->link[1] = xPtr;\n        if (xPtr == root) {\n          root = yPtr;\n        } else {\n          stack[ht - 3]->link[dir[ht - 3]] = yPtr;\n        }\n        break;\n      }\n    } else {\n      yPtr = stack[ht - 2]->link[0];\n      if ((yPtr != NULL) && (yPtr->color == RED)) {\n        stack[ht - 2]->color = RED;\n        stack[ht - 1]->color = yPtr->color = BLACK;\n        ht = ht - 2;\n      } else {\n        if (dir[ht - 1] == 1) {\n          yPtr = stack[ht - 1];\n        } else {\n          xPtr = stack[ht - 1];\n          yPtr = xPtr->link[0];\n          xPtr->link[0] = yPtr->link[1];\n          yPtr->link[1] = xPtr;\n          stack[ht - 2]->link[1] = yPtr;\n        }\n        xPtr = stack[ht - 2];\n        yPtr->color = BLACK;\n        xPtr->color = RED;\n        xPtr->link[1] = yPtr->link[0];\n        yPtr->link[0] = xPtr;\n        if (xPtr == root) {\n          root = yPtr;\n        } else {\n          stack[ht - 3]->link[dir[ht - 3]] = yPtr;\n        }\n        break;\n      }\n    }\n  }\n  root->color = BLACK;\n}\n\n// Delete a node\nvoid deletion(int data) {\n  struct rbNode *stack[98], *ptr, *xPtr, *yPtr;\n  struct rbNode *pPtr, *qPtr, *rPtr;\n  int dir[98], ht = 0, diff, i;\n  enum nodeColor color;\n\n  if (!root) {\n    printf(\"Tree not available\\n\");\n    return;\n  }\n\n  ptr = root;\n  while (ptr != NULL) {\n    if ((data - ptr->data) == 0)\n      break;\n    diff = (data - ptr->data) > 0 ? 1 : 0;\n    stack[ht] = ptr;\n    dir[ht++] = diff;\n    ptr = ptr->link[diff];\n  }\n\n  if (ptr->link[1] == NULL) {\n    if ((ptr == root) && (ptr->link[0] == NULL)) {\n      free(ptr);\n      root = NULL;\n    } else if (ptr == root) {\n      root = ptr->link[0];\n      free(ptr);\n    } else {\n      stack[ht - 1]->link[dir[ht - 1]] = ptr->link[0];\n    }\n  } else {\n    xPtr = ptr->link[1];\n    if (xPtr->link[0] == NULL) {\n      xPtr->link[0] = ptr->link[0];\n      color = xPtr->color;\n      xPtr->color = ptr->color;\n      ptr->color = color;\n\n      if (ptr == root) {\n        root = xPtr;\n      } else {\n        stack[ht - 1]->link[dir[ht - 1]] = xPtr;\n      }\n\n      dir[ht] = 1;\n      stack[ht++] = xPtr;\n    } else {\n      i = ht++;\n      while (1) {\n        dir[ht] = 0;\n        stack[ht++] = xPtr;\n        yPtr = xPtr->link[0];\n        if (!yPtr->link[0])\n          break;\n        xPtr = yPtr;\n      }\n\n      dir[i] = 1;\n      stack[i] = yPtr;\n      if (i > 0)\n        stack[i - 1]->link[dir[i - 1]] = yPtr;\n\n      yPtr->link[0] = ptr->link[0];\n\n      xPtr->link[0] = yPtr->link[1];\n      yPtr->link[1] = ptr->link[1];\n\n      if (ptr == root) {\n        root = yPtr;\n      }\n\n      color = yPtr->color;\n      yPtr->color = ptr->color;\n      ptr->color = color;\n    }\n  }\n\n  if (ht < 1)\n    return;\n\n  if (ptr->color == BLACK) {\n    while (1) {\n      pPtr = stack[ht - 1]->link[dir[ht - 1]];\n      if (pPtr && pPtr->color == RED) {\n        pPtr->color = BLACK;\n        break;\n      }\n\n      if (ht < 2)\n        break;\n\n      if (dir[ht - 2] == 0) {\n        rPtr = stack[ht - 1]->link[1];\n\n        if (!rPtr)\n          break;\n\n        if (rPtr->color == RED) {\n          stack[ht - 1]->color = RED;\n          rPtr->color = BLACK;\n          stack[ht - 1]->link[1] = rPtr->link[0];\n          rPtr->link[0] = stack[ht - 1];\n\n          if (stack[ht - 1] == root) {\n            root = rPtr;\n          } else {\n            stack[ht - 2]->link[dir[ht - 2]] = rPtr;\n          }\n          dir[ht] = 0;\n          stack[ht] = stack[ht - 1];\n          stack[ht - 1] = rPtr;\n          ht++;\n\n          rPtr = stack[ht - 1]->link[1];\n        }\n\n        if ((!rPtr->link[0] || rPtr->link[0]->color == BLACK) &&\n          (!rPtr->link[1] || rPtr->link[1]->color == BLACK)) {\n          rPtr->color = RED;\n        } else {\n          if (!rPtr->link[1] || rPtr->link[1]->color == BLACK) {\n            qPtr = rPtr->link[0];\n            rPtr->color = RED;\n            qPtr->color = BLACK;\n            rPtr->link[0] = qPtr->link[1];\n            qPtr->link[1] = rPtr;\n            rPtr = stack[ht - 1]->link[1] = qPtr;\n          }\n          rPtr->color = stack[ht - 1]->color;\n          stack[ht - 1]->color = BLACK;\n          rPtr->link[1]->color = BLACK;\n          stack[ht - 1]->link[1] = rPtr->link[0];\n          rPtr->link[0] = stack[ht - 1];\n          if (stack[ht - 1] == root) {\n            root = rPtr;\n          } else {\n            stack[ht - 2]->link[dir[ht - 2]] = rPtr;\n          }\n          break;\n        }\n      } else {\n        rPtr = stack[ht - 1]->link[0];\n        if (!rPtr)\n          break;\n\n        if (rPtr->color == RED) {\n          stack[ht - 1]->color = RED;\n          rPtr->color = BLACK;\n          stack[ht - 1]->link[0] = rPtr->link[1];\n          rPtr->link[1] = stack[ht - 1];\n\n          if (stack[ht - 1] == root) {\n            root = rPtr;\n          } else {\n            stack[ht - 2]->link[dir[ht - 2]] = rPtr;\n          }\n          dir[ht] = 1;\n          stack[ht] = stack[ht - 1];\n          stack[ht - 1] = rPtr;\n          ht++;\n\n          rPtr = stack[ht - 1]->link[0];\n        }\n        if ((!rPtr->link[0] || rPtr->link[0]->color == BLACK) &&\n          (!rPtr->link[1] || rPtr->link[1]->color == BLACK)) {\n          rPtr->color = RED;\n        } else {\n          if (!rPtr->link[0] || rPtr->link[0]->color == BLACK) {\n            qPtr = rPtr->link[1];\n            rPtr->color = RED;\n            qPtr->color = BLACK;\n            rPtr->link[1] = qPtr->link[0];\n            qPtr->link[0] = rPtr;\n            rPtr = stack[ht - 1]->link[0] = qPtr;\n          }\n          rPtr->color = stack[ht - 1]->color;\n          stack[ht - 1]->color = BLACK;\n          rPtr->link[0]->color = BLACK;\n          stack[ht - 1]->link[0] = rPtr->link[1];\n          rPtr->link[1] = stack[ht - 1];\n          if (stack[ht - 1] == root) {\n            root = rPtr;\n          } else {\n            stack[ht - 2]->link[dir[ht - 2]] = rPtr;\n          }\n          break;\n        }\n      }\n      ht--;\n    }\n  }\n}\n\n// Print the inorder traversal of the tree\nvoid inorderTraversal(struct rbNode *node) {\n  if (node) {\n    inorderTraversal(node->link[0]);\n    printf(\"%d  \", node->data);\n    inorderTraversal(node->link[1]);\n  }\n  return;\n}\n\n// Driver code\nint main() {\n  int ch, data;\n  while (1) {\n    printf(\"1. Insertion\\t2. Deletion\\n\");\n    printf(\"3. Traverse\\t4. Exit\");\n    printf(\"\\nEnter your choice:\");\n    scanf(\"%d\", &ch);\n    switch (ch) {\n      case 1:\n        printf(\"Enter the element to insert:\");\n        scanf(\"%d\", &data);\n        insertion(data);\n        break;\n      case 2:\n        printf(\"Enter the element to delete:\");\n        scanf(\"%d\", &data);\n        deletion(data);\n        break;\n      case 3:\n        inorderTraversal(root);\n        printf(\"\\n\");\n        break;\n      case 4:\n        exit(0);\n      default:\n        printf(\"Not available\\n\");\n        break;\n    }\n    printf(\"\\n\");\n  }\n  return 0;\n}\n"
  },
  {
    "path": "Data-Structures/Tree/Red-Black-Tree/Red-Black-Tree.cpp",
    "content": "#include <iostream>\nusing namespace std;\n\nstruct Node {\n  int data;\n  Node *parent;\n  Node *left;\n  Node *right;\n  int color;\n};\n\ntypedef Node *NodePtr;\n\nclass RedBlackTree {\n   private:\n  NodePtr root;\n  NodePtr TNULL;\n\n  void initializeNULLNode(NodePtr node, NodePtr parent) {\n    node->data = 0;\n    node->parent = parent;\n    node->left = nullptr;\n    node->right = nullptr;\n    node->color = 0;\n  }\n\n  // Preorder\n  void preOrderHelper(NodePtr node) {\n    if (node != TNULL) {\n      cout << node->data << \" \";\n      preOrderHelper(node->left);\n      preOrderHelper(node->right);\n    }\n  }\n\n  // Inorder\n  void inOrderHelper(NodePtr node) {\n    if (node != TNULL) {\n      inOrderHelper(node->left);\n      cout << node->data << \" \";\n      inOrderHelper(node->right);\n    }\n  }\n\n  // Post order\n  void postOrderHelper(NodePtr node) {\n    if (node != TNULL) {\n      postOrderHelper(node->left);\n      postOrderHelper(node->right);\n      cout << node->data << \" \";\n    }\n  }\n\n  NodePtr searchTreeHelper(NodePtr node, int key) {\n    if (node == TNULL || key == node->data) {\n      return node;\n    }\n\n    if (key < node->data) {\n      return searchTreeHelper(node->left, key);\n    }\n    return searchTreeHelper(node->right, key);\n  }\n\n  // For balancing the tree after deletion\n  void deleteFix(NodePtr x) {\n    NodePtr s;\n    while (x != root && x->color == 0) {\n      if (x == x->parent->left) {\n        s = x->parent->right;\n        if (s->color == 1) {\n          s->color = 0;\n          x->parent->color = 1;\n          leftRotate(x->parent);\n          s = x->parent->right;\n        }\n\n        if (s->left->color == 0 && s->right->color == 0) {\n          s->color = 1;\n          x = x->parent;\n        } else {\n          if (s->right->color == 0) {\n            s->left->color = 0;\n            s->color = 1;\n            rightRotate(s);\n            s = x->parent->right;\n          }\n\n          s->color = x->parent->color;\n          x->parent->color = 0;\n          s->right->color = 0;\n          leftRotate(x->parent);\n          x = root;\n        }\n      } else {\n        s = x->parent->left;\n        if (s->color == 1) {\n          s->color = 0;\n          x->parent->color = 1;\n          rightRotate(x->parent);\n          s = x->parent->left;\n        }\n\n        if (s->right->color == 0 && s->right->color == 0) {\n          s->color = 1;\n          x = x->parent;\n        } else {\n          if (s->left->color == 0) {\n            s->right->color = 0;\n            s->color = 1;\n            leftRotate(s);\n            s = x->parent->left;\n          }\n\n          s->color = x->parent->color;\n          x->parent->color = 0;\n          s->left->color = 0;\n          rightRotate(x->parent);\n          x = root;\n        }\n      }\n    }\n    x->color = 0;\n  }\n\n  void rbTransplant(NodePtr u, NodePtr v) {\n    if (u->parent == nullptr) {\n      root = v;\n    } else if (u == u->parent->left) {\n      u->parent->left = v;\n    } else {\n      u->parent->right = v;\n    }\n    v->parent = u->parent;\n  }\n\n  void deleteNodeHelper(NodePtr node, int key) {\n    NodePtr z = TNULL;\n    NodePtr x, y;\n    while (node != TNULL) {\n      if (node->data == key) {\n        z = node;\n      }\n\n      if (node->data <= key) {\n        node = node->right;\n      } else {\n        node = node->left;\n      }\n    }\n\n    if (z == TNULL) {\n      cout << \"Key not found in the tree\" << endl;\n      return;\n    }\n\n    y = z;\n    int y_original_color = y->color;\n    if (z->left == TNULL) {\n      x = z->right;\n      rbTransplant(z, z->right);\n    } else if (z->right == TNULL) {\n      x = z->left;\n      rbTransplant(z, z->left);\n    } else {\n      y = minimum(z->right);\n      y_original_color = y->color;\n      x = y->right;\n      if (y->parent == z) {\n        x->parent = y;\n      } else {\n        rbTransplant(y, y->right);\n        y->right = z->right;\n        y->right->parent = y;\n      }\n\n      rbTransplant(z, y);\n      y->left = z->left;\n      y->left->parent = y;\n      y->color = z->color;\n    }\n    delete z;\n    if (y_original_color == 0) {\n      deleteFix(x);\n    }\n  }\n\n  // For balancing the tree after insertion\n  void insertFix(NodePtr k) {\n    NodePtr u;\n    while (k->parent->color == 1) {\n      if (k->parent == k->parent->parent->right) {\n        u = k->parent->parent->left;\n        if (u->color == 1) {\n          u->color = 0;\n          k->parent->color = 0;\n          k->parent->parent->color = 1;\n          k = k->parent->parent;\n        } else {\n          if (k == k->parent->left) {\n            k = k->parent;\n            rightRotate(k);\n          }\n          k->parent->color = 0;\n          k->parent->parent->color = 1;\n          leftRotate(k->parent->parent);\n        }\n      } else {\n        u = k->parent->parent->right;\n\n        if (u->color == 1) {\n          u->color = 0;\n          k->parent->color = 0;\n          k->parent->parent->color = 1;\n          k = k->parent->parent;\n        } else {\n          if (k == k->parent->right) {\n            k = k->parent;\n            leftRotate(k);\n          }\n          k->parent->color = 0;\n          k->parent->parent->color = 1;\n          rightRotate(k->parent->parent);\n        }\n      }\n      if (k == root) {\n        break;\n      }\n    }\n    root->color = 0;\n  }\n\n  void printHelper(NodePtr root, string indent, bool last) {\n    if (root != TNULL) {\n      cout << indent;\n      if (last) {\n        cout << \"R----\";\n        indent += \"   \";\n      } else {\n        cout << \"L----\";\n        indent += \"|  \";\n      }\n\n      string sColor = root->color ? \"RED\" : \"BLACK\";\n      cout << root->data << \"(\" << sColor << \")\" << endl;\n      printHelper(root->left, indent, false);\n      printHelper(root->right, indent, true);\n    }\n  }\n\n   public:\n  RedBlackTree() {\n    TNULL = new Node;\n    TNULL->color = 0;\n    TNULL->left = nullptr;\n    TNULL->right = nullptr;\n    root = TNULL;\n  }\n\n  void preorder() {\n    preOrderHelper(this->root);\n  }\n\n  void inorder() {\n    inOrderHelper(this->root);\n  }\n\n  void postorder() {\n    postOrderHelper(this->root);\n  }\n\n  NodePtr searchTree(int k) {\n    return searchTreeHelper(this->root, k);\n  }\n\n  NodePtr minimum(NodePtr node) {\n    while (node->left != TNULL) {\n      node = node->left;\n    }\n    return node;\n  }\n\n  NodePtr maximum(NodePtr node) {\n    while (node->right != TNULL) {\n      node = node->right;\n    }\n    return node;\n  }\n\n  NodePtr successor(NodePtr x) {\n    if (x->right != TNULL) {\n      return minimum(x->right);\n    }\n\n    NodePtr y = x->parent;\n    while (y != TNULL && x == y->right) {\n      x = y;\n      y = y->parent;\n    }\n    return y;\n  }\n\n  NodePtr predecessor(NodePtr x) {\n    if (x->left != TNULL) {\n      return maximum(x->left);\n    }\n\n    NodePtr y = x->parent;\n    while (y != TNULL && x == y->left) {\n      x = y;\n      y = y->parent;\n    }\n\n    return y;\n  }\n\n  void leftRotate(NodePtr x) {\n    NodePtr y = x->right;\n    x->right = y->left;\n    if (y->left != TNULL) {\n      y->left->parent = x;\n    }\n    y->parent = x->parent;\n    if (x->parent == nullptr) {\n      this->root = y;\n    } else if (x == x->parent->left) {\n      x->parent->left = y;\n    } else {\n      x->parent->right = y;\n    }\n    y->left = x;\n    x->parent = y;\n  }\n\n  void rightRotate(NodePtr x) {\n    NodePtr y = x->left;\n    x->left = y->right;\n    if (y->right != TNULL) {\n      y->right->parent = x;\n    }\n    y->parent = x->parent;\n    if (x->parent == nullptr) {\n      this->root = y;\n    } else if (x == x->parent->right) {\n      x->parent->right = y;\n    } else {\n      x->parent->left = y;\n    }\n    y->right = x;\n    x->parent = y;\n  }\n\n  // Inserting a node\n  void insert(int key) {\n    NodePtr node = new Node;\n    node->parent = nullptr;\n    node->data = key;\n    node->left = TNULL;\n    node->right = TNULL;\n    node->color = 1;\n\n    NodePtr y = nullptr;\n    NodePtr x = this->root;\n\n    while (x != TNULL) {\n      y = x;\n      if (node->data < x->data) {\n        x = x->left;\n      } else {\n        x = x->right;\n      }\n    }\n\n    node->parent = y;\n    if (y == nullptr) {\n      root = node;\n    } else if (node->data < y->data) {\n      y->left = node;\n    } else {\n      y->right = node;\n    }\n\n    if (node->parent == nullptr) {\n      node->color = 0;\n      return;\n    }\n\n    if (node->parent->parent == nullptr) {\n      return;\n    }\n\n    insertFix(node);\n  }\n\n  NodePtr getRoot() {\n    return this->root;\n  }\n\n  void deleteNode(int data) {\n    deleteNodeHelper(this->root, data);\n  }\n\n  void printTree() {\n    if (root) {\n      printHelper(this->root, \"\", true);\n    }\n  }\n};\n\nint main() {\n  RedBlackTree bst;\n  bst.insert(55);\n  bst.insert(40);\n  bst.insert(65);\n  bst.insert(60);\n  bst.insert(75);\n  bst.insert(57);\n\n  bst.printTree();\n  cout << endl\n     << \"After deleting\" << endl;\n  bst.deleteNode(40);\n  bst.printTree();\n}\n"
  },
  {
    "path": "Data-Structures/Tree/Red-Black-Tree/Red-Black-Tree.java",
    "content": "\nclass Node {\n    int data;\n    Node parent;\n    Node left;\n    Node right;\n    int color;\n  }\n  \n  public class RedBlackTree {\n    private Node root;\n    private Node TNULL;\n  \n    // Preorder\n    private void preOrderHelper(Node node) {\n      if (node != TNULL) {\n        System.out.print(node.data + \" \");\n        preOrderHelper(node.left);\n        preOrderHelper(node.right);\n      }\n    }\n  \n    // Inorder\n    private void inOrderHelper(Node node) {\n      if (node != TNULL) {\n        inOrderHelper(node.left);\n        System.out.print(node.data + \" \");\n        inOrderHelper(node.right);\n      }\n    }\n  \n    // Post order\n    private void postOrderHelper(Node node) {\n      if (node != TNULL) {\n        postOrderHelper(node.left);\n        postOrderHelper(node.right);\n        System.out.print(node.data + \" \");\n      }\n    }\n  \n    // Search the tree\n    private Node searchTreeHelper(Node node, int key) {\n      if (node == TNULL || key == node.data) {\n        return node;\n      }\n  \n      if (key < node.data) {\n        return searchTreeHelper(node.left, key);\n      }\n      return searchTreeHelper(node.right, key);\n    }\n  \n    // Balance the tree after deletion of a node\n    private void fixDelete(Node x) {\n      Node s;\n      while (x != root && x.color == 0) {\n        if (x == x.parent.left) {\n          s = x.parent.right;\n          if (s.color == 1) {\n            s.color = 0;\n            x.parent.color = 1;\n            leftRotate(x.parent);\n            s = x.parent.right;\n          }\n  \n          if (s.left.color == 0 && s.right.color == 0) {\n            s.color = 1;\n            x = x.parent;\n          } else {\n            if (s.right.color == 0) {\n              s.left.color = 0;\n              s.color = 1;\n              rightRotate(s);\n              s = x.parent.right;\n            }\n  \n            s.color = x.parent.color;\n            x.parent.color = 0;\n            s.right.color = 0;\n            leftRotate(x.parent);\n            x = root;\n          }\n        } else {\n          s = x.parent.left;\n          if (s.color == 1) {\n            s.color = 0;\n            x.parent.color = 1;\n            rightRotate(x.parent);\n            s = x.parent.left;\n          }\n  \n          if (s.right.color == 0 && s.right.color == 0) {\n            s.color = 1;\n            x = x.parent;\n          } else {\n            if (s.left.color == 0) {\n              s.right.color = 0;\n              s.color = 1;\n              leftRotate(s);\n              s = x.parent.left;\n            }\n  \n            s.color = x.parent.color;\n            x.parent.color = 0;\n            s.left.color = 0;\n            rightRotate(x.parent);\n            x = root;\n          }\n        }\n      }\n      x.color = 0;\n    }\n  \n    private void rbTransplant(Node u, Node v) {\n      if (u.parent == null) {\n        root = v;\n      } else if (u == u.parent.left) {\n        u.parent.left = v;\n      } else {\n        u.parent.right = v;\n      }\n      v.parent = u.parent;\n    }\n  \n    private void deleteNodeHelper(Node node, int key) {\n      Node z = TNULL;\n      Node x, y;\n      while (node != TNULL) {\n        if (node.data == key) {\n          z = node;\n        }\n  \n        if (node.data <= key) {\n          node = node.right;\n        } else {\n          node = node.left;\n        }\n      }\n  \n      if (z == TNULL) {\n        System.out.println(\"Couldn't find key in the tree\");\n        return;\n      }\n  \n      y = z;\n      int yOriginalColor = y.color;\n      if (z.left == TNULL) {\n        x = z.right;\n        rbTransplant(z, z.right);\n      } else if (z.right == TNULL) {\n        x = z.left;\n        rbTransplant(z, z.left);\n      } else {\n        y = minimum(z.right);\n        yOriginalColor = y.color;\n        x = y.right;\n        if (y.parent == z) {\n          x.parent = y;\n        } else {\n          rbTransplant(y, y.right);\n          y.right = z.right;\n          y.right.parent = y;\n        }\n  \n        rbTransplant(z, y);\n        y.left = z.left;\n        y.left.parent = y;\n        y.color = z.color;\n      }\n      if (yOriginalColor == 0) {\n        fixDelete(x);\n      }\n    }\n  \n    // Balance the node after insertion\n    private void fixInsert(Node k) {\n      Node u;\n      while (k.parent.color == 1) {\n        if (k.parent == k.parent.parent.right) {\n          u = k.parent.parent.left;\n          if (u.color == 1) {\n            u.color = 0;\n            k.parent.color = 0;\n            k.parent.parent.color = 1;\n            k = k.parent.parent;\n          } else {\n            if (k == k.parent.left) {\n              k = k.parent;\n              rightRotate(k);\n            }\n            k.parent.color = 0;\n            k.parent.parent.color = 1;\n            leftRotate(k.parent.parent);\n          }\n        } else {\n          u = k.parent.parent.right;\n  \n          if (u.color == 1) {\n            u.color = 0;\n            k.parent.color = 0;\n            k.parent.parent.color = 1;\n            k = k.parent.parent;\n          } else {\n            if (k == k.parent.right) {\n              k = k.parent;\n              leftRotate(k);\n            }\n            k.parent.color = 0;\n            k.parent.parent.color = 1;\n            rightRotate(k.parent.parent);\n          }\n        }\n        if (k == root) {\n          break;\n        }\n      }\n      root.color = 0;\n    }\n  \n    private void printHelper(Node root, String indent, boolean last) {\n      if (root != TNULL) {\n        System.out.print(indent);\n        if (last) {\n          System.out.print(\"R----\");\n          indent += \"   \";\n        } else {\n          System.out.print(\"L----\");\n          indent += \"|  \";\n        }\n  \n        String sColor = root.color == 1 ? \"RED\" : \"BLACK\";\n        System.out.println(root.data + \"(\" + sColor + \")\");\n        printHelper(root.left, indent, false);\n        printHelper(root.right, indent, true);\n      }\n    }\n  \n    public RedBlackTree() {\n      TNULL = new Node();\n      TNULL.color = 0;\n      TNULL.left = null;\n      TNULL.right = null;\n      root = TNULL;\n    }\n  \n    public void preorder() {\n      preOrderHelper(this.root);\n    }\n  \n    public void inorder() {\n      inOrderHelper(this.root);\n    }\n  \n    public void postorder() {\n      postOrderHelper(this.root);\n    }\n  \n    public Node searchTree(int k) {\n      return searchTreeHelper(this.root, k);\n    }\n  \n    public Node minimum(Node node) {\n      while (node.left != TNULL) {\n        node = node.left;\n      }\n      return node;\n    }\n  \n    public Node maximum(Node node) {\n      while (node.right != TNULL) {\n        node = node.right;\n      }\n      return node;\n    }\n  \n    public Node successor(Node x) {\n      if (x.right != TNULL) {\n        return minimum(x.right);\n      }\n  \n      Node y = x.parent;\n      while (y != TNULL && x == y.right) {\n        x = y;\n        y = y.parent;\n      }\n      return y;\n    }\n  \n    public Node predecessor(Node x) {\n      if (x.left != TNULL) {\n        return maximum(x.left);\n      }\n  \n      Node y = x.parent;\n      while (y != TNULL && x == y.left) {\n        x = y;\n        y = y.parent;\n      }\n  \n      return y;\n    }\n  \n    public void leftRotate(Node x) {\n      Node y = x.right;\n      x.right = y.left;\n      if (y.left != TNULL) {\n        y.left.parent = x;\n      }\n      y.parent = x.parent;\n      if (x.parent == null) {\n        this.root = y;\n      } else if (x == x.parent.left) {\n        x.parent.left = y;\n      } else {\n        x.parent.right = y;\n      }\n      y.left = x;\n      x.parent = y;\n    }\n  \n    public void rightRotate(Node x) {\n      Node y = x.left;\n      x.left = y.right;\n      if (y.right != TNULL) {\n        y.right.parent = x;\n      }\n      y.parent = x.parent;\n      if (x.parent == null) {\n        this.root = y;\n      } else if (x == x.parent.right) {\n        x.parent.right = y;\n      } else {\n        x.parent.left = y;\n      }\n      y.right = x;\n      x.parent = y;\n    }\n  \n    public void insert(int key) {\n      Node node = new Node();\n      node.parent = null;\n      node.data = key;\n      node.left = TNULL;\n      node.right = TNULL;\n      node.color = 1;\n  \n      Node y = null;\n      Node x = this.root;\n  \n      while (x != TNULL) {\n        y = x;\n        if (node.data < x.data) {\n          x = x.left;\n        } else {\n          x = x.right;\n        }\n      }\n  \n      node.parent = y;\n      if (y == null) {\n        root = node;\n      } else if (node.data < y.data) {\n        y.left = node;\n      } else {\n        y.right = node;\n      }\n  \n      if (node.parent == null) {\n        node.color = 0;\n        return;\n      }\n  \n      if (node.parent.parent == null) {\n        return;\n      }\n  \n      fixInsert(node);\n    }\n  \n    public Node getRoot() {\n      return this.root;\n    }\n  \n    public void deleteNode(int data) {\n      deleteNodeHelper(this.root, data);\n    }\n  \n    public void printTree() {\n      printHelper(this.root, \"\", true);\n    }\n  \n    public static void main(String[] args) {\n      RedBlackTree bst = new RedBlackTree();\n      bst.insert(55);\n      bst.insert(40);\n      bst.insert(65);\n      bst.insert(60);\n      bst.insert(75);\n      bst.insert(57);\n      bst.printTree();\n  \n      System.out.println(\"\\nAfter deleting:\");\n      bst.deleteNode(40);\n      bst.printTree();\n    }\n  }"
  },
  {
    "path": "Data-Structures/Tree/Red-Black-Tree/Red-Black-Tree.py",
    "content": "import sys\n\n\n# Node creation\nclass Node():\n    def __init__(self, item):\n        self.item = item\n        self.parent = None\n        self.left = None\n        self.right = None\n        self.color = 1\n\n\nclass RedBlackTree():\n    def __init__(self):\n        self.TNULL = Node(0)\n        self.TNULL.color = 0\n        self.TNULL.left = None\n        self.TNULL.right = None\n        self.root = self.TNULL\n\n    # Preorder\n    def pre_order_helper(self, node):\n        if node != TNULL:\n            sys.stdout.write(node.item + \" \")\n            self.pre_order_helper(node.left)\n            self.pre_order_helper(node.right)\n\n    # Inorder\n    def in_order_helper(self, node):\n        if node != TNULL:\n            self.in_order_helper(node.left)\n            sys.stdout.write(node.item + \" \")\n            self.in_order_helper(node.right)\n\n    # Postorder\n    def post_order_helper(self, node):\n        if node != TNULL:\n            self.post_order_helper(node.left)\n            self.post_order_helper(node.right)\n            sys.stdout.write(node.item + \" \")\n\n    # Search the tree\n    def search_tree_helper(self, node, key):\n        if node == TNULL or key == node.item:\n            return node\n\n        if key < node.item:\n            return self.search_tree_helper(node.left, key)\n        return self.search_tree_helper(node.right, key)\n\n    # Balancing the tree after deletion\n    def delete_fix(self, x):\n        while x != self.root and x.color == 0:\n            if x == x.parent.left:\n                s = x.parent.right\n                if s.color == 1:\n                    s.color = 0\n                    x.parent.color = 1\n                    self.left_rotate(x.parent)\n                    s = x.parent.right\n\n                if s.left.color == 0 and s.right.color == 0:\n                    s.color = 1\n                    x = x.parent\n                else:\n                    if s.right.color == 0:\n                        s.left.color = 0\n                        s.color = 1\n                        self.right_rotate(s)\n                        s = x.parent.right\n\n                    s.color = x.parent.color\n                    x.parent.color = 0\n                    s.right.color = 0\n                    self.left_rotate(x.parent)\n                    x = self.root\n            else:\n                s = x.parent.left\n                if s.color == 1:\n                    s.color = 0\n                    x.parent.color = 1\n                    self.right_rotate(x.parent)\n                    s = x.parent.left\n\n                if s.right.color == 0 and s.right.color == 0:\n                    s.color = 1\n                    x = x.parent\n                else:\n                    if s.left.color == 0:\n                        s.right.color = 0\n                        s.color = 1\n                        self.left_rotate(s)\n                        s = x.parent.left\n\n                    s.color = x.parent.color\n                    x.parent.color = 0\n                    s.left.color = 0\n                    self.right_rotate(x.parent)\n                    x = self.root\n        x.color = 0\n\n    def __rb_transplant(self, u, v):\n        if u.parent == None:\n            self.root = v\n        elif u == u.parent.left:\n            u.parent.left = v\n        else:\n            u.parent.right = v\n        v.parent = u.parent\n\n    # Node deletion\n    def delete_node_helper(self, node, key):\n        z = self.TNULL\n        while node != self.TNULL:\n            if node.item == key:\n                z = node\n\n            if node.item <= key:\n                node = node.right\n            else:\n                node = node.left\n\n        if z == self.TNULL:\n            print(\"Cannot find key in the tree\")\n            return\n\n        y = z\n        y_original_color = y.color\n        if z.left == self.TNULL:\n            x = z.right\n            self.__rb_transplant(z, z.right)\n        elif (z.right == self.TNULL):\n            x = z.left\n            self.__rb_transplant(z, z.left)\n        else:\n            y = self.minimum(z.right)\n            y_original_color = y.color\n            x = y.right\n            if y.parent == z:\n                x.parent = y\n            else:\n                self.__rb_transplant(y, y.right)\n                y.right = z.right\n                y.right.parent = y\n\n            self.__rb_transplant(z, y)\n            y.left = z.left\n            y.left.parent = y\n            y.color = z.color\n        if y_original_color == 0:\n            self.delete_fix(x)\n\n    # Balance the tree after insertion\n    def fix_insert(self, k):\n        while k.parent.color == 1:\n            if k.parent == k.parent.parent.right:\n                u = k.parent.parent.left\n                if u.color == 1:\n                    u.color = 0\n                    k.parent.color = 0\n                    k.parent.parent.color = 1\n                    k = k.parent.parent\n                else:\n                    if k == k.parent.left:\n                        k = k.parent\n                        self.right_rotate(k)\n                    k.parent.color = 0\n                    k.parent.parent.color = 1\n                    self.left_rotate(k.parent.parent)\n            else:\n                u = k.parent.parent.right\n\n                if u.color == 1:\n                    u.color = 0\n                    k.parent.color = 0\n                    k.parent.parent.color = 1\n                    k = k.parent.parent\n                else:\n                    if k == k.parent.right:\n                        k = k.parent\n                        self.left_rotate(k)\n                    k.parent.color = 0\n                    k.parent.parent.color = 1\n                    self.right_rotate(k.parent.parent)\n            if k == self.root:\n                break\n        self.root.color = 0\n\n    # Printing the tree\n    def __print_helper(self, node, indent, last):\n        if node != self.TNULL:\n            sys.stdout.write(indent)\n            if last:\n                sys.stdout.write(\"R----\")\n                indent += \"     \"\n            else:\n                sys.stdout.write(\"L----\")\n                indent += \"|    \"\n\n            s_color = \"RED\" if node.color == 1 else \"BLACK\"\n            print(str(node.item) + \"(\" + s_color + \")\")\n            self.__print_helper(node.left, indent, False)\n            self.__print_helper(node.right, indent, True)\n\n    def preorder(self):\n        self.pre_order_helper(self.root)\n\n    def inorder(self):\n        self.in_order_helper(self.root)\n\n    def postorder(self):\n        self.post_order_helper(self.root)\n\n    def searchTree(self, k):\n        return self.search_tree_helper(self.root, k)\n\n    def minimum(self, node):\n        while node.left != self.TNULL:\n            node = node.left\n        return node\n\n    def maximum(self, node):\n        while node.right != self.TNULL:\n            node = node.right\n        return node\n\n    def successor(self, x):\n        if x.right != self.TNULL:\n            return self.minimum(x.right)\n\n        y = x.parent\n        while y != self.TNULL and x == y.right:\n            x = y\n            y = y.parent\n        return y\n\n    def predecessor(self,  x):\n        if (x.left != self.TNULL):\n            return self.maximum(x.left)\n\n        y = x.parent\n        while y != self.TNULL and x == y.left:\n            x = y\n            y = y.parent\n\n        return y\n\n    def left_rotate(self, x):\n        y = x.right\n        x.right = y.left\n        if y.left != self.TNULL:\n            y.left.parent = x\n\n        y.parent = x.parent\n        if x.parent == None:\n            self.root = y\n        elif x == x.parent.left:\n            x.parent.left = y\n        else:\n            x.parent.right = y\n        y.left = x\n        x.parent = y\n\n    def right_rotate(self, x):\n        y = x.left\n        x.left = y.right\n        if y.right != self.TNULL:\n            y.right.parent = x\n\n        y.parent = x.parent\n        if x.parent == None:\n            self.root = y\n        elif x == x.parent.right:\n            x.parent.right = y\n        else:\n            x.parent.left = y\n        y.right = x\n        x.parent = y\n\n    def insert(self, key):\n        node = Node(key)\n        node.parent = None\n        node.item = key\n        node.left = self.TNULL\n        node.right = self.TNULL\n        node.color = 1\n\n        y = None\n        x = self.root\n\n        while x != self.TNULL:\n            y = x\n            if node.item < x.item:\n                x = x.left\n            else:\n                x = x.right\n\n        node.parent = y\n        if y == None:\n            self.root = node\n        elif node.item < y.item:\n            y.left = node\n        else:\n            y.right = node\n\n        if node.parent == None:\n            node.color = 0\n            return\n\n        if node.parent.parent == None:\n            return\n\n        self.fix_insert(node)\n\n    def get_root(self):\n        return self.root\n\n    def delete_node(self, item):\n        self.delete_node_helper(self.root, item)\n\n    def print_tree(self):\n        self.__print_helper(self.root, \"\", True)\n\n\nif __name__ == \"__main__\":\n    bst = RedBlackTree()\n\n    bst.insert(55)\n    bst.insert(40)\n    bst.insert(65)\n    bst.insert(60)\n    bst.insert(75)\n    bst.insert(57)\n\n    bst.print_tree()\n\n    print(\"\\nAfter deleting an element\")\n    bst.delete_node(40)\n    bst.print_tree()\n"
  },
  {
    "path": "Data-Structures/Tree/Segment-Tree/Segment-Tree.c",
    "content": "/**\n * Segment Tree, or Segment Tree, is one of the most used data structures in competitive programming\n * due to its efficiency and versatility in operations of consultation in intervals and updating of elements in the array.\n * It consists of breaking the array into several intervals (segments).\n * Then, based on these intervals, we build a tree where each node stores the sum of the elements in the interval.\n * Complexity: construction - O (n); query & update - O (log n).\n * \n * @author Ytalo Ramon\n */\n\n#include \"stdio.h\"\n#include \"stdlib.h\"\n#include \"string.h\"\n\n#define MAX 10\n#define CALMIDDLE(a, b)((a + b) / 2)\n\nint build(int *listV, int *listSegment, int startInterv, int endInterv, int posi);\n\nint update(int newValue, int indexUpdate, int *listSegment, int startInterv, int endInterv, int posi);\n\nint getSum(int *listSegment, int findStartIndex, int findEndIndex, int startInterv, int endInterv, int posi);\n\nvoid show(char *title, int *l, int length);\n\nint main(int argc, char const *argv[]){\n    \n    // Allocation variable and defined values\n    int listValues[MAX] = {15, 2, 6, 9, 10, 1, 156, 7, 88, 65}, listSegmTree[MAX * 4];\n    // Set 0 the segment tree in all position \n    memset(listSegmTree, 0, sizeof(int) * MAX * 4);\n\n    // Constructor segment tree\n    build(listValues, listSegmTree, 0, MAX, 0);\n    show(\"Array\", listValues, MAX);\n    show(\"SegTree\", listSegmTree, MAX * 3 + 10);\n\n    printf(\"Update: idx=0; new_value=4\\n\");\n    listValues[0] = 4;\n    update(4, 0, listSegmTree, 0, MAX, 0);\n    show(\"Array\", listValues, MAX);\n    show(\"SegTree\", listSegmTree, MAX * 3 + 10);\n\n    printf(\"SUM: start=0; end=4 => %d\\n\", getSum(listSegmTree, 0, 4, 0, MAX, 0));\n    show(\"Array\", listValues, MAX);\n\n    printf(\"SUM: start=5; end=9 => %d\\n\", getSum(listSegmTree, 5, 9, 0, MAX, 0));\n    show(\"Array\", listValues, MAX);\n\n    printf(\"Update: idx=6; new_value=899\\n\");\n    listValues[6] = 899;\n    update(899, 6, listSegmTree, 0, MAX, 0);\n    show(\"Array\", listValues, MAX);\n    show(\"SegTree\", listSegmTree, MAX * 3 + 10);\n\n    printf(\"SUM: start=0; end=9 => %d\\n\", getSum(listSegmTree, 0, 9, 0, MAX, 0));\n    show(\"Array\", listValues, MAX);\n\n    printf(\"SUM: start=3; end=7 => %d\\n\", getSum(listSegmTree, 3, 7, 0, MAX, 0));\n    show(\"Array\", listValues, MAX);\n    \n    return 0;\n}\n\nint build(int *listV, int *listSegment, int startInterv, int endInterv, int posi){\n    if (startInterv == endInterv - 1)\n        return listSegment[posi] = listV[startInterv];\n\n    const int middle = CALMIDDLE(startInterv, endInterv),\n        sumInterv = build(listV, listSegment, startInterv, middle, posi * 2 + 1) +\n                    build(listV, listSegment, middle, endInterv, posi * 2 + 2);\n\n    return listSegment[posi] = sumInterv; \n}\n\nint update(int newValue, int indexUpdate, int *listSegment, int startInterv, int endInterv, int posi){\n    if (startInterv == endInterv - 1)\n        return listSegment[posi] = newValue;\n\n    const int middle = CALMIDDLE(startInterv, endInterv),\n            sumInterv = indexUpdate < middle ? \n                            update(newValue, indexUpdate, listSegment, startInterv, middle, posi * 2 + 1) + listSegment[posi * 2 + 2]:\n                            update(newValue, indexUpdate, listSegment, middle, endInterv, posi * 2 + 2) + listSegment[posi * 2 + 1];\n                                                \n    return listSegment[posi] = sumInterv;\n}\n\nint getSum(int *listSegment, int findStartIndex, int findEndIndex, int startInterv, int endInterv, int posi){\n    if (findStartIndex >= endInterv || findEndIndex < startInterv)\n        return 0;\n\n    if (findStartIndex <= startInterv && endInterv <= findEndIndex + 1)\n        return listSegment[posi];\n\n    const int middle = CALMIDDLE(startInterv, endInterv);\n\n    return getSum(listSegment, findStartIndex, findEndIndex, startInterv, middle, posi * 2 + 1) +\n            getSum(listSegment, findStartIndex, findEndIndex, middle, endInterv, posi * 2 + 2);\n}\n\nvoid show(char *title, int *l, int length){\n    printf(\"%s\\n\", title);\n    for (int i = 0; i < length; i++) printf(\"%d \", l[i]);\n    printf(\"\\n-----------------\\n\\n\");\n}"
  },
  {
    "path": "Data-Structures/Tree/Splay-Tree/Splay-Tree.c",
    "content": "#include <iostream>\n#include <cstdio>\n#include <cstdlib>\nusing namespace std;\nstruct s//node declaration\n{\n   int k;  \n   s* lch;\n   s* rch;\n};\nclass SplayTree\n{\n   public:\n   s* RR_Rotate(s* k2)\n   {\n      s* k1 = k2->lch;\n      k2->lch = k1->rch;\n      k1->rch = k2;\n      return k1;\n   }\n   s* LL_Rotate(s* k2)\n   {\n      s* k1 = k2->rch;\n      k2->rch = k1->lch;\n      k1->lch = k2;\n      return k1;\n   }\n   s* Splay(int key, s* root)\n   {\n      if (!root)\n      return NULL;\n      s header;\n      header.lch= header.rch = NULL;\n      s* LeftTreeMax = &header;\n      s* RightTreeMin = &header;\n      while (1)\n      {\n         if (key < root->k)\n         {\n            if (!root->lch)\n            break;\n            if (key< root->lch->k)\n            {\n               root = RR_Rotate(root);\n               if (!root->lch)\n               break;\n            }\n            RightTreeMin->lch= root;\n            RightTreeMin = RightTreeMin->lch;\n            root = root->lch;\n            RightTreeMin->lch = NULL;\n         }\n         else if (key> root->k)\n         {\n            if (!root->rch)\n            break;\n            if (key > root->rch->k)\n            {\n               root = LL_Rotate(root);\n               if (!root->rch)\n               break;\n            }\n            LeftTreeMax->rch= root;\n            LeftTreeMax = LeftTreeMax->rch;\n            root = root->rch;\n            LeftTreeMax->rch = NULL;\n         }\n         else\n         break;\n      }\n      LeftTreeMax→rch = root->lch;\n      RightTreeMin→lch = root->rch;\n      root->lch = header.rch;\n      root->rch = header.lch;\n      return root;\n   }\n   s* New_Node(int key)\n   {\n      s* p_node = new s;\n      if (!p_node)\n      {\n         fprintf(stderr, \"Out of memory!\\n\");\n         exit(1);\n      }\n      p_node->k = key;\n      p_node->lch = p_node->rch = NULL;\n      return p_node;\n   }\n   s* Insert(int key, s* root)\n   {\n      static s* p_node = NULL;\n      if (!p_node)\n      p_node = New_Node(key);\n      else\n      p_node->k = key;\n      if (!root)\n      {\n         root = p_node;\n         p_node = NULL;\n         return root;\n      }\n      root = Splay(key, root);\n      if (key < root->k)\n      {\n         p_node->lch= root->lch;\n         p_node->rch = root;\n         root->lch = NULL;\n         root = p_node;\n      }\n      else if (key > root->k)\n      {\n         p_node->rch = root->rch;\n         p_node->lch = root;\n         root->rch = NULL;\n         root = p_node;\n      }\n      else\n      return root;\n      p_node = NULL;\n      return root;\n   }\n   s* Delete(int key, s* root)//delete node\n   {\n      s* temp;\n      if (!root)//if tree is empty\n      return NULL;\n      root = Splay(key, root);\n      if (key != root->k)//if tree has one item\n      return root;\n      else\n      {\n         if (!root->lch)\n         {\n            temp = root;\n            root = root->rch;\n         }\n         else\n         {\n            temp = root;\n            root = Splay(key, root->lch);\n            root->rch = temp->rch;\n         }\n         free(temp);\n         return root;\n      }\n   }\n   s* Search(int key, s* root)//seraching\n   {\n      return Splay(key, root);\n   }\n   void InOrder(s* root)//inorder traversal\n   {\n      if (root)\n      {\n         InOrder(root->lch);\n         cout<< \"key: \" <<root->k;\n         if(root->lch)\n         cout<< \" | left child: \"<< root->lch->k;\n         if(root->rch)\n         cout << \" | right child: \" << root->rch->k;\n         cout<< \"\\n\";\n         InOrder(root->rch);\n      }\n   }\n};\nint main()\n{\n   SplayTree st;\n   s *root;\n   root = NULL;\n   st.InOrder(root);\n   int i, c;\n   while(1)\n   {\n      cout<<\"1. Insert \"<<endl;\n      cout<<\"2. Delete\"<<endl;\n      cout<<\"3. Search\"<<endl;\n      cout<<\"4. Exit\"<<endl;\n      cout<<\"Enter your choice: \";\n      cin>>c;\n      switch©//perform switch operation\n      {\n         case 1:\n            cout<<\"Enter value to be inserted: \";\n            cin>>i;\n            root = st.Insert(i, root);\n            cout<<\"\\nAfter Insert: \"<<i<<endl;\n            st.InOrder(root);\n            break;\n         case 2:\n            cout<<\"Enter value to be deleted: \";\n            cin>>i;\n            root = st.Delete(i, root);\n            cout<<\"\\nAfter Delete: \"<<i<<endl;\n            st.InOrder(root);\n            break;\n         case 3:\n            cout<<\"Enter value to be searched: \";\n            cin>>i;\n            root = st.Search(i, root);\n            cout<<\"\\nAfter Search \"<<i<<endl;\n            st.InOrder(root);\n            break;\n         case 4:\n            exit(1);\n         default:\n            cout<<\"\\nInvalid type! \\n\";\n      }\n   }\n   cout<<\"\\n\";\n   return 0;\n}\n"
  },
  {
    "path": "Data-Structures/Tree/Threaded Binary Tree/Threaded_Binary_Tree.cpp",
    "content": "/*\n\tAuthor : adi1212\n*/\n\n/*Problem Statement : \n\nImplement In-order Threaded Binary Tree and traverse it in In-order and Pre-order*/\n\n#include<bits/stdc++.h> \nusing namespace std; \n\n\n//Structure of the Threaded Binary Tree\nstruct TBT_nd \n{ \n   int data; \n   TBT_nd *left; \n   TBT_nd *right; \n   int th_left; \n   int th_right; \n} *head; \n\nTBT_nd *insert(TBT_nd *root, TBT_nd *temp) //Inserting node in Threaded Binary Tree\n{ \n   if(head->left==head && head->right==head) \n   { \n       temp->left=head; \n       temp->right=head; \n       head->left=temp; \n       head->th_left=1; \n       root=temp; \n       return root; \n   } \n   TBT_nd *curr=root; \n   if(temp->data < curr->data) \n   { \n       if(curr->th_left==0) \n       { \n           temp->left=curr->left; \n           curr->left=temp; \n           temp->right=curr; \n           curr->th_left=1; \n       } \n       else \n       { \n           insert(curr->left,temp); \n       } \n   } \n   else if(temp->data > curr->data) \n   { \n       if(curr->th_right==0) \n       { \n           temp->right=curr->right; \n           curr->right=temp; \n           temp->left=curr; \n           curr->th_right=1; \n       } \n       else \n       { \n           insert(curr->right,temp); \n       } \n   } \n   return root; \n} \n\nTBT_nd *new_nd() \n{ \n   TBT_nd *temp=new TBT_nd; \n   cout<<\"ENTER DATA : \"; \n   cin>>temp->data; \n   temp->left=NULL; \n   temp->right=NULL; \n   temp->th_left=0; \n   temp->th_right=0; \n   return temp; \n} \n\nTBT_nd *create(TBT_nd *root) //Create the node in Threaded Binary Tree\n{ \n   int ch; \n   TBT_nd *temp; \n   if(root==NULL) \n   { \n       head=new TBT_nd; \n       head->data=9999; \n       head->left=head; \n       head->right=head; \n       head->th_right=1; \n       head->th_left=0; \n       root=head; \n   } \n   do \n   { \n       temp=new_nd(); \n       if(root!=NULL) \n       { \n           root=insert(root,temp); \n       } \n       cout<<\"do you want to insert more nodes?? (enter 1 to continue)\\n\"; \n       cin>>ch; \n   } \n   while(ch==1); \n   return root; \n} \n\nTBT_nd *pre_suc(TBT_nd *t) //Predecessor of the node\n{ \n   if(t->th_left==1) \n       return(t->left); \n   while(t->th_right==0) \n       t=t->right; \n   return(t->right); \n\n} \n\nvoid TBTpreoder(TBT_nd *root) //Preoder Traversal in Threaded BT\n{ \n   TBT_nd *p=root; \n   while(p!=head) \n   { \n       cout<<p->data<<\"\\t\"; \n       p=pre_suc(p); \n   } \n} \n\nTBT_nd *in_suc(TBT_nd *t) //Successor of the node \n{ \n   if(t->th_right==0) \n       return (t->right); \n   t=t->right; \n   while(t->th_left==1) \n       t=t->left; \n   return(t); \n} \n\nvoid TBTinoder(TBT_nd *root) //Inoder Traversal in Threaded BT\n{ \n   TBT_nd *p=root; \n   while(p->th_left==1) \n   { \n       p=p->left; \n   } \n   while(p!=head) \n   { \n       cout<<p->data<<\"\\t\"; \n       p=in_suc(p); \n   } \n} \n\nint main() //Main function\n{ \n   TBT_nd *root=NULL; \n   int n; \n   cout<<\"INORDER THREADED BINARY TREE !\"; \n   do \n   { \n       cout<<\"\\n[1] CREATE (Or insert node in existing tree)?\\n\"; \n       cout<<\"[2] INORDER TRAVERSE?\\n\"; \n       cout<<\"[3] PREORDER TRAVERSE?\\n\"; \n       cout<<\"\\nEnter your choice: (enter 0 to exit)\"; \n       cin>>n; \n       if(n==1) \n       { \n           root=create(root); \n       } \n       else if(n==2) \n       { \n           cout<<\"INORDER TRAVERSAL: \\n\"; \n           TBTinoder(root); \n       } \n       else if(n==3) \n       { \n           cout<<\"PREORDER TRAVERSAL: \\n\"; \n           TBTpreoder(root); \n       } \n   } \n   while(n!=0); \n   cout<<\"\\nOPERATION COMPLETED!! THANK YOU\"; \n   return 0; \n}\n\n\n/*\n-----------------------------------------------------------------------------------------------------------------------------\nOUTPUT : \n\nINORDER THREADED BINARY TREE !\n[1] CREATE (Or insert node in existing tree)?\n[2] INORDER TRAVERSE?\n[3] PREORDER TRAVERSE?\n\nEnter your choice: (enter 0 to exit)1\nENTER DATA : 10\ndo you want to insert more nodes?? (enter 1 to continue)\n1\nENTER DATA : 6\ndo you want to insert more nodes?? (enter 1 to continue)\n1\nENTER DATA : 13\ndo you want to insert more nodes?? (enter 1 to continue)\n1\nENTER DATA : 15\ndo you want to insert more nodes?? (enter 1 to continue)\n1\nENTER DATA : 7\ndo you want to insert more nodes?? (enter 1 to continue)\n1\nENTER DATA : 20\ndo you want to insert more nodes?? (enter 1 to continue)\n1\nENTER DATA : 2\ndo you want to insert more nodes?? (enter 1 to continue)\n1\nENTER DATA : 3\ndo you want to insert more nodes?? (enter 1 to continue)\n0\n\n[1] CREATE (Or insert node in existing tree)?\n[2] INORDER TRAVERSE?\n[3] PREORDER TRAVERSE?\n\nEnter your choice: (enter 0 to exit)2\nINORDER TRAVERSAL: \n2       3       6       7       10      13      15      20\n[1] CREATE (Or insert node in existing tree)?\n[2] INORDER TRAVERSE?\n[3] PREORDER TRAVERSE?\n\nEnter your choice: (enter 0 to exit)3\nPREORDER TRAVERSAL: \n10      6       2       3       7       13      15      20\n[1] CREATE (Or insert node in existing tree)?\n[2] INORDER TRAVERSE?\n[3] PREORDER TRAVERSE?\n\nEnter your choice: (enter 0 to exit)0\n\nOPERATION COMPLETED!! THANK YOU\n\n...Program finished with exit code 0\nPress ENTER to exit console.\n*/\n"
  },
  {
    "path": "Data-Structures/Tree/Trie/README.md",
    "content": "# This folder is empty.\n"
  },
  {
    "path": "Data-Structures/Tree/Trie/Trie.c",
    "content": "#include <stdio.h> \r\n#include <stdlib.h> \r\n#include <string.h> \r\n#include <stdbool.h> \r\n  \r\n#define ARRAY_SIZE(a) sizeof(a)/sizeof(a[0]) \r\n\r\n#define ALPHABET_SIZE (26) \r\n \r\n#define CHAR_TO_INDEX(c) ((int)c - (int)'a') \r\n  \r\n// trie node \r\nstruct TrieNode \r\n{ \r\n    struct TrieNode *children[ALPHABET_SIZE]; \r\n  \r\n    bool isEndOfWord; \r\n}; \r\n  \r\nstruct TrieNode *getNode(void) \r\n{ \r\n    struct TrieNode *pNode = NULL; \r\n  \r\n    pNode = (struct TrieNode *)malloc(sizeof(struct TrieNode)); \r\n  \r\n    if (pNode) \r\n    { \r\n        int i; \r\n  \r\n        pNode->isEndOfWord = false; \r\n  \r\n        for (i = 0; i < ALPHABET_SIZE; i++) \r\n            pNode->children[i] = NULL; \r\n    } \r\n  \r\n    return pNode; \r\n} \r\n  \r\nvoid insert(struct TrieNode *root, const char *key) \r\n{ \r\n    int level; \r\n    int length = strlen(key); \r\n    int index; \r\n  \r\n    struct TrieNode *pCrawl = root; \r\n  \r\n    for (level = 0; level < length; level++) \r\n    { \r\n        index = CHAR_TO_INDEX(key[level]); \r\n        if (!pCrawl->children[index]) \r\n            pCrawl->children[index] = getNode(); \r\n  \r\n        pCrawl = pCrawl->children[index]; \r\n    } \r\n  \r\n\r\n    pCrawl->isEndOfWord = true; \r\n} \r\n  \r\n\r\nbool search(struct TrieNode *root, const char *key) \r\n{ \r\n    int level; \r\n    int length = strlen(key); \r\n    int index; \r\n    struct TrieNode *pCrawl = root; \r\n  \r\n    for (level = 0; level < length; level++) \r\n    { \r\n        index = CHAR_TO_INDEX(key[level]); \r\n  \r\n        if (!pCrawl->children[index]) \r\n            return false; \r\n  \r\n        pCrawl = pCrawl->children[index]; \r\n    } \r\n  \r\n    return (pCrawl != NULL && pCrawl->isEndOfWord); \r\n} \r\n  \r\nint main() \r\n{ \r\n    char keys[][8] = {\"the\", \"a\", \"there\", \"answer\", \"any\", \r\n                     \"by\", \"bye\", \"their\"}; \r\n  \r\n    char output[][32] = {\"Not present in trie\", \"Present in trie\"}; \r\n  \r\n  \r\n    struct TrieNode *root = getNode(); \r\n  \r\n    // Construct trie \r\n    int i; \r\n    for (i = 0; i < ARRAY_SIZE(keys); i++) \r\n        insert(root, keys[i]); \r\n  \r\n    printf(\"%s --- %s\\n\", \"the\", output[search(root, \"the\")] ); \r\n    printf(\"%s --- %s\\n\", \"these\", output[search(root, \"these\")] ); \r\n    printf(\"%s --- %s\\n\", \"their\", output[search(root, \"their\")] ); \r\n    printf(\"%s --- %s\\n\", \"thaw\", output[search(root, \"thaw\")] ); \r\n  \r\n    return 0; \r\n} \r\n"
  },
  {
    "path": "Data-Structures/Tree/Trie/trie.cpp",
    "content": "#include <bits/stdc++.h>\nusing namespace std;\n\nstruct TrieNode\n{\n\tunordered_map<char, TrieNode*> branches;\n\tbool isEnd;\n};\n\n// creates new node and initialises isEnd to false\nTrieNode* createNode(void) \n{\n\n\tTrieNode* node = new TrieNode;\n\tnode->isEnd = false;\n\n\treturn node;\n}\t\t\t\t\n\nvoid insert(TrieNode*& node, const string &str, int index = 0) \n{\n\t// inserts a character node to existing trie structure\n\n\tif (node == NULL)  // creates a new root if there is none\n\t{\n\t\tnode = createNode();\n\t\tcout<<\"Creating ROOT\"<<endl;\n\t}\n\n\tTrieNode* temp = node;\n\n\tif (index >= str.length())\t// check if we have reached end of the word\n\t{\n\t\ttemp->isEnd = true;\n\n\t\treturn;\n\t}\n\t\n\t// assigns letter on i'th position of string to key\n\tchar key = str[index];\n\tif (temp->branches.find(key) == temp->branches.end())\n\t{\n\t\ttemp->branches[key] = createNode();\n\t}\n\n\t// recursive definition to insert into trie\n\treturn insert(temp->branches[key], str, index+1);\n}\n\nstring search(TrieNode* root, const string &str, int index = 0) \n{\n\t// function which returns word if found else error message\n\n\tif (root == NULL) // return not found if no words added\n\t{\n\t\treturn \"Word not found.\";\n\t}\n\n\tTrieNode* temp = root;\n\n\tif (index >= str.length()) // return found if end of word encountered\n\t{\n\t\treturn \"Word found.\";\n\t}\n\n\tchar key = str[index];\n\t// recursive definition to iterate through trie\n\treturn search(temp->branches[key], str, index+1);\n}\n\nint main() \n{ \n    TrieNode* root = NULL; \n\n    // Build the dictionary \n    insert(root, \"trie\"); \n    insert(root, \"is\");\n    insert(root, \"an\"); \n    insert(root, \"efficient\");  \n    insert(root, \"retrieval\"); \n    insert(root, \"structure\");\n  \n  \t// search for \"book\" in our trie\n    string str; \n    cout<<\"Enter Word to search:\";\n    cin>>str;\n    cout << search(root, str); \n  \n    return 0; \n} \n"
  },
  {
    "path": "Data-Structures/Tree/Trie/trie.py",
    "content": "class TrieNode: \n\t\n\tdef __init__(self): \n\t\tself.children = [None]*26\n\n\t\tself.isEndOfWord = False\n\nclass Trie: \n\tdef __init__(self): \n\t\tself.root = self.getNode() \n\n\tdef getNode(self): \n\t\n\t\t# Returns new trie node (initialized to NULLs) \n\t\treturn TrieNode() \n\n\tdef _charToIndex(self,ch): \n\t\t\n\t\treturn ord(ch)-ord('a') \n\n\n\tdef insert(self,key): \n\t\tpCrawl = self.root \n\t\tlength = len(key) \n\t\tfor level in range(length): \n\t\t\tindex = self._charToIndex(key[level]) \n\n\t\t\t# if current character is not present \n\t\t\tif not pCrawl.children[index]: \n\t\t\t\tpCrawl.children[index] = self.getNode() \n\t\t\tpCrawl = pCrawl.children[index] \n\n\n\t\tpCrawl.isEndOfWord = True\n\n\tdef search(self, key): \n\t\tpCrawl = self.root \n\t\tlength = len(key) \n\t\tfor level in range(length): \n\t\t\tindex = self._charToIndex(key[level]) \n\t\t\tif not pCrawl.children[index]: \n\t\t\t\treturn False\n\t\t\tpCrawl = pCrawl.children[index] \n\n\t\treturn pCrawl != None and pCrawl.isEndOfWord \n\n# driver function \ndef main(): \n\n\n\tprint(\"Input keys (use only 'a' through 'z' and lower case\") \n  keys=[]\n  n=input(\"Enter number of arguments\")\n  for i in range(n):\n    keys.append(input())\n\t\n\toutput = [\"Not present in trie\", \n\t\t\t\"Present in trie\"] \n\n\t# Trie object \n\tt = Trie() \n\n\t# Construct trie \n\tfor key in keys: \n\t\tt.insert(key) \n\n\n\tprint(\"{} ---- {}\".format(\"the\",output[t.search(\"the\")])) \n\tprint(\"{} ---- {}\".format(\"these\",output[t.search(\"these\")])) \n\tprint(\"{} ---- {}\".format(\"their\",output[t.search(\"their\")])) \n\tprint(\"{} ---- {}\".format(\"thaw\",output[t.search(\"thaw\")])) \n\nif __name__ == '__main__': \n\tmain() \n"
  },
  {
    "path": "LICENSE",
    "content": "MIT License\n\nCopyright (c) 2021 Priyanshu Tiwari\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n"
  },
  {
    "path": "Maths/Algebra/Babylionian/Babylionian.cs",
    "content": "// C# Porgram for Babylonian \n// method of square root \n// Contributed By - Ayush Sharma (belphegor-s)\nusing System; \n\nclass SQRT { \n\n\t// Returns the square root of n. \n\t// Note that the function \n\tstatic float squareRoot(float n) \n\t{ \n\n\t\t// We are using n itself as \n\t\t// initial approximation This \n\t\t// can definitely be improved \n\t\tfloat x = n; \n\t\tfloat y = 1; \n\n\t\t// e decides the \n\t\t// accuracy level \n\t\tdouble e = 0.000001; \n\t\twhile (x - y > e) { \n\t\t\tx = (x + y) / 2; \n\t\t\ty = n / x; \n\t\t} \n\t\treturn x; \n\t} \n\n\t \n\tpublic static void Main() \n\t{ \n\t\tint n = Console.ReadLine();\n\t\tConsole.Write(\"Square root of \"\n\t\t\t\t\t+ n + \" is \" + squareRoot(n)); \n\t} \n} \n\n\n"
  },
  {
    "path": "Maths/Algebra/Babylionian/Babylionian.go",
    "content": "package main\n\nimport (\n\t\"fmt\"\n\t\"strconv\"\n)\n\nfunc main() {\n\tfmt.Println(\"Enter the number for which square root is to be found :\")\n\tvar n string\n\tfmt.Scan(&n)\n\tvar a float64 = 1\n\tvar e float64 = 0.000001\n\tvalue, err := strconv.ParseFloat(n, 64)\n\tvar temp float64 = value\n\tif err != nil {\n\t\tfmt.Printf(\"%s is not a valid number \", n)\n\t\treturn\n\t}\n\tfor temp-a > e {\n\t\ttemp = (temp + a) / 2\n\t\ta = value / temp\n\t}\n\tfmt.Printf(\"Square rooot of %f is %.02f \\n\", value, temp)\n}\n"
  },
  {
    "path": "Maths/Algebra/Babylionian/Babylonian.java",
    "content": "class Babylonian {\n\n    /*Returns the square root of n. \n    Note that the function */\n    static float squareRoot(float n) {\n\n        /*We are using n itself as  \n        initial approximation This  \n        can definitely be improved */\n        float x = n;\n        float y = 1;\n\n        // e decides the accuracy level \n        double e = 0.000001;\n        while (x - y > e) {\n            x = (x + y) / 2;\n            y = n / x;\n        }\n        return x;\n    }\n\n    /* Driver program to test \n    above function*/\n    public static void main(String[] args) {\n        System.out.print(\"Please enter a number: \");\n        Scanner myObj = new Scanner(System.in);\n        try {\n            Float n = myObj.nextFloat();\n            System.out.printf(\"Square root of \" +\n                n + \" is \" + squareRoot(n));\n        } catch (InputMismatchException e) {\n            String msg = e.getMessage();\n            System.out.println(\"That is not a number, please try again.\");\n        }\n    }\n}\n"
  },
  {
    "path": "Maths/Algebra/Babylonian/Babylonian.js",
    "content": "function babylonianSqrt(n) {\n\n  // Checks for valid number input\n  if (!(typeof n === 'number' && n >= 0 && !isNaN(n))) {\n    return NaN;\n  } else if (n === 0) {\n    return 0;\n  } else if (n === Infinity) {\n    return Infinity;\n  }\n\n  var value = n;\n\n  while (true) {\n    var last = value;\n\n    // Calculate value\n    value = (value + n / value) * 0.5;\n    // Check if true\n    if (Math.abs(value - last) < 1e-9) {\n      break;\n    }\n  }\n\n  return value;\n}\n\n// Test\nlet userInput = parseInt(prompt(\"Enter a number to find the Babylonian square root:\"))\n\nbabylonianSqrt(userInput);\n"
  },
  {
    "path": "Maths/Algebra/Babylonian/babylonian_square_root.c",
    "content": "/*\nBabylonian is used to find the square root of a number.\nIt is a very old method.\n*/\n\n#include<stdio.h>\n/*\n  squareRoot function\n  @param:num the number whose square root is to find.\n  return square root of the number in float.\n*/\nfloat squareRoot( int num ){\n float x = num, y = 1.0, diff = 0.000001;\n\n while( x - y > diff  ){\n  x = ( x + y ) / 2 ;\n  y = num / x ;\n }\n return x;\n}\n\n//main function\nint main(){\n int num = 0;\n float result = 0.0;\n printf( \"Enter a number to find Square Root :\" );\n scanf( \"%d\", &num );\n result = squareRoot( num );\n\n if( num < 0 ){\n    printf( \"Square Root is not real for negative numbers. \\n\");\n    return 0;\n }\n\n printf( \"The Square Root of %d : %f\\n\", num, result );\n return 0;\n}\n\n// Contributed by Vishwaroop Shah\n"
  },
  {
    "path": "Maths/Algebra/Derivative_Of_Polynomial/Matrix_Multiplication.c",
    "content": "#include<stdio.h>\n#define MAX 100\nint main()\n{\n    int arow,acolumn,brow,bcolumn,i,j,k;\n    int a[MAX][MAX],b[MAX][MAX],product[MAX][MAX];\n    int sum=0;\n\n    printf(\"Enter the number of row and column of matrix A:\");\n    scanf(\"%d%d\",&arow,&acolumn);\n    printf(\"Enter the elements of matric A:\");\n    for(i=0;i<arow;i++);\n    {\n        for(j=0;j<acolumn;j++)\n        {\n            scanf(\"%d\",&a[i][j]);\n        }\n    }\n    printf(\"Enter the number of rows and column of amtrix B:\");\n    scanf(\"%d%d\",&brow,&bcolumn);\n    if(brow!=acolumn)\n        printf(\"Invalid input of matric B\");\n    else\n    {\n        printf(\"Ente the elements of matric B\");\n        for(i=0;i<brow;i++);\n        {\n            for(j=0;j<bcolumn;j++)\n            {\n                scanf(\"%d\",&b[i][j]);\n            }\n        }\n    }\n    for(i=0;i<arow;i++)\n    {\n        for(j=0;j<bcolumn;j++)\n        {\n            for(k=0;k<brow;k++)\n            {\n                sum+=a[i][k]*b[j][k];\n            }\n        product[i][j]=sum;\n        sum=0;\n        }\n    }\n    printf(\"The Resultant matric:\\n\");\n    for(i=0;i<arow;i++)\n    {\n        for(j=0;j<bcolumn;j++)\n        {\n            printf(\"%d\",product[i][j]);\n        }\n        printf(\"\\n\");\n    }\n    return 0;\n}"
  },
  {
    "path": "Maths/Algebra/Derivative_Of_Polynomial/README.md",
    "content": "## This folder is empty.\n"
  },
  {
    "path": "Maths/Algebra/Diophantine/README.md",
    "content": "## This folder is empty.\n"
  },
  {
    "path": "Maths/Algebra/Factorial/Factorial.hs",
    "content": "module Factorial (fact) where\n\nfact x = foldr (*) [1..x]\n"
  },
  {
    "path": "Maths/Algebra/Factorial/Factorial.java",
    "content": "import java.util.Scanner;\n\npublic class Factorial {\n    static int factorial(int n) {\n        int res = 1;\n        int i;\n        for (i = 2; i <= n; i++)\n            res *= i;\n        return res;\n    }\n\n    public static void main(String[] args) {\n        Scanner scanner = new Scanner(System.in);\n        System.out.print(\"Enter a non-negative number: \");\n        int num = scanner.nextInt();\n        System.out.println(\"Factorial of \" + num + \" is \" + factorial(num));\n    }\n}"
  },
  {
    "path": "Maths/Algebra/Factorial/README.md",
    "content": "## This folder is empty.\n"
  },
  {
    "path": "Maths/Algebra/Factorial/factorial.c",
    "content": "#include <stdio.h>\n\nunsigned int factorial(unsigned int n)\n{\n    int fact = 1, i;\n    for (i = 2; i <= n; i++)\n        fact *= i;\n    return fact;\n}\n\nint main()\n{\n    int num;\n    printf(\"Enter a non-negative number: \");\n    scanf(\"%d\",&num);\n    if(num<0){\n        printf(\"Factorial of a negative integer cannot be found\");\n    }\n    else{\n    printf(\"Factorial of %d is %d\",\n           num, factorial(num));\n    }\n    return 0;\n}"
  },
  {
    "path": "Maths/Algebra/Factorial/factorial.cpp",
    "content": "#include<iostream>\nusing namespace std;\n\nint factorial(int n);\n\nint main()\n{\n    int n;\n\n    cout << \"Enter a positive integer: \";\n    cin >> n;\n\n    cout << \"Factorial of \" << n << \" = \" << factorial(n);\n\n    return 0;\n}\n\nint factorial(int n)\n{\n    if(n > 1)\n        return n * factorial(n - 1);\n    else\n        return 1;\n}"
  },
  {
    "path": "Maths/Algebra/Factorial/factorial.cs",
    "content": "using System;  \n  public class FactorialExample  \n   {  \n     public static void Main(string[] args)  \n      {  \n       int i,fact=1,number;      \n       Console.Write(\"Enter a non-negative Number: \");      \n       number= int.Parse(Console.ReadLine());     \n       for(i=1;i<=number;i++){      \n        fact=fact*i;      \n       }      \n       Console.Write(\"Factorial of \" +number+\" is: \"+fact);    \n     }  \n  }  "
  },
  {
    "path": "Maths/Algebra/Factorial/factorial.go",
    "content": "package main  \n  \nimport (  \n \"fmt\"  \n)  \n  \nfunc IterativeFactorial(number int) uint64 {  \n var result uint64 = 1  \n if number < 0 {  \n  \n } else {  \n  for i := 1; i <= number; i++ {  \n   result *= uint64(i)  \n  \n  }  \n }  \n return result  \n}  \nfunc main() {  \n var number int  \n fmt.Print(\"Enter Number:\")  \n fmt.Scanln(&number)  \n fmt.Printf(\"Factorial of %d = %d\", number, IterativeFactorial(number))  \n}  \n"
  },
  {
    "path": "Maths/Algebra/Factorial/factorial.js",
    "content": "let number = parseInt(prompt(\"Enter a positive integer: \"));\n\nif (number < 0) {\n  console.log(\"Factorial for negative number does not exist.\");\n}\nelse if (number === 0) {\n  console.log(`The factorial of ${number} is 1.`);\n}\nelse {\n  let fact = 1;\n  for (let i = 1; i <= number; i++) {\n    fact *= i;\n  }\n  console.log(`The factorial of ${number} is ${fact}.`);\n}\n"
  },
  {
    "path": "Maths/Algebra/Factorial/factorial.php",
    "content": "<html>  \n<head>  \n<title>Factorial Program using loop in PHP</title>  \n</head>  \n<body>  \n<form method=\"post\">  \n    Enter the Number:<br>  \n    <input type=\"number\" name=\"number\" id=\"number\">  \n    <input type=\"submit\" name=\"submit\" value=\"Submit\" />  \n</form>  \n<?php   \n    function fact ($n)  \n    {  \n        if($n <= 1)   \n        {  \n            return 1;  \n        }  \n        else   \n        {  \n            return $n * fact($n - 1);  \n        }  \n    }  \n    if($_POST){  \n        $fact = 1;  \n        //getting value from input text box 'number'  \n        $number = $_POST['number'];  \n        echo \"Factorial of $number:<br><br>\";  \n        echo fact($number) . \"<br>\";  \n    }  \n?>  \n</body>  \n</html>  "
  },
  {
    "path": "Maths/Algebra/Factorial/factorial.py",
    "content": "# recursive function to calculate factorial of a number\ndef fact(num):\n\n    # if the number is greater than 0\n    # make a recursive call to the function\n    if num > 0:\n        factorial = num * fact(num-1)\n    \n    else:\n        factorial = 1\n    \n    # return the factorial\n    return factorial\n\n# taking an integer input\nn = int(input(\"Enter the number: \"))\n\n# print the factorial of the number\nprint(fact(n))"
  },
  {
    "path": "Maths/Algebra/Factorial/factorial.rb",
    "content": "puts \"Enter a non-negative number:\"\nnum= gets.to_i\n\nfact=1\nif (num<0)\n\tputs \"Factorial of a non-negative number doesn't exists\"\nelse\n\ti=1\n\twhile(i<=num)\n\t\tfact=fact*i\n\t\ti+=1\n\tend\n\t\n\tputs \"factorial of #{num} is #{fact}\"\nend"
  },
  {
    "path": "Maths/Algebra/Factorial/factorial.sh",
    "content": "#!/bin/bash\n# Usage: factorial [n]\n\nfactorial=1\n\nif [ $# -eq 1 ]; then\n\tn=$1\n\twhile [ $n -gt 0 ]; do\n\t\tfactorial=$(( $n * $factorial ))\n\t\tn=$(( $n - 1 ))\n\tdone\n\techo $factorial\nelse\n\techo \"Usage: $0 [n]\"\nfi\n"
  },
  {
    "path": "Maths/Algebra/Factorial/factorial.swift",
    "content": "import UIKit\nlet num=readline()\nvar a=Int(num!)\nfunc factorial(a: Int) -> Int {\n    let n = a\n    if(n == 1){\n      return 1\n    }else{\n      return n*factorial(n-1)\n    }\n}\nfactorial(a: a)"
  },
  {
    "path": "Maths/Algebra/Factorial/factorial.ts",
    "content": "// tail recyrsion not work in js, but not the worst decision\n\nconst factorial = (n: number): number => rFactorial(n, 1);\n\nconst rFactorial = (n:number, acc:number): number => (n <= 0) ? acc : rFactorial(n-1, n*acc);\n\nfactorial(11)\n"
  },
  {
    "path": "Maths/Algebra/Factorial_of_Large_Number/Factorial_of_Large_Number.cs",
    "content": "using System;\nusing System.Collections.Generic;\n\npublic class Factorial_of_Large_Number\n{\n    private static List<int> resultDigits;\n\n    public static void Main(string[] args)\n    {\n        resultDigits = null;\n\n        Console.Write(\"Enter a number to find its factorial: \");\n        int number = Convert.ToInt32(Console.ReadLine());\n\n        FindFactorial(number);\n\n        Console.WriteLine(\"The factorial value is: \");\n        DisplayDigits();\n        \n        resultDigits = null;\n    }\n\n    // initializes resultDigits list with one element, 1\n    // multiplies factors 2, 3, ..., n-1, n\n    static void FindFactorial(int n)\n    {\n        resultDigits = new List<int>();\n        resultDigits.Add(1);\n        for (int factor = 2; factor <= n; ++factor)\n        {\n            DigitWiseMultiply(factor);\n        }\n    }\n\n    // multiplies factor to list treating each element as digit\n    // this accounts for carry as well\n    static void DigitWiseMultiply(int factor)\n    {\n        int carry = 0;\n        for (int i = resultDigits.Count - 1; i >= 0; --i)\n        {\n            int temp = resultDigits[i] * factor + carry;\n            resultDigits[i] = temp % 10;\n            carry = temp / 10;\n        }\n\n        // inserts leftover carry to the start of list\n        while (carry > 0)\n        {\n            resultDigits.Insert(0, carry % 10);\n            carry /= 10;\n        }\n    }\n\n    // loops through resultDigits and prints it\n    static void DisplayDigits()\n    {\n        for (int i = 0; i < resultDigits.Count; ++i)\n        {\n            Console.Write(resultDigits[i]);\n        }\n    }\n}\n"
  },
  {
    "path": "Maths/Algebra/Factorial_of_Large_Number/Factorial_of_Large_Number.hs",
    "content": "module Factorial_of_Large_Number (fact) where\n\nfact x = foldr (*) [1..x]\n"
  },
  {
    "path": "Maths/Algebra/Factorial_of_Large_Number/Factorial_of_Large_Number.js",
    "content": "/*\r\n  Factorial simply tells us to multiply any natural number by all the natural numbers that are smaller than it. \r\n  \r\n  Example :\r\n  If we're asked to evaluate 5!, I simply have to do 5 * 4 * 3 * 2 * 1, and I get 120.\r\n*/\r\n\r\n// Recursive function to calculate factorial of a large number \r\n\r\nconst largeNumberFactorial = (num) => {\r\n  if (num === 0n) return 1n;\r\n  return num * largeNumberFactorial(num - 1n);\r\n};\r\n\r\n\r\nconst number = 50;\r\n\r\n// Calling Function\r\nconst factorial = String(largeNumberFactorial(BigInt(number)));\r\n\r\nconsole.log(`Factorial of ${number} is ${factorial}`);\r\n\r\n/*\r\n  Output : \r\n  Factorial of 50 is 30414093201713378043612608166064768844377641568960512000000000000\r\n*/\r\n\r\n"
  },
  {
    "path": "Maths/Algebra/Factorial_of_Large_Number/Factorial_of_Large_Number.php",
    "content": "<?php\n\n$digitArray = [];\n\n/**\n * Factorial calculation\n *\n * @param int $number\n * @return mixed $factorial\n */\nfunction factorial(int $number) {\n    if($number < 2) {\n        return 1;\n    }\n\n    global $digitArray;\n    $digitArray[] = 1;\n\n    for($i = 2; $i <= $number; $i++) {\n        calcFactorialInDigit($i);\n    }\n    return implode('', $digitArray);\n}\n\n/**\n * Calculate factorial and stored in array as digit\n * \n * @param int $number\n * @return void\n */\nfunction calcFactorialInDigit(int $number) {\n    global $digitArray;\n    $carry = 0;\n\n    for($i = count($digitArray) - 1; $i >= 0; $i--) {\n        $currentResult = $digitArray[$i] * $number + $carry;\n        $digitArray[$i] = (int) ($currentResult % 10);\n        $carry = (int) ($currentResult / 10);\n    }\n\n    while($carry > 0) {\n        array_unshift($digitArray, (int) ($carry % 10));\n        $carry = (int) ($carry / 10);\n    }\n}\n\n// Test\n$number = 70;\necho \"Factorial of {$number} is: \" . factorial($number);\n\n//Output => Factorial of 70 is: 11978571669969891796072783721689098736458938142546425857555362864628009582789845319680000000000000000\n"
  },
  {
    "path": "Maths/Algebra/Factorial_of_Large_Number/Factorial_of_large_number.c",
    "content": "#include <stdio.h>\n\nunsigned int factorial(unsigned int n)\n{\n    int fact = 1, i;\n    for (i = 2; i <= n; i++)\n        fact *= i;\n    return fact;\n}\n\nint main()\n{\n    int num;\n    printf(\"Enter a non-negative number: \");\n    scanf(\"%d\",&num);\n    if(num<0){\n        printf(\"Factorial of a negative integer cannot be found\");\n    }\n    else{\n    printf(\"Factorial of %d is %d\", num , factorial(num));\n    }\n    return 0;\n}"
  },
  {
    "path": "Maths/Algebra/Factorial_of_Large_Number/README.md",
    "content": "## This folder is empty.\n"
  },
  {
    "path": "Maths/Algebra/Factorial_of_Large_Number/bigfactorial.cpp",
    "content": "#include<iostream> \nusing namespace std; \n#define MAX 500 \nint multiply(int x, int res[], int res_size); \nvoid factorial(int n) \n{ \n    int res[MAX]; \n    res[0] = 1; \n    int res_size = 1; \n    for (int x=2; x<=n; x++) \n        res_size = multiply(x, res, res_size); \n  \n    cout << \"Factorial of given number is \\n\"; \n    for (int i=res_size-1; i>=0; i--) \n        cout << res[i]; \n} \nint multiply(int x, int res[], int res_size) \n{ \n    int carry = 0;  // Initialize carry \n    for (int i=0; i<res_size; i++) \n    { \n        int prod = res[i] * x + carry;   \n        res[i] = prod % 10;    \n        carry  = prod/10;     \n    }  \n    while (carry) \n    { \n        res[res_size] = carry%10; \n        carry = carry/10; \n        res_size++; \n    } \n    return res_size; \n} \nint main() { \n    factorial(100); \n    return 0; \n} \n"
  },
  {
    "path": "Maths/Algebra/Factorial_of_Large_Number/largeFactorial.java",
    "content": "import java.util.*;\nimport java.math.BigInteger;\npublic class Main \n{\n   static  BigInteger facorial(BigInteger n)\n    {\n        if(n==BigInteger.valueOf(0))\n        return BigInteger.valueOf(1);\n        return n.multiply(facorial((n.subtract(BigInteger.valueOf(1)))));\n    }\n    public static void main(String[] args)\n    {\n        Scanner sc = new Scanner(System.in);\n        System.out.println(\"Enter a number \");\n        BigInteger n = BigInteger.valueOf(sc.nextInt());\n        System.out.println(\"The facorial of the number is \"+facorial(n));\n    }\n}\n\n/* \nExample - \nEnter a number \n30\nThe facorial of the number is 265252859812191058636308480000000\n*/\n\n\n"
  },
  {
    "path": "Maths/Algebra/GCD/EuclidGCD.swift",
    "content": "//\n//  EuclidGCD.swift\n//  Hacktoberfest\n//\n//  Created by Dipankar Goswami on 03/10/20.\n//\n\nimport Foundation\n\nfunc getGCD(input1: Int, input2: Int) -> Int {\n    \n    var bigger = max(input1, input2)\n    var smaller = min(input1, input2)\n\n    while smaller > 0 {\n        let rem = bigger % smaller\n        bigger = smaller;\n        smaller = rem\n    }\n\n    return bigger\n}\n\nvar number1 = Int(readLine()!)!\nvar number2 = Int(readLine()!)!\n\nlet res = getGCD(input1: number1, input2: number2)\nprint(\"GCD of \\(number1) and \\(number2) is \\(res)\")\n"
  },
  {
    "path": "Maths/Algebra/GCD/Euclidean_gcd.py",
    "content": "def euclideanGCD(x, y): \n\nwhile(y): \n\tx, y = y, x % y \n\nreturn x \n\na = 10\nb= 35\n\nprint (\"The gcd of 10 and 35 is : \",end=\"\") \nprint (euclideanGCD(10,35)) \n"
  },
  {
    "path": "Maths/Algebra/GCD/EuclidianGCD.py",
    "content": "def gcd(a, b):  \n    if a == 0 : \n        return b  \n      \n    return gcd(b%a, a)\n\t\t\na,b=map(int,input().split())\nprint(gcd(a,b))\n"
  },
  {
    "path": "Maths/Algebra/GCD/GCD.cpp",
    "content": "// Implementing Euclid algorithm to find GCD\n\n#include <bits/stdc++.h> \nusing namespace std; \n\n// Finding GCD using Euclid algorithm by recursion\nint gcd(int a, int b)\n{\n\tif (a == 0)\n\t{\n\t\treturn b;\n\t}\n\t\n\treturn gcd(b % a, a);\n}\n\n//main function\nint main()\n{\n\t// taking input the required two numbers\n\t// whose gcd is to be calculated\n\tint a, b;\n\tcin >> a >> b;\n\tcout << gcd(a, b);\n\treturn 0;\n}\n"
  },
  {
    "path": "Maths/Algebra/GCD/GCD.cs",
    "content": "using System;\npublic class Program\n{\n    static int GCD(int num1, int num2)\n    {\n        int Remainder;\n \n        while (num2 != 0)\n        {\n            Remainder = num1 % num2;\n            num1 = num2;\n            num2 = Remainder;\n        }\n \n        return num1;\n    }\n \n    static int Main(string[] args)\n    {\n        int x, y;\n        Console.Write(\"Enter the First Number : \");\n        x = int.Parse(Console.ReadLine());\n        Console.Write(\"Enter the Second Number : \");\n        y = int.Parse(Console.ReadLine());\n        Console.Write(\"\\nThe Greatest Common Divisor of \");\n        Console.WriteLine(\"{0} and {1} is {2}\", x, y, GCD(x, y));\n        Console.ReadLine();\n        return 0;\n    }\n}"
  },
  {
    "path": "Maths/Algebra/GCD/GCD.js",
    "content": "function gcd_two_numbers(x, y) {\n    // Check if number is numerial or not\n    if ((typeof x !== 'number') || (typeof y !== 'number'))\n        return false;\n    // Taking absolute values\n    x = Math.abs(x);\n    y = Math.abs(y);\n    // Calculating GCD\n    while (y) {\n        var t = y;\n        y = x % y;\n        x = t;\n    }\n    return x;\n}\n\n// Test Cases\nconsole.log(gcd_two_numbers(12, 13));\nconsole.log(gcd_two_numbers(9, 3));\n\n// Output : >\n// 1 \n// 3"
  },
  {
    "path": "Maths/Algebra/GCD/GCD.php",
    "content": "Here's my solution for getting the GCD of several numbers.\n\n<?php\n\n/*\n* function gcd()\n*\n* returns greatest common divisor\n* between two numbers\n* tested against gmp_gcd()\n*/\nfunction gcd($a, $b)\n{\n    if ($a == 0 || $b == 0)\n        return abs( max(abs($a), abs($b)) );\n       \n    $r = $a % $b;\n    return ($r != 0) ?\n        gcd($b, $r) :\n        abs($b);\n}\n\n/*\n* function gcd_array()\n*\n* gets greatest common divisor among\n* an array of numbers\n*/\nfunction gcd_array($array, $a = 0)\n{\n    $b = array_pop($array);\n    return ($b === null) ?\n        (int)$a :\n        gcd_array($array, gcd($a, $b));\n}\n\n?>\n"
  },
  {
    "path": "Maths/Algebra/GCD/GCD.py",
    "content": "# function\ndef euclid_gcd(a, b):\n    if b == 0:\n        print(a)\n        return a\n    c = a%b\n    euclid_gcd(b, c)\n\n\n# input 2 numbers with a space between them\na, b = map(int, input().split())\neuclid_gcd(min(a, b),max(a,b))\n"
  },
  {
    "path": "Maths/Algebra/GCD/GCD.rb",
    "content": "#!/usr/bin/env ruby -w\n\ndef gcd(num1, num2)\n  return num1 if num2 == 0\n\n  gcd(num2, num1 % num2)\nend\n\nnum1 = gets.chomp.to_i\nnum2 = gets.chomp.to_i\nputs gcd(num1, num2)"
  },
  {
    "path": "Maths/Algebra/GCD/GCD.sh",
    "content": "#!/bin/bash\necho \"Enter two numbers to find their GCD\"\nread a b\nx=$((a))\ny=$((b))\nwhile [ $a -ne $b ]\ndo\nif [ $a -gt $b ]\nthen \nlet \"a-=b\"\nelse\nlet \"b-=a\"\nfi\ndone \necho \"The GCD of \"$((x))\" and \"$((y))\" is =  \"$((a))\nexit\n"
  },
  {
    "path": "Maths/Algebra/GCD/README.md",
    "content": "## This folder is empty.\n"
  },
  {
    "path": "Maths/Algebra/GCD/gcd.java",
    "content": "import java.util.Scanner;\npublic class GCD\n{\n    public static void main(String args[])\n    {   \n                Scanner sc = new Scanner(System.in);\n                System.out.println(\"Please enter first number to find GCD\");\n                int n1 = sc.nextInt();\n                System.out.println(\"Please enter second number to find GCD\");\n                int n2 = sc.nextInt();\n              \n                System.out.println(\"GCD of two numbers \" + n1 +\" and \" \n                                   + n2 +\" is :\" + findGCD(n1,n2));\n              \n              \n    }\n        \n            /*\n             * Java method to find GCD of two number using Euclid's method\n             * @return GDC of two numbers in Java\n             */\n            private static int findGCD(int number1, int number2) \n            {\n                //base case\n                if(number2 == 0)\n                {\n                    return number1;\n                }\n                return findGCD(number2, number1%number2);\n            }\n          \n }\n    \n"
  },
  {
    "path": "Maths/Algebra/Inverse_of_a_Matrix/README.md",
    "content": "## This folder is empty.\n"
  },
  {
    "path": "Maths/Algebra/LCM/LCM.c",
    "content": "#include <stdio.h>\nint main() {\n    int n1, n2, max;\n    printf(\"Enter two positive integers: \");\n    scanf(\"%d %d\", &n1, &n2);\n\n    // maximum number between n1 and n2 is stored in min\n    max = (n1 > n2) ? n1 : n2;\n\n    while (1) {\n        if (max % n1 == 0 && max % n2 == 0) {\n            printf(\"The LCM of %d and %d is %d.\", n1, n2, max);\n            break;\n        }\n        ++max;\n    }\n    return 0;\n}\n"
  },
  {
    "path": "Maths/Algebra/LCM/LCM.cpp",
    "content": "#include <type_traits>\nnamespace algo_ds\n{\n    /*\n     * The implementation are kinda cryptic. I will try my best to explain what all the template stuff means\n     * First off, both lcm and gcd are function templates, taking `a` of type T and `b` of type U\n     * \n     * If both T and U are the same, the return type is gonna be just that, otherwise, std::common_type_t comes in.\n     * std::common_type_t does some hackery, and gives us a type both T and U are convertible to. If such a type\n     * doesn't exist... there's gonna be some template errors (although on clang 10.1 at least, they are pretty good)\n     * \n     * the noexcept basically means, that if T and U are primitives, i.e. [int, long, unsigned, char] etc., it is guaranteed\n     * the \"functions\" won't throw an exception\n     */\n\n\n    //implementation for a gcd function template in C++ 14\n    template<typename T, typename U>\n    [[nodiscard]] constexpr std::common_type_t<T, U> gcd(const T& a, const U& b) noexcept(std::is_integral<T>::value && std::is_integral<U>::value)\n    {\n        if (a == 0)\n        {\n          return b;\n        }\n        return gcd(b % a, a); \n    }\n    //implementation for a lcm function template in C++ 14\n    template<typename T, typename U>           \n    [[nodiscard]] constexpr std::common_type_t<T, U> lcm(const T& a, const U& b) noexcept(std::is_integral<T>::value && std::is_integral<U>::value)\n    {\n        return (a / gcd(a, b)) * b;\n    }\n}\n\n/**\n * Prints a nice table, the output should look like this:\n \n \n    Table of the least common multiples for the pairs in the range 1-9:\n    \n        1 |    2     3     4     5     6     7     8     9 \n    ______________________________________________________\n        2 |    2     6     4    10     6    14     8    18 \n        3 |    6     3    12    15     6    21    24     9 \n        4 |    4    12     4    20    12    28     8    36 \n        5 |   10    15    20     5    30    35    40    45 \n        6 |    6     6    12    30     6    42    24    18 \n        7 |   14    21    28    35    42     7    56    63 \n        8 |    8    24     8    40    24    56     8    72 \n        9 |   18     9    36    45    18    63    72     9 \n \n */ \n#include <iostream>\n#include <iomanip>\nint main()\n{\n    std::cout << \"Table of the least common multiples for the pairs in the range 1-9:\\n\\n\";\n    for(auto i = 1; i < 10; i++)\n    {\n        //Make the table look pretty by giving it a border\n        if(i == 2)\n        {\n            for(auto j = 0; j < 6*9; j++)\n            {\n                std::cout << '_';\n            }\n            std::cout << '\\n';\n        }\n        for(auto j = 1; j < 10; j++)\n        {\n            //setw() to align the numbers in the table\n            std::cout << std::setw(5) << algo_ds::lcm(i, j) << ' ';\n            if(j == 1) //again, making a border\n            {\n                std::cout << '|';\n            }\n        }\n        std::cout << '\\n';\n    }\n}\n"
  },
  {
    "path": "Maths/Algebra/LCM/LCM.java",
    "content": "// Java program to find LCM of two numbers.\nclass Test\n{\n\t\n\tstatic int gcd(int a, int b)\n\t{\n\t\tif (a == 0)\n\t\t\treturn b; \n\t\treturn gcd(b % a, a); \n\t}\n\t\n\t\n\tstatic int lcm(int a, int b)\n\t{\n\t\treturn (a / gcd(a, b)) * b;\n\t}\n\t\n\t\n\tpublic static void main(String[] args) \n\t{\n\t\tint a = 15, b = 20;\n\t\tSystem.out.println(\"LCM of \" + a +\n\t\t\t\t\t\t\" and \" + b + \n\t\t\t\t\t\" is \" + lcm(a, b));\n\t}\n}\n"
  },
  {
    "path": "Maths/Algebra/LCM/LCM.js",
    "content": "let lcm = (n1, n2) => {\n  //Find the smallest and biggest number from both the numbers\n  let lar = Math.max(n1, n2);\n  let small = Math.min(n1, n2);\n\n  //Loop till you find a number by adding the largest number which is divisble by the smallest number\n  let i = lar;\n  while (i % small !== 0) {\n    i += lar;\n  }\n\n  //return the number\n  return i;\n};\n\nconsole.log(lcm(12, 13));\nconsole.log(lcm(9, 3));\n"
  },
  {
    "path": "Maths/Algebra/LCM/LCM.py",
    "content": "def lcm(x:int, y:int) -> int:\n\t'''\n    Input: 2 integers x and y \n\n    Output: The smallest integer which is divisible by both x and y\n    '''\n    greater = max(x,y)\n\tlesser = min(x,y)\n\n\tmultiple = 1\n\twhile ((greater * multiple) % lesser != 0):\n    # I use <greater * multiple> instead of <lesser * multiple> because greater steps through the number line faster\n\t\tmultiple += 1\n\treturn greater * multiple\n\n\ndef main():\n    num1 = int(input())\n    num2 = int(input())\n    print(f\"LCM({num1}, {num2}) = {lcm(num1,num2)}\")\n\n\nif __name__ == \"__main__\":\n    main()"
  },
  {
    "path": "Maths/Algebra/LCM/LCM.sh",
    "content": "echo \"Enter any two numbers to find their LCM : \"\nread a b\nx=$((a))\ny=$((b))\nwhile [ $a -ne $b ]\ndo\nif [ $a -gt $b ]\nthen \nlet \"a-=b\"\nelse\nlet \"b-=a\"\nfi\ndone \nlcm=$(((x*y)/a))\necho \"LCM of \"$x\" and \"$y\" is = \"$lcm\n"
  },
  {
    "path": "Maths/Algebra/LCM/LCM_GCD.c",
    "content": "#include<stdio.h>\nint main()\n{\n    int x,y,gcd,lcm;\n    printf(\"Enter any two number to find LCM AND GCD:\");\n    scanf(\"%d%d\",&x,&y);\n    if(x>y)\n        z=x;\n    else\n    {\n        z=y;\n    }\n    for(gcd=z;gcd>=1;gcd--)\n    {\n        if(x%gcd==0 && y%gcd==0)\n        break;\n    }\n    printf(\"The Gcd of %d,%d = %d\",x,y,gcd);\n    lcm=(x*y)/gcd;\n    printf(\"The Lcm of %d, %d = %d\",x,y,lcm);\n    return 0;\n}"
  },
  {
    "path": "Maths/Algebra/LCM/LCM_python.py",
    "content": "def compute_gcd(x, y):\n\n    while(y):\n       x, y = y, x % y\n    return x\n\n\ndef compute_lcm(x, y):\n    lcm = (x*y)//compute_gcd(x,y)\n    return lcm\n\nnum1 = 54\nnum2 = 24 \n\nprint(\"The L.C.M. is\", compute_lcm(num1, num2))\n"
  },
  {
    "path": "Maths/Algebra/LCM/README.md",
    "content": "## This folder is empty.\n"
  },
  {
    "path": "Maths/Algebra/Markov_Matrix/MarkovMatrix.java",
    "content": "import java.util.Scanner;\n\npublic class MarkovMatrix{\n\n     public static void main(String []args){\n        Scanner sc = new Scanner(System.in);\n        int n = sc.nextInt();\n        int m = sc.nextInt();\n        double[][] markovMatrix = new double[n][m];\n        for (int i = 0; i < n; i++)\n        {\n            for (int j = 0; j < m; j++)\n            {\n                markovMatrix[i][j] = sc.nextDouble();\n            }\n        }\n        double rowSum = 0;\n        for (int i = 0; i < n; i++)\n        {\n            rowSum = 0;\n            for (int j = 0; j < m; j++)\n            {\n                rowSum += markovMatrix[i][j];\n            }\n            if (rowSum != 1) throw new RuntimeException(\"Row sum != 1\");\n        }\n        System.out.print (\"Input matrix is a Markov matrix\");\n     }\n}\n\n/*\n2 2 0.4 0.6 0.5 0.5 = Markov matrix\n2 2 0.1 0.1 1 1 = not a Markov matrix, results in error\n*/"
  },
  {
    "path": "Maths/Algebra/Markov_Matrix/Markov_Matrix.c++",
    "content": "#include <bits/stdc++.h> \nusing namespace std; \n\n  \nint main()  \n{ \n    int i ,j ,n,m;\n    cout << \"Enter Number of Rows and Columns :- \" << \"\\n\";\n    cin >> n >> m;\n    double Matrix[n][m]; \n    cout << \"Enter Matrix Elements :- \" << \"\\n\";\n    for (i = 0; i < n; i++)\n    {\n        for(j = 0 ; j < m;j++)\n            cin >> Matrix[i][j];\n    }\n    int flag = -1;\n    for(i = 0; i <n; i++) \n    { \n        double sum = 0; \n        for (j = 0; j < m; j++) \n            sum = sum + Matrix[i][j]; \n        if (sum != 1)\n        {\n            flag = 1;\n            break;\n        }        \n    }\n    \n    if (flag == 1) \n        cout << \"Not a Markov Matrix\" << \"\\n\"; \n    else\n        cout << \"Yes , It's a Markov Matrix\" << \"\\n\"; \n        \n} "
  },
  {
    "path": "Maths/Algebra/Markov_Matrix/Markov_Matrix.cs",
    "content": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\n//A Markov Matrix  is a matrix used to describe the transitions of a Markov chain.\n//Each of its entries is a nonnegative real number representing a probability between 0 and 1.\n//There are three possible types of the Markov Matrix:\n//A right stochastic matrix is a matrix with each row summing to 1.\n//A left stochastic matrix is a matrix with each column summing to 1.\n//A doubly stochastic matrix is a matrix with each row and column summing to 1.\n\n//NOTE: This solution will iterate the whole matrix three times. This can be terribly inefficient for large datasets.\n//There are ways to solve this with only one iteration over the matrix, but for the sake of better readability\n//this example is not optimized in that way.\n\npublic static class MarkovMatrix {\n    public static MatrixType Validate(decimal[,] matrix)\n    {\n        //At first, we check if any element is outside the defined range. If so, the input is not a Markov Matrix\n        if (ContainsInvalidElements(matrix))\n            return MatrixType.NotAMarkovMatrix;\n        \n        //Then we first check each row sum\n        var isRight = IsRightStochastic(matrix);\n        //Then we check each column sum\n        var isLeft = IsLeftStochastic(matrix);\n        \n        //Depending on the results of each check, we return the corresponding result\n        var result = (isLeft, isRight);\n        switch (result)\n        {\n            case (true, true):\n                return MatrixType.DoublyStochasticMatrix;\n            case (true, false):\n                return MatrixType.LeftStochasticMatrix;\n            case (false, true):\n                return MatrixType.RightStochasticMatrix;\n            case (false, false):\n                return MatrixType.NotAMarkovMatrix;\n        }\n    }\n\n    private static bool ContainsInvalidElements(decimal[,] matrix)\n    {\n        //check if any element of the matrix is either below 0 or above 1\n        return matrix.Cast<decimal>().Any(element => element > 1 || element < 0);\n    }\n    private static bool IsLeftStochastic(decimal[,] matrix)\n    {\n        //a left stochastic matrix has a sum of 1 for each column\n        //to check this, we iterate through each column and check the sum of it's elements\n        var columnCount = matrix.GetLength(1);\n        \n        for (var i = 0; i < columnCount; i++)\n        {\n            if (GetColumn(matrix, i).Sum() != 1) return false;\n        }\n\n        return true;\n    }\n    \n    private static bool IsRightStochastic(decimal[,] matrix)\n    {\n        //a right stochastic matrix has a sum of 1 for each row\n        //to check this, we iterate through each row and check the sum of it's elements\n        var rowCount = matrix.GetLength(0);\n\n        for (var i = 0; i < rowCount; i++)\n        {\n            if (GetRow(matrix, i).Sum() != 1) return false;\n        }\n\n        return true;\n    }\n\n    private static IEnumerable<decimal> GetRow(decimal[,] matrix, int rowIndex)\n    {\n        //Get a certain row inside the matrix: iterate through all columns with fixed row index\n        var columnCount = matrix.GetLength(1);\n        \n        for (var i = 0; i < columnCount; i++)\n        {\n            yield return matrix[rowIndex, i];\n        }\n    }\n    \n    private static IEnumerable<decimal> GetColumn(decimal[,] matrix, int columnIndex)\n    {\n        //Get a certain column inside the matrix: iterate through all rows with fixed column index\n        var rowCount = matrix.GetLength(0);\n        \n        for (var i = 0; i < rowCount; i++)\n        {\n            yield return matrix[i, columnIndex];\n        }\n    }\n}\n\npublic enum MatrixType\n{\n    NotAMarkovMatrix = 0,\n    RightStochasticMatrix = 1,\n    LeftStochasticMatrix = 2,\n    DoublyStochasticMatrix = 3\n}\n\n    \n//use dotnet-script to run this code\nConsole.WriteLine(\"Enter Matrix to check, line by line\");\nConsole.WriteLine(\"Columns are separated by single space character\");\nConsole.WriteLine(\"Empty string ends input and starts validation\");\n\nvar input = Console.ReadLine();\nvar numbersList = input.Split(' ').Select(i => decimal.Parse(i)).ToList();\nvar columns = numbersList.Count();\nvar rows = 1;\n\ninput = Console.ReadLine();\nwhile (!string.IsNullOrWhiteSpace(input))\n{\n    var row = input.Split(' ').Select(i => decimal.Parse(i)).ToList();\n    if (row.Count == columns)\n    {\n        numbersList.AddRange(row);\n        rows++;\n    }\n    else\n    {\n        Console.WriteLine(\"All rows must have the same amount of columns\");\n    }\n    input = Console.ReadLine();\n};\n\nvar matrix = ConvertToSquareArray(rows, columns, numbersList);\n\nConsole.WriteLine(MarkovMatrix.Validate(matrix));\n\nprivate static decimal[,] ConvertToSquareArray(int rows, int columns, List<decimal> numbers)\n{\n    var index = 0;\n    var rowIndex = 0;\n    var colIndex = 0;\n    var matrix = new decimal[rows, columns];\n    foreach (var number in numbers)\n    {\n        matrix.SetValue(number, rowIndex, colIndex);\n        index++;\n        rowIndex += 1;\n        rowIndex %= rows;\n        colIndex += 1;\n        colIndex %= columns;\n    }\n\n    return matrix;\n}\n    "
  },
  {
    "path": "Maths/Algebra/Markov_Matrix/Markov_Matrix.js",
    "content": "function isMarkovMatrix(matrix) {\n    let isRight = isRightMarkov(matrix)\n    let isLeft = isLeftMarkov(matrix)\n    if (isRight && isLeft) { //If the matrix is a right and left Markov algorithm -> doubly markov matrix\n        return 3\n    } else if (isLeft) { //If the matrix is a left markov algorithm\n        return 2\n    } else if (isRight) { //If the matrix is a right markov algorithm\n        return 1\n    } else { //If every test fails, then its not a Markov matrix\n        return 0\n    }\n}\n\nfunction isRightMarkov(matrix) { //Each row summing to 1\n    if (\n        matrix\n            .map(val => { //Get each row of the matrix and transform it to the\n                //sum of all the elements in each row \n                return val.reduce((prev, curr) => prev + curr)\n            })\n            .every(row => row == 1) //Check if every sum equals to 1\n    ) {\n        return true //If check is true\n    }\n    return false //If check is false\n}\n\nfunction isLeftMarkov(matrix) { //Each collumn summing to 1\n    let rot_matrix = matrix.map((val, index) => matrix.map(row => row[index])) //Rotates the matrix 90°\n\n    //When rotated, collumns become rows, so we can reuse the isRightMarkov function\n\n    return isRightMarkov(rot_matrix) //See if its a right markov matrix\n}\n\n//EXAMPLE INPUT\nlet example_matrix = [\n    [0.9, 0.1],   //Right markov matrix example\n    [0.5, 0.5],\n\n    /* [0.9, 0.5], //left markov matrix example\n    [0.1, 0.5],\n\n    [1, 0, 0,], //not markov matrix example\n    [0, 0, 2],\n    [0, 0, 1]\n\n    [1, 0, 0,], //doubly markov matrix example\n    [0, 1, 0],\n    [0, 0, 1] */\n]\n\n//EXAMPLE OUTPUT\nswitch (isMarkovMatrix(example_matrix)) {\n    case 3:\n        console.log(\"doubly markov matrix\")\n        break\n    case 2:\n        console.log(\"left markov matrix\")\n        break\n    case 1:\n        console.log(\"right markov matrix\")\n        break\n    case 0:\n        console.log(\"its not a markov matrix\")\n        break\n}"
  },
  {
    "path": "Maths/Algebra/Matrix_Multipication/MatMul.cpp",
    "content": "#include <vector>\n#include <array>\n#include <cstddef>\n#include <iostream>\n#include <exception>\n#include <string>\n\ntemplate<typename T> class Matrix {\n    std::vector<std::vector<T>> data;\npublic:\n\n    Matrix(std::vector<std::vector<T>> dataArray) {\n        data = dataArray;\n    }\n\n    Matrix(size_t row, size_t col) {\n        data = std::vector<std::vector < T >> (row, std::vector<T>(col, 0));\n        ;\n    }\n\n    T& operator[](std::array<size_t, 2> index) {\n        size_t row = index[0];\n        size_t column = index[1];\n        return data[row][column];\n    }\n\n    size_t rowCount() {\n        return data.size();\n    }\n\n    size_t columnCount() {\n        return data[0].size();\n    }\n\n    std::string toString() {\n        std::string r = \"{\";\n        for (size_t y = 0; y < rowCount(); y++) {\n            r += '{';\n            for (size_t x = 0; x < columnCount(); x++) {\n\n                r += std::to_string((*this)[{y, x}]);\n                if (x != columnCount() - 1)r += ',';\n            }\n            r+='}';\n            if (y != rowCount() - 1)r += ',';\n        }\n        r += '}';\n        return r;\n    }\n};\n\ntemplate<typename T>\nMatrix<T> operator*(Matrix<T> &a, Matrix<T> &b) {\n    if (a.columnCount() != b.rowCount()) throw std::invalid_argument(\"Must be multiplication between matrixes MxN and NxP\");\n    Matrix<T> r(a.rowCount(), b.columnCount());\n    int sharedVal = a.columnCount();\n    for (size_t i = 0; i < r.rowCount(); i++)\n        for (size_t j = 0; j < r.columnCount(); j++)\n            for (size_t n = 0; n < sharedVal; n++) {\n                r[{i, j}] += a[{i, n}] * b[{n, j}];\n            }\n    return r;\n}\n\nint main() {\n    int m, n, p;\n    std::cout << \"insert m, n, and p: \";\n    std::cout.flush();\n    std::cin >> m;\n    std::cin >> n;\n    std::cin >> p;\n    Matrix<float> a(m, n);\n    for (size_t y = 0; y < m; y++) {\n        for (size_t x = 0; x < n; x++) {\n            std::cout << \"a(\" << y << ',' << x << \"): \";\n            std::cout.flush();\n            std::cin >> a[{y, x}];\n        }\n    }\n    Matrix<float> b(n, p);\n    for (size_t y = 0; y < n; y++) {\n        for (size_t x = 0; x < p; x++) {\n            std::cout << \"b(\" << y << ',' << x << \"): \";\n            std::cout.flush();\n            std::cin >> b[{y, x}];\n        }\n    }\n    Matrix<float> r = a*b;\n    std::cout << \"a: \" << a.toString() << std::endl;\n    std::cout << \"b: \" << b.toString() << std::endl;\n    std::cout << \"r: \" << r.toString() << std::endl;\n}"
  },
  {
    "path": "Maths/Algebra/Matrix_Multipication/MatrixMultipication.py",
    "content": "def matrixMultiplication(matrixA, matrixB):\n    resultMatrix = []\n    sizeOfMatrixA = len(matrixA)\n    sizeOfMatrixB = len(matrixB)\n\n    for rowIndex in range(sizeOfMatrixA):\n        tempList = []\n\n        for columnIndex in range(sizeOfMatrixB):\n            sum = 0\n\n            for columnIndexMatrixA in range(len(matrixA[0])):\n                sum += matrixA[rowIndex][columnIndexMatrixA] * matrixB[columnIndexMatrixA][columnIndex]\n\n            tempList.append(sum)\n        resultMatrix.append(tempList)\n\n    return resultMatrix\n\n\nA = [[1, 2, 3],\n     [4, 5, 6],\n     [7, 8, 9]]\nB = [[9, 8, 7],\n     [6, 5, 4],\n     [3, 2, 1]]\nprint(matrixMultiplication(A, B))"
  },
  {
    "path": "Maths/Algebra/Matrix_Multipication/MatrixMultiply.java",
    "content": "import java.util.*;\r\n\r\npublic class MatrixMultiply {\r\n\r\n\tprivate static Scanner sc = new Scanner(System.in);\r\n\t\r\n\tpublic static void main(String[] args) {\r\n\t\t\r\n\t\t\r\n\t\tSystem.out.println(\"Enter the number of rows of 1st matrix\");\r\n\t\tint m = sc.nextInt();\r\n\t\tSystem.out.println(\"Enter the number of columns of 1st matrix\");\r\n\t\tint n = sc.nextInt();\r\n\t\tSystem.out.println(\"Enter the number of rows of 2nd matirx\");\r\n\t\tint p = sc.nextInt();\r\n\t\tSystem.out.println(\"Enter the number of columns of 2nd matrix\");\r\n\t\tint q = sc.nextInt();\r\n\t\t\r\n\t\tif(n!=p) {\r\n\t\t\tSystem.out.println(\"Sorry the matrix cannot be multiplied\");\r\n\t\t}else {\r\n\t\t\t\r\n\t\t\tint first[][] = new int[m][n];\r\n\t\t\tint second[][] = new int[p][q];\r\n\t\t\t\r\n\t\t\tSystem.out.println(\"Enter the elements of the 1st matrix\");\r\n\t\t\tfor(int i=0;i<m;i++) {\r\n\t\t\t\tfor (int j=0;j<n;j++) {\r\n\t\t\t\t\tfirst[i][j] = sc.nextInt();\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\tSystem.out.println(\"Enter the elements of the 2nd matrix\");\r\n\t\t\tfor(int i=0;i<p;i++) {\r\n\t\t\t\tfor(int j=0;j<q;j++) {\r\n\t\t\t\t\tsecond[i][j]=sc.nextInt();\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\tSystem.out.println(\"1st matrix\");\r\n\t\t\tfor(int i=0;i<m;i++) {\r\n\t\t\t\tfor(int j=0;j<n;j++) {\r\n\t\t\t\t\tSystem.out.print(first[i][j]+\" \");\r\n\t\t\t\t}\r\n\t\t\t\tSystem.out.println();\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\tSystem.out.println(\"2nd matrix\");\r\n\t\t\tfor(int i=0;i<p;i++) {\r\n\t\t\t\tfor(int j=0;j<q;j++) {\r\n\t\t\t\t\tSystem.out.print(second[i][j]+\" \");\r\n\t\t\t\t}\r\n\t\t\t\tSystem.out.println();\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\tint result[][]=new int[m][q];\r\n\t\t\t\r\n\t\t\t\r\n\t\t\tfor(int i=0;i<m;i++) {\r\n\t\t\t\tfor(int j=0;j<q;j++) {\r\n\t\t\t\t\tresult[i][j]=0;\r\n\t\t\t\t\tfor(int k=0;k<m;k++) {\r\n\t\t\t\t\t\tresult[i][j]+=first[i][k]*second[k][j];\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\t\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\tSystem.out.println(\"Result(1st matrix x 2nd matrix) :\");\r\n\t\t\tfor(int i=0;i<m;i++) {\r\n\t\t\t\tfor(int j=0;j<q;j++) {\r\n\t\t\t\t\tSystem.out.print(result[i][j]+\" \");\r\n\t\t\t\t}\r\n\t\t\t\tSystem.out.println();\r\n\t\t\t}\r\n\t\t\t\r\n\t\t}\r\n\t\t\r\n\t}\r\n}\r\n"
  },
  {
    "path": "Maths/Algebra/Matrix_Multipication/Matrix_Multiplication.js",
    "content": "function multiply(a, b) {\n\n    const aNumRows = a.length, aNumCols = a[0].length,\n        bNumRows = b.length, bNumCols = b[0].length,\n        m = new Array(aNumRows);  // initialize array of rows\n\n    for (let r = 0; r < aNumRows; ++r) {\n\n        m[r] = new Array(bNumCols); // initialize the current row\n\n        for (let c = 0; c < bNumCols; ++c) {\n          m[r][c] = 0;             // initialize the current cell\n          for (let i = 0; i < aNumCols; ++i) {\n            m[r][c] += a[r][i] * b[i][c];\n          }\n        }\n    }\n    return m;\n}\n\n\nfunction display(m) {\n  for (let r = 0; r < m.length; ++r) {\n    console.log('\\t'+m[r].join(' ')+'\\n');\n  }\n\n}\n\n\n\nconst a = [[8, 3, 4], [2, 4, 5], [3, 6, 2]],\n    b = [[1, 2, 3], [4, 6, 8], [3, 8, 1]];\n\n\nconsole.log('matrix a:\\n');\ndisplay(a);\nconsole.log('matrix b:\\n');\ndisplay(b);\nconsole.log('a * b =\\n');\ndisplay(multiply(a, b));"
  },
  {
    "path": "Maths/Algebra/Matrix_Multipication/README.md",
    "content": "## This folder is empty.\n"
  },
  {
    "path": "Maths/Algebra/Matrix_Multipication/multiply.c",
    "content": "#include<stdio.h>    \n#include<stdlib.h>  \n\n\nint main(){  \n  int a[10][10],b[10][10],mul[10][10],r,c,i,j,k;    \n  system(\"cls\");  \n\n  printf(\"enter the number of row=\");    \n  scanf(\"%d\",&r);    \n  printf(\"enter the number of column=\");    \n  scanf(\"%d\",&c);    \n  printf(\"enter the first matrix element=\\n\");    \n  \n  for(i=0;i<r;i++)    \n  {    \n    for(j=0;j<c;j++)    \n    {    \n      scanf(\"%d\",&a[i][j]);    \n    }    \n  }    \n  \n  printf(\"enter the second matrix element=\\n\");    \n  \n  for(i=0;i<r;i++)    \n  {    \n    for(j=0;j<c;j++)    \n    {    \n      scanf(\"%d\",&b[i][j]);    \n    }    \n  }    \n\n  printf(\"multiply of the matrix=\\n\");    \n  for(i=0;i<r;i++)    \n  {    \n    for(j=0;j<c;j++)    \n    {    \n      mul[i][j]=0;    \n      for(k=0;k<c;k++)    \n      {    \n        mul[i][j]+=a[i][k]*b[k][j];    \n      }    \n    }    \n  }    \n  \n  //for printing result    \n  for(i=0;i<r;i++)    \n  {    \n    for(j=0;j<c;j++)    \n    {    \n      printf(\"%d\\t\",mul[i][j]);    \n    }    \n    printf(\"\\n\");    \n  }    \n  return 0;  \n}  \n"
  },
  {
    "path": "Maths/Algebra/Matrix_Multipication/multiply.cpp",
    "content": "#include <iostream>  \nusing namespace std;  \nint main()  \n{  \n  int a[10][10],b[10][10],mul[10][10],r,c,i,j,k;    \n  cout<<\"enter the number of row=\";    \n  cin>>r;    \n  cout<<\"enter the number of column=\";    \n  cin>>c;    \n  cout<<\"enter the first matrix element=\\n\";    \n  \n  for(i=0;i<r;i++)    \n  {    \n    for(j=0;j<c;j++)    \n    {    \n      cin>>a[i][j];  \n    }    \n  }    \n  \n  cout<<\"enter the second matrix element=\\n\";    \n  for(i=0;i<r;i++)    \n  {    \n  for(j=0;j<c;j++)    \n    {    \n    cin>>b[i][j];    \n    }    \n  }    \n  \n  cout<<\"multiply of the matrix=\\n\";    \n  for(i=0;i<r;i++)    \n  {    \n    for(j=0;j<c;j++)    \n    {    \n      mul[i][j]=0;    \n      for(k=0;k<c;k++)    \n      {    \n        mul[i][j]+=a[i][k]*b[k][j];    \n      }    \n    }    \n  }    \n  \n  //for printing result    \n  for(i=0;i<r;i++)    \n  {    \n    for(j=0;j<c;j++)    \n    {    \n      cout<<mul[i][j]<<\" \";    \n    }    \n    cout<<\"\\n\";    \n  }    \n  return 0;  \n}    \n"
  },
  {
    "path": "Maths/Algebra/Matrix_Multipication/multiply.java",
    "content": "public class MatrixMultiplicationExample{  \npublic static void main(String args[]){  \n//creating two matrices    \nint a[][]={{1,1,1},{2,2,2},{3,3,3}};    \nint b[][]={{1,1,1},{2,2,2},{3,3,3}};    \n    \n//creating another matrix to store the multiplication of two matrices    \nint c[][]=new int[3][3];  //3 rows and 3 columns  \n    \n//multiplying and printing multiplication of 2 matrices    \nfor(int i=0;i<3;i++){    \n  for(int j=0;j<3;j++){    \n    c[i][j]=0;      \n    for(int k=0;k<3;k++)      \n      {      \n        c[i][j]+=a[i][k]*b[k][j];      \n      }//end of k loop  \n     System.out.print(c[i][j]+\" \");  //printing matrix element  \n     }//end of j loop  \n    System.out.println();//new line    \n   }    \n  }\n}  \n"
  },
  {
    "path": "Maths/Algebra/Matrix_Multipication/multiply.php",
    "content": "<?php \nfunction multiply(&$mat1, &$mat2, &$res) \n{ \n\t$N = 4; \n\tfor ($i = 0; $i < $N; $i++) \n\t{ \n\t\tfor ($j = 0; $j < $N; $j++) \n\t\t{ \n\t\t\t$res[$i][$j] = 0; \n\t\t\tfor ($k = 0; $k < $N; $k++) \n\t\t\t\t$res[$i][$j] += $mat1[$i][$k] * \n\t\t\t\t\t\t\t\t$mat2[$k][$j]; \n\t\t} \n\t} \n} \n\n// Driver Code \n$mat1 = array(array(1, 6, 5, 1), \n\t\t\tarray(2, 8, 2, 2), \n\t\t\tarray(3, 4, 3, 2), \n\t\t\tarray(8, 7, 9, 4)); \n\n$mat2 = array(array(1, 1, 1, 1), \n\t\t\tarray(2, 2, 2, 2), \n\t\t\tarray(3, 3, 3, 3), \n\t\t\tarray(4, 4, 4, 4)); \n\nmultiply($mat1, $mat2, $res); \n$N = 4; \necho (\"Result matrix is \\n\"); \nfor ($i = 0; $i < $N; $i++) \n{ \n\tfor ($j = 0; $j < $N; $j++) \n\t{ \n\t\techo ($res[$i][$j]); \n\t\techo(\" \"); \n\t} \n\t\n} \n?> \n"
  },
  {
    "path": "Maths/Algebra/Matrix_Multipication/multiply.py",
    "content": "matB = []\nmatA = []\n\nrows,columns = map(int,input(\"Enter rows and columns for matrices\").split())\n\nfor i in range(rows):\n    matA.append([])\n    for j in range(columns):\n        matA[i].append(int(input(f\"Enter a no. for matrixA[{i}][{j}] : \")))\n\nfor i in range(rows):\n    matB.append([])\n    for j in range(columns):\n        matB[i].append(int(input(f\"Enter a no. for matrixB[{i}][{j}] : \")))\n\nprint(\"------------------------------\\n  Matrix A is : \")        \nfor i in matA:\n    print(i)\n    \nprint(\"------------------------------\\n  Matrix B is : \")        \nfor i in matB:\n    print(i)\n\n\n\nmatM = []\nfor i in range(rows):\n    matM.append([])\n    for j in range(columns):\n        sum_of_column = 0\n        for k in range(rows):\n            sum_of_column += matA[i][k]*matB[k][i]\n        matM[i].append(sum_of_column)\n\nprint(\"------------------------------\\nMultiplication of the Matrix A and B is : \")  \nfor i in matM:\n    print(i)\n    \n    \n    \n#          OUTPUT\n#Enter rows and columns for matrices2 2\n#Enter a no. for matrixA[0][0] : 1\n#Enter a no. for matrixA[0][1] : 2\n#Enter a no. for matrixA[1][0] : 3\n#Enter a no. for matrixA[1][1] : 4\n#Enter a no. for matrixB[0][0] : 1\n#Enter a no. for matrixB[0][1] : 1\n#Enter a no. for matrixB[1][0] : 1\n#Enter a no. for matrixB[1][1] : 1\n#------------------------------\n#  Matrix A is : \n#[1, 2]\n#[3, 4]\n#------------------------------\n#  Matrix B is : \n#[1, 1]\n#[1, 1]\n#------------------------------\n#Multiplication of the Matrix A and B is : \n#[3, 3]\n#[7, 7]\n"
  },
  {
    "path": "Maths/Algebra/Permutation_And_Combination/Permutations_Combinations.ipynb",
    "content": "{\n  \"nbformat\": 4,\n  \"nbformat_minor\": 0,\n  \"metadata\": {\n    \"colab\": {\n      \"name\": \"Untitled3.ipynb\",\n      \"provenance\": []\n    },\n    \"kernelspec\": {\n      \"name\": \"python3\",\n      \"display_name\": \"Python 3\"\n    }\n  },\n  \"cells\": [\n    {\n      \"cell_type\": \"code\",\n      \"metadata\": {\n        \"id\": \"UPeL109N3trH\",\n        \"outputId\": \"d0555f7e-a5be-4fac-e437-57534267f35b\",\n        \"colab\": {\n          \"base_uri\": \"https://localhost:8080/\",\n          \"height\": 187\n        }\n      },\n      \"source\": [\n        \"#finding permutations of elements in a list\\n\",\n        \"from itertools import permutations\\n\",\n        \"n=int(input('enter no of elements'))\\n\",\n        \"list=[]\\n\",\n        \"for i in range (0,n):\\n\",\n        \"  a=int(input('enter number'))\\n\",\n        \"  list.append(a)\\n\",\n        \"seq=permutations(list)\\n\",\n        \"for p in seq:\\n\",\n        \"   print(p)\"\n      ],\n      \"execution_count\": 4,\n      \"outputs\": [\n        {\n          \"output_type\": \"stream\",\n          \"text\": [\n            \"enter no of elements3\\n\",\n            \"enter number1\\n\",\n            \"enter number2\\n\",\n            \"enter number3\\n\",\n            \"(1, 2, 3)\\n\",\n            \"(1, 3, 2)\\n\",\n            \"(2, 1, 3)\\n\",\n            \"(2, 3, 1)\\n\",\n            \"(3, 1, 2)\\n\",\n            \"(3, 2, 1)\\n\"\n          ],\n          \"name\": \"stdout\"\n        }\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"metadata\": {\n        \"id\": \"gDYpPS7I5Reo\",\n        \"outputId\": \"2707482d-92dc-472f-f8be-29a515d95bb1\",\n        \"colab\": {\n          \"base_uri\": \"https://localhost:8080/\",\n          \"height\": 119\n        }\n      },\n      \"source\": [\n        \"#Find the permutation by defining the length of the permutation.\\n\",\n        \"seq = permutations(list, 2)\\n\",\n        \"for p in seq:\\n\",\n        \"   print(p)\"\n      ],\n      \"execution_count\": 5,\n      \"outputs\": [\n        {\n          \"output_type\": \"stream\",\n          \"text\": [\n            \"(1, 2)\\n\",\n            \"(1, 3)\\n\",\n            \"(2, 1)\\n\",\n            \"(2, 3)\\n\",\n            \"(3, 1)\\n\",\n            \"(3, 2)\\n\"\n          ],\n          \"name\": \"stdout\"\n        }\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"metadata\": {\n        \"id\": \"V3wJrRPC5ujs\",\n        \"outputId\": \"4101b4de-0bfc-4da3-c8cf-b14e45820a4e\",\n        \"colab\": {\n          \"base_uri\": \"https://localhost:8080/\",\n          \"height\": 68\n        }\n      },\n      \"source\": [\n        \"from itertools import combinations\\n\",\n        \"#Getting all combination of a particular length.\\n\",\n        \"combi = combinations(list, 2)\\n\",\n        \"\\n\",\n        \"#Print the list of combinations\\n\",\n        \"\\n\",\n        \"for c in combi:\\n\",\n        \"   print(c)\"\n      ],\n      \"execution_count\": 7,\n      \"outputs\": [\n        {\n          \"output_type\": \"stream\",\n          \"text\": [\n            \"(1, 2)\\n\",\n            \"(1, 3)\\n\",\n            \"(2, 3)\\n\"\n          ],\n          \"name\": \"stdout\"\n        }\n      ]\n    }\n  ]\n}"
  },
  {
    "path": "Maths/Algebra/Permutation_And_Combination/README.md",
    "content": "## This folder is empty.\n"
  },
  {
    "path": "Maths/Algebra/Permutation_And_Combination/permutation_combination.cpp",
    "content": "#include<iostream>\nusing namespace std;\n\nlong long factorial( long long  num ){\n if( ( num == 0 ) || ( num == 1 )){\n    return num;\n }\n long long fact = 1;\n while( num > 0 ){\n    fact = fact * num;\n    num = num - 1;\n }\n return fact;\n}\n\nlong long permutation( long long n , long long r ){\n    return ( factorial( n ) / factorial( n - r ) );\n}\n\nlong long combination( long long n , long long r ){\n    return  ( factorial ( n ) / ( factorial ( r ) * factorial ( n - r )  ) );\n}\n\nint main(){\n long long selection = 0, n = 0 , r = 0;\n cout<<\"Press 1 for Permutaion  or Press 2 for Combination :\";\n cin >> selection;\n if( (selection != 1 ) && ( selection != 2 ) ){\n    cout <<\"<!-----Incorrect Option Selected-----!>\"<<\"\\n\";\n    return 1;\n }\n cout<<\"Enter the value of the places [n] and the number of objects [r] :\";\n cin >> n >> r;\n\n if( n < r ){\n    cout<<\"<!----Incorrect Value of [n] and [r] is inserted.----!>\\n\";\n    return 1;\n }\n\n if( selection == 1 ){\n cout <<\"Permutation :\"<<permutation( n , r)<<\"\\n\";\n }\n else if( selection == 2 ){\n cout <<\"Combination :\"<<combination( n , r)<<\"\\n\";\n }\n return 1;\n}\n"
  },
  {
    "path": "Maths/Algebra/Permutation_And_Combination/permutation_combination.js",
    "content": "/// this is a node js script to calcualate permuatations and combinations\n/// this is built by github.com/ahmeddrawy for hacktoberfest 2020 \n/// hope this helps you \n\n/// to run open terminal and run \n/// node <filename> [option 1] [option 2] [option 3]\n// example \"node permutation_combination.js c 100 40\"\n\n/// this is a self-invoked  function\n(function run(){\n   /// check if the input size is right node <filename> [option 1] [option 2] [option 3]\n   let inputSize = process.argv.length === 5 ;\n   /// validate first option to be <p> or <c>\n   let validateFirstInput = (process.argv[2]).toLowerCase() ==='p' || (process.argv[2]).toLowerCase() ==='c';  \n   /// validate that options 3 and 4 are not a not a number (this is a double negation lol :'D )  \n   let validateSecondAndThirdInput = !isNaN( process.argv[3])  && !isNaN( process.argv[4]);\n  \n   const permutationOrCombination = process.argv[2].toLowerCase();\n   const N = parseInt( process.argv[3]);\n   const R = parseInt( process.argv[4]);\n   let nGreaterthanR = N > R;\n   let greaterThanZero = N>0 && R > 0\n   /// the input must meet all above constraints anded together so if not we output the menu then return \n   if(!(inputSize && validateFirstInput  &&  validateSecondAndThirdInput  && nGreaterthanR && greaterThanZero)){\n      promoptForInput();\n      return ;\n   }\n   if(permutationOrCombination ==='p'){\n      console.log(`permutation ${N}P${R} =` , permutation(N,R));\n   }\n   else {\n      console.log(`Combination ${N}C${R} =` , permutation(N,R));\n\n   }\n})();\n/// this is the simplest implementation for nPr and nCr \n/// but not the most efficient one \n/// this is the first release so I will improve it in future if I have time\nfunction permutation(N , R){\n   return Factorial(N)/Factorial(N-R);\n}\nfunction permutation(N , R){\n   return Factorial(N)/Factorial(N-R);\n}\nfunction combination(N, R){\n   return Factorial(N)/(Factorial(N-R) * Factorial(R));\n   \n}\nfunction Factorial(N){\n   if(N<=1) return 1 ;  \n   return N* Factorial(N-1);\n}\n/// this function is a guide for input style\nfunction promoptForInput(){\n   console.log('this is a node js script to calcualate permuatations (nPr) and combinations (nCr)');\n   console.log('please provide options like this from ');\n   console.log('node <filename> [option 1] [option2] [option3]');\n   console.log('where\\n\\t[option 1] is P or C where P is for permutation and C is for Combination ');\n   console.log('\\t[option 2] is ( N ) where N is for nCr or nPr ');\n   console.log('\\t[option 3] is ( R ) where R is for nCr or nPr ');\n   console.log('Conditions :');\n   console.log('\\t N must be larger than R and both are larger than Zero');\n   console.log('Examples :');\n   console.log('\\tnode permutation_combination.js c 10 4');\n   console.log('\\tnode permutation_combination.js p 10 4');\n}"
  },
  {
    "path": "Maths/Algebra/Prime_Factorization/PrimeFactorisation.cpp",
    "content": "// Calculating Prime factors of a given number\n\n#include <bits/stdc++.h> \nusing namespace std; \n  \n// Function to find prime factors of a number num\nvoid PrimeFactorisation(int num)  \n{  \n    // first checking for 2\n    while (num % 2 == 0)  \n    {  \n        cout << 2 << \" \";  \n        num = num / 2;  \n    }  \n  \n    // now finding rest of prime factors\n    for (int i = 3; i <= sqrt(num); i += 2)  \n    {  \n        while (num % i == 0)  \n        {  \n            cout << i << \" \";  \n            num = num / i;  \n        }  \n    }  \n  \n    // If num != 1 then it itself is a prime number\n    if (num > 2)  \n        cout << num << \" \";  \n}  \n \n// main function\nint main()  \n{  \n    // taking input\n    int num;\n    cin >> num;\n    PrimeFactorisation(num);  \n    \n    return 0;  \n}"
  },
  {
    "path": "Maths/Algebra/Prime_Factorization/Prime_Factor.c",
    "content": "/* C Program to Find Prime Factors of a Number*/\n \n#include <stdio.h>\n \nint main()\n{\n  \tint i, j, Number, isPrime; \n   \n  \tprintf(\"\\n Please Enter any number to Find Factors :  \");\n  \tscanf(\"%d\", &Number);\n \n  \tfor (i = 2; i <= Number; i++)\n   \t{\n     \tif(Number % i == 0)\n        {\n   \t\t\tisPrime = 1;\n\t\t\tfor (j = 2; j <= i/2; j++)\n\t\t\t{\n\t\t\t\tif(i % j == 0)\n\t\t\t\t{\n\t\t\t\t\tisPrime = 0;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t} \n\t\t\tif(isPrime == 1)\n\t\t\t{\n\t\t\t\tprintf(\"\\n %d is a Prime Factor \", i);\n\t\t\t}\t          \t\n\t\t}\n   }\n  \treturn 0;\n}\n"
  },
  {
    "path": "Maths/Algebra/Prime_Factorization/Prime_Factorisation.cpp",
    "content": "#include <bits/stdc++.h> \nusing namespace std; \n\nvoid primeFactors(int n)  \n{  \n    // Print the number of 2s that divide n  \n    while (n % 2 == 0)  \n    {  \n        cout << 2 << \" \";  \n        n = n/2;  \n    }  \n\n    for (int i = 3; i <= sqrt(n); i = i + 2)  \n    {  \n        // While i divides n, print i and divide n  \n        while (n % i == 0)  \n        {  \n            cout << i << \" \";  \n            n = n/i;  \n        }  \n    }  \n  \n    if (n > 2)  \n        cout << n << \" \";  \n}  \n\nint main()  \n{  \n    int n = 315;  \n    primeFactors(n);  \n    return 0;  \n}  "
  },
  {
    "path": "Maths/Algebra/Prime_Factorization/Prime_Factorization.cs",
    "content": "using System;\n\nusing System.Collections.Generic;\n\nusing System.Text;\n\n \n\nnamespace SoftwareAndFinance\n\n{\n\n    class Math\n\n    {\n\n        const int MAX_SIZE = 15000;\n\n \n\n        static bool IsPrimeNumber(int num)\n\n        {\n\n            bool bPrime = true;\n\n            int factor = num / 2;\n\n \n\n            int i = 0;\n\n \n\n            for (i = 2; i <= factor; i++)\n\n            {\n\n                if ((num % i) == 0)\n\n                    bPrime = false;\n\n            }\n\n            return bPrime;\n\n        }\n\n \n\n        static public int GetPrimeFactors(int num, out int [] arrResult)\n\n        {\n\n            int count = 0;\n\n            int [] arr = new int[MAX_SIZE];\n\n            arrResult = new int[MAX_SIZE];\n\n            int i = 0;\n\n            int idx = 0;\n\n        \n\n            for(i = 2; i <= num; i++)\n\n            {\n\n                if(IsPrimeNumber(i) == true)\n\n                    arr[count++] = i;\n\n            }\n\n        \n\n            while(true)\n\n            {\n\n                if(IsPrimeNumber(num) == true)\n\n                {\n\n                    arrResult[idx++] = num;\n\n                    break;\n\n                }\n\n        \n\n                for(i = count - 1; i >= 0; i--)\n\n                {\n\n                    if( (num % arr[i]) == 0)\n\n                    {\n\n                        arrResult[idx++] = arr[i];\n\n                        num = num / arr[i];\n\n                        break;\n\n                    }\n\n                }\n\n            }\n\n            return idx;\n\n        }\n\n \n\n \n\n        static void Main(string[] args)\n\n        {\n\n           \n\n            int [] arrResult;\n\n            Console.Write(\"Enter a number to find prime factor: \");\n\n            int n = Convert.ToInt32(Console.ReadLine());\n\n            int count = GetPrimeFactors(n, out arrResult);\n\n            for (int i = 0; i < count; i++)\n\n            {\n\n                Console.Write(\"{0,4:n}\", arrResult[i]);\n\n                if (i != count - 1)\n\n                    Console.Write(\" * \");\n\n            }\n\n            Console.WriteLine();\n\n        }\n\n    }\n\n}"
  },
  {
    "path": "Maths/Algebra/Prime_Factorization/README.md",
    "content": "## This folder is empty.\n"
  },
  {
    "path": "Maths/Algebra/Prime_Factorization/prime-factorisation.js",
    "content": "/*Explanation=> The following code is to calculate all the prime factors of a desired number \"num\" \nSteps followed :-\n1. Took input num;\n2. Made a for loop to traverse through 2 to num and check the number completely divisible by num using (num%i ==0)\n3.Made another loop to see if the number is prime or not \n4.If prime then push it into the array and print out \n*/\n\n\nlet findPrimeFactors = (num) => {\n    let arr = [];\n\n\n    for ( var i = 2; i < num; i++) {\n        let isPrime\n        if (num % i === 0) {\n            isPrime = true;\n            for (var j = 2; j <= i; j++) {\n                if ( i % j === 0) {\n                isPrime == false;\n                }\n            } \n        }if (isPrime == true) { arr.push(i)}\n\n    }console.log(arr)\n}\n\nfindPrimeFactors(num);"
  },
  {
    "path": "Maths/Algebra/Prime_Factorization/prime.cpp",
    "content": "\n#include <iostream> \n#include<stdio.h>\nusing namespace std; \n  \nvoid PF(int n)  \n{  \n    // Print the number of 2s that divide n  \n    while (n % 2 == 0)  \n    {  \n        cout << 2 << \" \";  \n        n = n/2;  \n    }  \n  \n    // n must be odd at this point. So we can skip  \n    // one element (Note i = i +2)  \n    for (int i = 3; i <= sqrt(n); i = i + 2)  \n    {  \n        // While i divides n, print i and divide n  \n        while (n % i == 0)  \n        {  \n            cout << i << \" \";  \n            n = n/i;  \n        }  \n    }  \n  \n    // This condition is to handle the case when n  \n    // is a prime number greater than 2  \n    if (n > 2)  \n        cout << n << \" \";  \n}  \n  \n/* Driver code */\nint main()  \n{  \n    int n;\n    cout<<\"Enter a number\";\n    cin>>n;\n    PF(n);  \n    return 0;  \n}  \n  \n"
  },
  {
    "path": "Maths/Algebra/Prime_Factorization/prime_factorization.cpp",
    "content": "using namespace std;\n\nlong fac(long i)\n{\nif (i==0)\n{\nreturn (1);\n}\nelse\n{return (i*fac(i-1));}\n}\nint main()\n{\nint z;\ncout<<“enter number”;\ncin>>z;\ncout<<z<<\"!=\"<< fac (z);\n"
  },
  {
    "path": "Maths/Algebra/Prime_Factorization/prime_factorization.java",
    "content": "import java.util.*;\nimport java.lang.Math;\n\n/*\n sample input 1: 60\n sample output 1: \n Prime Factorization of 60 ->\n      60 = 2x2x3x5\n \n sample input 2: 297\n sample output 2:\n Prime Factorization of 297 ->\n      297 = 3x3x3x11\n \n sample input 3: 1024\n sample output 3:\n Prime Factorization of 1024 ->\n      1024 = 2x2x2x2x2x2x2x2x2x2\n \n sample input 4: 547\n sample output 4: \n Prime Factorization of 547 ->\n      547 = 547\n */\nclass prime_factorization{\n\n    // method for factorization.\n    private static void factorize(int n){\n\n        System.out.println(\"Prime Factorization of \"+n+\" -> \");\n\n        System.out.print(\"\\t \"+n+\" = \");\n\n        // any number can have atmost 1 prime factor greater than sqrt(n). \n        for(int i=2;i<=(int)Math.sqrt(n);i++){\n\n            // if n=1 exit the loop \n            if(n<2){\n                break;\n            }\n\n            // until n is divisible by i print i and divide n\n            while(n%i==0){\n                System.out.print(i);\n                n/=i;  \n                if(n>=2){\n                    System.out.print(\"x\");\n                }\n            }\n        }\n\n        if(n>2){\n            // prints the only prime factor that is greater than sqrt(n)\n            System.out.print(n);\n        }\n\n    }\n    public static void main(String[] args){\n        Scanner input = new Scanner(System.in);\n        int n; // input variable for which prime factors are to be generated\n        try{\n            n = input.nextInt();  // scanning for input\n            if(n>2){\n                factorize(n);  // passing parameter to 'factorize' method.\n            }\n            else{\n                System.out.println(n+\" cannot have any prime factors\");   // negative and numbers lesser than 2 are excluded\n            }\n        }catch(Exception e){\n            System.out.println(\"error: invalid input\\nValid input: Integers only\");  // handling execption for invalid or large input\n        }finally{\n            input.close();\n        }\n        \n    }\n}"
  },
  {
    "path": "Maths/Algebra/Prime_Factorization/prime_factorization.py",
    "content": "# Python program to print prime factors \n\nimport math\n\ndef primeFactors(n):\n\n        while n % 2 == 0:\n                print(\"2 \")\n                n = n / 2\n\n        for i in range(3,int(math.sqrt(n))+1,2):\n                while n % i== 0:\n                        print(i, \" \")\n                        n = n / i\n        if n > 2:\n                print(n,\" \")\n\nn = int(input())\nprimeFactors(n)\n"
  },
  {
    "path": "Maths/Algebra/Prime_Factorization/prime_factorization.ts",
    "content": "let findPrimeFactors = (num: number) => {\n    const arr: number[] = [];\n    for (let i: number = 2; i <= num; i++) {\n      while ((num % i) === 0) {\n        arr.push(i);\n        num /= i;\n      }\n  }\n  return arr;\n}\n\n\nfindPrimeFactors(777)\n"
  },
  {
    "path": "Maths/Algebra/Quadratic_Formula/Quadratic_Formula.cpp",
    "content": "#include <iostream>\n#include <cmath>\nusing namespace std;\n\nint main() {\n\n    float a, b, c, x1, x2, discriminant, realPart, imaginaryPart;\n    cout << \"Enter coefficients a, b and c: \";\n    cin >> a >> b >> c;\n    discriminant = b*b - 4*a*c;\n    \n    if (discriminant > 0) {\n        x1 = (-b + sqrt(discriminant)) / (2*a);\n        x2 = (-b - sqrt(discriminant)) / (2*a);\n        cout << \"Roots are real and different.\" << endl;\n        cout << \"x1 = \" << x1 << endl;\n        cout << \"x2 = \" << x2 << endl;\n    }\n    \n    else if (discriminant == 0) {\n        cout << \"Roots are real and same.\" << endl;\n        x1 = (-b + sqrt(discriminant)) / (2*a);\n        cout << \"x1 = x2 =\" << x1 << endl;\n    }\n\n    else {\n        realPart = -b/(2*a);\n        imaginaryPart =sqrt(-discriminant)/(2*a);\n        cout << \"Roots are complex and different.\"  << endl;\n        cout << \"x1 = \" << realPart << \"+\" << imaginaryPart << \"i\" << endl;\n        cout << \"x2 = \" << realPart << \"-\" << imaginaryPart << \"i\" << endl;\n    }\n\n    return 0;\n}\n"
  },
  {
    "path": "Maths/Algebra/Quadratic_Formula/Quadratic_Formula.hs",
    "content": "module Quadratic_Formula (csqrt, quadratic) where\n\nimport Data.Complex\n\ncsqrt z@(a :+ b) = let (mag, ph) = polar z in mkPolar (sqrt mag) (ph/2)\n\nquadratic a b c = (\n    quad (conjugate a) (conjugate b) (conjugate c) (+),\n    quad (conjugate a) (conjugate b) (conjugate c) (-)\n    ) where quad a b c op = (-b `op` csqrt ( b^2 - 4 * a * c))/(2 * a)\n"
  },
  {
    "path": "Maths/Algebra/Quadratic_Formula/Quadratic_Formula.sh",
    "content": "#!/bin/bash\necho \"Enter coefficients of a, b and c : \"\nread a b c\nd=$((b*b - (4*a*c))) \n\nif [ $d -gt 0 ]\nthen\ndisc=$(bc <<< \"scale=4;sqrt($d)\")\nx1=$(bc<<<\"scale=4;((((-$b + $disc)/(2*$a))))\")\nx2=$(bc<<<\"scale=4;((((-$b - $disc)/(2*$a))))\")\necho \"Roots are real and different\"\necho \" x1 = \" $x1\necho \" x2 = \" $x2\n\nelif [ $d -eq 0 ]\nthen\ndisc=$(bc <<< \"scale=4;sqrt($d)\")\nx1=$(bc<<<\"scale=4;(((((-$b + $disc)/(2*$a))))\")\necho \"Roots are real and equal\"\necho \" x1=x2= \"$x1\n\nelif [ $d -lt 0 ]\nthen\nlet \"d=-d\"\ndisc=$(bc<<<\"scale=4;sqrt($d)\")\nreal=$(bc<<<\"scale=4;((-$b/(2*$a)))\")\nimag=$(bc<<<\"scale=4;(($disc/(2*$a)))\")\necho \" x1 = \"$real \" + \"$imag \" i\"\necho \" x2 = \"$real \" - \"$imag \" i\"\nfi\n"
  },
  {
    "path": "Maths/Algebra/Quadratic_Formula/README.md",
    "content": "## This folder is empty.\n"
  },
  {
    "path": "Maths/Algebra/Quadratic_Formula/quadraticformula.py",
    "content": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sat Oct  3 03:34:46 2020\r\n\r\n@author: Erik\r\n\r\nQuadratic formula\r\n\"\"\"\r\nimport math as m\r\n\r\na = int(input(\"constant 'a' for x^2: \"))\r\n\r\nb = int(input(\"constant 'b' for x^1: \"))\r\n\r\nc = int(input(\"free constant 'c': \"))\r\n\r\nprint(\"the function is \", a, \"x^2 + \", b, \"x + \", c)\r\n#f = a*x^2 + b*x + c\r\n\r\nroot = (b**2) - (4*a*c)\r\nx1 = (-b + m.sqrt(root))/(2*a)\r\nx2 = (-b - m.sqrt(root))/(2*a)\r\n\r\nprint(\"x1 = \", x1, \". and x2 = \", x2)"
  },
  {
    "path": "Maths/Algebra/README.md",
    "content": "# This folder is empty.\n"
  },
  {
    "path": "Maths/Algebra/Sieve of Eratosthenes/SieveOfEratosthenes.cpp",
    "content": "#include <bits/stdc++.h> \nusing namespace std; \n#define mp make_pair\n#define pb push_back\n#define f first\n#define s second\n\nvoid Sieve(int n) \n{ \n    bool prime[n+1]; \n    memset(prime, true, sizeof(prime)); \n  \n    for (int p=2; p*p<=n; p++) \n    { \n        if (prime[p] == true) \n        { \n            \n            for (int i=p*p; i<=n; i += p) \n                prime[i] = false; \n        } \n    } \n    int c = 0;\n  \n    for (int p=2; p<=n; p++) \n    {\n        if (prime[p])\n            c++;\n    }\n\n    cout << \"Prime Numbers <= n:- \" << c << endl;\n}\nint main() \n{ \n    int N;\n    cout << \"Enter N :-\" << endl;\n    cin >> N;\n    Sieve(N);\n    return 0; \n} "
  },
  {
    "path": "Maths/Algebra/Sieve of Eratosthenes/SieveOfEratosthenes.py",
    "content": "import timeit\n\ndef Sieve(n):\n    prime = [True for i in range(n+1)]\n    p = 2\n    while (p * p <= n):\n        if (prime[p] == True):\n            for i in range(p*2,n+1,p):\n                prime[i] = False\n        p += 1\n    c = 0\n    for p in range(2,n):\n        if prime[p]:\n            print(p)\n            c += 1\n    return c\nt0 = timeit.default_timer()\nc = Sieve(100000)\nprint(\"Total prime numbers in range: \", c)\nt1 = timeit.default_timer()\nprint(\"Time required: \", t1-t0 )\n"
  },
  {
    "path": "Maths/Algebra/Sieve of Eratosthenes/SieveOfEratosthens.c",
    "content": "/*C program to print all prime number less than or equal to n using Sieve of Eratosthenes*/\n\n#include<stdio.h>\n#include<stdbool.h>\n\nvoid SieveOfEratosthenes(int num)\n{\n\t/*Boolean array to mark a number is prime or not*/\n\tbool prime[num+1];\n\tint i,j;\n\t\n\t/*Initialisation(Mark all number as prime)*/\n\tfor(i=0;i<=num;i++)\n\tprime[i]=true;\n\t\n\t/*Zero is not prime*/\n\tprime[0]=false;\n\t\n\t/*One is not prime*/\n\tprime[1]=false;\n\t\n\t/*Mark all non prime number as false*/\n\tfor(i=2;i<=num;i++){\n\t\tif(prime[i]==true){\n\t\t\tfor(j=i*i;j<=num;j+=i)\n\t\t\tprime[j]=false;\n\t\t}\n\t}\n\t/*Print all the prime numbers*/\n\tfor(i=2;i<=num;i++){\n\t\tif(prime[i]==true)\n\t\tprintf(\"%d \",i);\n\t}\n\tprintf(\"\\n\");\n}\n\nint main()\n{\n\tint num;\n\t/*Take input from the user*/\n\tscanf(\"%d\",&num);\n\t/*Prime number generation using Sieve of Eratosthenes*/\n\tSieveOfEratosthenes(num);\n\treturn 0;\n}\n"
  },
  {
    "path": "Maths/Algebra/Sieve of Eratosthenes/SieveofEratosthenes.java",
    "content": "/*\r\nThis is a Java program to find prime numbers up to a limit\r\nusing the Sieve of Eratosthenes approach.\r\n\r\nTime complexity: O(nlog(log n))\r\nSpace complexity: O(n)\r\n */\r\n\r\nimport java.util.*;\r\n\r\npublic class SieveofEratosthenes {\r\n    public static void main (String[] args)\r\n    {\r\n        Scanner scanner = new Scanner(System.in);\r\n        System.out.println(\"Enter a number:\");\r\n        int limit = scanner.nextInt();\r\n\r\n        if(limit < 2) {\r\n            System.out.println(String.format(\"There are no prime numbers up to %d\", limit));\r\n            return;\r\n        }\r\n\r\n        SieveofEratosthenes Sieve = new SieveofEratosthenes();\r\n        System.out.println(String.format(\"Prime numbers up to %d are:\", limit));\r\n        boolean[] isPrime = Sieve.getPrimes(limit);\r\n        Sieve.printPrimes(isPrime);\r\n    }\r\n\r\n    // Function to get the prime numbers up to the limit.\r\n    public boolean[] getPrimes(int limit) {\r\n        boolean[] isPrime = new boolean[limit + 1];\r\n\r\n        // Set all the values from 2 to max as primes.\r\n        for(int i = 2; i <= limit; i++) {\r\n            isPrime[i] = true;\r\n        }\r\n\r\n        for(int i = 2; i*i <= limit; i++) {\r\n\r\n            // If a value is already set as prime,\r\n            // mark its multiples as non-primes (composites).\r\n            if(isPrime[i]) {\r\n                for(int j = i*2; j <= limit; j += i) {\r\n                    isPrime[j] = false;\r\n                }\r\n            }\r\n        }\r\n        return isPrime;\r\n    }\r\n\r\n    // Function to print the obtained prime numbers.\r\n    public void printPrimes(boolean[] isPrime) {\r\n        for(int i = 2; i < isPrime.length; i++) {\r\n            if(isPrime[i]) {\r\n                System.out.println(i);\r\n            }\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "Maths/Algebra/Strassens_Algorithm/README.md",
    "content": "## This folder is empty.\n"
  },
  {
    "path": "Maths/Algebra/Strassens_Algorithm/Strassen.java",
    "content": "import java.util.Scanner;\nclass Strassen\n{\n    public int[][] multiply(int[][] A, int[][] B)\n    {        \n        int n = A.length;\n        int[][] R = new int[n][n];\n\n        if (n == 1)\n            R[0][0] = A[0][0] * B[0][0];\n        else\n        {\n            int[][] A11 = new int[n/2][n/2];\n            int[][] A12 = new int[n/2][n/2];\n            int[][] A21 = new int[n/2][n/2];\n            int[][] A22 = new int[n/2][n/2];\n            int[][] B11 = new int[n/2][n/2];\n            int[][] B12 = new int[n/2][n/2];\n            int[][] B21 = new int[n/2][n/2];\n            int[][] B22 = new int[n/2][n/2];\n \n            split(A, A11, 0 , 0);\n            split(A, A12, 0 , n/2);\n            split(A, A21, n/2, 0);\n            split(A, A22, n/2, n/2);\n \n            split(B, B11, 0 , 0);\n            split(B, B12, 0 , n/2);\n            split(B, B21, n/2, 0);\n            split(B, B22, n/2, n/2);\n \n            /** \n              M1 = (A11 + A22)(B11 + B22)\n              M2 = (A21 + A22) B11\n              M3 = A11 (B12 - B22)\n              M4 = A22 (B21 - B11)\n              M5 = (A11 + A12) B22\n              M6 = (A21 - A11) (B11 + B12)\n              M7 = (A12 - A22) (B21 + B22)\n            **/\n \n            int [][] M1 = multiply(add(A11, A22), add(B11, B22));\n            int [][] M2 = multiply(add(A21, A22), B11);\n            int [][] M3 = multiply(A11, sub(B12, B22));\n            int [][] M4 = multiply(A22, sub(B21, B11));\n            int [][] M5 = multiply(add(A11, A12), B22);\n            int [][] M6 = multiply(sub(A21, A11), add(B11, B12));\n            int [][] M7 = multiply(sub(A12, A22), add(B21, B22));\n \n\n              C11 = M1 + M4 - M5 + M7\n              C12 = M3 + M5\n              C21 = M2 + M4\n              C22 = M1 - M2 + M3 + M6\n \n            int [][] C11 = add(sub(add(M1, M4), M5), M7);\n            int [][] C12 = add(M3, M5);\n            int [][] C21 = add(M2, M4);\n            int [][] C22 = add(sub(add(M1, M3), M2), M6);\n \n            join(C11, R, 0 , 0);\n            join(C12, R, 0 , n/2);\n            join(C21, R, n/2, 0);\n            join(C22, R, n/2, n/2);\n        }\n\n        return R;\n    }\n\n    public int[][] sub(int[][] A, int[][] B)\n    {\n        int n = A.length;\n        int[][] C = new int[n][n];\n        for (int i = 0; i < n; i++)\n            for (int j = 0; j < n; j++)\n                C[i][j] = A[i][j] - B[i][j];\n        return C;\n    }\n    public int[][] add(int[][] A, int[][] B)\n    {\n        int n = A.length;\n        int[][] C = new int[n][n];\n        for (int i = 0; i < n; i++)\n            for (int j = 0; j < n; j++)\n                C[i][j] = A[i][j] + B[i][j];\n        return C;\n    }\n    public void split(int[][] P, int[][] C, int iB, int jB) \n    {\n        for(int i1 = 0, i2 = iB; i1 < C.length; i1++, i2++)\n            for(int j1 = 0, j2 = jB; j1 < C.length; j1++, j2++)\n                C[i1][j1] = P[i2][j2];\n    }\n    \n    public void join(int[][] C, int[][] P, int iB, int jB) \n    {\n        for(int i1 = 0, i2 = iB; i1 < C.length; i1++, i2++)\n            for(int j1 = 0, j2 = jB; j1 < C.length; j1++, j2++)\n                P[i2][j2] = C[i1][j1];\n    }    \n    \n    public static void main (String[] args) \n    {\n        Scanner scan = new Scanner(System.in);\n        System.out.println(\"Strassen Multiplication Algorithm Test\\n\");\n    \n        Strassen s = new Strassen();\n \n        System.out.println(\"Enter order n :\");\n        int N = scan.nextInt();\n \n        System.out.println(\"Enter N order matrix 1\\n\");\n        int[][] A = new int[N][N];\n        for (int i = 0; i < N; i++)\n            for (int j = 0; j < N; j++)\n                A[i][j] = scan.nextInt();\n \n        System.out.println(\"Enter N order matrix 2\\n\");\n        int[][] B = new int[N][N];\n        for (int i = 0; i < N; i++)\n            for (int j = 0; j < N; j++)\n                B[i][j] = scan.nextInt();\n \n        int[][] C = s.multiply(A, B);\n \n        System.out.println(\"\\nProduct of matrices A and  B : \");\n        for (int i = 0; i < N; i++)\n        {\n            for (int j = 0; j < N; j++)\n                System.out.print(C[i][j] +\" \");\n            System.out.println();\n        }\n \n    }\n}"
  },
  {
    "path": "Maths/Algebra/Strassens_Algorithm/Strassens_Algorithm.c++",
    "content": "#include <bits/stdc++.h>\nusing namespace std;\n\nint** initializeMatrix(int n) {\n    int** temp = new int*[n];\n    for(int i=0; i<n; i++)\n        temp[i] = new int[n];\n    return temp;\n}\n\nvoid input(int** M, int n) {\n    cout << \"Enter matrix: \" << endl;\n    for(int i=0; i<n; i++)\n        for(int j=0; j<n; j++)\n            cin >> M[i][j];\n    cout << endl;\n}\n\nvoid printMatrix(int** M, int n) {\n    for(int i=0; i<n; i++) {\n        for(int j=0; j<n; j++)\n            cout << M[i][j] << \" \";\n        cout << endl;\n    }\n    cout << endl;\n}\n\nint** add(int** M1, int** M2, int n) {\n    int** temp = initializeMatrix(n);\n    for(int i=0; i<n; i++)\n        for(int j=0; j<n; j++)\n            temp[i][j] = M1[i][j] + M2[i][j];\n    return temp;\n}\n\nint** subtract(int** M1, int** M2, int n) {\n    int** temp = initializeMatrix(n);\n    for(int i=0; i<n; i++)\n        for(int j=0; j<n; j++)\n            temp[i][j] = M1[i][j] - M2[i][j];\n    return temp;\n}\n\nint** strassenMultiply(int** A, int** B, int n) {\n    if (n == 1) {\n        int** C = initializeMatrix(1);\n        C[0][0] = A[0][0] * B[0][0];\n        return C;\n    }\n    int** C = initializeMatrix(n);\n    int k = n/2;\n\n    int** A11 = initializeMatrix(k);\n    int** A12 = initializeMatrix(k);\n    int** A21 = initializeMatrix(k);\n    int** A22 = initializeMatrix(k);\n    int** B11 = initializeMatrix(k);\n    int** B12 = initializeMatrix(k);\n    int** B21 = initializeMatrix(k);\n    int** B22 = initializeMatrix(k);\n\n    for(int i=0; i<k; i++)\n        for(int j=0; j<k; j++) {\n            A11[i][j] = A[i][j];\n            A12[i][j] = A[i][k+j];\n            A21[i][j] = A[k+i][j];\n            A22[i][j] = A[k+i][k+j];\n            B11[i][j] = B[i][j];\n            B12[i][j] = B[i][k+j];\n            B21[i][j] = B[k+i][j];\n            B22[i][j] = B[k+i][k+j];\n        }\n\n    int** P1 = strassenMultiply(A11, subtract(B12, B22, k), k);\n    int** P2 = strassenMultiply(add(A11, A12, k), B22, k);\n    int** P3 = strassenMultiply(add(A21, A22, k), B11, k);\n    int** P4 = strassenMultiply(A22, subtract(B21, B11, k), k);\n    int** P5 = strassenMultiply(add(A11, A22, k), add(B11, B22, k), k);\n    int** P6 = strassenMultiply(subtract(A12, A22, k), add(B21, B22, k), k);\n    int** P7 = strassenMultiply(subtract(A11, A21, k), add(B11, B12, k), k);\n\n    int** C11 = subtract(add(add(P5, P4, k), P6, k), P2, k);\n    int** C12 = add(P1, P2, k);\n    int** C21 = add(P3, P4, k);\n    int** C22 = subtract(subtract(add(P5, P1, k), P3, k), P7, k);\n\n    for(int i=0; i<k; i++)\n        for(int j=0; j<k; j++) {\n            C[i][j] = C11[i][j];\n            C[i][j+k] = C12[i][j];\n            C[k+i][j] = C21[i][j];\n            C[k+i][k+j] = C22[i][j];\n        }\n\n    for(int i=0; i<k; i++)\n        delete[] A11[i];\n    delete[] A11;\n\n    for(int i=0; i<k; i++)\n        delete[] A12[i];\n    delete[] A12;\n\n    for(int i=0; i<k; i++)\n        delete[] A21[i];\n    delete[] A21;\n\n    for(int i=0; i<k; i++)\n        delete[] A22[i];\n    delete[] A22;\n\n    for(int i=0; i<k; i++)\n        delete[] B11[i];\n    delete[] B11;\n\n    for(int i=0; i<k; i++)\n        delete[] B12[i];\n    delete[] B12;\n\n    for(int i=0; i<k; i++)\n        delete[] B21[i];\n    delete[] B21;\n\n    for(int i=0; i<k; i++)\n        delete[] B22[i];\n    delete[] B22;\n\n    for(int i=0; i<k; i++)\n        delete[] P1[i];\n    delete[] P1;\n\n    for(int i=0; i<k; i++)\n        delete[] P2[i];\n    delete[] P2;\n\n    for(int i=0; i<k; i++)\n        delete[] P3[i];\n    delete[] P3;\n\n    for(int i=0; i<k; i++)\n        delete[] P4[i];\n    delete[] P4;\n\n    for(int i=0; i<k; i++)\n        delete[] P5[i];\n    delete[] P5;\n\n    for(int i=0; i<k; i++)\n        delete[] P6[i];\n    delete[] P6;\n\n    for(int i=0; i<k; i++)\n        delete[] P7[i];\n    delete[] P7;\n\n    for(int i=0; i<k; i++)\n        delete[] C11[i];\n    delete[] C11;\n\n    for(int i=0; i<k; i++)\n        delete[] C12[i];\n    delete[] C12;\n\n    for(int i=0; i<k; i++)\n        delete[] C21[i];\n    delete[] C21;\n\n    for(int i=0; i<k; i++)\n        delete[] C22[i];\n    delete[] C22;\n\n    return C;\n}\n\nint main() {\n    cout << \"Strassen's Matrix Multiplication Algorithm\\n\" <<\n    \"only works on square matrices whose dimension is a power of 2.\\n\" <<\n    \"So, please enter a valid dimension(size) of matrix.\" << endl;\n    cout << \"Enter size of the matrix: \";\n    int n;\n    cin >> n;\n\n    int** A = initializeMatrix(n);\n    int** B = initializeMatrix(n);\n    input(A, n);\n    cout << \"Matrix A:\" << endl;\n    printMatrix(A,n);\n    input(B, n);\n    cout << \"Matrix B:\" << endl;\n    printMatrix(B, n);\n\n    int** C = initializeMatrix(n);\n    C = strassenMultiply(A, B, n);\n    cout << \"Multipliction result:\" << endl;\n    printMatrix(C, n);\n\n    for(int i=0; i<n; i++)\n        delete[] A[i];\n    delete[] A;\n\n    for(int i=0; i<n; i++)\n        delete[] B[i];\n    delete[] B;\n\n    for(int i=0; i<n; i++)\n        delete[] C[i];\n    delete[] C;\n\n    return 0;\n}"
  },
  {
    "path": "Maths/Algebra/Strassens_Algorithm/strassens.py",
    "content": "import numpy as np \n  \ndef split(matrix): \n    row, col = matrix.shape \n    row2, col2 = row//2, col//2\n    return matrix[:row2, :col2], matrix[:row2, col2:], matrix[row2:, :col2], matrix[row2:, col2:] \n  \ndef strassen(x, y): \n    if len(x) == 1: \n        return x * y \n    a, b, c, d = split(x) \n    e, f, g, h = split(y) \n    p1 = strassen(a, f - h)   \n    p2 = strassen(a + b, h)         \n    p3 = strassen(c + d, e)         \n    p4 = strassen(d, g - e)         \n    p5 = strassen(a + d, e + h)         \n    p6 = strassen(b - d, g + h)   \n    p7 = strassen(a - c, e + f)   \n\n    c11 = p5 + p4 - p2 + p6   \n    c12 = p1 + p2            \n    c21 = p3 + p4             \n    c22 = p1 + p5 - p3 - p7  \n    c = np.vstack((np.hstack((c11, c12)), np.hstack((c21, c22))))  \n  \n    return c \n\na=np.array([[1,2],[3,4]])\nb=np.array([[1,2],[3,4]])\nprint(strassen(a,b))\n"
  },
  {
    "path": "Maths/Algebra/Taylor-Expansion/README.md",
    "content": "## This folder is empty.\n"
  },
  {
    "path": "Maths/Algebra/Vertex_Formula/README.md",
    "content": "## This folder is empty.\n"
  },
  {
    "path": "Maths/Calculus/Euler_Approximation/Euler_Approximation.c",
    "content": "#include<stdio.h>\r\n#include<stdlib.h>\r\n\r\nfloat fun(float x, float y)\r\n{\r\n    float f;\r\n    f = x + y;\r\n    return f;\r\n}\r\n\r\nint main()\r\n{\r\n    //input x0, y0, h, t\r\n    //basic formula implementation is required.\r\n    float a, b, x, y, h, t, k;\r\n\r\n    printf(\"\\nEnter x0, y0, h, xn: \");\r\n    scanf(\"%f%f%f%f\", &a, &b, &h, &t);\r\n    printf(\"\\n\");\r\n\r\n    x = a;\r\n    y = b;\r\n    printf(\"\\nX and Y respectively are: \\n\");\r\n\r\n    //basic formula implementation\r\n    while (x <= t)\r\n    {\r\n        k = h * fun(x, y);\r\n        y = y + k;\r\n        x = x + h;\r\n        printf(\"%0.3f, %0.3f\\n\", x, y);\r\n    }\r\n}"
  },
  {
    "path": "Maths/Calculus/Euler_Approximation/Euler_Approximation.cpp",
    "content": "/* CPP  Program to find approximation \n   of a ordinary differential equation \n   using euler method.*/\n#include <iostream> \nusing namespace std; \n  \n// Consider a differential equation \n// dy/dx=(x + y + xy) \nfloat func(float x, float y) \n{ \n    return (x + y + x * y); \n} \n  \n// Function for Euler formula \nvoid euler(float x0, float y, float h, float x) \n{ \n    float temp = -0; \n  \n    // Iterating till the point at which we \n    // need approximation \n    while (x0 < x) { \n        temp = y; \n        y = y + h * func(x0, y); \n        x0 = x0 + h; \n    } \n  \n    // Printing approximation \n    cout << \"Approximate solution at x = \"\n         << x << \"  is  \" << y << endl; \n} \n  \n// Driver program \nint main() \n{ \n    // Initial Values \n    float x0; \n    float y0; \n    float h;\n    cin>>x0>>y0>>h;\n  \n    // Value of x at which we need approximation \n    float x ;\n    cin>>x;\n  \n    euler(x0, y0, h, x); \n    return 0; \n} \n"
  },
  {
    "path": "Maths/Calculus/Euler_Approximation/Euler_Approximation.java",
    "content": "\r\npublic class Euler_Approximation {\r\n\r\n\r\n    /**\r\n     * Represents dy/dx. Change this function to your desired differential equation\r\n     * @return dy/dx evaluated at the coordinate (x, y)\r\n     */\r\n    public static double function(double x, double y) {\r\n        return (x + y);\r\n    }\r\n\r\n\r\n    /**\r\n     * Uses Euler's method to approximate a point.\r\n     * @param xInitial initial coniditon for the X value\r\n     * @param yInitial initial coniditon for the Y value\r\n     * @param xApprox value to approximate\r\n     * @param steps number of steps to use for the appromixation. Used to determine step size.\r\n     * @return approximation of f(xApprox)\r\n     * @see #function(double, double)\r\n     */\r\n    public static double approximate(final double xInitial, final double yInitial, double xApprox, int steps) {\r\n        // find step size\r\n        // (b - a) / n\r\n        final double stepSize = (xApprox - xInitial) / (double)steps;\r\n\r\n        // check track of the X and Y coordinates\r\n        double prevX = xInitial;\r\n        double prevY = yInitial;\r\n\r\n        // iterate until we meet our end coordinate\r\n        for(int i = 0; i < steps; i++) {\r\n            // apply Euler's method\r\n            // f(x) = f(prevY) + stepSize * dy/dx(prevX, prevY)\r\n            prevY = prevY + stepSize * function(prevX, prevY);\r\n            prevX += stepSize;\r\n        }\r\n\r\n        return prevY;\r\n    }\r\n\r\n    public static void main(String[] args) {\r\n        \r\n        // approximates f(2) given dy/dx = x + y; y(-1) = 1\r\n        //  using 6 equal subdivisions\r\n        System.out.println(approximate(-1, 1, 2, 6));\r\n    }\r\n\r\n}"
  },
  {
    "path": "Maths/Calculus/Euler_Approximation/Euler_Approximation.py",
    "content": "# Python Code to find approximation \r\n# of a ordinary differential equation \r\n# using euler method. \r\n  \r\n# Consider a differential equation \r\n# dy / dx =(2x + 3y + 4xy) \r\ndef func( x, y ): \r\n    return (2 * x + 3 * y + 4 * x * y) \r\n      \r\ndef euler( x0, y, h, x ): \r\n  \r\n    # Iterating till the point at which we \r\n    # need approximation \r\n    while x0 < x: \r\n        temp = y \r\n        y = y + h * func(x0, y) \r\n        x0 = x0 + h \r\n    \r\n  \r\n    print(\"Approximate solution at x = \", x, \" is \", \"%.6f\"% y) \r\n      \r\n# Initial Values \r\nx0 = float(input(\"Enter value of x0:- \"))\r\ny0 = float(input(\"Enter value oy y0:- \"))\r\nh = float(input(\"Enter step size:- \"))\r\n  \r\n# Value of x at which we need approximation \r\nx = float(input(\"Enter value of x at which you want to approximate:- \"))\r\n  \r\neuler(x0, y0, h, x) "
  },
  {
    "path": "Maths/Calculus/Euler_Approximation/README.md",
    "content": "## This folder is empty.\n"
  },
  {
    "path": "Maths/Calculus/Leibniz_formula/LeibnizFormula.py",
    "content": "from sympy import *\nfrom math import comb\n'''\nrequirements \n    - pip install sympy\n'''\n\n\ndef leibniz_formula(u, v, n: int):\n    '''\n    Compute the nth order derivative of the product of two functions u and v\n\n    Parameters\n    ----------\n    u : function\n        function with one variable - x\n    v : function\n        function with one variable - x\n    n : integer\n        the order of the derivative to be computed\n\n    Returns\n    -------\n    function\n        nth order derivative of the product of u and v computed \n        using leibniz formula\n    '''\n\n    x = symbols('x')\n    f = 0\n    for i in range(n+1):\n        f += comb(n, i) * diff(u, x, n-i) * diff(v, x, i)\n    return simplify(f)\n\n\nx = symbols('x')\n\n# examples\n\n# 1\nu = exp(x)\nv = sin(x)\nn = 4\nf = leibniz_formula(u, v, n)\nprint(f\"The {n}th order derivative of {u}*{v} is : {f}\")\n\n# 2\nu = x\nv = log(x)\nn = 10\nf = leibniz_formula(u, v, n)\nprint(f\"The {n}th order derivative of {u}*{v} is : {f}\")\n"
  },
  {
    "path": "Maths/Calculus/Leibniz_formula/Leibniz_Formula.java",
    "content": "public class Leibniz_formula {\n   public static void main(String[] args) {\n \n      int count = 999999999;\n      double pi = 0;\n      double denominator = 1;\n \n      for (int x = 0; x < count; x++) {\n \n         if (x % 2 == 0) {\n            pi = pi + (1 / denominator);\n         } else {\n            pi = pi - (1 / denominator);\n         }\n         denominator = denominator + 2;\n      }\n      pi = pi * 4;\n      System.out.println(pi);\n   }\n}"
  },
  {
    "path": "Maths/Calculus/Leibniz_formula/Leibniz_formula.cpp",
    "content": "#include <iostream>\n#include <cmath>\nusing namespace std;\nint main()\n{\n    int n;\n    double sum = 0;\n\n    cout.precision(12);\n    cout << \"Enter an n number of iterations: \" << endl;\n    cin >> n;\n    cout << \"Pi estimated at \" << n << \" iterations is: \" << endl;\n\n    int i = 0;\n    while (i < n)\n    {\n        cout << i << \" \";\n        i++;\n        sum = sum + 4 * (pow(-1.0, i) / ((2.0 * i) + 1));\n        cout << sum << endl;\n        cout << endl;\n    }\n    cout.precision(12);\n    cout << sum << endl;\n    cout << \"The value of pi to \" << n << \" iterations is \" << sum << endl;\n    cout << \"cmath library estimates Pi at \" << M_PI << endl;\n    return 0;\n"
  },
  {
    "path": "Maths/Calculus/Leibniz_formula/README.md",
    "content": "## This folder is empty.\n"
  },
  {
    "path": "Maths/Calculus/Probability_Density_Functions/README.md",
    "content": "## This folder is empty.\n"
  },
  {
    "path": "Maths/Calculus/README.md",
    "content": "# This folder is empty.\n"
  },
  {
    "path": "Maths/Calculus/Riemann_Sum/README.md",
    "content": "## This folder is empty.\n"
  },
  {
    "path": "Maths/Calculus/Riemann_Sum/Riemann.py",
    "content": "from math import sin, pi\n\ndef Rsum(a,b):\n\n    for i in range(1001):\n        s = 0.0\n        delx = float(b-a)/1000.0\n        g = i*delx\n        h = (i+1.0)*delx\n\n        y_i = float(sin(a+g))\n        y_ii = float(sin(a+h))\n        s += 1.0/2.0 * (y_i + y_ii) * delx\n        #s += 1/2 * (sin(a+i*delx) + sin(a+(i+1)*delx)) * delx\n\n    return s\n\nprint Rsum(0,pi)\n"
  },
  {
    "path": "Maths/Calculus/Riemann_Sum/Riemann_Sum.cpp",
    "content": "#include<stdio.h>\n#include<math.h>\n\ndouble F1(double x,double a){\n    double f1=0.0;\n    f1=(sqrt(a-pow(x,2)));\n    return f1;\n}\n\nint main(){\n    double a=0.0,p=0.0,q=0.0,h=0.0,x=0.0,err=0;\n    int func=3,n=2;\n    double power=0.0,T=0.0;\n    double sum=0.0,last=0.0,difference=1.0;\n\n    scanf(\"%d\",&func);\n\n    while(func!=0){\n        n=2;\n        scanf(\"%lf%lf%lf%lf\",&a,&p,&q,&err);\n        power=pow(10.0,-err);\n        h=(q-p)/n;\n\n        if(func==1){\n            difference=1.0;\n            while(difference>=power){\n                h=(q-p)/n;\n                sum=0.0;\n                for(x=p+h;x<=q-h;x++){\n                    sum+=(2*F1(x,a));\n                }\n                T=(h/2)*(F1(p,a)+F1(q,a)+sum);\n                if(difference==1.0){\n                    difference=T;\n                }else{\n                    difference=last-T;\n                }\n                last=T;\n                n++;\n                }\n        }\n    printf(\"%.5lf\\n\",T);\n    scanf(\"%d\",&func);\n    }\nreturn 0;\n}\n"
  },
  {
    "path": "Maths/Calculus/Riemann_Sum/Riemann_Sum.cs",
    "content": "using System;\n\ninternal interface IFunction\n{\n    float CalculateFx(float x);\n}\n\ninternal class XPowerN : IFunction\n{\n    private float n = 0;\n\n    public XPowerN(float n)\n    {\n        this.n = n;\n    }\n\n    public float CalculateFx(float x)\n    {\n        return MathF.Pow(x, n);\n    }\n\n    public override string ToString()\n    {\n        return $\"y = x^{n}\";\n    }\n}\n\ninternal class AsinNX : IFunction\n{\n    private float a = 0;\n    private float n = 0;\n\n    public AsinNX(float a, float n)\n    {\n        this.a = a;\n        this.n = n;\n    }\n\n    public float CalculateFx(float x)\n    {\n        return a * MathF.Sin(n * x);\n    }\n\n    public override string ToString()\n    {\n        return $\"y = {a} * sin {n}x\";\n    }\n}\n\ninternal class AcosNX : IFunction\n{\n    private float a = 0;\n    private float n = 0;\n\n    public AcosNX(float a, float n)\n    {\n        this.a = a;\n        this.n = n;\n    }\n\n    public float CalculateFx(float x)\n    {\n        return a * MathF.Cos(n * x);\n    }\n\n    public override string ToString()\n    {\n        return $\"y = {a} * cos {n}x\";\n    }\n}\n\ninternal class AtanNX : IFunction\n{\n    private float a = 0;\n    private float n = 0;\n\n    public AtanNX(float a, float n)\n    {\n        this.a = a;\n        this.n = n;\n    }\n\n    public float CalculateFx(float x)\n    {\n        return a * MathF.Tan(n * x);\n    }\n\n    public override string ToString()\n    {\n        return $\"y = {a} * tan {n}x\";\n    }\n}\n\npublic class Riemann_Sum\n{\n    public static void Main(string[] args)\n    {\n        do\n        {\n            IFunction function;\n            Console.Clear();\n            Console.WriteLine(\"Select the desired function: \");\n            Console.WriteLine(\"1. y = x^n\");\n            Console.WriteLine(\"2. y = A * sin nx\");\n            Console.WriteLine(\"3. y = A * cos nx\");\n            Console.WriteLine(\"4. y = A * tan nx\");\n\n            Console.Write(\"\\nPick a function: \");\n            float tempA;\n            switch (Convert.ToInt32(Console.ReadLine()))\n            {\n                // TODO: finish\n                case 1:\n                    Console.Write(\"Enter a value for n: \");\n                    function = new XPowerN(Convert.ToSingle(Console.ReadLine()));\n                    break;\n                case 2:\n                    Console.Write(\"Enter a value for A: \");\n                    tempA = Convert.ToInt32(Console.ReadLine());\n                    Console.Write(\"Enter a value for n: \");\n                    function = new AsinNX(tempA, Convert.ToSingle(Console.ReadLine()));\n                    break;\n                case 3:\n                    Console.Write(\"Enter a value for A: \");\n                    tempA = Convert.ToInt32(Console.ReadLine());\n                    Console.Write(\"Enter a value for n: \");\n                    function = new AcosNX(tempA, Convert.ToSingle(Console.ReadLine()));\n                    break;\n                case 4:\n                    Console.Write(\"Enter a value for A: \");\n                    tempA = Convert.ToInt32(Console.ReadLine());\n                    Console.Write(\"Enter a value for n: \");\n                    function = new AtanNX(tempA, Convert.ToSingle(Console.ReadLine()));\n                    break;\n                default:\n                    continue;\n            }\n\n            // Enter bounds of the evaluation. Note that lower must be less than upper\n            Console.Write(\"Enter the lower limit of the evaluation: \");\n            float lower = Convert.ToSingle(Console.ReadLine());\n\n            Console.Write(\"Enter the upper limit of the evaluation: \");\n            float upper = Convert.ToSingle(Console.ReadLine());\n\n            // must be non-zero\n            Console.Write(\"Enter the resolution of the Riemann approximation: \");\n            uint resolution = Convert.ToUInt32(Console.ReadLine());\n\n            Console.WriteLine();\n            EvaluateRiemannSumLeft(function, lower, upper, resolution);\n            EvaluateRiemannSumRight(function, lower, upper, resolution);\n            EvaluateRiemannSumTrapezoid(function, lower, upper, resolution);\n            break;\n        } while (true);\n    }\n\n    private static void EvaluateRiemannSumLeft(\n        IFunction function,\n        in float lowerLimit,\n        in float upperLimit,\n        in uint resolution)\n    {\n        float riemannSum = 0f;\n        float xIncrement = (upperLimit - lowerLimit) / resolution;\n        for (int i = 0; i < resolution; ++i)\n        {\n            float x = lowerLimit + xIncrement * i;\n            float height = function.CalculateFx(x);\n            riemannSum += xIncrement * height;\n        }\n\n        Console.WriteLine($\"The Left  Riemann sum of {function} between {lowerLimit} and {upperLimit} is {riemannSum}.\");\n    }\n\n    private static void EvaluateRiemannSumRight(\n        IFunction function,\n        in float lowerLimit,\n        in float upperLimit,\n        in uint resolution)\n    {\n        float riemannSum = 0f;\n        float xIncrement = (upperLimit - lowerLimit) / resolution;\n        for (int i = 1; i <= resolution; ++i)\n        {\n            float x = lowerLimit + xIncrement * i;\n            float height = function.CalculateFx(x);\n            riemannSum += xIncrement * height;\n        }\n        Console.WriteLine($\"The Right Riemann sum of {function} between {lowerLimit} and {upperLimit} is {riemannSum}.\");\n    }\n\n    private static void EvaluateRiemannSumTrapezoid(\n        IFunction function,\n        in float lowerLimit,\n        in float upperLimit,\n        in uint resolution)\n    {\n        float riemannSum = 0f;\n        float xIncrement = (upperLimit - lowerLimit) / resolution;\n        for (int i = 0; i < resolution; ++i)\n        {\n            float x = lowerLimit + xIncrement * i;\n            float leftValue = function.CalculateFx(x);\n            float rightValue = function.CalculateFx(x + xIncrement);\n\n            if (leftValue < rightValue)    // leftValue is lower, section is increasing\n            {\n                // adding area of smallest rect\n                riemannSum += xIncrement * leftValue;\n\n                // adding triangle area\n                riemannSum += 0.5f * xIncrement * (rightValue - leftValue);\n            }\n            else                           // rightValue is lower, section is decreasing\n            {\n                // adding area of smallest rect\n                riemannSum += xIncrement * rightValue;\n\n                // adding triangle area\n                riemannSum += xIncrement * (leftValue - rightValue);\n            }\n\n\n        }\n\n        Console.WriteLine($\"The Trapezoid Riemann sum of {function} between {lowerLimit} and {upperLimit} is {riemannSum}.\");\n    }\n}\n"
  },
  {
    "path": "Maths/Calculus/Riemann_Sum/riemann_sum.py",
    "content": "import numpy as np\n\n\ndef riemann_sum(f, a, b, N: int, method='midpoint'):\n    '''\n    Compute the Riemann sum of f(x) over the interval [a,b].\n\n    Parameters\n    ----------\n    f : function\n        Vectorized function of one variable\n    a , b : numbers\n        Endpoints of the interval [a,b]\n    N : integer\n        Number of subintervals of equal length in the partition of [a,b]\n    method : string\n        Determines the kind of Riemann sum:\n        right : Riemann sum using right endpoints\n        left : Riemann sum using left endpoints\n        midpoint (default) : Riemann sum using midpoints\n\n    Returns\n    -------\n    float\n        Approximation of the integral given by the Riemann sum.\n    '''\n    dx = (b - a)/N\n    x = np.linspace(a, b, N+1)\n\n    # left riemann sum\n    if method == 'left':\n        x_left = x[:-1]\n        return np.sum(f(x_left)*dx)\n\n    # right reimann sum\n    elif method == 'right':\n        x_right = x[1:]\n        return np.sum(f(x_right)*dx)\n\n    # midpoint reimann sum\n    elif method == 'midpoint':\n        x_mid = (x[:-1] + x[1:])/2\n        return np.sum(f(x_mid)*dx)\n    else:\n        raise ValueError(\"Method must be 'left', 'right' or 'midpoint'.\")\n\n\n# example problems\n\n# 1\nf = np.sin\nr_sum = riemann_sum(f, 0, np.pi/2, 100)\nright_r_sum = riemann_sum(f, 0, np.pi/2, 100, 'right')\nleft_r_sum = riemann_sum(f, 0, np.pi/2, 100, 'left')\nprint(f\"\"\"Sin(x) in the interval [0,pi/2] partition with 100 sub-intervals\nLeft Riemann Sum: {left_r_sum}\nMidpoint Riemann Sum: {r_sum}\nRight Riemann Sum: {right_r_sum}\"\"\")\n\n\n# 2\nf = lambda x : 1 / (1 + x**2)\nr_sum = riemann_sum(f, 0, 5, 10)\nright_r_sum = riemann_sum(f, 0, 5, 10, 'right')\nleft_r_sum = riemann_sum(f, 0, 5, 10, 'left')\nprint(f\"\"\"\n1/(1+x^2) in the interval [0,5] partition with 10 sub-intervals\nLeft Riemann Sum: {left_r_sum}\nMidpoint Riemann Sum: {r_sum}\nRight Riemann Sum: {right_r_sum}\"\"\")\n"
  },
  {
    "path": "Maths/Calculus/Runge–Kutta_Method/Range-Kutta.c",
    "content": "#include<math.h>\nint compare_float(float x, float y)\n{\n\tfloat val=0.0001f;\n   if(fabs(x - y) < val)\n      return 1; //they are same\n      return 0; //they are not same\n}\n// for the equation 2xy +e^x/x^2+x*e^x\nfloat equation(float x,float y)\n{\n\tfloat val=0;\n\tval=(2*x*y+pow(2.71828,x))/(pow(x,2)+x*pow(2.71828,x));\n\treturn(val);\n}\nfloat next(float x,float y,float h)\n{\n\tfloat k[4];\n\tk[0]=h*equation(x,y);\n\tk[1]=h*equation(x+0.5*h,y+0.5*k[0]);\n\tk[2]=h*equation(x+0.5*h,y+0.5*k[1]);\n\tk[3]=h*equation(x+h,y+k[2]);\n\tk[0]=(k[0]+2*k[1]+2*k[2]+k[3])/6;\n\ty=y+k[0];\n\treturn(y);\n}\nint main()\n{\n\tfloat xg,yg,yf,xgf,h;\n\tprintf(\"Enter the given X value: \");\n\tscanf(\"%f\",&xg);\n\tprintf(\"Enter corresponding Y value: \");\n\tscanf(\"%f\",&yg);\n\tprintf(\"Enter the X value which value have to be find: \");\n\tscanf(\"%f\",&xgf);\n\tprintf(\"Enter the h value : \");\n\tscanf(\"%f\",&h);\n\twhile(1)\n\t{\n\t\tyg=next(xg,yg,h);\n\t\txg=xg+h;\n\t\tif(compare_float(xg,xgf))\n\t\t{\n\t\t\tbreak;\n\t\t}\n\t}\n\tprintf(\"The value of y(%f) is : %f\",xgf,yg);\n}\n"
  },
  {
    "path": "Maths/Calculus/Runge–Kutta_Method/Runge-Kutta.cpp",
    "content": "#include <math.h> \n#include <iostream>\n#include <iomanip>\n\nusing namespace std;\n/*======================================================================*/\n/*===================== Runge-Kutta Method for ODE =====================*/\n/*======================================================================*/\n\n\n\n//getting dx/dt \nstatic double dx_dt(double t, double x)\n{\n    return tan(x) + 1;\n}\n\n//Formula used :\n//Yn+1 = Yn  + 1/6 *(k1+2*k2+2*k3+k4) :: let interval = h  \n//where k1=dx/dt(Xn,Yn)  ,k2=dx/dt((Xn+ h/2 ,Yn+k1/2 ),k3=dx/dt((Xn+ h/2 ,Yn+k2/2 ) and k4=dx/dt((Xn+ h ,Yn+k3 )\n\n//Instead of dx/dt we can also use other differential function\n\n\nvoid calculate_Y(double &initial_X, double final_X,double interval ,double &y ){\n\n    int n = static_cast<int>((final_X - initial_X) /interval);\n\n        for (int i = 0; i < n; i++)\n        {\n            double k1 = dx_dt(initial_X, y);\n            double k2 = dx_dt(initial_X + interval / 2.0, y + interval*k1 / 2.0);\n            double k3 = dx_dt(initial_X + interval/ 2.0, y + interval*k2 / 2.0);\n            double k4 = dx_dt(initial_X + interval, y + interval*k3);\n\n            y += (k1 + 2 * k2 + 2 * k3 + k4) * interval / 6.0;\n\n            //cout << initial_X << \": \" << y << endl;\n\n            initial_X += interval;\n        }\n}\n\nint main(int argc, const char * argv[])\n{\n   \n    cout<<\"Press 1 for giving Your own input and 2 for default example\"<<endl;\n    int option;\n    cin>>option;\n\n    cout << setprecision(16);\n    double initial_X = 1.0; \n    double final_X = 1.1;\n\n    double y = 1.0;\n    double h = 0.025;\n    if(option == 1){\n        cout<<\" Enter Initial value of X i.e X0 \"<<endl;\n        cin>>initial_X;\n        cout<<\" Final Value of X \"<<endl;\n        cin>>final_X;\n        cout<<\" Enter Initial value of Y i.e Y0 \"<<endl;\n        cin>>y;\n        cout<<\" Enter Interval \"<<endl;\n        cin>>h;\n\n        calculate_Y(initial_X,final_X,h,y);\n\n\n\n\n    }else if(option ==2){\n\n   \n    \n    \n    cout<<\" For the example The values taken are :\"<<endl;\n    cout<<\" X0  :\"<<initial_X<<endl;\n    cout<<\" Xn  :\"<<final_X<<endl;\n    cout<<\" Y0  :\"<<y<<endl;\n    cout<<\" interval i.e h :\"<<h<<endl;\n    calculate_Y(initial_X,final_X,h,y);\n    \n\n    \n    }else{\n        cout<<\"You chose wrong option \"<<endl;\n    }\n\n   \n  \n    cout << \"----------------------------------------------\\n\";\n    cout<<\" By calculating using Runge-Kutta method  \"<<endl;\n    cout << \"Xn =  \" << initial_X << \",  Y =  \" << y << endl;\n\n    getchar();\n}"
  },
  {
    "path": "Maths/Calculus/Runge–Kutta_Method/Runge-Kutta.py",
    "content": "import numpy as np\n\n\ndef dydx(x, y):\n    return 2*x + np.sin( x * y )\n\n\nx0 = float(input(\"Enter value of x0:- \"))\ny0 = float(input(\"Enter value oy y0:- \"))\nh = float(input(\"Enter step size:- \"))\nn = int(input(\"Enter number of points.\"))\n\ny_vec = np.zeros((n, 1))\ny_vec[0] = y0\nx_vec = np.zeros((n, 1))\nx_vec[0] = x0\nfor i in range(n-1):\n    xi, yi = x_vec[i], y_vec[i]\n    k1 = dydx(xi, yi)\n    k2 = dydx(xi + h/2, yi + h*k1/2)\n    k3 = dydx(xi + h/2, yi + h*k2/2)\n    k4 = dydx(xi + h, yi + k3)\n    x_vec[i+1] = xi + h\n    y_vec[i+1] = yi + h / 6 * (k1 + 2*k2 + 2*k3 + k4)\n\nprint(\"--- Results ---\")\nprint(\"x    |   y\")\nprint(np.array([x_vec, y_vec]).T)\n"
  },
  {
    "path": "Maths/Discrete/Ackermann_Peter/Ackermann_Peter.c",
    "content": "#include <stdio.h>\nint ackermann_peter(int m, int n)\n{\n    if (m == 0){\n        return n+1;\n    }\n    else if((m > 0) && (n == 0)){\n        return ackermann_peter(m-1, 1);\n    }\n    else if((m > 0) && (n > 0)){\n        return ackermann_peter(m-1, ackermann_peter(m, n-1));\n    }\n}\n\nint main(){\n    //accept values\n    int ackermann_result, num1, num2;\n    scanf(\"%d %d\", &num1, &num2);\n\n    //compute the result and print it\n    ackermann_result = ackermann_peter(num1, num2);\n    printf(\"%d\", ackermann_result);\n    return 0;\n}\n"
  },
  {
    "path": "Maths/Discrete/Ackermann_Peter/Ackermann_Peter.cpp",
    "content": "#include <iostream>\nusing namespace std;\nint A(int, int);\nint main()\n{\n        int m=NULL, n=0, count=0;\n\t\t\n\t\twhile(count<=7)\n\t\t{\n\t\t\tcout<<A(m,n);\n\t\t\t\n\t\t\tcount++;\t\n\t\t};\n        return 0;\n}\nint A(int m,int n)\n{\tif(n==1 && m==0)\n\t{\n\t\tm+=1;\n\t}\n    if (m==0)\n\t{\n\t  cout<<\"A(\"<<m<<\",\"<<n<<\")\";\n      return n+1;\n\t}\n    else if (n==0)\n\t{\n\t\tcout<<\"A(\"<<m<<\",\"<<n<<\")\";\n       return A(m-1,1);\n\t}\n\telse\n\t{\n\t\tcout<<\"A(\"<<m<<\",\"<<n<<\")\";\n       return A(m-1, A(m,n-1));\n\t}\n}\n"
  },
  {
    "path": "Maths/Discrete/Ackermann_Peter/Ackermann_Peter.js",
    "content": "function ackermann_peter(m, n){\n    if(m===0){\n        return n+1\n    }else if (n===0){\n        return ackermann_peter(m-1, 1)\n    }else{\n        return ackermann_peter(m - 1, ackermann_peter(m, n-1))\n    }\n}\n\n//Example\nlet result = ackermann_peter(1, 2)\n// this should return 4\n"
  },
  {
    "path": "Maths/Discrete/Ackermann_Peter/Ackermann_Peter.py",
    "content": "def ackermann_peter_10(m, n):\n    assert isinstance(m, int) and m >= 0, 'm is unacceptable'\n    assert isinstance(n, int) and n >= 0, 'n is unacceptable'\n    stack = []\n    while True:\n        if not m:\n            if not stack:\n                return n + 1\n            m, n = stack.pop(), n + 1\n        elif not n:\n            m, n = m - 1, 1\n        else:\n            stack.append(m - 1)\n            n -= 1\n"
  },
  {
    "path": "Maths/Discrete/Ackermann_Peter/Python/ackermann.py",
    "content": "def ackermann(m,n):\n     if m == 0:\n          return (n + 1)\n     elif n == 0:\n          return ackermann(m - 1, 1)\n     else:\n          return ackermann(m - 1, ackermann(m, n - 1)) \n\n#Example\n# ackermann(2, 1) --> 5\n# ackermann(2, 2) --> 7"
  },
  {
    "path": "Maths/Discrete/Ackermann_Peter/README.md",
    "content": "## DISCRETE MATHEMATICS\nDiscrete mathematics is a branch of mathematics wherein we study about discrete or disconnected objects.\nThe tools and techniques of DM make you fall in love with beauty of mathematics and computer science.\n\n## Topics coming under Discrete Mathematics\n1. Number Theory and Cryptography\n2. Induction and Recursion \n3. Counting\n4. Discrete Probability\n5. Advanced counting techniques\n6. Relations\n7. Graphs\n8. Trees \n9. Boolean Algebra\n10. Modeling Computation\n\n## Books Recommended\nDiscrete Mathematics and Its Applications by Kenneth H. Rosen \nYou can easily find on the internet.\n\nAll the best!!\n"
  },
  {
    "path": "Maths/Discrete/README.md",
    "content": "## DISCRETE MATHEMATICS\nDiscrete mathematics is a branch of mathematics wherein we study about discrete or disconnected objects.\nThe tools and techniques of DM make you fall in love with beauty of mathematics and computer science.\n\n## Topics coming under Discrete Mathematics\n1. Number Theory and Cryptography\n2. Induction and Recursion \n3. Counting\n4. Discrete Probability\n5. Advanced counting techniques\n6. Relations\n7. Graphs\n8. Trees \n9. Boolean Algebra\n10. Modeling Computation\n\n## Books Recommended\nDiscrete Mathematics and Its Applications by Kenneth H. Rosen \nYou can easily find on the internet.\n\nAll the best!!\n"
  },
  {
    "path": "Maths/Geometry/Clock_Angle/ClockAngle.cs",
    "content": "﻿using System;\r\n\r\nnamespace clock_angle\r\n{\r\n    class ClockAngle\r\n    {\r\n        static void Main(string[] args)\r\n        {\r\n\t    Console.WriteLine(\"Enter hours:\");\r\n            int hours = Convert.ToInt32(Console.ReadLine());\r\n\t    Console.WriteLine(\"Enter minutes:\");\r\n            int minutes = Convert.ToInt32(Console.ReadLine());\r\n            double angle = findAngleBetweenHourAndMinuteHand(hours, minutes);\r\n            Console.WriteLine(angle);\r\n        }\r\n        \r\n        private static double findAngleBetweenHourAndMinuteHand(int hours, int minutes)\r\n        {\r\n            if(hours<0||minutes<0||hours>12||minutes>59)\r\n            {\r\n                Console.WriteLine(\"Invalid input\");\r\n                return 0;\r\n            }\r\n            double angleHoursHandMoved = 0.5*((hours*60)+minutes);\r\n            double angleMinutesHandMoved = 6*minutes;\r\n            return Math.Abs(angleHoursHandMoved-angleMinutesHandMoved);\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "Maths/Geometry/Clock_Angle/Clock_Angle.c",
    "content": "#include<stdio.h>\r\n\r\nint main(){\r\n    int hour,minute;\r\n    float hourAngle,minAngle,angle;\r\n    printf(\"Enter Hour (12 hour format) -> \");\r\n    scanf(\"%d\",&hour);\r\n    printf(\"Enter Minute -> \");\r\n    scanf(\"%d\",&minute);\r\n\r\n    minAngle = 6 * minute;\r\n    hourAngle = (30 * hour) + (0.5 * minute);\r\n\r\n    if(hourAngle>minAngle){\r\n        angle = hourAngle - minAngle;\r\n    }else{\r\n        angle = minAngle - hourAngle;\r\n    }\r\n    if(angle>180){\r\n        angle = 360 - angle;\r\n    }\r\n    printf(\"Smallest Angle between hour and minute hand for the entered time is -> %0.1f\",angle);\r\n\r\n    return 0;\r\n}"
  },
  {
    "path": "Maths/Geometry/Clock_Angle/Clock_Angle.cpp",
    "content": "CODE:\n#include <iostream>\nusing namespace std;\n\nint findAngle(int hour, int min)\n{\n\tint h = (hour * 360) / 12 + (min * 360) / (12 * 60);\n\tint m = (min * 360) / (60);\n\tint angle = abs(h - m);\n\tif (angle > 180)\n\t\tangle = 360 - angle;\n\n\treturn angle;\n}\nint main()\n{\n\tint hour;\n\tint min;\n  cin>>hour>>min;\n\n\tcout << findAngle(hour, min);\n\n\treturn 0;\n}\n\nINPUT:hour=5, min=30\nOUTPUT:15\n"
  },
  {
    "path": "Maths/Geometry/Clock_Angle/Clock_Angle.hs",
    "content": "module Clock_Angle (clock_angle) where\n\nclock_angle hour minute =\n    if (hour `elem` [1..12]) && (minute `elem` [0..59])\n    then let {\n        hour' = if hour == 12 then 0 else hour;\n        minute_angle = minute * 6;\n        hour_angle = hour' * 30 + minute * 0.5;\n    }\n    in Just (abs (hour_angle - minute_angle))\n    else Nothing\n"
  },
  {
    "path": "Maths/Geometry/Clock_Angle/Clock_Angle.java",
    "content": "public class Clock_Angle {\r\n\tpublic static int findAngle(int hour, int minute){\r\n\t\tif (hour <0 || minute < 0 || hour >12 || minute > 59){\r\n\t\t\tSystem.out.println(\"Wrong input\");\r\n\t\t\treturn -1;\r\n\t\t}\r\n            \r\n\t\t\r\n\t\tif(hour == 12){\r\n\t\t\thour = 0;\r\n\t\t}\r\n\t\tif(hour >12){\r\n\t\t\thour = hour-12;\r\n\t\t}\r\n\t\t\r\n\t\tint hour_angle = (int)(0.5 * (hour*60 + minute));\r\n        int minute_angle = (int)(6*minute);\r\n\t\t\r\n\t\tint angle = Math.abs(hour_angle - minute_angle);\r\n\t\t\r\n\t\treturn angle;\r\n\t}\r\n\t\r\n\tpublic static void main(String[] args){\r\n\t\tSystem.out.println(findAngle(10,12));\r\n\t}\r\n}\r\n\r\n//Maths_And_Stats => Geometry => Clock_Angle => Clock_Angle.java"
  },
  {
    "path": "Maths/Geometry/Clock_Angle/Clock_Angle.js",
    "content": "var hour = prompt(\"Enter Hour (12 hour format) -> \");\r\nvar minute = prompt(\"Enter Minute -> \");\r\nvar hourAngle,minAngle,angle;\r\n\r\nminAngle = 6 * minute;\r\nhrAngle = (30 * hour) + (0.5 * minute);\r\n\r\nif(hrAngle>minAngle){\r\n    angle = hrAngle - minAngle;\r\n}else{\r\n    angle = minAngle - hrAngle;\r\n}\r\nif(angle>180){\r\n    angle = 360 - angle;\r\n}\r\nalert(\"Smallest Angle between hour and minute hand for the entered time is -> \" + angle);"
  },
  {
    "path": "Maths/Geometry/Clock_Angle/README.md",
    "content": "## This folder is empty.\n"
  },
  {
    "path": "Maths/Geometry/Clock_Angle/clock_angle.go",
    "content": "package main\n\nimport (\n\t\"fmt\"\n\t\"math\"\n)\n\n// use consts instead of \"magic numbers\"\nconst minutesPerHour = 60\nconst hourHandDegreePerMinute = 0.5\nconst minuteHandDegreePerMinute = 6\n\n// Calculate clock angle between hour hand and minute hand in degrees\n// Where:\n// hours in range 0 - 12\n// minutes in range 0 -59\nfunc clockAngle(hours uint, minutes uint) (float64, error) {\n\t// Check user input\n\tif hours < 0 || minutes < 0 || hours > 12 || minutes > 59 {\n\t\treturn 0, fmt.Errorf(\"Invalid input:\\n0 < hour < 12 and 0 < minute < 59\")\n\t}\n\n\thourAngle := hourHandDegreePerMinute * float64((hours * minutesPerHour + minutes))\n\tminuteAngle := float64(minuteHandDegreePerMinute * minutes)\n\n\tangle := math.Abs(hourAngle - minuteAngle)\n\n\treturn angle, nil\n}\n\nfunc main() {\n\tvar (\n\t\thours uint\n\t\tminutes uint\n\t)\n\n\t// Get user input\n\tfmt.Printf(\"Please enter hours and minutes separated by a space where h(0-12) m(0, 59): \")\n\t_, err := fmt.Scanf(\"%d%d\", &hours, &minutes)\n\tif err != nil {\n\t\tfmt.Println(\"Invalid input type, decimal values required !\")\n\t\treturn\n\t}\n\n\t// Calculate and display the clock angle based on a 12 hour clock\n\tangle, err := clockAngle(hours, minutes)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn\n\t}\n\n\tfmt.Printf(\"The angle between hour hand and minute hand is %.2f (deg)\", angle)\n}"
  },
  {
    "path": "Maths/Geometry/Clock_Angle/clock_angle.py",
    "content": "\"\"\"\nauthor- Ose Oaiya (esoiya)\n\nSubmission Description:\nClock angle problems relate two different measurements: angles and time.\nThe angle is typically measured in degrees from the mark of number 12 clockwise.\nThe time is usually based on a 12-hour clock.\nThe hour hand of a normal 12-hour analogue clock turns 360° in 12 hours (720 minutes) or 0.5° per minute.\n\"\"\"\n\n\ndef clock_angle(hour, minute):\n    \"\"\"\n    Calculate Clock Angle between hour hand and minute hand\n\n    param hour: hour\n    type: int\n\n    param minute: number of minutes pas the hour\n    type: int\n\n    return: the smallest angle of the two possible angles\n    \"\"\"\n\n    if (hour < 0 or minute < 0 or hour > 12 or minute > 59):\n        raise ValueError(\"Invalid Input: Time is based on a 12-hour clock\")\n\n    if hour == 12:\n        hour = 0\n    \n    # calculate the angle moved by the hour and minute hands\n    # with reference to 12:00\n    hour_angle = 0.5 * (hour * 60 + minute)\n    minute_angle = 6 * minute\n\n    # Find the difference between the two angles\n    angle = abs(minute_angle - hour_angle)\n\n    return angle\n"
  },
  {
    "path": "Maths/Geometry/Distance_Formula/Distance_Formula.c",
    "content": "#include<stdio.h>\n#include<math.h>\n\nint main()\n\n{\n    \n\tint x1,x2,y1,y2;\n\tint x,y;\t\t//temporary variables\n\tfloat distance;\n\tprintf(\"Enter X and Y coordinates of first point: \");\n\tscanf(\"%d %d\",&x1,&y1);\n\tprintf(\"Enter X and Y coordinates of Second point: \");\n\tscanf(\"%d %d\",&x2,&y2);\n\n\tx=x2-x1;\n\ty=y2-y1;\n\tdistance=sqrt((x*x)+(y*y)); \n\tprintf(\"Distance: %.2f\",distance);\n    \n\treturn 0;\n\n}\n"
  },
  {
    "path": "Maths/Geometry/Distance_Formula/Distance_Formula.cpp",
    "content": "#include <iostream>\n#include <cmath>\nusing namespace std;\n\nint main() {\n\n\tdouble point_1[2];\n\tdouble point_2[2];\n\tcout << \"Enter the co-ordinates of point 1: \\n\";\n\tcout << \"x1: \";\n\tcin >> point_1[0];\n\tcout << \"y1: \";\n\tcin >> point_1[1];\n\n\tcout << \"Enter the co-ordinates of point 2: \\n\";\n\tcout << \"x2: \";\n\tcin >> point_2[0];\n\tcout << \"y2: \";\n\tcin >> point_2[1];\n\n\tdouble a_square;\n\tdouble b_square;\n\n\ta_square = pow((point_2[0] - point_1[0]), 2);\n\tb_square = pow((point_2[1] - point_1[1]), 2);\n\n\tcout << \"The distance between both points is \" << sqrt(a_square+b_square) << \" units.\\n\";\n}"
  },
  {
    "path": "Maths/Geometry/Distance_Formula/Distance_Formula.cs",
    "content": "using System;\n\ninternal struct Point\n{\n    public float x;\n    public float y;\n\n    public Point(float x, float y)\n    {\n        this.x = x;\n        this.y = y;\n    }\n\n    public override string ToString()\n    {\n        return $\"({x},{y})\";\n    }\n}\n\npublic class Distance_Formula\n{\n    public static void Main(string[] args)\n    {\n        string[] input = new string[2];\n\n        // Get coordinates of point A from stdin\n        Console.WriteLine(\"Enter coordinates of point A: \");\n        Console.Write(\"x: \");\n        input[0] = Console.ReadLine();\n        Console.Write(\"y: \");\n        input[1] = Console.ReadLine();\n        Point pointA = new Point(\n            x: Convert.ToSingle(input[0]),\n            y: Convert.ToSingle(input[1])\n        );\n\n        // Get coordinates of point B from stdin\n        Console.WriteLine(\"Enter coordinates of point B: \");\n        Console.Write(\"x: \");\n        input[0] = Console.ReadLine();\n        Console.Write(\"y: \");\n        input[1] = Console.ReadLine();\n        Point pointB = new Point(\n            x: Convert.ToSingle(input[0]),\n            y: Convert.ToSingle(input[1])\n        );\n\n        // calculate distance\n        double distance = Math.Sqrt(\n            (pointB.x - pointA.x) * (pointB.x - pointA.x) +\n            (pointB.y - pointA.y) * (pointB.y - pointA.y));\n\n        // output to stdout\n        Console.WriteLine($\"The distance between {pointA} and {pointB} is {distance}\");\n    }\n}\n"
  },
  {
    "path": "Maths/Geometry/Distance_Formula/Distance_Formula.go",
    "content": "package main\n\nimport \"fmt\"\nimport \"strconv\"\nimport \"math\"\n\nfunc main() {\n\t\n\t//Getting input of user for x1,x2,y1 and y2 coordinates then converting them to float types if numeric values are not entered then program stops.\n\t\n\tfmt.Println(\"Enter X1 coordinate: \")\n\tvar x1 string\n\tfmt.Scanln(&x1)\n\tconvX1,err:= strconv.ParseFloat(x1,64)\n\tif err!=nil{\n\t\tfmt.Println(\"Bad Input please enter numeric values only for X1.\")\n\t\treturn\n\t}\n\tfmt.Println(\"Enter Y1 coordinate: \")\n\tvar y1 string\n\tfmt.Scanln(&y1)\n\tconvY1,err:= strconv.ParseFloat(y1,64)\n\t\n\tif err!=nil{\n\t\tfmt.Println(\"Bad Input please enter numeric values only for Y1.\")\n\t\treturn\n\t}\n\n\tfmt.Println(\"Enter X2 coordinate: \")\n\tvar x2 string\n\tfmt.Scanln(&x2)\n\tconvX2,err:= strconv.ParseFloat(x2,64)\n\t\n\tif err!=nil{\n\t\tfmt.Println(\"Bad Input please enter numeric values only for X2.\")\n\t\treturn\n\t}\n\t\n\tfmt.Println(\"Enter Y2 coordinate: \")\n\tvar y2 string\n\tfmt.Scanln(&y2)\n\tconvY2,err:= strconv.ParseFloat(y2,64)\n\t\n\tif err!=nil{\n\t\tfmt.Println(\"Bad Input please enter numeric values only for Y2:\",)\n\t\treturn\n\t}\n\t\n\t//calculating difference between x1,x2 and y1,y2 coordinates\n\n\tdiffXC:= math.Abs(convX2-convX1)\n\tdiffYC:= math.Abs(convY2-convY1)\n\n\t//Calculating squares of the differences obtained above.\n\t\n\tsquX:=diffXC*diffXC\n\tsquY:=diffYC*diffYC\n\n\t//Calculating the final distance after adding and finding the square root.\n\ttotalDistance:=math.Sqrt(squX+squY)\n\tfmt.Printf(\"The distance between the two points (x1=%0.2F,y1=%0.2F) and (x2=%0.2F,y2=%0.2F) is %0.2F\\n\",convX1,convY1,convX2,convY2,totalDistance)\n\n}\n"
  },
  {
    "path": "Maths/Geometry/Distance_Formula/Distance_Formula.hs",
    "content": "module Distance_Formula (distance_formula) where\n\ndistance_formula [a,b] [c,d] = sqrt $ (a-c)^2 + (b-d)^2\n"
  },
  {
    "path": "Maths/Geometry/Distance_Formula/Distance_Formula.java",
    "content": "public class Distance_Formula {\r\n\tpublic static double findDistance(double x1, double y1 , double x2, double y2){\r\n\t\tdouble length = x2 - x1;\r\n\t\tdouble height = y2 - y1;\r\n\t\t\r\n\t\treturn Math.sqrt(length*length + height*height);\r\n\t}\r\n}"
  },
  {
    "path": "Maths/Geometry/Distance_Formula/Distance_Formula.js",
    "content": "// function to calculate distance between two points\nconst distanceFormula = (x1, y1, x2, y2) => {\n  const x_diff = x2 - x1;\n  const y_diff = y2 - y1;\n  return Math.sqrt(x_diff * x_diff + y_diff * y_diff);\n};\n\n// Take two points as input\nlet x1 = prompt(\"Enter x value of first point: \");\nlet y1 = prompt(\"Enter y value of first point: \");\nlet x2 = prompt(\"Enter x value of second point: \");\nlet y2 = prompt(\"Enter x value of second point: \");\n\n// output\nconsole.log(distanceFormula(x1, y1, x2, y2));\n"
  },
  {
    "path": "Maths/Geometry/Distance_Formula/Distance_Formula.php",
    "content": "<?php\n\t$x1=readline(\"Enter first X point :\");\n\t$y1=readline(\"Enter first Y point :\");\n\t$x2=readline(\"Enter second X point :\");\n\t$y2=readline(\"Enter second Y point :\");\n\t\n\techo \"(\".$x1.\",\".$x2.\") (\".$y1.\",\".$y2.\")\";\n\techo \"<br>\";\n\tdistance($x1,$x2,$y1,$y2);\n\t\n\tfunction distance($x1,$x2,$y1,$y2){\n\t\t\t$d = sqrt(pow($x2-$x1,2)+pow($y2-$y1,2));\n\t\t\techo \"Distance = \".$d;\n\t\t}\n?>\n"
  },
  {
    "path": "Maths/Geometry/Distance_Formula/Distance_Formula.py",
    "content": "\"\"\"\nLANGUAGE: PYTHON\n\n\"\"\"\n\nfrom math import sqrt\n\ndef Distance_Formula(x, y):\n    return sqrt((y[0]-x[0])**2+(y[1]-x[1])**2)\n\n"
  },
  {
    "path": "Maths/Geometry/Distance_Formula/README.md",
    "content": "## This folder is empty.\n"
  },
  {
    "path": "Maths/Geometry/Manhattan_Distance/ManhattanDistance.java",
    "content": "// Java Program to implement Manhattan Distance in JAVA\nimport java.util.*;\n\npublic class ManhattanDistance  \n{ \n\t// Driver Program \n      public static void main(String[] args) {\n            Scanner scanner = new Scanner(System.in); \n\n            int x1 = scanner.nextInt(); \n            int y1 = scanner.nextInt(); \n            int x2 = scanner.nextInt(); \n            int y2 = scanner.nextInt(); \n\n            int manhattanDistance = Math.abs(x1 - x2) + Math.abs(y1 - y2); \n            System.out.println(\"MANHATTAN DISTANCE IS : \" + manhattanDistance); \n      }\n} \n"
  },
  {
    "path": "Maths/Geometry/Manhattan_Distance/ManhattanDistance.js",
    "content": "const manhattanDistance = (x1, y1, x2, y2) => {\n\treturn Math.abs(x2 - x1) + Math.abs(y2 - y1);\n};\n\n// Test Cases:\n// Horizontal Direction\n// Vertical Direction\n// Diagonal Direction\n// No Movement\n// Non-(0, 0) Origin\n// Negative and Positive Values Mixed\nconst startXPositions = [0, 0, 0, 0, 1, -3];\nconst startYPositions = [0, 0, 0, 0, 1, 4];\nconst endXPositions = [5, 0, 5, 0, 6, 2];\nconst endYPositions = [0, 5, 5, 0, 6, -8];\n\nfor (var i = 0; i < startXPositions.length; i++) {\n\tconst startXPos = startXPositions[i];\n\tconst startYPos = startYPositions[i];\n\tconst endXPos = endXPositions[i];\n\tconst endYPos = endYPositions[i];\n\t\n\tconsole.log(`The manhattan distance between (${startXPos}, ${startYPos}) and (${endXPos}, ${endYPos}) is ${manhattanDistance(startXPos, startYPos, endXPos, endYPos)}!`);\n};"
  },
  {
    "path": "Maths/Geometry/Manhattan_Distance/Manhattan_Distance.c",
    "content": "// Nothing Special\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n\nint manhattan_dist(int a1 , int a2 , int b1 , int b2) {\n    return (abs(a1 - a2) + abs(b1 - b2));\n}\n\nint main() {\n\tint x1, x2, y1, y2, dist=0;\n    printf(\"Enter points of A: \");\n    scanf(\"%d %d\" , &x1 , &x2);\n    printf(\"Enter points of B: \");\n    scanf(\"%d %d\" , &x2 , &y2);\n    dist = manhattan_dist(x1 , x2 , y1 , y2);\n    printf(\"The Manhattan distance is: %d\\n\" , dist);\n\treturn 0;\n}\n"
  },
  {
    "path": "Maths/Geometry/Manhattan_Distance/Manhattan_Distance.hs",
    "content": "{-- Calculates Manhattan distance between points in any dimension.\n -\n - Syntax:\n - > manhattan_distance [1,2,3] [7,7,8]\n - 16\n -}\n\nmodule Manhattan_Distance (manhattan_distance) where\n\nmanhattan_distance xs ys = sum $ map (\\(x, y) -> abs (x-y)) (zip xs ys)\n"
  },
  {
    "path": "Maths/Geometry/Manhattan_Distance/README.md",
    "content": "## This folder is empty.\n"
  },
  {
    "path": "Maths/Geometry/Manhattan_Distance/manhattan_dist.cpp",
    "content": "#include<bits/stdc++.h>\nusing namespace std;\n\nint manhattan_dist(int, int, int, int);\n\nint main()\n{\n\tint x1, x2, y1, y2, dist=0;\n\tcout << \"Enter points of A: \";\n\tcin >> x1 >> y1;\n\tcout << \"Enter points of B: \";\n\tcin >> x2 >> y2;\n\tdist = manhattan_dist(x1, x2, y1, y2);\n\tcout << \"The Manhattan distance is: \" << dist << endl;\n\treturn 0;\n}\n\nint manhattan_dist(int a1, int a2, int b1, int b2)\n{\n\treturn (abs(a1-a2)+abs(b1-b2));\n}\n"
  },
  {
    "path": "Maths/Geometry/Manhattan_Distance/manhattan_dist.go",
    "content": "package main\n\nimport (\n\t\"fmt\"\n\t\"math\"\n)\n\nfunc calcManhattanDist(x1, y1, x2, y2 int) {\n\tdist := math.Abs(float64(x1 - x2)) + math.Abs(float64(y1 - y2))\n\tfmt.Println(dist)\n}\n\nfunc main() {\n\tcalcManhattanDist(2, 5, 10, 14)\n}"
  },
  {
    "path": "Maths/Geometry/Manhattan_Distance/manhattan_dist.py",
    "content": "def calcManhattanDist(x1, y1, x2, y2) -> float:\n    return abs(x1 - x2) + abs(y1 - y2)\n\ndef main():\n    print(calcManhattanDist(2, 5, 10, 14))\n\nif __name__ == \"__main__\":\n    main()"
  },
  {
    "path": "Maths/Geometry/Manhattan_Distance/manhattan_distance.py",
    "content": "# function to calculate Manhattan Distance between two points\ndef manhattan_dist(x1, y1, x2, y2):\n    return abs(x1-x2) + abs(y1-y2)\n\nx1, y1 = (list(map(int, input(\"Enter the first point (x,y): \").split(\",\"))))\nx2, y2 = (list(map(int, input(\"Enter the second point (x,y): \").split(\",\"))))\nprint(\"Manhattan Distance: \", manhattan_dist(x1, y1, x2, y2))"
  },
  {
    "path": "Maths/Geometry/N_Dimensional_Distance/N_Dimensional_Distance.c",
    "content": "#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n\n/**\n * This function calculates the euclidian (or L2) distance of two points.\n * @param point1 coordinates of first point stored in an array\n * @param point2 coordinates of second point stored in an array\n * @param dimension the number of coordinates each point is expected to have\n *\n * @return The euclidian distance between the points\n */\nfloat n_dimensional_distance(double const *point1, double const * point2, const size_t dimension)\n{\n\tdouble result = 0;\n\n\tfor (size_t index = 0; index < dimension; ++index)\n\t{\n\t\tdouble difference = point1[index] - point2[index];\n\t\tresult += difference*difference;\n\t}\n\n\treturn sqrt(result);\n}\n\nint main(void)\n{\n\tconst size_t N = 3;\n\tconst double point1[] = {1,1,1};\n\tconst double point2[] = {3,4,7};\n\n\tdouble distance = n_dimensional_distance(point1, point2, N);\n\n\tprintf(\"The %zu-dimensional distance between the points point1 and point2 is %f\", N, distance);\n\n\treturn EXIT_SUCCESS;\n}\n"
  },
  {
    "path": "Maths/Geometry/Polar_Cartesian_Conversion/Polar_Cartesian_Conversion.go",
    "content": "/*\n\tThis code takes input r and θ in Polar Coordinates and converts them into cartesian coordinates.\n\tLanguage : Golang\n\tAuthor : Pulkit Sapra\n*/\n\npackage main\n\n//Package fmt implements formatted I/O with functions analogous to C's printf and scanf. \nimport (\n\t\"fmt\"\n\t\"math\"\n\t)\n\nfunc convert_to_cartesian(r float64, theta float64){\n\tvar x,y float64\n\n\t//convert degree to radians\n\ttheta = theta*math.Pi/180 \n\n\t//Conversion of polar coord. to Cartesian\n\tx = r * math.Cos(theta)\n\ty = r * math.Sin(theta) \n\n\tfmt.Printf(\"x = %0.3f, y = %0.3f\\n\", x , y)\n\n}\n\n// Main Function\nfunc main() {\n\tfmt.Print(\"Please enter radius(r) and theta(in degree) : \")\n\t\n\t// Declaring variables and their types.\n\tvar r,theta float64\n\n\t// Taking input for r adn theta\n\tfmt.Scan(&r)\n\tfmt.Scan(&theta)\n\n\t//Function call\n\tconvert_to_cartesian(r,theta)\n\t\n}\n"
  },
  {
    "path": "Maths/Geometry/Polar_Cartesian_Conversion/Polar_Cartesian_Conversion.hs",
    "content": "module Polar_Cartesian_Conversion (polar_to_cartesian) where\n\npolar_to_cartesian [mod, arg] = [mod * cos(arg), mod * sin(arg)]\n"
  },
  {
    "path": "Maths/Geometry/Polar_Cartesian_Conversion/Polar_Cartesian_Conversion.java",
    "content": "import java.util.Scanner;\n\npublic class PolarCartesian {\n\n    public static void main(String[] args) {\n        Scanner sc = new Scanner(System.in);\n        System.out.print(\"Input radius: \");\n        double radius = sc.nextDouble();\n        System.out.print(\"Input theta in degrees: \");\n        double theta = sc.nextDouble();\n\n        // converting theta from degrees to radians\n        theta = theta * Math.PI / 180f;\n\n        double x = radius * Math.cos(theta);\n        double y = radius * Math.sin(theta);\n\n        System.out.printf(\"Cartesian coordinates: (%5.3f, %5.3f)\", x, y);\n    }\n}\n"
  },
  {
    "path": "Maths/Geometry/Polar_Cartesian_Conversion/Polar_Cartesian_Conversion.py",
    "content": "import math\n\ndef polarToCart(r, theta):\n    \n    theta = theta*math.pi/180.0\n    \n    x = r*math.cos(theta)\n    y = r*math.sin(theta)\n    \n    return (x, y)"
  },
  {
    "path": "Maths/Geometry/Pythagorean_theorem/PythagoreanTheorem.cs",
    "content": "using System;\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.Linq;\n\nclass PythagoreanTheorem\n{\n    // Derived from the Pythagorean Theorem\n    // a^2 + b^2 = c^2 in reference to a right triangle's sides a, b, and hypotenuse c\n    \n    // c = sqrt(a^2 + b^2)\n    private static double GetHypotenuse(float a, float b)\n    {\n        return Math.Sqrt(a * a + b * b);\n    }\n\n    // a = sqrt(c^2 - b^2)\n    private static double GetSideA(float b, float c)\n    {\n        return Math.Sqrt(c * c - b * b);\n    }\n\n    // b = sqrt(c^2 - a^2)\n    private static double GetSideB(float a, float c)\n    {\n        return Math.Sqrt(c * c - a * a);\n    }\n\n    private static bool IsRightAngled(float a, float b, float c)\n    {\n        return GetHypotenuse(a, b) == c;\n    }\n\n    static void Main(string[] args)\n    {\n        Console.WriteLine(GetHypotenuse(3, 4));\n        Console.WriteLine(GetSideA(4, 5));\n        Console.WriteLine(GetSideB(3, 5));\n        Console.WriteLine(IsRightAngled(3, 4, 5));\n        Console.WriteLine(IsRightAngled(3.5f, 4, 5));\n        Console.ReadLine();\n    }\n}\n"
  },
  {
    "path": "Maths/Geometry/Pythagorean_theorem/Pythagorean_theorem.cpp",
    "content": "#include<bits/stdc++.h>\nusing namespace std;\n\nint main() {\n\n\tdouble sides[3];\n\tcout << \"Enter the sides of triangle: \";\n\tcin >> sides[0] >> sides[1] >> sides[2];\n\n\tsort(sides, sides + 3);\n\n\tif((sides[0] * sides[0]) + (sides[1] * sides[1]) == sides[2] * sides[2]) {\n\n\t\tcout << \"True, it is a right angled triangle as it follows Pythagorean Theorem (a^2 + b^2 = c^2)\" << endl;\n\n\t}\n\n\telse {\n\t\tcout << \"False, it is not a right angled triangle as it does not follow the Pythagorean Theorem\" << endl;\n\t}\n\n\treturn 0;\n}"
  },
  {
    "path": "Maths/Geometry/Pythagorean_theorem/Pythagorean_theorem.hs",
    "content": "main = do {\n    putStrLn \"Enter sides of the triangle\";\n    sides <- getLine;\n    putStrLn (\n        let {\n            [x,y,z] = map (\\x -> read x :: Int) (words sides);\n            hyp = maxx x y z;\n            legs = filter (< hyp) [x,y,z];\n        } in (\n            if isRectTriangle [x,y,z]\n            then \"Hypotenuse: \" ++ show hyp ++ \", legs: \" ++ show legs\n            else \"The sides don't follow Pythagoras' theorem.\"\n        )\n    )\n}\n\nisRectTriangle [a,b,c] = or [\n    a^2 + b^2 == c^2,\n    b^2 + c^2 == a^2,\n    c^2 + a^2 == b^2]\n\nmaxx a b c = max a (max b c)\n"
  },
  {
    "path": "Maths/Geometry/Pythagorean_theorem/Pythagorean_theorem.js",
    "content": "\n//This function checks the 3 numbers. If they form a pythagorean triplet, it finds out hypotenuse and legs\n// else it return null\nconst checkPythagoreanTriplet = (a, b, c) => {\n    if (!a || !b || !c) {\n        return null;\n    }\n    if (a * a + b * b === c * c) {\n        return { hypotenuse: c, legs: [a, b] }\n    }\n    else if (a * a + c * c === b * b) {\n        return { hypotenuse: b, legs: [a, c] }\n    }\n    else if (c * c + b * b === a * a) {\n        return { hypotenuse: a, legs: [c, b] }\n    }\n    return null;\n}\n\nconsole.log(checkPythagoreanTriplet(3, 4, 5),\n    checkPythagoreanTriplet(13, 12, 5),\n    checkPythagoreanTriplet(3, 4, 6))\n"
  },
  {
    "path": "Maths/Geometry/Pythagorean_theorem/Pythagorean_theorem.py",
    "content": "def CheckPythagoreanTriplet(a, b, c):\n    if not a or not b or not c:\n        return\n    elif a ** 2 == b ** 2 + c ** 2:\n        return a\n\n    elif b ** 2 == a ** 2 + c ** 2:\n        return b\n\n    elif c ** 2 == a ** 2 + b ** 2:\n        return c\n\n    return\n\nprint(\"Enter the sides of right angled triangle: \")\nx = int(input())\ny = int(input())\nz = int(input())\n\nhypotenuse = CheckPythagoreanTriplet(x, y, z)\n\nif hypotenuse == x:\n    print(\"{0}, {1}, {2} are the sides of a right angled triangle with  {0} as hypotenuse and {1}, {2} as legs\"\n          .format(x, y, z))\n\nelif hypotenuse == y:\n    print(\"{1}, {0}, {2} are the sides of a right angled triangle with  {0} as hypotenuse and {1}, {2} as legs\"\n          .format(y, x, z))\n\nelif hypotenuse == z:\n    print(\"{1}, {2}, {0} are the sides of a right angled triangle with {0} as hypotenuse and {1}, {2} as legs\"\n          .format(z, x, y))\n\nelse:\n    print(\"{}, {}, {} are not the sides of a right angled triangle\".format(x, y, z))\n"
  },
  {
    "path": "Maths/Geometry/Pythagorean_theorem/Pythagorean_theorem.rb",
    "content": "#!/usr/bin/env ruby\n\nputs \"Enter the sides of the triangle:\"\nsides = gets.chomp(\" \")\n            .split(\" \")\n            .map(&:to_f)\n            .sort\n\nif sides.length != 3\n  raise ArgumentError, \"Please enter the lengths of the three sides of a triangle\"\nend\n\nif sides[0]**2 + sides[1]**2 == sides[2]**2\n  puts \"According to Pythagorean Theorem, a^2 + b^2 = c^2, you have a right triangle\"\nelse\n  puts \"According to Pythagorean Theorem, you do not have a right triangle\"\nend\n"
  },
  {
    "path": "Maths/Geometry/Pythagorean_theorem/Pythagorean_theorem.swift",
    "content": "import Foundation\n\nfunc isPythagorean(_ sideA: Float64, _ sideB: Float64, _ sideC: Float64) -> Bool {\n    let sideA_squared = sideA * sideA\n    let sideB_squared = sideB * sideB\n    let sideC_squared = sideC * sideC\n\n    return (sideA_squared == sideB_squared + sideC_squared)\n        || (sideB_squared == sideA_squared + sideC_squared)\n        || (sideC_squared == sideA_squared + sideB_squared)\n}\n\nprint(\"Enter side A:\")\nlet sideAinString = readLine(strippingNewline: true)\n\nprint(\"Enter side B:\")\nlet sideBinString = readLine(strippingNewline: true)\n\nprint(\"Enter side C:\")\nlet sideCinString = readLine(strippingNewline: true)\n\nif let sideA = Double(sideAinString!), let sideB = Double(sideBinString!), let sideC = Double(sideCinString!) {\n    print(isPythagorean(sideA, sideB, sideC))\n} else {\n    print(\"Input value cannot be converted to a number\")\n}"
  },
  {
    "path": "Maths/Geometry/Pythagorean_theorem/README.md",
    "content": "## This folder is empty.\n"
  },
  {
    "path": "Maths/Geometry/Pythagorean_theorem/pythogoras_theorem.java",
    "content": "import java.util.*;\nimport java.lang.*;\n\nclass pythogoras_theorem{\n\tpublic static void main(String args[]){\n\t\tScanner sc= new Scanner(System.in);\n\t\tdouble arr[] = new int[3];\n\t\tSystem.out.println(\"Enter the length of the sides of the triangle\");\n\t\tfor(int i = 0;i<3;i++){\n\t\t\tarr[i] = sc.nextDouble();\n\t\t}\n\t\t\n\t\t// The user may enter sides length in any order\n\t\tArrays.sort(arr);\n\t\t\n\t\tif(Math.pow(arr[0],2) + Math.pow(arr[1],2) == Math.pow(arr[2],2)){\n\t\t\tSystem.out.println(\"The sides of the triangle follow pythogorean theorem.\");\n\t\t}\n\t\telse{\n\t\t\tSystem.out.println(\"The sides of the triangle does not follow pythogorean theorem.\");\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "Maths/Geometry/README.md",
    "content": "# This folder is empty.\n"
  },
  {
    "path": "Maths/Geometry/Radians_Degrees_Conversion/README.md",
    "content": "## This folder is empty.\n"
  },
  {
    "path": "Maths/Geometry/Radians_Degrees_Conversion/Radians_Degree_Conversion.c",
    "content": "// Nothing Special\n\n#include <stdio.h> \n#include <math.h> \n\n// Function for conversion \ndouble Convert(double degree) {\n    double pi = 3.14159265359;\n    return (degree * (pi / 180)); \n} \n\n// Driver code \nint main() { \n    double degree;\n    printf(\"Enter a value:\\n\");\n    scanf(\"%lf\" , &degree);\n    double radian = Convert(degree);\n    printf(\"%lf\\n\" , radian);\n    return 0; \n} \n"
  },
  {
    "path": "Maths/Geometry/Radians_Degrees_Conversion/Radians_Degrees_Conversion.c",
    "content": "#include <stdio.h>\n#define M_PI 3.14159265358979323846\n\nfloat convert(float *n, int _case);\n\nint main()\n{\n    int _case = 0; //to indicate direction of the conversion\n    float value;\n    printf(\"What do you want to do?\\n\");\n    while(_case != 1 && _case != 2)\n    {\n        printf(\"\\n\\t1) Convert degrees to radians.\\n\\t2) Convert radians to degrees.\\n\");\n        scanf(\"%d\", &_case); //get direction of conversion\n        switch(_case)\n        {\n            case 1:\n                printf(\"Enter your value in degrees: \");\n                break;\n            case 2:\n                printf(\"Enter your value in radians: \");\n                break;\n            default:\n                printf(\"\\nInvalid choice! Please choose one of the options below...\");\n                break;\n        }\n    }\n    scanf(\"%f\", &value);\n    printf(\"Value of %f \", value);\n    printf(\"%s in %s is:  %f\",\n    ((_case==1) ? \"degrees\" : \"radians\"), \n    ((_case==1) ? \"radians\" : \"degrees\"), \n    convert(&value, _case));\n    if(_case == 1)\n        printf(\" rad or %.3fPi rad\", value/M_PI); \n    else\n        printf(\" deg\");\n    char c;\n    scanf(\"%c\", &c); //wait for user input\n    return 0;\n}\n\nfloat convert(float *n, int _case)\n{\n    switch(_case)\n    {\n        case 1: //convert from degrees to radians\n            *n=(*n*M_PI)/180; \n            return(*n);\n            break;\n        case 2: //convert from radians to degrees\n            *n=(*n*180)/M_PI;\n            return(*n);\n            break;\n    }\n}\n"
  },
  {
    "path": "Maths/Geometry/Radians_Degrees_Conversion/Radians_Degrees_Conversion.cpp",
    "content": "#include <iostream> \n#include <math.h> \nusing namespace std; \n  \n// Function for conversion \ndouble Convert(double degree) \n{ \n    double pi = 3.14159265359; \n    return (degree * (pi / 180)); \n} \n  \n// Driver code \nint main() \n{ \n    double degree;\n    cout<<\"Enter a value: <<endl;\n    cin>>degree;\n    double radian = Convert(degree); \n    cout << radian; \n    return 0; \n} \n"
  },
  {
    "path": "Maths/Geometry/Radians_Degrees_Conversion/Radians_Degrees_Conversion.hs",
    "content": "module Radians_Degrees_Conversion (radToDeg) where\n\nradToDeg deg = deg * pi / 180\n"
  },
  {
    "path": "Maths/Geometry/Radians_Degrees_Conversion/Radians_Degrees_Conversion.java",
    "content": "class Conversion {\n    private static double radiansToDegrees(double radians) {\n        return round(radians * (180 / Math.PI));\n    }\n\n    private static double degreesToRadians(double degrees) {\n        return round(degrees * (Math.PI / 180));\n    }\n\n    private static double round(double value) {\n        return (double) Math.round(value * 100) / 100;\n    }\n\n    public static void main(String[] args) {\n        final double radians = 1;\n        final double degrees = 57.30;\n\n        assert radiansToDegrees(radians) == degrees;\n        assert degreesToRadians(degrees) == radians;\n    }\n}\n"
  },
  {
    "path": "Maths/Geometry/Radians_Degrees_Conversion/Radians_Degrees_Conversion.js",
    "content": "const pi = 3.1415926535;\n\n// function to convert degrees to radians\nconst degreesToRadians = (degrees) => {\n  return degrees * (pi / 180);\n};\n\n// function to convert radians to degrees\nconst radiansToDegrees = (radians) => {\n  return radians * (180 / pi);\n};\n\n//driver code\nconst degreeInput = prompt(\"Enter a number to convert from degree to radian: \");\nlet radianOutput = degreesToRadians(degreeInput);\nconsole.log(`${degreeInput}° = ${radianOutput} rad`);\n\nconst radianInput = prompt(\"Enter a number to convert from radian to degree: \");\nlet degreeOutput = radiansToDegrees(radianInput);\nconsole.log(`${radianInput} rad = ${degreeOutput}°`);\n"
  },
  {
    "path": "Maths/Geometry/Radians_Degrees_Conversion/Radians_Degrees_Conversion.py",
    "content": "def convert(degree):\n\n\tpi = 3.14159265359\n\treturn degree * (pi/180)\n\ndegree = float(input(\"Enter degrees:\"))\nprint(\"In radians:\", convert(degree))"
  },
  {
    "path": "Maths/Geometry/Scalar_Product/README.md",
    "content": "## This folder is empty.\n"
  },
  {
    "path": "Maths/Geometry/Scalar_Product/Scalar_Product.c",
    "content": "// Nothing Special\n\n#include <stdio.h>\n\nint main() {\n    int a1,b1,c1,a2,b2,c2;\n\n    printf(\"Enter the 1st Vector\\n\\n\");\n    printf(\"A1 = \");    scanf(\"%d\" , &a1);\n    printf(\"B1 = \");    scanf(\"%d\" , &b1);\n    printf(\"C1 = \");    scanf(\"%d\" , &c1);\n\n    printf(\"Enter the 2nd Vector\\n\\n\");\n    printf(\"A2 = \");    scanf(\"%d\" , &a2);\n    printf(\"B2 = \");    scanf(\"%d\" , &b2);\n    printf(\"C2 = \");    scanf(\"%d\" , &c2);\n\n    puts(\"\");\n\n    printf(\"Scalar Product of both vectors is %d\\n\" , a1 * a2 + b1 * b2 + c1 * c2);\n    return 0;\n}\n\n"
  },
  {
    "path": "Maths/Geometry/Scalar_Product/Scalar_Product.hs",
    "content": "module Scalar_Product (scalar) where\n\n[] `scalar` [] = 0\n(x:xs) `scalar` (y:ys) = x * y + xs `scalar` ys\n"
  },
  {
    "path": "Maths/Geometry/Scalar_Product/Scalar_Product.java",
    "content": "import java.io.*; \n  \nclass ScalarProduct {\n\tstatic int n = 3; \n\n\tstatic int dotProduct(int vect_A[], int vect_B[]) {\n\t\tint product = 0; \n\t\tfor (int i = 0; i < n; i++) \n\t\t\tproduct = product + vect_A[i] * vect_B[i]; \n\t\treturn product; \n\t} \n\n\tpublic static void main(String[] args) { \n\t\tint vect_A[] = {1, 2, 6};\n\t\tint vect_B[] = {-5, 3, 4};\n\t\tint cross_P[] = new int[n]; \n\t\tSystem.out.print(\"Dot product:\"); \n\t\tSystem.out.println(dotProduct(vect_A, vect_B)); \n\t} \n}"
  },
  {
    "path": "Maths/Geometry/Scalar_Product/Scalar_Product.js",
    "content": "/**\n * @description given two equal-length vectors, returns a single scalar number.\n * @param {Number[]} vectorA \n * @param {Number[]} vectorB\n * @returns {Number} scalar number\n */\nexport function scalarProduct(vectorA, vectorB) {\n    if (vectorA.length != vectorB.length) {\n        throw (\"The dimension of the vectors must be the same.\")\n    }\n    return vectorA.reduce((accumulator, _, i) => accumulator += (vectorA[i] * vectorB[i]), 0)\n}"
  },
  {
    "path": "Maths/Geometry/Scalar_Product/Scalar_Product.py",
    "content": "\"\"\"\nLANGUAGE: PYTHON\nAUTHOR: Diadochokinetic\nGITHUB: https://github.com/Diadochokinetic\n\"\"\"\n\nfrom operator import mul\n\ndef Scalar_Product(x, y):\n    return sum(map(mul, x, y))\n\ndef float_input(string_input):\n    return [float(element) for element in string_input.split()]\n\nif __name__ == '__main__':\n    a = float_input(input(\"Please enter a vector containing n elements, e.g. 1 2 3: \"))\n    b = float_input(input(\"Please enter another vector containing n elements, e.g. 4 5 6: \"))\n    print(f'The scalar product for {a} and {b} is: {Scalar_Product(a, b)}')\n"
  },
  {
    "path": "Maths/Geometry/Scalar_Product/scalar_product.cpp",
    "content": "#include<bits/stdc++.h>\nusing namespace std;\n\nvoid scalar_prod(int [], int [], int);\n\nint main()\n{\n\tint n, a[100], b[100];\n\tcout << \"Enter size: \";\n\tcin >> n;\n\t\n\tcout << \"Enter data of a: \";\n\tfor(int i=0; i<n; i++)\n\t\tcin >> a[i];\n\t\n\tcout << \"Enter data of b: \";\n\tfor(int i=0; i<n; i++)\n\t\tcin >> b[i];\n\t\t\n\tscalar_prod(a, b, n);\n\t\n\treturn 0;\n}\n\nvoid scalar_prod(int x[], int y[], int num)\n{\n\tint prod=0;\n\tfor(int j=0; j<num; j++)\n\t{\n\t\tprod += x[j] * y[j];\n\t}\n\t\n\tcout << \"Scalar product: \" << prod << endl;\n}\n"
  },
  {
    "path": "Maths/Geometry/Scalar_Product/scalar_product.rb",
    "content": "# @param [Array] vector_a\n# @param [Array] vector_b\ndef scalar_product(vector_a, vector_b)\n  raise \"Different vector dimension\" unless vector_a.length == vector_b.length\n  vector_a.zip(vector_b)\n    .map { |a, b| a * b }\n    .sum\nend\n\nputs \"Enter vector value separated by comma, like 1,2,3,4,5\"\nprint \"First vector => \"\nvector_a = gets.chomp.split(\",\").map(&:to_f)\nprint \"Second vector => \"\nvector_b = gets.chomp.split(\",\").map(&:to_f)\nputs \"Scalar product: #{scalar_product(vector_a, vector_b)}\"\n"
  },
  {
    "path": "Maths/Geometry/Vector_Product/README.md",
    "content": "## This folder is empty.\n"
  },
  {
    "path": "Maths/Geometry/Vector_Product/Vector_Product.c",
    "content": "// Nothing Special\n\n#include <stdio.h>\n\nint main() {\n    int a1,b1,c1,a2,b2,c2;\n\n    printf(\"Enter the 1st Vector\\n\\n\");\n    printf(\"A1 = \");    scanf(\"%d\" , &a1);\n    printf(\"B1 = \");    scanf(\"%d\" , &b1);\n    printf(\"C1 = \");    scanf(\"%d\" , &c1);\n\n    printf(\"Enter the 2nd Vector\\n\\n\");\n    printf(\"A2 = \");    scanf(\"%d\" , &a2);\n    printf(\"B2 = \");    scanf(\"%d\" , &b2);\n    printf(\"C2 = \");    scanf(\"%d\" , &c2);\n\n    puts(\"\");\n\n    printf(\"Vector Product of both vectors is %d %d %d\\n\" , (b1 * c2) - (b2 * c1) , (a1 * c2) - (a2 * c1) , (a1 * b2) - (a2 * b1));\n    return 0;\n}\n"
  },
  {
    "path": "Maths/Geometry/Vector_Product/Vector_Product.cpp",
    "content": "#include <bits/stdc++.h>\nusing namespace std;\n\nvector <int> vector_product (vector <int>a, vector <int> b){\n\tif (a.size()!=3 || b.size()!=3){\n\t\tcout<<\"Invalid INPUT\"<<\"\\n\";\n\t\treturn {};\n\t}\n\tvector <int> ans(3);\n\tans[0] = a[1]*b[2] - a[2]*b[1];\n\tans[1] = a[2]*b[0] - a[0]*b[2];\n\tans[2] = a[0]*b[1] - a[1]*b[0];\n\treturn ans;\n}\n\nint main(){\n\tvector <int> a (3);\n\tvector <int> b (3);\n\tcout<<\"Enter the coordinartes of First Vector\"<<endl;\n\tcin>>a[0]>>a[1]>>a[2];\n\tcout<<\"Enter the coordinartes of First Vector\"<<endl;\n\tcin>>b[0]>>b[1]>>b[2];\n\tcout<<\"Output is :\"\n\tfor (auto x:vector_product(a,b))\n\t\tcout<<x<<\" \";\n\tcout<<endl;\n\treturn 0;\n}\n"
  },
  {
    "path": "Maths/Geometry/Vector_Product/Vector_Product.hs",
    "content": "module Vector_Product (vector) where\n\n[x1,x2,x3] `vector` [y1,y2,y3] = \n    [x2 * y3 - x3 * y2,\n     x3 * y1 - x1 * y3,\n     x1 * y2 - x2 * y1]\n"
  },
  {
    "path": "Maths/Geometry/Vector_Product/Vector_Product.js",
    "content": "/**\n * @description given two linearly indepent vectors of R3, returns a vector that is perpendicular to both.\n * @param {Number[]} vectorA \n * @param {Number[]} vectorB\n * @returns {Number[]} the perpendicular vector to both A and B\n */\nexport function crossProduct(vectorA, vectorB) {\n    if (vectorA.length !== vectorB.length || vectorA.length !== 3) {\n        throw (\"The dimension of the vectors must be 3.\")\n    }\n    return [\n        vectorA[1] * vectorB[2] - vectorA[2] * vectorB[1],\n        vectorA[2] * vectorB[0] - vectorA[0] * vectorB[2],\n        vectorA[0] * vectorB[1] - vectorA[1] * vectorB[0]\n    ]\n}"
  },
  {
    "path": "Maths/Geometry/Vector_Product/Vector_Product.py",
    "content": "\"\"\"\nLANGUAGE: PYTHON\nAUTHOR: Diadochokinetic\nGITHUB: https://github.com/Diadochokinetic\n\"\"\"\n\ndef Vector_Product(a, b):\n    return [a[1]*b[2] - a[2]*b[1], a[2]*b[0] - a[0]*b[2], a[0]*b[1] - a[1]*b[0]]\n\ndef float_input(string_input):\n    return [float(element) for element in string_input.split()]\n\nif __name__ == '__main__':\n    a = float_input(input(\"Please enter a vector containing 3 elements, e.g. 1 2 3: \"))\n    b = float_input(input(\"Please enter another vector containing 3 elements, e.g. 4 5 6: \"))\n    print(f'The vector product for {a} and {b} is: {Vector_Product(a, b)}')\n"
  },
  {
    "path": "Maths/Geometry/Vector_Product/Vector_Product.ts",
    "content": "/* \n* This function can run in any TS environment or be compiled to any JS environment: they're specific-agnostic.\n* It returns the vector/cross product between two three-dimensional vectors.\n* A 3D vector is described as an array of three numbers (x, y, z).\n*/\n\n/*\n* A 3D Vector, which is an array of three numbers (x, y, z).\n* @typedef {[number, number, number]} ThreeDimensionalVector\n*/\ntype ThreeDimensionalVector = [number, number, number];\n\n/*\n* @description Given two three-dimensional vectors, returns the cross product: a vector that is perpendicular to both.\n* @param {ThreeDimensionalVector} vectorA - The first vector;\n* @param {ThreeDimensionalVector} vectorB - The second vector;\n* @returns {ThreeDimensionalVector} - The resulting vector product (vectorC).\n*/\nfunction crossProduct(vectorA: ThreeDimensionalVector, vectorB: ThreeDimensionalVector): ThreeDimensionalVector {\n    return [\n        vectorA[1] * vectorB[2] - vectorA[2] * vectorB[1],\n        vectorA[2] * vectorB[0] - vectorA[0] * vectorB[2],\n        vectorA[0] * vectorB[1] - vectorA[1] * vectorB[0]\n    ];\n}\n"
  },
  {
    "path": "Maths/MOs-Algorithm/Mos_Algorithm.c",
    "content": "// Program in C to compute sum of ranges for different range queries\n#include <bits/stdc++.h>\nusing namespace std;\n\n// Query range\nstruct Query\n{\n  int L, R;\n};\n\n// Prints sum of all query ranges (m is the number of queries, n is the size of the array)\nvoid printQuerySums(int a[], int n, Query q[], int m)\n{\n  // One by one compute sum of all queries\n  for (int i = 0; i < m; i++)\n  {\n    // Left and right boundaries of current range\n    int L = q[i].L, R = q[i].R;\n\n    // Compute sum of current query range\n    int sum = 0;\n    for (int j = L; j <= R; j++)\n      sum += a[j];\n\n    // Print sum of current query range\n    cout << \"Sum of [\" << L << \", \"\n         << R << \"] is \" << sum << endl;\n  }\n}\n\nint main()\n{\n  int a[] = {1, 1, 2, 1, 3, 4, 5, 2, 8};\n  int n = sizeof(a) / sizeof(a[0]);\n  Query q[] = {{0, 4}, {1, 3}, {2, 4}};\n  int m = sizeof(q) / sizeof(q[0]);\n  printQuerySums(a, n, q, m);\n  return 0;\n}\n"
  },
  {
    "path": "Maths/MOs-Algorithm/Mos_Algorithm.cpp",
    "content": "// Mos Algorithm.cpp : This file contains the 'main' function. Program execution begins and ends there.\n//\n// User: kcirym10\n// Mos Algorithm is widely used for decreasing complexity in query base problems\n\n#include <iostream>\n#include <algorithm>\n#include <vector>\n\nusing namespace std;\n\n//This variable represents the block size and is global in order to be used insede of the compare function\nint block;\n\n//Structure that represents a query range\nstruct Query {\n    int L, R;\n};\n\nbool compare(Query x, Query y) {\n    if (x.L / block != y.L / block)\n        return x.L / block < y.L / block;\n\n    return x.R < y.R;\n}\n\nvoid queryResults(vector<int> a, const int n, vector<Query> q, const int m) {\n    //Set the block size\n    block = (int)sqrt(n);\n\n    //Sort all queries using the compare function so that\n    //all queries belonging to the same block are grouped together\n    sort(q.begin(), q.end(), compare);\n\n    //Initialize the current L, current R and the current sum\n    int currentL = 0, currentR = 0, currentSum = 0;\n\n    for (int i = 0; i < m; i++) {\n        //Get the L and R values of the current range\n        int L = q[i].L, R = q[i].R;\n\n        //Remove the extra elements of the previous range\n        while (currentL < L) {\n            currentSum -= a[currentL];\n            currentL++;\n        }\n\n        //Add elements from the current range\n        while (currentL > L) {\n            currentSum += a[currentL - 1];\n            currentL--;\n        }\n\n        while (currentR <= R) {\n            currentSum += a[currentR];\n            currentR++;\n        }\n\n        //Remove the elements from the previous range\n        while (currentR > R + 1) {\n            currentSum -= a[currentR - 1];\n            currentR--;\n        }\n\n        // Print sum of current range \n        cout << \"Sum of [\" << L << \", \" << R\n            << \"] is \" << currentSum << endl;\n    }\n}\n\nint main()\n{\n    //Default values in order to run the code but a vector can be implemented in order to \n    /*int a[] = { 1, 1, 2, 1, 3, 4, 5, 2, 8 };\n    int n = sizeof(a) / sizeof(a[0]);\n    Query q[] = { {0, 4}, {1, 3}, {2, 4} };\n    int m = sizeof(q) / sizeof(q[0]);*/\n    vector<int> a;\n    vector<Query> q;\n    int n;\n    int m;\n    Query temp;\n    int iTemp;\n\n\n    cout << \"Enter the number of elements: \";\n    cin >> n;\n\n    cout << \"Enter all n elements\\n\";\n    for (int i = 0; i < n; i++) {\n        cin >> iTemp;\n        a.push_back(iTemp);\n    }\n\n    cout << \"Enter the number of query calls: \";\n    cin >> m;\n    \n    cout << \"Enter the pair of query calls\\n\";\n    for (int i = 0; i < m; i++) {\n        cin >> temp.L;\n        cin >> temp.R;\n        q.push_back(temp);\n    }\n    \n    queryResults(a, n, q, m);\n    \n    return 0;\n}\n"
  },
  {
    "path": "Maths/MOs-Algorithm/README.md",
    "content": "# This folder is empty.\n"
  },
  {
    "path": "Maths/Number-Theory/Armstrong_Number/ArmstrongNumber.java",
    "content": "// Implementing Armstrong Number using Java\n// Code written by Sayan Manna\n\nimport java.util.*;\n\npublic class ArmstrongNum {\n\n    public static void main(String[] args) {\n\n        Scanner scanner = new Scanner(System.in);\n        System.out.println(\"Enter the number : \");\n        int number = scanner.nextInt();\n        int originalNumber, remainder, result = 0;\n\n        originalNumber = number;\n\n        while (originalNumber != 0)\n        {\n            remainder = originalNumber % 10;\n            result += Math.pow(remainder, 3);\n            originalNumber /= 10;\n        }\n\n        if(result == number)\n            System.out.println(number + \" is an Armstrong number.\");\n        else\n            System.out.println(number + \" is not an Armstrong number.\");\n    }\n}"
  },
  {
    "path": "Maths/Number-Theory/Armstrong_Number/Armstrong_Number.c",
    "content": "#include <iostream>\n\nusing namespace std;\n\nint main()\n{\n    //The number of test cases\n    cout << \"Enter the number of testcases\" << endl;\n    int t;\n    scanf(\"%d\", &t);\n    while(t--){\n        int n,rem,ans=0;\n        printf(\"Enter a Number: \");\n        scanf(\"%d\", &c);\n\n        int n1=n;\n        while(n1>0){\n            rem = n1%10;\n            ans = ans + (rem*rem*rem);\n            n1 = n1/10;\n        }\n\n        if(ans == n)\n             printf(\"The number %d is an armstrong number\", n);\n        else\n            printf(\"The number %d is not an armstrong number\", n);\n    }\n"
  },
  {
    "path": "Maths/Number-Theory/Armstrong_Number/armstrong.py",
    "content": "def check_armstrong(num):\n    sums = 0\n    p = num\n    while num != 0:\n        digit = num % 10\n        sums += pow(digit, 3)\n        num //= 10\n    if sums == p:\n        return \"Yes\"\n    else:\n        return \"No\"\n\n\nnumber = int(input(\"Enter a number: \"))\nresult = check_armstrong(number)\nprint(result)"
  },
  {
    "path": "Maths/Number-Theory/Armstrong_Number/armstrongin.java",
    "content": "public class Armstrong {\n\n    public static void main(String[] args) {\n\n        int number = 371, originalNumber, remainder, result = 0;\n\n        originalNumber = number;\n\n        while (originalNumber != 0)\n        {\n            remainder = originalNumber % 10;\n            result += Math.pow(remainder, 3);\n            originalNumber /= 10;\n        }\n\n        if(result == number)\n            System.out.println(number + \" is an Armstrong number.\");\n        else\n            System.out.println(number + \" is not an Armstrong number.\");\n    }\n}\n"
  },
  {
    "path": "Maths/Number-Theory/Armstrong_Number/armstrongnumber.cpp",
    "content": "/*\r\n    This is a code for armstrong number\r\n    Code written by Manas Ranjan Swain\r\n*/\r\n\r\n\r\n#include <iostream>\r\n#define ll long long int\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    //The number of test cases\r\n    cout << \"Enter the number of testcases\" << endl;\r\n    int t;\r\n    cin >> t;\r\n    while(t--){\r\n        ll n,rem,ans=0;\r\n        cout << \"Enter a number\" << endl;\r\n        cin >> n;\r\n\r\n        ll n1=n;\r\n        while(n1>0){\r\n            rem = n1%10;\r\n            ans = ans + (rem*rem*rem);\r\n            n1 = n1/10;\r\n        }\r\n\r\n        if(ans == n)\r\n            cout << \"The number \" << n << \" is an armstrong number\" << endl;\r\n        else\r\n            cout << \"The number \" << n << \" is not an armstrong number\" << endl;\r\n    }\r\n}\r\n"
  },
  {
    "path": "Maths/Number-Theory/Armstrong_Number/armstrongnumber.js",
    "content": "// program to check an Armstrong number of n digits\n\n// take an input\nlet number = prompt(\"Enter a positive integer\");\nlet numberOfDigits = number.length;\nlet sum = 0;\n\n// create a temporary variable\nlet temp = number;\n\nwhile (temp > 0) {\n\n    let remainder = temp % 10;\n\n    sum += remainder ** numberOfDigits;\n\n    // removing last digit from the number\n    temp = parseInt(temp / 10); // convert float into integer\n}\n\nif (sum == number) {\n    console.log(`${number} is an Armstrong number`);\n} else {\n    console.log(`${number} is not an Armstrong number.`);\n}"
  },
  {
    "path": "Maths/Number-Theory/Extended Euclidean Algorithm/extendEuclid.cpp",
    "content": "// C++ program to demonstrate working of\n// extended Euclidean Algorithm\n#include <bits/stdc++.h>\nusing namespace std;\n\n// Function for extended Euclidean Algorithm\nint gcdExtended(int a, int b, int *x, int *y)\n{\n    // Base Case\n    if (a == 0)\n    {\n        *x = 0;\n        *y = 1;\n        return b;\n    }\n\n    int x1, y1; // To store results of recursive call\n    int gcd = gcdExtended(b%a, a, &x1, &y1);\n\n    // Update x and y using results of\n    // recursive call\n    *x = y1 - (b/a) * x1;\n    *y = x1;\n\n    return gcd;\n}\n\n// Driver Code\nint main()\n{\n    int x, y, a = 35, b = 15;\n    int g = gcdExtended(a, b, &x, &y);\n    cout << \"GCD(\" << a << \", \" << b\n         << \") = \" << g << endl;\n    return 0;\n}"
  },
  {
    "path": "Maths/Number-Theory/Extended Euclidean Algorithm/extendEuclid.py",
    "content": "# Python program to demonstrate working of extended Euclidean Algorithm\n# function for extended Euclidean Algorithm\ndef gcdExtended(a, b):\n    # Base Case\n    if a == 0:\n        return b, 0, 1\n\n    gcd, x1, y1 = gcdExtended(b % a, a)\n\n    # Update x and y using results of recursive\n    # call\n    x = y1 - (b // a) * x1\n    y = x1\n\n    return gcd, x, y\n\n\n# Driver code\nfirst_number, second_number = 35, 15\ng, x, y = gcdExtended(first_number, second_number)\nprint(\"gcd(\", first_number, \",\", second_number, \") = \", g)\n"
  },
  {
    "path": "Maths/Number-Theory/Fibonacci_Number/Fibonacci.cs",
    "content": "using System;\nusing System.Text;\n\npublic static class Fibonacci {\n\n    //The Fibonacci Sequence is described as a sequence of numbers in which each number is the sum of the two preceding ones, starting from 0 and 1\n    //Creating the sequence 0, 1, 1, 2, 3, 5, 8, 12, ...\n    //The following method shows how recursion can be used to calculate the value of any given index in the Fibonacci Sequence, \n    //with indexes 0 and 1 used as termination condition\n    public static int GetValue(int index) {\n        if (index <= 0)\n            return 0;\n\n        if (index == 1) \n            return 1;\n\n        return GetValue(index-1) + GetValue(index-2);\n    }\n}\n\n\n//use dotnet-script to test this\nConsole.WriteLine(\"Please enter the index to be computed\");\nvar input = Console.ReadLine();\nvar index = 0;\nwhile(!Int32.TryParse(input, out index)) {\n    Console.WriteLine(\"Please enter the index to be computed\");\n    input = Console.ReadLine();\n}\nvar fibonacciValue = Fibonacci.GetValue(index);\nConsole.WriteLine($\"The value for index {index} is  {fibonacciValue}\");\n\n    "
  },
  {
    "path": "Maths/Number-Theory/Fibonacci_Number/FibonacciNumbers.java",
    "content": "import java.util.Scanner;\n\npublic class FibonacciNumbers {\n\n\tpublic static void main(String[] args) {\n\t\t// TODO Auto-generated method stub\n\t\tScanner sc = new Scanner(System.in);\n\t\tint n1 = 0, n2 = 1, ni, i;\n\t\tSystem.out.print(\"Enter number in series : \");\n\t\tint number = sc.nextInt();\n\t\t// printing 0 and 1\n\t\tSystem.out.print(n1 + \" \" + n2);\n\n\t\t// loop starts from 2 as 0 and 1 are already printed\n\t\tfor (i = 2; i < number; i++) {\n\t\t\tni = n1 + n2;\n\t\t\tSystem.out.print(\" \" + ni);\n\t\t\tn1 = n2;\n\t\t\tn2 = ni;\n\t\t}\n\n\t}\n\n}\n"
  },
  {
    "path": "Maths/Number-Theory/Fibonacci_Number/Fibonacci_Number.clj",
    "content": "; lazy sequence of fibonacci\n(def fibonacci\n  (map first (iterate \n             (fn [[a b]] [b (+ a b)]) [0 1])))\n  \n(defn generate-fibonacci\n  [n]\n  (take n fibonacci))\n\n(print (generate-fibonacci 30))\n; will print \n; (0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765 10946 17711 28657 46368 75025 121393 196418 317811 514229)\n"
  },
  {
    "path": "Maths/Number-Theory/Fibonacci_Number/Fibonacci_Number.cpp",
    "content": "#include <iostream>\nusing namespace std;\n\nint main()\n{\n    int n, t1 = 0, t2 = 1, nextTerm = 0;\n\n    cout << \"Enter the number of terms: \";\n    cin >> n;\n\n    cout << \"Fibonacci Series: \";\n\n    for (int i = 1; i <= n; ++i)\n    {\n        // Prints the first two terms.\n        if(i == 1)\n        {\n            cout << \" \" << t1;\n            continue;\n        }\n        if(i == 2)\n        {\n            cout << t2 << \" \";\n            continue;\n        }\n        nextTerm = t1 + t2;\n        t1 = t2;\n        t2 = nextTerm;\n        \n        cout << nextTerm << \" \";\n    }\n    return 0;\n}\n"
  },
  {
    "path": "Maths/Number-Theory/Fibonacci_Number/Fibonacci_Number.py",
    "content": "def fibonacci(number):\n    # return 0 and 1 for first and second terms\n    if number == 0:\n        return 0\n    elif number == 1:\n        return 1\n    else:\n        # return the sum of two numbers\n        return fibonacci(number - 1) + fibonacci(number - 2)\n  \n# read the total number of items in Fibonacci series\nmax_item_input = input(\"Enter the number of items in Fibonacci series\\n\")\nmax_item = int(max_item_input)\n  \n# iterate from 0 till number of terms\nfor count in range(max_item):\n    print(fibonacci(count), end=\",\")\n"
  },
  {
    "path": "Maths/Number-Theory/Fibonacci_Number/fibonacci.sh",
    "content": "fibonacci()\n{\n\tif [ $1 -le 0 ]\n\tthen\n\t\techo -n \"invalid input !\"\n\telif [ $1 == 1 ]\n\tthen\n\t\techo -n \"0 \"\n\telif [ $1 == 2 ]\n\tthen\n\t\techo -n \"1 \"\n\telse\n\t\techo -n \"$[`fibonacci $[$1-2]` + `fibonacci $[$1 - 1]` ] \"\n\tfi\n}\necho \"Enter a number: \"\nread n\nfibonacci $n\necho \n\n"
  },
  {
    "path": "Maths/Number-Theory/Perfect_Number/Perfect Number.cpp",
    "content": "#include <iostream> \n#include <cctype>\nusing namespace std; \n\nint main(){\n    int n,i=1,sum=0;\n    cout << \"Enter a number: \";\n    cin >> n;\n       while(i<n){\n       if(n%i==0)\n       sum=sum+i;\n       i++; \n}\n\nif(sum==n)\n    cout << i << \" is a perfect number\\n\"; \nelse\n    cout << i << \" is not a perfect number\\n\";\n    system(\"pause\"); \n\nreturn 0;\n}\n"
  },
  {
    "path": "Maths/Number-Theory/Perfect_Number/PerfectNumber.py",
    "content": "\r\n\r\nnumlist = []\r\nnum1 = int(input(\"number: \\n\"))\r\n\r\nfor i in range(1, num1 - 1):\r\n    y = num1%i\r\n    if(y == 0):\r\n        numlist.append(i)\r\nx = 0\r\nfor i in range(len(numlist)):\r\n    x = x + numlist[i]\r\n\r\nif(x == num1):\r\n    print(num1, \" is a perfect number!\")\r\n\r\nelse:\r\n    print(num1, \" is not a perfect number\")\r\n"
  },
  {
    "path": "Maths/Number-Theory/Perfect_Number/Perfect_Number,sh",
    "content": "#!/bin/bash\necho \"Enter a number : \"\nread a\ni=1\nwhile [ $((i)) -lt $((a)) ]\ndo\nif [ $((a%i)) == 0 ]\nthen\nlet \"$((sum+=i))\"\nfi\nlet \"$((i+=1))\"\ndone\nif [ $((sum)) -eq $((a)) ]\nthen \necho \"$((a)) is a Perfet Number.\"\nelse\necho \"$((a)) is not a Perfect Number.\"\nfi\n"
  },
  {
    "path": "Maths/Number-Theory/Perfect_Number/Perfect_Number.java",
    "content": "// Nothing Special\n\nimport java.util.Scanner;\n\npublic class Nothing {\n    public static void main(String[] args) {\n        int n, sum = 0;\n        Scanner s = new Scanner(System.in);\n\n        System.out.print(\"Enter any integer you want to check:\");\n        n = s.nextInt();\n\n        for(int i = 1; i < n; i++) {\n            if(n % i == 0) {\n                sum = sum + i;\n            }\n        }\n\n        if(sum == n) {\n            System.out.println(\"Given number is Perfect\");\n        }\n        else {\n            System.out.println(\"Given number is not Perfect\");\n        }    \n    }\n    int divisor(int x) {\n        return x;\n    }\n}\n"
  },
  {
    "path": "Maths/Number-Theory/Perfect_Number/perfec_numper.py",
    "content": "def isPerfect( n ):  \n    sum,i = 1,2\n    while i * i <= n: \n        if n % i == 0: \n            sum = sum + i + n/i \n        i += 1  \n    return (True if sum == n and n!=1 else False) \n  \nn = int(input(\"Enter a number to check if it's Perfect or not : \"))\n\nif isPerfect(n):\n    print(n, \"is aPerfect Number\")\nelse:\n    print(n, \"is not a Perfect Number\")\n    "
  },
  {
    "path": "Maths/Number-Theory/Perfect_Number/perfectnumber.cpp",
    "content": "#include <iostream>\n#include <math.h>\nusing namespace std;\n\nint main()\n{\n  int i, n, num, sum = 0;\n  cout << \"Enter The Number\" << endl;\n  cin >> num;\n\n  for (i = 1; i <= sqrt(num); i++)\n  {\n    if (num % i == 0)\n    {\n      if (num / i == 1)\n      {\n        sum = 0;\n      }\n      else\n      {\n        sum = sum + i;\n      }\n      if (num / i != i && num / i != num)\n      {\n        sum = sum + (num / i);\n      }\n    }\n  }\n  if (sum == num)\n  {\n    printf(\"PERFECT NUMBER  \\n\");\n  }\n  else\n  {\n    printf(\"NOT A PERFECT NUMBER  \\n\");\n  }\n  return 0;\n}\n"
  },
  {
    "path": "Maths/Number-Theory/Perfect_Number/perfectnumber.js",
    "content": "function is_perfect(number) {\n    var temp = 0;\n    for (var i = 1; i <= number / 2; i++) {\n        if (number % i === 0) {\n            temp += i;\n        }\n    }\n\n    if (temp === number && temp !== 0) {\n        console.log(\"It is a perfect number.\");\n    } else {\n        console.log(\"It is not a perfect number.\");\n    }\n}\nis_perfect(28); //enter the number here"
  },
  {
    "path": "Maths/Number-Theory/Perfect_Number/perfectnumber.php",
    "content": "function isPerfect($n) { \n    $sum = 1; \n    for ($i = 2; $i * $i <= $n; $i++) { \n        if ($n % $i == 0) { \n            if($i * $i != $n) {\n                $sum = $sum + $i + (int)($n / $i); \n            } else {\n                $sum = $sum + $i;\n            } \n        }\n    }  \n    if ($sum == $n && $n != 1) {\n        echo \"$n is a perfect number\"; \n    } else {\n        echo \"$n is not a perfect number\"; \n    }\n}\nisPerfect(6);"
  },
  {
    "path": "Maths/Number-Theory/README.md",
    "content": "# This folder is empty.\n"
  },
  {
    "path": "Maths/Number-Theory/Segmented_Sieve/README.md",
    "content": "## This folder is empty.\n"
  },
  {
    "path": "Maths/Number-Theory/Segmented_Sieve/Segmented_Sieve.php",
    "content": "<?php\ndeclare(strict_types=1);\n\nfunction segmentedSieve(int $maxValue): array\n{\n    // Prepare a sieve, assume all numbers are prime.\n    $primes = array_fill(0, $maxValue + 1, true);\n\n    // 0 and 1 are not primes, skip\n    $primes[0] = false;\n    $primes[1] = false;\n\n    for ($i = 2; $i <= $maxValue; $i++) {\n        if ($primes[$i] === false) {\n            // We already know this is not a prime, stop waisting time here\n            continue;\n        }\n        for ($j = $i + $i; $j <= $maxValue; $j += $i) {\n            // Mark every multiple of a prime as not prime\n            $primes[$j] = false;\n        }\n    }\n\n    // filter out all non-primes, then return the keys (primes)\n    return array_keys(array_filter($primes));\n}\n\n$maxValue = isset($argv[1]) && is_numeric($argv[1]) ? (int) $argv[1] : 100;\n\n$primes = segmentedSieve($maxValue);\n\nprintf('[%s]' . PHP_EOL, implode(', ', $primes));\n"
  },
  {
    "path": "Maths/Number-Theory/Segmented_Sieve/segmented_sieve.js",
    "content": "function segmented_sieve(n){\n    //Create an boolean array with all values True\n    var primes = new Array(n).fill(true)\n\n    for(var i=2;i<=n;i++){\n        //If prime[p] is True,it is a prime and its multiples are not prime\n        if(primes[i]){\n            for(var j=i*2;j<=n;j+=i){\n\n                //Mark every multiple of a prime as not prime\n                primes[j]=false\n            }\n        }\n    }\n    //If value is true it is prime and print value\n    for(var k=2;k<n;k++){\n        if(primes[k])\n            console.log(k)\n    }\n}\n\n//Test\nlet number = prompt(\"Enter a positive integer\")\nsegmented_sieve(parseInt(number))"
  },
  {
    "path": "Maths/Number-Theory/Segmented_Sieve/segmented_sieve.py",
    "content": "def segmented_sieve(n):\n\n    # Create an boolean array with all values True\n    primes = [True]*n\n\n    for p in range(2,n):\n        #If prime[p] is True,it is a prime and its multiples are not prime\n\n        if primes[p]:\n            for i in range(2*p,n,p):\n\n                # Mark every multiple of a prime as not prime\n                primes[i]=False\n\n    #If value is true it is prime and print value\n    for l in range(2,n):\n        if primes[l]:\n            print(f\"{l} \")\n\n#Test\nwhile True:\n    try:\n        input_value = int(input(\"Please a number: \"))\n        segmented_sieve(input_value)\n        break\n    except ValueError:\n        print(\"No valid integer! Please try again ...\")"
  },
  {
    "path": "Maths/Number-Theory/Sieve_of_Eratosthenes/SieveOfEratosthenes.c",
    "content": "/*C program to print all prime number less than or equal to n using Sieve of Eratosthenes*/\n\n#include<stdio.h>\n#include<stdbool.h>\n\nvoid SieveOfEratosthenes(int num)\n{\n\t/*Boolean array to mark a number is prime or not*/\n\tbool prime[num+1];\n\tint i,j;\n\t\n\t/*Initialisation(Mark all number as prime)*/\n\tfor(i=0;i<=num;i++)\n\tprime[i]=true;\n\t\n\t/*Zero is not prime*/\n\tprime[0]=false;\n\t\n\t/*One is not prime*/\n\tprime[1]=false;\n\t\n\t/*Mark all non prime number as false*/\n\tfor(i=2;i<=num;i++){\n\t\tif(prime[i]==true){\n\t\t\tfor(j=i*i;j<=num;j+=i)\n\t\t\tprime[j]=false;\n\t\t}\n\t}\n\t/*Print all the prime numbers*/\n\tfor(i=2;i<=num;i++){\n\t\tif(prime[i]==true)\n\t\tprintf(\"%d \",i);\n\t}\n\tprintf(\"\\n\");\n}\n\nint main()\n{\n\tint num;\n\t/*Take input from the user*/\n\tscanf(\"%d\",&num);\n\t/*Prime number generation using Sieve of Eratosthenes*/\n\tSieveOfEratosthenes(num);\n\treturn 0;\n}\n"
  },
  {
    "path": "Maths/Number-Theory/Sieve_of_Eratosthenes/SieveOfEratosthenes.cs",
    "content": "using System;\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.Linq;\n\nclass SieveOfEratosthenes\n{\n    // Implementation using the Sieve of Eratosthenes algorithm\n    private static int[] GetAllPrimesUpTo(int num) // Includes num\n    {\n        if (num < 2)\n        {\n            return new int[0];\n        }\n\n        BitArray primes = new BitArray(num + 1);\n        primes[2] = true;\n        for (int i = 3; i < num; i += 2)\n        {\n            primes[i] = true;\n        }\n\n        for (int i = 0; i * i < num; i++)\n        {\n            if (primes[i])\n            {\n                for (int primeMultiple = i * i; primeMultiple < num; primeMultiple += i)\n                {\n                    primes[primeMultiple] = false;\n                }\n            }\n        }\n        \n        List<int> primesList = new List<int>();\n        for (int i = 0; i < primes.Length; i++)\n        {\n            if (primes[i])\n            {\n                primesList.Add(i);\n            }\n        }\n\n        return primesList.ToArray();\n    }\n\n    static void Main(string[] args)\n    {\n        // Test Cases:\n        // Small Number\n        // 3\n        // 2\n        // 1\n        // 0\n        // Negative Number\n        // Large Number\n        int[] primes = GetAllPrimesUpTo(100).ToArray();\n        Console.WriteLine($\"Primes Found: {primes.Length}\"); // Primes Found: 25\n\n        primes = GetAllPrimesUpTo(3).ToArray();\n        Console.WriteLine($\"Primes Found: {primes.Length}\"); // Primes Found: 1\n\n        primes = GetAllPrimesUpTo(2).ToArray();\n        Console.WriteLine($\"Primes Found: {primes.Length}\"); // Primes Found: 1\n\n        primes = GetAllPrimesUpTo(1).ToArray();\n        Console.WriteLine($\"Primes Found: {primes.Length}\"); // Primes Found: 0\n\n        primes = GetAllPrimesUpTo(0).ToArray();\n        Console.WriteLine($\"Primes Found: {primes.Length}\"); // Primes Found: 0\n\n        primes = GetAllPrimesUpTo(-100).ToArray();\n        Console.WriteLine($\"Primes Found: {primes.Length}\"); // Primes Found: 0\n\n        primes = GetAllPrimesUpTo(1000000000).ToArray(); // 1 Billion\n        Console.WriteLine($\"Primes Found: {primes.Length}\"); // Primes Found: 50847534\n\n        Console.ReadLine();\n    }\n}\n"
  },
  {
    "path": "Maths/Number-Theory/Sieve_of_Eratosthenes/Sieve_of_Erastosthenes.rb",
    "content": "class SieveOfErastosthenes\n  def initialize(limit)\n    @limit = limit\n    @primes = initial_array\n  end\n\n  # Auto invokation of the class\n  def self.call(limit)\n    new(limit).call\n  end\n\n  def call\n    find_primes\n    @primes.select { |n| n }.length # Select only prime numbers in array and return only prime values.\n  end\n  \n  private\n  \n  def initial_array\n    (0..@limit).map {|i| i >= 2 ? true : false}\n  end\n  \n  # Iterates over all truthies values to filter multiples and get primes\n  def find_primes\n    index = 0\n    while index < @primes.length do\n      find_multiples(index) if @primes[index]\n      index += 1\n    end\n  end\n\n  # Finds all multiples of the current index number, starting with its square.\n  def find_multiples(index)\n    multiples_index = index * index\n    while multiples_index < @primes.length do\n      @primes[multiples_index] = false\n      multiples_index += index\n    end\n  end  \nend\n\nputs SieveOfErastosthenes.call(-1) # 0\nputs SieveOfErastosthenes.call(1) # 0\nputs SieveOfErastosthenes.call(100) # 25 \nputs SieveOfErastosthenes.call(1000000) # 78498"
  },
  {
    "path": "Maths/Number-Theory/Sieve_of_Eratosthenes/Sieve_of_Erastosthenes.ts",
    "content": "const getAllPrimesUpToNumber = (num: number): number[] => {\n  //Prefill array up to max num.\n  const maxNumArray: boolean[] = new Array(num).fill(true)\n\n  //Won't find any primes > sqrt of num.\n  const limit = Math.floor(Math.sqrt(num))\n\n  //Increment by 2, as no even numbers besides 2 are prime.\n  for (let i = 3; i < limit; i += 2) {\n    if (maxNumArray[i]) {\n      //Remove multiples of primes.\n      for (let j = i * i; j < num; j += i * 2) {\n        maxNumArray[j] = false\n      }\n    }\n  }\n\n  //Initialize with 2, as it is the only even prime and we have not checked them.\n  const primes: number[] = [2]\n\n  //Push all items that are truthy to primes array.\n  for (let i = 3; i < num; i += 2) {\n    maxNumArray[i] && primes.push(i)\n  }\n\n  return primes\n}\n\nconsole.log(getAllPrimesUpToNumber(10000000))\n"
  },
  {
    "path": "Maths/Number-Theory/Sieve_of_Eratosthenes/Sieve_of_Eratosthenes.c",
    "content": "#include <stdio.h>\n\nint main()\n{\n    int number,i,j;\n    printf(\"Enter the number\\n\");\n    scanf(\"%d\",&number);\n\n    int primes[number+1];\n\n    //populating array with naturals numbers\n    for(i = 2; i<=number; i++)\n        primes[i] = i;\n\n    i = 2;\n    while ((i*i) <= number)\n    {\n        if (primes[i] != 0)\n        {\n            for(j=2; j<number; j++)\n            {\n                if (primes[i]*j > number)\n                    break;\n                else\n                    // Instead of deleteing , making elemnets 0\n                    primes[primes[i]*j]=0;\n            }\n        }\n        i++;\n    }\n\n    for(i = 2; i<=number; i++)\n    {\n        //If number is not 0 then it is prime\n        if (primes[i]!=0)\n            printf(\"%d\\n\",primes[i]);\n    }\n\n    return 0;\n}\n"
  },
  {
    "path": "Maths/Number-Theory/Sieve_of_Eratosthenes/Sieve_of_Eratosthenes.cpp",
    "content": "// C++ program to print all primes smaller than or equal to \n// n using Sieve of Eratosthenes \n#include <bits/stdc++.h> \nusing namespace std; \n\nvoid SieveOfEratosthenes(int n) \n{ \n\t// Create a boolean array \"prime[0..n]\" and initialize \n\t// all entries it as true. A value in prime[i] will \n\t// finally be false if i is Not a prime, else true. \n\tbool prime[n+1]; \n\tmemset(prime, true, sizeof(prime)); \n\n\tfor (int p=2; p*p<=n; p++) \n\t{ \n\t\t// If prime[p] is not changed, then it is a prime \n\t\tif (prime[p] == true) \n\t\t{ \n\t\t\t// Update all multiples of p greater than or \n\t\t\t// equal to the square of it \n\t\t\t// numbers which are multiple of p and are \n\t\t\t// less than p^2 are already been marked. \n\t\t\tfor (int i=p*p; i<=n; i += p) \n\t\t\t\tprime[i] = false; \n\t\t} \n\t} \n\n\t// Print all prime numbers \n\tfor (int p=2; p<=n; p++) \n\tif (prime[p]) \n\t\tcout << p << \" \"; \n} \n\n// Driver Program to test above function \nint main() \n{ \n\tint n = 30; \n\tcout << \"Following are the prime numbers smaller \"\n\t\t<< \" than or equal to \" << n << endl; \n\tSieveOfEratosthenes(n); \n\treturn 0; \n} \n"
  },
  {
    "path": "Maths/Number-Theory/Sieve_of_Eratosthenes/Sieve_of_Eratosthenes.go",
    "content": "package main\n\nimport \"fmt\"\n\nfunc checkPrime(n int) bool {\n\tif n > 1 {\n\t\tif n == 2 {\n\t\t\treturn true\n\t\t}\n\n\t\tfor i := 2; i < n; i++ {\n\t\t\tif n % i == 0 {\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t} else {\n\t\treturn false\n\t}\n\treturn true\n}\n\nfunc generateSieve(n int) []int {\n\tvar sieve []int\n\tfor i := 1; i < n; i++ {\n\t\tif checkPrime(i) {\n\t\t\tsieve = append(sieve, i)\n\t\t}\n\t}\n\treturn sieve\n}\n\nfunc main() {\n\tfmt.Println(generateSieve(500))\n}"
  },
  {
    "path": "Maths/Number-Theory/Sieve_of_Eratosthenes/SieveofErastosthenes.java",
    "content": "public class PrimeSieve {\n    public static void main(String[] args) { \n        int n = Integer.parseInt(args[0]);\n\n        // initially assume all integers are prime\n        boolean[] isPrime = new boolean[n+1];\n        for (int i = 2; i <= n; i++) {\n            isPrime[i] = true;\n        }\n\n        // mark non-primes <= n using Sieve of Eratosthenes\n        for (int factor = 2; factor*factor <= n; factor++) {\n\n            // if factor is prime, then mark multiples of factor as nonprime\n            // suffices to consider mutiples factor, factor+1, ...,  n/factor\n            if (isPrime[factor]) {\n                for (int j = factor; factor*j <= n; j++) {\n                    isPrime[factor*j] = false;\n                }\n            }\n        }\n\n        // count primes\n        int primes = 0;\n        for (int i = 2; i <= n; i++) {\n            if (isPrime[i]) primes++;\n        }\n        System.out.println(\"The number of primes <= \" + n + \" is \" + primes);\n    }\n}\n"
  },
  {
    "path": "Maths/Number-Theory/Sieve_of_Eratosthenes/prime_and_base.py",
    "content": "#include<bits/stdc++.h>\nusing namespace std;\n\nchar letterconverter(int number)\n{\n    return 'A' + (number-10);\n}\n\nint main()\n{\n    vector<int> primes;\n    int num, flag, x, base2, i, upto;\n\n    // Take input from user\n    cout << \"Find prime numbers upto : \";\n    cin >> upto;\n\n    for(num = 2; num <= upto; num++)\n    {\n        flag = 0;\n        for(i = 2; i <= (num / 2); i++)\n        {\n            if(num % i == 0) {\n                flag = 1;\n                break;\n            }\n        }\n        \n        // If the number is prime then store it in primes vector\n        if(flag == 0)\n            primes.push_back(num);\n    }\n    \n    // Printing all primes between [2, N]\n    cout << endl << \"All prime numbers upto \" << upto << \" are : \" << endl;\n    for(i=0; i<primes.size(); i++)\n    {\n        cout<<primes[i]<<\" \";\n    }\n    cout<<\"\\n\";\n\n    cout << \"What base do you want it to be?\\n\";\n    cin>>base2;\n  \n    for (int j =0; j<primes.size(); j++)\n    {\n        string temp = \"\";\n        num = primes[j];\n        while(num > 0)\n        {\n            x = num % base2;\n            if(x <= 9)\n            {\n                temp += to_string(x);\n            }\n            else\n            {\n                temp += letterconverter(x);\n            }\n                \n            num /= base2;\n        \n        }\n        reverse(temp.begin(), temp.end());\n        cout<<temp<<\" \";\n    }\n}"
  },
  {
    "path": "Maths/Number-Theory/Smith_number/SmithNumber.py",
    "content": "# ---------------------------------PROBLEM STATEMENT--------------------------------\n# Given a number n, the task is to find out whether this number is smith number or not. \n# Smith Number is a composite number whose sum of digits is equal to the \n# sum of digits in its prime factorization.\n\n# Python Code to identify Smith Number -\n\ndef factors(n):\n    f, fs = 3, []\n    while n % 2 == 0:    \n        fs.append(2)\n        n /= 2\n    while f * f <= n:\n        while n % f == 0:\n            fs.append(f)\n            n /= f\n        f += 2\n    if n > 1: fs.append(n)\n    return fs\n\n# Finding sum of digits of prime factor of the given number\n \ndef getIntLetterCount(n):\n    return sum([int(l) for l in list(str(n))])\n \ndef isSmithNumber(n):\n    return sum([getIntLetterCount(f) for f in factors(n)]) == getIntLetterCount(n)\n\n# Driver Code :    \n \nif __name__ == '__main__':\n\n    # Input the number to be checked whether Smith number or not \n    n = input()\n \n    if isSmithNumber(n):\n        print (\"It is Smith Number\")\n    else:\n        print (\"It is not a Smith Number\")\n\n\n\n# The first few Smith Numbers are as follows : 4 22 27 58 85 94 121 166 202 265 274 319 346 355..."
  },
  {
    "path": "Maths/Number-Theory/Smith_number/smith_numbers_till_n.cpp",
    "content": "// ---------------------------------PROBLEM STATEMENT--------------------------------\n//Given a number n, the task is to find out whether this number is smith number or not. \n//Smith Number is a composite number whose sum of digits is equal to the \n//sum of digits in its prime factorization.\n\n\n#include<bits/stdc++.h>\nusing namespace std;\nint num;\n\n// array to store prime numbers\nvector <int> is_prime;\n\n// function for sieve of Sundaram\nvoid sieve_of_sundaram()\n{\n    // sieve of sundaram will give primes smaller than 2+2*n for a given number n\n    // we will reduce num to num/2 as it won't effect our answer\n\t// is_marked array is used to separate numbers of the form i+j+2*i*j from others where 1 <= i <= j\n\tbool is_marked[num/2 + 100] = {0};\n\n    //logic : \n    // marking all numbers i where 2*i+1 is not prime\n\tfor (int i=1; i<=(sqrt(num)-1)/2; i++)\n\t\tfor (int j=(i*(i+1))<<1; j<=num/2; j=j+2*i+1)\n\t\t\tis_marked[j] = true;\n\n\tis_prime.push_back(2);// as 2 is the first prime number \n\n\t// rest primes are pushed in is_prime vecto, they are of the form 2*i + 1 where is_marked[i] is false.\n\tfor (int i=1; i<=num/2; i++)\n\t\tif (is_marked[i] == false)\n\t\t\tis_prime.push_back(2*i + 1);\n}\n\n// function to check if a number is Smith number or not\nbool is_smith_number(int n)\n{\n\tint initial_n = n;// storing the initial value of n in a variable \n\n\tint sum_of_digits = 0;// to store the sum of digits of prime factores of n\n\tfor (int i = 0; is_prime[i] <= n/2; i++)\n\t{\n\t\twhile (n % is_prime[i] == 0)\n\t\t{\n            //adding the digits of primes[i] to sum_of_digits of primes[i] is a prime factor\n\t\t\tint p = is_prime[i];\n\t\t\tn = n/p;\n\t\t\twhile (p > 0)\n\t\t\t{\n\t\t\t\tsum_of_digits += (p % 10);\n\t\t\t\tp = p/10;\n\t\t\t}\n\t\t}\n\t}\n\n    // if n is not 1, one prime factor of n still exist and we need to sum its digits too\n\tif (n != 1 && n != initial_n)\n\t{\n\t\twhile (n > 0)\n\t\t{\n\t\t\tsum_of_digits = sum_of_digits + n%10;\n\t\t\tn = n/10;\n\t\t}\n\t}\n\n    // after covering all the prime factors of initial n, we add the digits of initial n too\n\tint sumDigits = 0;\n\twhile (initial_n > 0)\n\t{\n\t\tsumDigits = sumDigits + initial_n % 10;\n\t\tinitial_n = initial_n/10;\n\t}\n\n    // we return true only if the sum of digits in prime factors of inital n and sum of digits \n    // of initial n are same\n\treturn (sum_of_digits == sumDigits);\n}\n\n// main function\nint main()\n{\n    int n;\n    // taking input for number n\n    cout<<\"Enter the value of n: \";\n    cin>>n;\n    num=n;\n    // calling the function sieve_of_sundaram\n    sieve_of_sundaram();\n    // printing smith numbers present between 1 and n\n    cout << \"Smith numbers present between 1 and n: \\n\";\n    for (int i=1; i<=n; i++)\n    {\n        if (is_smith_number(i))\n            cout << i << \" \";\n    }\n\treturn 0;\n}\n"
  },
  {
    "path": "Maths/Number-Theory/Strong_Number/strong_number.c",
    "content": "#include <stdio.h>  \nint main()  \n{  \n    int n;  \n    int sum=0;  \n    printf(\"Enter a number\");  \n    scanf(\"%d\",&n);  \n    int k=n;  \n    int r;  \n    while(k!=0)  \n    {  \n        r=k%10;  \n        int f=fact(r);  \n        k=k/10;  \n        sum=sum+f;  \n    }  \n    if(sum==n)  \n    {  \n        printf(\"\\nNumber is a strong\");  \n    }  \n    else  \n    {  \n        printf(\"\\nNumber is not a strong\");  \n    }  \n    return 0;  \n}  \nint fact(int r)  \n{  \n    int mul=1;  \n    for(int i=1;i<=r;i++)  \n    {  \n        mul=mul*i;  \n    }  \n    return mul;  \n      \n}  "
  },
  {
    "path": "Maths/Number-Theory/Strong_Number/strong_number.cpp",
    "content": "#include<iostream>\nusing namespace std;\n\nint main()\n{\nint n,i;\nint fact,rem;\ncout << \"\\nEnter a number : \";\ncin >> n;\ncout << endl;\nint sum = 0;\nint temp = n;\nwhile(n)\n{\ni = 1,fact = 1;\nrem = n % 10;\n\nwhile(i <= rem)\n{\nfact = fact * i;\ni++;\n}\nsum = sum + fact;\nn = n / 10;\n}\nif(sum == temp)\n     cout << temp << \" is a strong number\\n\";\nelse\n     cout << temp << \" is not a strong number\\n\";\n\nreturn 0;\n}"
  },
  {
    "path": "Maths/Number-Theory/Strong_Number/strong_number.java",
    "content": "import java.util.*;\npublic class Main\n{\npublic static void main(String[] args) {\nint n,i;\nint fact,rem;\nScanner sc = new Scanner(System.in);\nSystem.out.print(\"\\nEnter the number : \");\nn = sc.nextInt();\nint sum = 0;\nint temp = n;\nwhile(n != 0)\n{\ni = 1;\nfact = 1;\nrem = n % 10;\n\nwhile(i <= rem)\n{\nfact = fact * i;\ni++;\n}\nsum = sum + fact;\nn = n / 10;\n}\n\nif(sum == temp)\nSystem.out.println(temp + \" is a strong number\\n\");\nelse\nSystem.out.println(temp + \" is not a strong number\\n\");\n\nSystem.out.println();\n}\n}"
  },
  {
    "path": "Maths/Number-Theory/Strong_Number/strong_number.py",
    "content": "n= int(input(\"Enter the number : \"))\nsum = 0\ntemp = n\nwhile (n):\n    i = 1\n    fact = 1\n    rem = int(n % 10)\n\nwhile(i <= rem):\n    fact = fact * i\n    i = i + 1\n    sum = sum + fact\n    n = int(n / 10)\n\nif(sum == temp):\n    print(temp,end = \"\")\n    print(\" is a strong number\")\nelse:\n    print(temp,end = \"\") \n    print(\" is not a strong number\")\n\n"
  },
  {
    "path": "Maths/Number-Theory/Strong_Number/strong_number.sh",
    "content": "!#bin/bash\necho enter the value of n\nread n\nsum=0\nk=$n\nwhile [ $n -gt 0 ]\ndo\nd=`echo $n%10|bc`\nfact=1\ni=1\nwhile [ $i -le $d ]\ndo\nfact=`echo $fact*$i|bc`\ni=`echo $i+1|bc`\ndone\nsum=`echo $sum+$fact|bc`\nn=`echo $n/10|bc`\ndone\nif [ $sum -eq $k ]\nthen\necho it is strong number\nelse\necho it is not strong number\nfi"
  },
  {
    "path": "Maths/Number-Theory/Tribonacci_Number/nthTribonacci.kt",
    "content": "fun nthTribonacci(n: Int): Int{\n    \n    //create a dp array of size n+1 filled with 0's\n    val dp = IntArray(n+1){0}\n    for(i in 0..n){\n        if(i < 3)\n            dp[i] = i/2 \n        //since first three elements are 0, 0 and 1\n        //so we can cleverly write dp[i] = i/2\n        else \n        //otherwise, the sum of preceeding three values is the ith Tribonacci\n            dp[i] = dp[i - 1] + dp[i - 2] + dp[i - 3]\n    }\n    return dp[n]\n}\n\nfun main(){\n    \n    //read input value of n\n    val n = readLine()!!.toInt()\n    \n    //print the corresponding output\n    println(nthTribonacci(n))\n}"
  },
  {
    "path": "Maths/Number-Theory/Ugly_Number/README.md",
    "content": "## This folder is empty.\n"
  },
  {
    "path": "Maths/Number-Theory/Ugly_Number/UglyNumber.go",
    "content": "// This file has the implementation to check whether a number is Ugly or not\n\npackage main\n\nimport (\n\t\"bufio\"\n\t\"fmt\"\n\t\"os\"\n\t\"strconv\"\n\t\"strings\"\n)\n\n// Check whether the function is ugly or not\nfunc isUgly(num int) bool {\n\tfor num >= 2 {\n\t\tif num%2 == 0 {\n\t\t\tnum /= 2\n\t\t} else if num%3 == 0 {\n\t\t\tnum /= 3\n\t\t} else if num%5 == 0 {\n\t\t\tnum /= 5\n\t\t} else {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn num == 1\n}\n\nfunc main() {\n\treader := bufio.NewReader(os.Stdin)\n\tfmt.Print(\"Enter Number: \")\n\tinput, _ := reader.ReadString('\\n')\n\tfmt.Println(input)\n\tinput = strings.TrimSuffix(input, \"\\n\")\n\tinputNum, err := strconv.Atoi(input)\n\tif err != nil {\n\t\tfmt.Println(\"Input Number is not valid\", input, err)\n\t\treturn\n\t}\n\n\tif isUgly(inputNum) {\n\t\tfmt.Println(\"Input Number is Ugly Number\")\n\t} else {\n\t\tfmt.Println(\"Input number is not Ugly\")\n\t}\n}\n"
  },
  {
    "path": "Maths/Number-Theory/Ugly_Number/UglyNumbers.sh",
    "content": "#!/bin/bash\necho \"Enter a positive integer : \"\nread x\nwhile [ $x -ne 1 ]\ndo\nif [ $((x%2)) -eq 0 ]\nthen\n  let \"x/=2\"\nelif [ $((x%3)) -eq 0 ]\nthen\n  let \"x/=3\"\nelif [ $((x%5)) -eq 0 ]\nthen\n  let \"x/=5\"\nelse\nlet \"n=1\"\necho \"It is not a Ugly Number.\"\nbreak\nfi\ndone\nif [ $((n)) -eq 0 ]\nthen\necho \"It is a Ugly Number.\"\nfi\nexit\n"
  },
  {
    "path": "Maths/Number-Theory/Ugly_Number/Ugly_Number.c",
    "content": "# include <stdio.h>\n# include <string.h>\n\nint main()\n{\n    int n , x = 0;\n    printf(\"\\n\\n Check whether a given number is an ugly number:\\n\");\n    printf(\"----------------------------------------------------\\n\");\n    printf(\"Input an integer number: \");\n    scanf(\"%d\",&n);\n    if (n <= 0) \n        printf(\"Input a correct number.\");  \n    while (n != 1) \n    {  \n        if (n % 5 == 0) \n        n /= 5;  \n        else if (n % 3 == 0) \n        n /= 3;  \n        else if (n % 2 == 0) \n        n /= 2;  \n        else \n        {  \n            printf(\"It is not an ugly number.\\n\"); \n            x = 1;  \n            break;  \n        }  \n    } \n    if(x == 0)\n        printf(\"It is an ugly number.\\n\");\n}\n"
  },
  {
    "path": "Maths/Number-Theory/Ugly_Number/Ugly_Number.java",
    "content": "//Implementing Ugly Number in Java\n\nimport java.util.*;\nclass Solution{\n//function to calculate whether ugly number or not\npublic boolean isUgly(int number) {\n    if (number <= 0){ \n      return false;\n    }\n    if (number == 1){ \n      return true;\n    }\n    if (number % 2 == 0) {\n        return isUgly(number/2);\n    }\n    if (number % 3 == 0) {\n        return isUgly(number/3);\n    }\n    if (number % 5 == 0) {\n        return isUgly(number/5);\n    }\n    return false;\n  }\n}\n\n//main class\npublic class Ugly_Number\n{\n  public static void main(String[] args){\n    Scanner scanner = new Scanner(System.in);\n    System.out.println(\"Enter the number: \");\n    int input_number = scanner.nextInt();\n    Solution object = new Solution();\n    boolean answer = object.isUgly(input_number);\n    if(answer==true)\n      System.out.println(\"Number is Ugly\");\n    else\n      System.out.println(\"Number is not Ugly\");\n  }\n}\n"
  },
  {
    "path": "Maths/Number-Theory/Ugly_Number/Ugly_Number.js",
    "content": "const uglyNumber = (number) => {\n\n    //determine if a number is prime\n    const numIsPrime = (num) => {\n        for (let i = 2; i <= Math.sqrt(num); i++) {\n            if (num % i === 0) {\n                return false;\n            }\n        }\n        return num > 1;\n    } \n\n    const primeFactors = [];\n    const uglyPrimeFactors = [2, 3, 5]\n    \n    //push distinct prime factors to the array\n    for (let i = 2; i <= number; i++) {\n        while (numIsPrime(i) && number % i === 0) {\n            if (!primeFactors.includes(i)) {\n                primeFactors.push(i);\n            }\n            number /= i;\n        }\n    }\n\n    //find out if number is an ugly number i.e has prime factors consisting of 2, 3, or 5\n    const numberIsUgly = primeFactors.some(factor => uglyPrimeFactors.includes(factor)) ? true : false;\n\n    return numberIsUgly;\n}\n"
  },
  {
    "path": "Maths/Number-Theory/Ugly_Number/Ugly_Number.php",
    "content": "<?php\n    //Check if the request has a number\n    if (isset($_REQUEST['number'])) {\n        $number = $_REQUEST['number'];\n    }\n    else {\n        //Set random number\n        $number = random_int(-10000, 10000);\n    }\n    \n    echo \"Number: \".$number;\n    //Check if the number is ugly\n    $isUglyNumber = checkUglyNumber($number);\n    if($isUglyNumber){\n        echo \" is an Ugly Number\";\n    }\n    else {\n        echo \" is not an Ugly Number\";\n    }\n    \n\n    //Function that checks if a number is ugly\n    function checkUglyNumber($number) {\n        if ($number<=1) {\n            return false;\n        }\n        elseif ($number==2) {\n            return true;\n        }\n        elseif ($number==3) {\n            return true;\n        }\n        elseif ($number==5) {\n            return true;\n        }\n        elseif ($number%2==0) {\n            return checkUglyNumber($number/2);\n        }\n        elseif ($number%3==0) {\n            return checkUglyNumber($number/3);\n        }\n        elseif ($number%5==0) {\n            return checkUglyNumber($number/5);\n        }\n        else {\n            return false;\n        }\n    }"
  },
  {
    "path": "Maths/Number-Theory/Ugly_Number/Ugly_Number.py",
    "content": "#Function checks if input is an ugly number or not\nimport sys\n\n#Function from: w3resource.com\ndef is_ugly_number(num):\n    if num == 0:\n        return False\n    for i in [2, 3, 5]: #2,3 and 5 must be the only prime factors of the ugly number\n        while num % i == 0:\n            num /= i\n    return num == 1\n\nprint(is_ugly_number(int(sys.argv[1])))\n"
  },
  {
    "path": "Maths/Number-Theory/Ugly_Number/Ugly_Number.rb",
    "content": "class UglyNumber\n  VALID_DIVIDERS = [2, 3, 5] # All valid dividers are stored in array for a better manipulation\n  \n  def self.is_ugly?(number)\n    # Checks if number is less or equal to one\n    if number < 1\n      return false\n    elsif number == 1\n      return true\n    end\n    ugly_dividers = VALID_DIVIDERS.select { |divider| number % divider == 0} # Select only the values which number can be divided\n    ugly_dividers.any? ? is_ugly?(number / ugly_dividers.first) : false # If some divider exists, returns recursively the function with number divided by first divider as param\n  end\nend\n\nputs UglyNumber.is_ugly?(0) # false\nputs UglyNumber.is_ugly?(1) # true\nputs UglyNumber.is_ugly?(6) # true\nputs UglyNumber.is_ugly?(8) # true\nputs UglyNumber.is_ugly?(14) # false\nputs UglyNumber.is_ugly?(29) # false\nputs UglyNumber.is_ugly?(101) # false\nputs UglyNumber.is_ugly?(81) # true"
  },
  {
    "path": "Maths/Number-Theory/Ugly_Number/Ugly_Number_Till_N.cpp",
    "content": "# include<bits/stdc++.h> \n\nusing namespace std; \n\nunsigned getNthUglyNo(unsigned n) \n{ \n    unsigned ugly[n];  \n    unsigned i2 = 0, i3 = 0, i5 = 0; \n    unsigned next_multiple_of_2 = 2; \n    unsigned next_multiple_of_3 = 3; \n    unsigned next_multiple_of_5 = 5; \n    unsigned next_ugly_no = 1; \n  \n    ugly[0] = 1; \n    for (int i=1; i<n; i++) \n    { \n       next_ugly_no = min(next_multiple_of_2, \n                           min(next_multiple_of_3, \n                               next_multiple_of_5)); \n       ugly[i] = next_ugly_no; \n       if (next_ugly_no == next_multiple_of_2) \n       { \n           i2 = i2+1; \n           next_multiple_of_2 = ugly[i2]*2; \n       } \n       if (next_ugly_no == next_multiple_of_3) \n       { \n           i3 = i3+1; \n           next_multiple_of_3 = ugly[i3]*3; \n       } \n       if (next_ugly_no == next_multiple_of_5) \n       { \n           i5 = i5+1; \n           next_multiple_of_5 = ugly[i5]*5; \n       } \n    } \n    return next_ugly_no; \n} \n  \nint main() \n{ \n    int n;\n\tcin>>n; \n    cout << getNthUglyNo(n); \n    return 0; \n} \n"
  },
  {
    "path": "Maths/Number-Theory/Ugly_Number/Ugly_Numbers.sh",
    "content": "#!/bin/bash\necho \"Enter a positive integer : \"\nread x\nwhile [ $x != 1 ] \ndo\n\tif [ $x%2 == 0 ]\n\tthen\n\t$x = $x/2\t\n\tfi\ndone\necho \"done\"\nexit\n"
  },
  {
    "path": "Maths/README.md",
    "content": "# Index\n\n* [Algebra](Algebra/)\n* [Calculus](Calculus/)\n* [Discrete](Discrete/)   \n* [Geometry](Geometry/) \n* [MOs-Algorithm](MOs-Algorithm/) \n* [Number-Theory](Number-Theory/) \n* [Series](Series/) \n* [Statistics](Statistics/)"
  },
  {
    "path": "Maths/Series/Arithmetic_Progression/AP.py",
    "content": "def AP(a,d,n): \n    sum=0       \n    curr_term=a \n    for i in range(1,n+1): \n        print(curr_term, end=' ') \n        curr_term =curr_term + d \n\n\na = 5   \nd = 1   \nn = 10 \n  \nAP(a, d, n) \n"
  },
  {
    "path": "Maths/Series/Arithmetic_Progression/Arithematic_Progression.cpp",
    "content": "#include<bits/stdc++.h>\nusing namespace std;\nint main()\n{  int A,N,D;//A=First Term,N= N th term, D=Common Difference\n   A=5;\n   N=8;\n   D=2;\n   for(int i=0;i<N;i++)\n   { cout<<A+i*D<<\" \"; }\n   }\n"
  },
  {
    "path": "Maths/Series/Arithmetic_Progression/Arithmetic_Progression.c",
    "content": "#include <stdio.h>\n\nvoid main(){\n    int a, n, d, i;\n\n    printf(\"Enter the first term: \");\n    scanf(\"%d\", &a);\n    printf(\"Enter the number of terms: \");\n    scanf(\"%d\", &n);\n    printf(\"Enter the difference between the terms: \");\n    scanf(\"%d\", &d);\n\n\tprintf(\"AP: \");\n    for (i = 0; i < n; i++)\n        printf(\"%d \", a + (i * d));\n}\n"
  },
  {
    "path": "Maths/Series/Arithmetic_Progression/Arithmetic_Progression.java",
    "content": "\nimport java.util.Scanner;\n\npublic class Arithmetic_Progression {\n\tpublic static void main(String[] args) {\n\t\tScanner sc = new Scanner(System.in);\n\t\tStringBuffer answer;\n\t\tdouble firstTerm, prevTerm, commonDiff;\n\t\tint numTerms;\n\t\t\n\t\t// user prompts\n\t\tSystem.out.print(\"What is the first term in the arithmetic progression? \");\n\t\tfirstTerm = sc.nextDouble();\n\t\tSystem.out.print(\"How many terms? \");\n\t\tnumTerms = sc.nextInt();\n\t\tSystem.out.print(\"What is the difference between each term? \");\n\t\tcommonDiff = sc.nextDouble();\n\t\t\n\t\tanswer = new StringBuffer(firstTerm + \" \");\n\t\tprevTerm = firstTerm;\n\t\t\n\t\tfor (int i = 0; i < numTerms; i++) {\n\t\t\tprevTerm += commonDiff;\n\t\t\tanswer.append(prevTerm + \" \");\n\t\t}\n\t\t\n\t\tSystem.out.println(answer.toString());\n\t} \n}\n"
  },
  {
    "path": "Maths/Series/Arithmetic_Progression/Arithmetic_Progression.js",
    "content": "/* \n* These functions can run in any JS environment: they're specific-agnostic.\n* Basically, they help getting an entire arithmetic progression,\n* calculating a progression's nth term or the sum of the progression\n* faster without using iterations.\n*/\n\n/* \n* Function to calculate an arithmetic progression, starting from a term,\n* with given difference, up to a given number of terms.\n* This function follows this formula:\n*   an = a + n * d\n* @param {Number} firstTerm - The term which starts the progression;\n* @param {Number} difference - The common difference of the progression;\n* @param {Number} nTerms - The maximum number of terms you wish to know;\n* @returns {Number[]} - The [nTerms] terms of the arithmetic progression.\n*/\nfunction arithmeticProgression(firstTerm, difference, nTerms) {\n    const terms = [];\n    for (let term = firstTerm; (term / difference) < nTerms; term += difference) {\n        terms.push(term);\n    }\n\n    return terms;\n}\n\n/* \n* Function to calculate the nth term of an arithmetic progression.\n* This function follows this formula:\n*   an = a1 + (n-1)d\n* @param {Number} nTerm - The nth term you wish to know;\n* @param {Number} firstTerm - The term which starts the progression;\n* @param {Number} difference - The common difference of the progression;\n* @returns {Number} - The nth term of the arithmetic progression.\n*/\nfunction arithmeticProgressionNthTerm(nTerm, firstTerm, difference) {\n    return firstTerm + ((nTerm - 1) * difference);\n}\n\n/*\n* Function to calculate the arithmetic series of an arithmetic progression,\n* which is the sum of all the progression's terms, starting from a term \n* and ending with another, without knowing the difference.\n* This function follows this formula:\n*   S = 1/2 * n * (a1 + an)\n* @param {Number} firstTerm - The term which starts the progression;\n* @param {Number} lastTerm - The last term of the progression;\n* @param {Number} nTerms - The number of terms which compose the progression;\n* @returns {Number} - The arithmetic series of the progression.\n*/\nfunction arithmeticSeries(firstTerm, lastTerm, nTerms) {\n    return 1 / 2 * nTerms * ( firstTerm + lastTerm );\n}\n\n\n/*\n* There is no need to create a function to calculate\n* the difference between two terms, because, well,\n* that's just a difference.\n* lastTerm - firstTerm = common difference of the progression.\n*/\n"
  },
  {
    "path": "Maths/Series/Arithmetic_Progression/Arithmetic_Progression.php",
    "content": "<?php\n\n$a = (int)readline(\"Enter the first term: \");\n$n = (int)readline(\"Enter the number of terms: \");\n$d = (int)readline(\"Enter the difference between the terms: \");\n\necho \"AP: \";\nfor ($i=0; $i < $n; $i++) { \n    echo $a + ($i * $d);\n}\n\n?>"
  },
  {
    "path": "Maths/Series/Arithmetic_Progression/Arithmetic_Progression.sh",
    "content": "#!/bin/bash\necho \"Enter first term of the AP : \"\nread a\necho \"Enter the common differnce :\"\nread d\necho \"Enter number of terms :\"\nread n\nfor ((i=0;i<=n;i++))\ndo\necho $((a+(i*d)))\ndone\n"
  },
  {
    "path": "Maths/Series/Arithmetic_Progression/Arithmetic_Progression.ts",
    "content": "/* \n* This class can run in any TS environment or be compiled to any JS environment: they're specific-agnostic.\n* Basically, it helps getting an entire arithmetic progression, calculating a progression's nth term or the \n* sum of the progression faster without using iterations.\n*/\n\nclass ArithmeticProgression {\n    firstTerm: number;\n    difference?: number;\n\n    /*\n    * @constructor\n    * @params {Number} [firstTerm=0] - The first term of the progression is required for all methods in this class, so it's a required param.\n    * @params {Number} [difference=1] - If known, this is the common difference between the progression's terms. It's required for the two main methods.\n    */\n    constructor(firstTerm: number = 0, difference: number = 1) {\n        this.firstTerm = firstTerm;\n        this.difference = difference;\n    }\n\n    /* \n    * Method to calculate an arithmetic progression, starting from a term,\n    * with given difference, up to a given number of terms.\n    * The \"difference\" parameter in the constructor is required.\n    * This method follows this formula:\n    *   an = a + n * d\n    * @param {Number} nTerms - The maximum number of terms you wish to know;\n    * @returns {Number[]} - The [nTerms] terms of the arithmetic progression.\n    */\n    calculate(nTerms: number): number[] {\n        const terms = [];\n        for (let term = this.firstTerm; (term / this.difference) < nTerms; term += this.difference) {\n            terms.push(term);\n        }\n    \n        return terms;\n    }\n\n    /* \n    * Method to calculate the nth term of an arithmetic progression.\n    * The \"difference\" parameter in the constructor is required.\n    * This method follows this formula:\n    *   an = a1 + (n-1)d\n    * @param {Number} nTerm - The nth term you wish to know;\n    * @returns {Number} - The nth term of the arithmetic progression.\n    */\n    getNthTerm(nTerm: number): number {\n        return this.firstTerm + ((nTerm - 1) * this.difference);\n    }\n\n    /*\n    * Method to calculate the arithmetic series of an arithmetic progression,\n    * which is the sum of all the progression's terms, starting from a term \n    * and ending with another, without knowing the difference.\n    * This method follows this formula:\n    *   S = 1/2 * n * (a1 + an)\n    * @param {Number} lastTerm - The last term of the progression;\n    * @param {Number} nTerms - The number of terms which compose the progression;\n    * @returns {Number} - The arithmetic series of the progression.\n    */\n    getSeries(lastTerm: number, nTerms: number): number {\n        return 1 / 2 * nTerms * ( this.firstTerm + lastTerm );\n    }\n\n    /*\n    * There is no need to create a method to calculate\n    * the difference between two terms, because, well,\n    * that's just a difference.\n    * lastTerm - firstTerm = common difference of the progression.\n    * I'll do it anyways, because a method which does it can be handy.\n    * @param {Number} secondTerm - The second term to get the difference along with the first;\n    * @param {Boolean} abs - If you want the result as an absolute value or not;\n    * @returns {Number} - The difference between the first and second terms.\n    */\n    getDifference(secondTerm: number, abs: boolean): number {\n        return abs\n                ? Math.abs(secondTerm - this.firstTerm)\n                : secondTerm - this.firstTerm;\n    }\n}\n"
  },
  {
    "path": "Maths/Series/Arithmetic_Progression/README.md",
    "content": "## This folder is empty.\n"
  },
  {
    "path": "Maths/Series/Fibonacci/Fibonacci.c",
    "content": "// Nothing Special\n\n#include <stdio.h>\n#include <inttypes.h>\n\nint main() {\n    int32_t t1 = 0 , t2 = 1 , next_term;\n    \n    int32_t n;  scanf(\"%\" PRId32 , &n);\n\n    puts(\"Fibonacci Series ...\");\n\n    for (int32_t i = 0; i <= n; i++) {\n        printf(\"%\" PRId32 \"\\t\" , t1);\n        next_term = t1 + t2;\n        t1 = t2;\n        t2 = next_term;\n    }\n    printf(\"\\n\");\n    return 0;\n}\n"
  },
  {
    "path": "Maths/Series/Fibonacci/Fibonacci.cpp",
    "content": "#include<bits/stdc++.h> \n\nusing namespace std; \n\nint fib(int n) \n\n{ \n\n    int a = 0, b = 1, c, i; \n\n    if( n == 0) \n\n        return a; \n\n    for(i = 2; i <= n; i++) { \n\n       c = a + b; \n\n       a = b; \n\n       b = c; \n\n    } \n\n    return b; \n\n} \n\nint main(){ \n\n    int n;\n    \n    cin>>n;\n\n    cout << fib(n); \n\n    return 0; \n\n} \n\n\n"
  },
  {
    "path": "Maths/Series/Fibonacci/Fibonacci.sh",
    "content": "#!/bin/bash\necho \"Enter number of terms in Fibonacci Series : \"\nread n\nf0=0\nf1=1\nfor((i=0;i<=n;i++))\ndo\nf=$f0+$f1\nf0=$f1\nf1=$f\necho $((f))\ndone\n"
  },
  {
    "path": "Maths/Series/Fibonacci/Fiboncci.py",
    "content": "def fibonacci(number):\n    # return 0 and 1 for first and second terms\n    if number == 0:\n        return 0\n    elif number == 1:\n        return 1\n    else:\n        # return the sum of two numbers\n        return fibonacci(number - 1) + fibonacci(number - 2)\n  \n# read the total number of items in Fibonacci series\nmax_item_input = input(\"Enter the number of items in Fibonacci series\\n\")\nmax_item = int(max_item_input)\n  \n# iterate from 0 till number of terms\nfor count in range(max_item):\n    print(fibonacci(count), end=\",\")\n"
  },
  {
    "path": "Maths/Series/Fibonacci/README.md",
    "content": "## This folder is empty.\n"
  },
  {
    "path": "Maths/Series/Fibonacci/fibonacci.cpp",
    "content": "#include<bits/stdc++.h> \n\nusing namespace std; \n\nint fib(int n) \n\n{ \n\n    int a = 0, b = 1, c, i; \n\n    if( n == 0) \n\n        return a; \n\n    for(i = 2; i <= n; i++) { \n\n       c = a + b; \n\n       a = b; \n\n       b = c; \n\n    } \n\n    return b; \n\n} \n\nint main(){ \n\n    int n;\n    \n    cin>>n;\n\n    cout << fib(n); \n\n    return 0; \n\n} \n\n\n"
  },
  {
    "path": "Maths/Series/Fibonacci/fibonacci.java",
    "content": "public class Fibonacci {\n\n    public static void main(String[] args) {\n\n        int n = 10, t1 = 0, t2 = 1;\n        System.out.print(\"First \" + n + \" terms: \");\n\n        for (int i = 1; i <= n; ++i)\n        {\n            System.out.print(t1 + \" + \");\n\n            int sum = t1 + t2;\n            t1 = t2;\n            t2 = sum;\n        }\n    }\n}\n"
  },
  {
    "path": "Maths/Series/Geometric_Progression/Geometric Progression.py",
    "content": "def gp(a,r,n):\n\tfor i in range(n):\n\t\ttemp = a*pow(r,i)\n\t\tprint(temp,end=\" \")\na = int(input())\nr = int(input())\nn = int(input())\ngp(a,r,n)\n"
  },
  {
    "path": "Maths/Series/Geometric_Progression/GeometricProgression.cs",
    "content": "using System;\nclass GeometricProgression {\n    \n    static int gp(int a, int q, int n){\n        return ((int) (a * Math.Pow(q, n-1)));\n    }\n    \n    static void Main() {\n      int a = Convert.ToInt32(Console.ReadLine());\n      int q = Convert.ToInt32(Console.ReadLine());\n      int n = Convert.ToInt32(Console.ReadLine());\n      \n      Console.WriteLine(\"\" + gp(a,q,n));\n    }\n}\n"
  },
  {
    "path": "Maths/Series/Geometric_Progression/GeometricProgression.java",
    "content": "import java.lang.*;\npublic class Main\n{\n    //Function that prints GP for given value of a, r and n where nth GP=a*r^(n-1)\n    static void GP(int a, int r, int n){\n        for(int i=0;i<n;i++){\n            System.out.print(a*(int)Math.pow(r,i)+ \" \");\n        }\n        System.out.println();\n    }\n    \n    //Function determines if the given array is a GP or no.\n    static boolean validGP(int[] ar,int n){\n        if(n==1){\n            return true;\n        }\n        int r = ar[1]/ar[0];\n        for(int i=1;i<n;i++){\n            if(ar[i]/ar[i-1]!=r){\n                return false;\n            }\n        }\n        return true;\n    }\n    \n    //Function prints the nth element of GP\n    static void nthGP(int a, int r, int n){\n        System.out.println(a*(int)Math.pow(r,n-1));\n    }\n    \n    //Funtion for nth partial sum of a geometric sequence\n    static void sum(int a, int r, int n){\n        int num = a*(1-(int)Math.pow(r,n));\n        int deno = 1-r;\n        int ans = num/deno;\n        System.out.println(n + \"th partial sum of a geometric sequence is \"+ ans);\n    }\n  \n}"
  },
  {
    "path": "Maths/Series/Geometric_Progression/Geometric_Progression.sh",
    "content": "#!/bin/bash\necho \"Enter first term of the Geometric Progression : \"\nread a\necho \"Enter the common ratio : \"\nread r\necho \"Enter the number of terms in Geometric Progression : \"\nread n\necho $((a))\nfor((i=1;i<=n;i++))\ndo\nnth=$((a*(r**i)))\necho $((nth))\ndone\n"
  },
  {
    "path": "Maths/Series/Geometric_Progression/README.md",
    "content": "## This folder is empty.\n"
  },
  {
    "path": "Maths/Series/Harmonic_Progression/Harmonic Progression.cpp",
    "content": "#include<iostream>\nusing namespace std;\nint main()\n{\n    long d,n,a;\n    long an;\n    cout<<\"Enter first term : \";\n    cin>>a;\n    cout<<\"Enter difference : \";\n    cin>>d;\n    cout<<\"Enter number of terms :\";\n    cin>>n;\n    cout<<\"Harmonic progression : \";\n    for(int y=1;y<=n;y++)\n    {\n        an=a+(y-1)*d;\n        cout<<\"1/\"<<an<<\"   \";\n    }\n    return 0;\n}"
  },
  {
    "path": "Maths/Series/Harmonic_Progression/HarmonicProgresion.c",
    "content": "#include <stdio.h>\r\n#include <stdlib.h>\r\n \r\nint main() {\r\n    int terms, i, first, denominator, diff;\r\n    float sum = 0.0;\r\n    printf(\"Enter the number of terms in HP series\\n\");\r\n    scanf(\"%d\", &terms);\r\n \r\n    printf(\"Enter denominator of first term and common difference of HP series\\n\");\r\n    scanf(\"%d %d\", &first, &diff);\r\n \r\n    denominator = first;\r\n    printf(\"HP SERIES\\n\");\r\n    for(i = 0; i < terms; i++) {\r\n        printf(\"1/%d \", denominator);\r\n        sum += 1/(float)denominator;\r\n        denominator += diff;\r\n    }\r\n \r\n    printf(\"\\nSum of the HP series till %d terms is %f\\n\", terms, sum);\r\n \r\n    getch();\r\n return 0;\r\n}\r\n\r\n/*Enter the number of terms in HP series\r\n5\r\nEnter denominator of first term and common difference of HP series\r\n2 4\r\nHP SERIES\r\n1/2 1/6 1/10 1/14 1/18\r\nSum of the HP series till 5 terms is 0.893651*/\r\n"
  },
  {
    "path": "Maths/Series/Harmonic_Progression/Harmonic_Expression.java",
    "content": "import java.util.Scanner;\n\npublic class Harmonic_Expression{\t\n\tpublic static void main(String args[]){\n\t\tScanner scan = new Scanner(System.in);\n\t\tlong difference, startTerm, numberOfTerms;\n\t\tSystem.out.print(\"Enter Starting Term : \");\n\t\tstartTerm = scan.nextLong();\n\t\tSystem.out.print(\"Enter Difference : \");\n\t\tdifference = scan.nextLong();\n\t\tSystem.out.print(\"Enter Number of Terms : \");\n\t\tnumberOfTerms = scan.nextLong();\n\t\tif( startTerm == 0 ){\n\t\t\tSystem.out.println(\"Invalid start of Harmonic Progression.\");\n\t\t}\n\t\telse{\n\t\t\tSystem.out.println(\"Sequence is :\");\n\t\t\tfor(int i = 1; i <= numberOfTerms; i++){\n\t\t\t\tSystem.out.print(String.format(\"1/%s\",(startTerm+((i-1)*difference))));\n\t\t\t\tif(i!=numberOfTerms)\n\t\t\t\t\tSystem.out.print(\" , \");\n\t\t\t}\n\t\t}\n\t\tSystem.out.println();\n\t}\n}\n"
  },
  {
    "path": "Maths/Series/Harmonic_Progression/README.md",
    "content": "## This folder is empty.\n"
  },
  {
    "path": "Maths/Series/Harmonic_Progression/SumOfHP.swift",
    "content": "//\n//  SumOfHP.swift\n//  Hacktoberfest\n//\n//  Created by Dipankar Goswami on 03/10/20.\n//\n\nimport Foundation\n\nfunc getHPSum(first_term: Double, common_diff: Double, no_of_terms: Int) -> Double {\n    var res:Double = 0.0\n    for i in 0...no_of_terms-1 {\n        res = res + 1/(first_term + Double(i) * common_diff)\n    }\n    return res\n}\n\nvar first_term = Double(readLine()!)!\nvar common_diff = Double(readLine()!)!\nvar no_of_terms = Int(readLine()!)!\n\n/* Following Code blocm checks if any of the term in arithmatic progression can be zero.\n    In that case corresponding term in HP is undefined.\n    Checks are -\n    1. If first term is zero.\n    2. if negative of (first_term/common_diff) is a positive integer between 1 and number of terms (inclusive)\n */\nif first_term == 0 ||\n    (common_diff != 0 && Int(first_term) % Int(common_diff) == 0\n        && (Int(first_term/common_diff ) * (-1) < no_of_terms && Int(first_term/common_diff) * -1 > 0)) {\n    print(\"Harmonic progression potentially contains zero as one of the terms.\")\n} else {\n    let res = getHPSum(first_term: first_term, common_diff: common_diff, no_of_terms: no_of_terms)\n    print(\"Sum of Harmonic progression for given inputs is \\(res)\")\n}\n"
  },
  {
    "path": "Maths/Series/Harmonic_Progression/harmonic_progression.py",
    "content": "def HP(a,d,n):      \n    curr_term=a \n    for i in range(1,n+1): \n        temp=a+(i-1)*d\n        print(1/temp)\n\n\na = 2   \nd = 1   \nn = 5  \n  \nHP(a, d, n) \n"
  },
  {
    "path": "Maths/Series/Lucas_Series/Lucas_Series.c",
    "content": "#include<stdio.h>\n#include<stdlib.h>\nint main()\n{\n      int first_term, second_term, third_term;\n      int limit, count;\n      printf(\"Enter the Limit :-\\n\");\n      scanf(\"%d\", &limit);\n      first_term = 2;\n      second_term = 1;\n      printf(\"Series :-\\n\");\n      for(count = 0; count < limit; count++)\n      {\n            printf(\"%d \", first_term);\n            third_term = first_term + second_term;\n            first_term = second_term;\n            second_term = third_term;\n      }\n      printf(\"\\n\");\n      return 0;\n}"
  },
  {
    "path": "Maths/Series/Lucas_Series/Lucas_Series.cpp",
    "content": "#include <iostream>\nusing namespace std;\n\nint main() {\n\n    int term_1 = 2;\n    int term_2 = 1;\n    int next_term;\n    \n    int num_terms;  \n    cout << \"Number of terms to be found: \";\n    cin >> num_terms;\n\n    cout << \"The first \" << num_terms << \" of the Lucas Series are:\\n\";\n\n    for (int i = 1; i <= num_terms; i++) {\n        cout << term_1 << \"\\t\";\n        next_term = term_1 + term_2;\n        term_1 = term_2;\n        term_2 = next_term;\n    }\n    \n    cout << \"\\n\";\n}"
  },
  {
    "path": "Maths/Series/Lucas_Series/Lucas_Series.go",
    "content": "package main\n\nimport (\n\t\"bufio\"\n\t\"fmt\"\n\t\"os\"\n\t\"strconv\"\n\t\"strings\"\n)\n\nfunc printLucasSeries(size int) {\n\t// Print first two terms\n\tl1 := 2\n\tl2 := 1\n\tfmt.Print(l1, \"  \", l2, \"  \")\n\tfor i := 2; i < size; i++ {\n\t\tl2 = l1 + l2\n\t\tl1 = l2 - l1\n\t\tfmt.Print(l2, \"  \")\n\t}\n\tfmt.Println()\n}\nfunc main() {\n\treader := bufio.NewReader(os.Stdin)\n\tfmt.Print(\"Enter the size of sequence (Number of values) for Lucas Series: \")\n\tinput, _ := reader.ReadString('\\n')\n\tinput = strings.TrimSuffix(input, \"\\n\")\n\tinputNum, err := strconv.Atoi(input)\n\tif err != nil {\n\t\tfmt.Println(\"Input is not valid, Please enter a valid number\", input, err)\n\t\treturn\n\t}\n\n\tfmt.Printf(\"The first %v numbers in Lucas Series are \\n\", inputNum)\n\tprintLucasSeries(inputNum)\n\n}\n"
  },
  {
    "path": "Maths/Series/Lucas_Series/Lucas_Series.php",
    "content": "<?php\nfunction Lucas_Number($n){\n\t$counter = 0;\n\t$x = 2; //Represent Ln //L stands for Lucas Number\n\t$y = 1; //Represent Ln+1\n\t$z = 0; //Represent Ln+2\n\n\techo $x.\", \";\n\techo $y.\", \";\n\n\twhile($counter < $n-2){\n\t\t$z = $x + $y;\n\t\t$x = $y;\n\t\t$y = $z;\n\t\t$counter++;\n\t\techo $z;\n\t\tif($counter==$n-2){\n\t\t\tbreak;\n\t\t}\n\t\telse{\n\t\t\techo \", \";\n\t\t}\n\t}\n}\n\n//Example Case\necho Lucas_Number(5);\n\n?>\n"
  },
  {
    "path": "Maths/Series/Lucas_Series/README.md",
    "content": "## This folder is empty.\n"
  },
  {
    "path": "Maths/Series/Lucas_Series/lucas_series.cs",
    "content": "using System;\n\nclass Program\n{\n    static void Main(string[] args)\n    {\n        Console.WriteLine(\"How many Lucas numbers do you want to write out?\");\n        int count = int.Parse(Console.ReadLine());\n        ulong first = 2;\n        ulong second = 1;\n        Console.WriteLine(first);\n        Console.WriteLine(second);\n        ulong number;\n        for (int i = 0; i < count - 2; i++)\n        {\n            number = first + second;\n            first = second;\n            second = number;\n            Console.WriteLine(number);\n        }\n        Console.ReadLine(); // otherwise the console closes\n    }\n}\n"
  },
  {
    "path": "Maths/Series/Lucas_Series/lucas_series.py",
    "content": "def LucasSum(N): \n    a = 2\n    b = 1\n    c = 0\n    print(a)\n    while (b <= N): \n        c = a + b \n        print(c)\n        a = b \n        b = c \n\n\n# Driver code \nN = int(input())\nLucasSum(N)\n\n\n"
  },
  {
    "path": "Maths/Series/Lucas_Series/lucas_series.ts",
    "content": "// This is required for console input\nvar readline = require('readline');\nvar rl = readline.createInterface({\n  input: process.stdin,\n  output: process.stdout\n});\n\nrl.question(\"Number of terms to be found: \", function(answer) {\n    let first = 2;\n    let second = 1;\n    let result;\n    console.log(first);\n    console.log(second);\n  for (let i = 0; i < +answer - 2; i++) {\n    result = first + second;\n    console.log(result);\n    first = second;\n    second = result;\n  }\n  rl.close();\n});\n"
  },
  {
    "path": "Maths/Series/Modular_Exponentiation/Modular_Exponentiation.cpp",
    "content": "#include<iostream>\n#include<bits/stdc++.h>\n\nusing namespace std;\n\nint main(){\n    int b, e, m;\n    int power, res;\n    cout<<\"Enter the base value: \";\n    cin>>b;\n    cout<<\"Enter the exponent value: \";\n    cin>>e;\n    cout<<\"Enter the modulus value: \";\n    cin>>m;\n    power = pow(b,e);\n    res = power % m;\n    cout<<\"The modular exponentiation value of given set of values is: \"<<res;\n\n    return 0;\n}"
  },
  {
    "path": "Maths/Series/Modular_Exponentiation/Modular_Exponentiation.py",
    "content": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\n@ Author: Sandip Dutta\r\n--------------------------------------------------------------\r\nCode for Modular Exponentiation\r\nModular Exponentiation is an algorithm for calculating\r\n(a^b) % m fast.\r\n\r\na^b is useful for us but it's value may be large \r\nand it might overflow. So we calculate (a^b) % m.\r\n\r\nThe idea of modular exponentiation can be shown with the \r\nhelp of the following ideas\r\n    1.  (a * b) % (m) = (a %(m) * b %(m)) %(m)\r\n    2.  a ^ b   = (a ^ (b/2) * a ^ (b/2)) when b is even\r\n                = (a * a ^ (b-1)) when b is odd\r\n\r\nThese two ideas gives us the recursive version of the algorithm\r\nwe will implement.\r\n\r\n>   Runtime - O(log (b))\r\n---------------------------------------------------------------\r\nNOTE : In python, pow() function implements this idea\r\n---------------------------------------------------------------\r\n\"\"\"\r\n\r\ndef modularExp(a, b, m):\r\n    '''\r\n    Performs modular Exponentiation, that is a^b % m fast.\r\n    @ Args:\r\n        a - (int) mantissa / base\r\n        b - (int) exponent\r\n        m - (int) number with respect to which modulus is calculated\r\n    @ Return:\r\n        y - (int) the value of (a ^ b) % m\r\n    '''\r\n    # Base Case - a == 0, return 0; b == 0, return 1\r\n    if a == 0: return 0\r\n    if b == 0: return 1\r\n\r\n    y = 0 # Final Value\r\n\r\n    # If b is odd, then b & 1(bitwise AND) == 1, else 0\r\n    # We do not use b % 2 here as bitwise operations might be \r\n    # faster for larger b value\r\n\r\n    # b is odd\r\n    if b & 1:\r\n        y = a % m    # Break as per step 1 above\r\n        y = (y * modularExp(a, b - 1, m) % m) % m    \r\n        # Break as per step 2 above\r\n    \r\n    else:\r\n        y = modularExp(a, b // 2, m)\r\n        y = (y * y) % m\r\n        # Break as per step 2 above\r\n\r\n    # this is to ensure that y is not negative\r\n    return ((y + m) % m)\r\n\r\n#------------------------------------------------------\r\n\r\nif __name__ == \"__main__\":\r\n    a, b, m = list(map(int, input(\"Enter a, b, m: \").split()))\r\n    print(modularExp(a, b, m))"
  },
  {
    "path": "Maths/Series/Modular_Exponentiation/README.md",
    "content": "# Modular Exponentiation \n\nModular Exponentiation is useful for calculating (a ^ b) % m. This has applications in cryptography.\nThis is a divide and conquer algorithm. \n\n#### Contributed by Sandip Dutta\n"
  },
  {
    "path": "Maths/Series/Modular_Exponentiation/modular_exponentiation.c",
    "content": "#include<stdio.h>\r\n#include<math.h>\r\n\r\nint main(){\r\n    int b, e, m;\r\n    printf(\"Enter the base value: \");\r\n    scanf(\"%d\", &b);\r\n    printf(\"Enter the exponent value: \");\r\n    scanf(\"%d\", &e);\r\n    printf(\"Enter the modulus value: \");\r\n    scanf(\"%d\", &m);\r\n    int power, res;\r\n    power = pow(b,e);\r\n    res = power%m;\r\n    printf(\"The modular exponentiation of the given set of values is: %d\",res);\r\n\r\n    return 0;\r\n}"
  },
  {
    "path": "Maths/Series/Modular_Exponentiation/modular_exponentiation.cpp",
    "content": "#include<iostream>\n#include<bits/stdc++.h>\n\nusing namespace std;\n\nint main(){\n    int b, e, m;\n    int power, res;\n    cout<<\"Enter the base value: \";\n    cin>>b;\n    cout<<\"Enter the exponent value: \";\n    cin>>e;\n    cout<<\"Enter the modulus value: \";\n    cin>>m;\n    power = pow(b,e);\n    res = power % m;\n    cout<<\"The modular exponentiation value of given set of values is: \"<<res;\n\n    return 0;\n}"
  },
  {
    "path": "Maths/Series/Modular_Exponentiation/modular_exponentiation.java",
    "content": "import java.util.Scanner;\r\n\r\npublic class modular_exponentiation{\r\n    public static void main(String[] args) {\r\n        double b, e, m;\r\n        Scanner scan = new Scanner(System.in);\r\n        System.out.print(\"Enter the base value: \");\r\n        b = scan.nextDouble();\r\n        System.out.println();\r\n        System.out.print(\"Enter the exponent value: \");\r\n        e = scan.nextDouble();\r\n        System.out.println();\r\n        System.out.print(\"Enter the modulus value: \");\r\n        m = scan.nextDouble();\r\n        System.out.println();\r\n        double res_double = Math.pow(b, e) % m;\r\n        int res = (int) (res_double);\r\n        System.out.println(\"The modular exponentiation of the given set of values is: \" + res);\r\n        scan.close();\r\n    }\r\n}"
  },
  {
    "path": "Maths/Series/README.md",
    "content": "# This folder is empty.\n"
  },
  {
    "path": "Maths/Series/Relative_Primes/README.md",
    "content": "## This folder is empty.\n"
  },
  {
    "path": "Maths/Series/Relative_Primes/RelativePrimes.c",
    "content": "#include<stdio.h>\r\n\r\nvoid main(){\r\n        int p,i,j;\r\n        int remainder = 2;\r\n        int divident,divisor;\r\n\r\n        printf(\"Enter Number\\n\");\r\n        scanf(\"%d\",&p);\r\n\r\n        for(i = 2 ; i < p ; i++){\r\n\r\n                divident  = p;\r\n                divisor = i;\r\n\r\n                while(divisor != 0){\r\n\r\n                        remainder = divident % divisor;\r\n                        divident  = divisor;\r\n                        divisor  = remainder;\r\n                }\r\n       \r\n                if(divident  == 1){\r\n                        printf(\"Relatively Prime Number is : %d \\n\" ,i);\r\n                }\r\n        }\r\n\r\n}\r\n\r\n/* Output:\r\nEnter Number \r\n8\r\nRelatively Prime Number is : 3\r\nRelatively Prime Number is : 5\r\nRelatively Prime Number is : 7 */\r\n \r\n"
  },
  {
    "path": "Maths/Series/Relative_Primes/RelativePrimes.java",
    "content": "\npublic class relativelyPrime {\n\t\n\tstatic int gcd(int a, int b)\n    {\n      if (b == 0)\n        return a;\n      return gcd(b, a % b); \n    }\n\t\n\tprivate static boolean relativelyPrime(int a, int b) {\n\t    return gcd(a,b) == 1;\n\t}\n\t\n\t\n\tpublic static void main(String[] args) {\n\t\tint n = 10,m = 9;\n\t\tSystem.out.println(n+\" and \"+ m+\" is relative Prime \"+relativelyPrime(n, m));\n\t}\n\n}\n"
  },
  {
    "path": "Maths/Series/Relative_Primes/RelativePrimes.php",
    "content": "<?php\n\n// This will return their greatest common divisor (gcd)\nfunction gcd($int1, $int2) {\n    if ($int1 == 0 || $int2 == 0) return 0;\n    if ($int1 == $int2) return $int1;\n    if ($int1 > $int2) return gcd($int1 - $int2, $int2);\n    return gcd($int1, $int2 - $int1);\n}\n\n// check if they are both relatively prime or not\nfunction isRelativelyPrime($int1, $int2) {\n    $result = gcd($int1, $int2) == 1 ? \"is relatively prime \\n\": \"is not relatively prime \\n\";\n    return $result;\n}\n\necho isRelativelyPrime(4, 9);\necho isRelativelyPrime(6, 8);\n"
  },
  {
    "path": "Maths/Series/Relative_Primes/RelativePrimes.py",
    "content": "def gcd(num1, num2):\n\n    if num2 == 0:\n        return num1\n    \n    return gcd(num2, num1 % num2)\n\ndef is_relative_prime(num1, num2):\n\n    if gcd(num1, num2) == 1:\n        return True\n    \n    return False\n\n\nnumber = int(input(\"Enter a number: \"))\n\nprint(\"Numbers that are relatively prime to \", number,\" are:\")\n\nfor i in range(2, number):\n\n    if is_relative_prime(number, i):\n        print(i)\n\n\"\"\"\nExample:\nEnter a number: 9\nNumbers that are relatively prime to 9 are:\n2\n4\n5\n7\n8\n\"\"\"\n"
  },
  {
    "path": "Maths/Series/Relative_Primes/Relative_Prime.cpp",
    "content": "#include<bits/stdc++.h>// this includes all the predefined libraries required in the program;\r\nusing namespace std;\r\n\r\n\r\nint main()\r\n{\r\n\r\n    int num1,num2;\r\n    //The value of two numbers is being entered below\r\n    cin>>num1;\r\n    cin>>num2;\r\n    //we will use the _gcd function to find the gcd or hcf of the numbers that have been entered.\r\n    int hcf;\r\n    hcf=__gcd(num1,num2);\r\n    if(hcf==1)\r\n    cout<<\"The numbers are relatively prime\";\r\n    else\r\n    cout<<\"The numbers are not relatively prime\";\r\n    return 0;\r\n\r\n}"
  },
  {
    "path": "Maths/Series/Relative_Primes/Relative_Primes.go",
    "content": "package main\n\nimport (\n\t\"fmt\"\n\t\"math/big\"\n)\n\nfunc main() {\n\tnum1 := big.NewInt(0)\n\tnum2 := big.NewInt(0)\n\tgreatest := big.NewInt(0)\n\n\tfmt.Scanln(num1)\n\tfmt.Scanln(num2)\n\n\tgreatest.GCD(nil, nil, num1, num2)\n\n\tif greatest.Int64() == 1 {\n\t\tfmt.Println(\"The numbers are relatively prime\")\n\t} else {\n\t\tfmt.Println(\"The numbers are not relatively prime\")\n\t}\n}\n"
  },
  {
    "path": "Maths/Series/Sum_of_AP/Sum_Of_AP.CPP",
    "content": "#include <iostream.h>\n#include <conio.h>\n\n// Function to check whether given sequence is in AP or not \n// The common differences for the sequence is calculated and checked\nint is_ap(int ap[],int terms,int common_difference[])\n{\n    int index=0;\n    // Looping through elements to get the common differences between them in given sequence\n    while(index<(terms-1))\n    {\n\t// Storing current common difference by substracting prev number from next number\n\tcommon_difference[index]=ap[index+1]-ap[index];\n\t// If the index is not zero and if current commmon difference\n\t// is not equal to previous common difference then sequence is not in AP\n\tif ((index!=0) && (common_difference[index] != common_difference[index-1]))\n\t\tbreak;\n\tindex += 1;\n    }\n\n    // If loop runs upto index becoming terms-1 then sequence in AP\n    // as all common difference are same, hence returning 1\n    if(index==(terms-1))\n\treturn 1;\n    // otherwise returning -1\n    else\n\treturn -1;\n}\n\n// Function to calculate sum if number of terms is even\nint evensum_ap(int ap[], int terms, int common_difference[])\n{\n    int sum;\n    // Implementing the formula for sum of AP with even no of terms = (n/2)*(2*a +(n-1)*d)\n    sum = (terms / 2) * ((2 * ap[0]) + ((terms - 1) * common_difference[0]));\n    return sum;\n}\n\n// Function to calculate sum if number of terms is odd\nint oddsum_ap(int ap[], int terms, int common_difference[])\n{\n    int sum;\n    // Implementing the formula for sum of AP with odd no of terms = n*(a+((n-1)/2)*d)\n    sum = terms*(ap[0]+((terms-1)/2)*common_difference[0]);\n    return sum;\n}\n\n\n// Driver Code\n\nvoid main()\n{\n    clrscr();\n\n    int terms;\n    // Taking input for no of terms\n    cout<<\"Enter the no of terms :\"<<endl;\n    cin>>terms;\n    \n    // Initialising the two arrays for sequence and common difference\n    int ap[100], common_difference[100];\n\n    // Taking input for terms in sequence\n    cout<<\"Enter the terms of sequence :\"<<endl;\n    for(int i=0;i<terms;i++)\n\tcin>>ap[i];\n\n    // If sequence not in AP, print message for the same\n    if(is_ap(ap,terms,common_difference)==-1)\n\tcout<<\"Sequence is not an AP.\"<<endl;\n\n    // If sequence is in AP\n    else\n\t// If no of terms is even, calculate sum for even no of terms\n\tif(terms%2==0)\n\t\tcout<<\"Sum Of AP is : \"<<evensum_ap(ap,terms,common_difference);\n\n\t// Otherwise calculate sum for odd no of terms\n\telse\n\t\tcout<<\"Sum Of AP is : \"<<oddsum_ap(ap,terms,common_difference);\n    getch();\n}\n\n\n/*\nInput description: \n    Line 1 -- No of terms\n    Line 2 -- Elements of the sequence (each on a newline)\n\nOutput Description :\n    Sum of AP is : Sum\n\tor\n    Sequence is not in AP.\n\n\nExample Outputs:\n\n    Input 1:\n\tEnter the no of terms :\n\t4\n\tEnter the terms of sequence :\n\t1\n\t3\n\t5\n\t7\n    \n    Output 1:\n\tSum Of AP is : 16\n    \n\n\n    Input 2:\n\tEnter the no of terms :\n\t3\n\tEnter the terms of sequence :\n\t2\n\t6\n\t10\n    \n    Output 2:\n\tSum Of AP is : 18\n*/"
  },
  {
    "path": "Maths/Series/Sum_of_AP/Sum_Of_AP.py",
    "content": "# Function to calculate sum of a given AP sequence\ndef Sum_AP(ap):\n    terms = len(ap) # Number of terms in AP\n    common_difference = [] # A list for storing all the common differences\n    index = 0\n    # Loop to get all common differences\n    while index < (terms-1):\n        # adding the common difference of current and net element\n        common_difference.append(ap[index+1]-ap[index])\n        # if this and previous common difference are not same and if index is not zero, sequence is not in AP\n        if (index!=0) and (common_difference[index] != common_difference[index-1]):\n            return \"Not in AP\"\n        index += 1\n    # this part will be executed only if sequence is in AP\n\n    # if no of terms is even\n    if terms % 2 == 0:\n        # if all common difference are same, index will be term - 1\n        if index == (terms - 1):\n            # implementing the formula for sum of AP with even no of terms= (n/2)*(2*a +(n-1)*d)\n            sum = (terms // 2) * ((2 * ap[0]) + ((terms - 1) * common_difference[0]))\n            return \"Sum of AP = \"+str(sum)\n\n    # if no of terms is even\n    if terms % 2 == 1:\n        # if all common difference are same, index will be term - 1\n        if index == (terms-1):\n            # implementing the formula for sum of AP with odd no of terms = n*(a+((n-1)/2)*d)\n            sum = terms*(ap[0]+((terms-1)//2)*common_difference[0])\n            return \"Sum of AP = \"+str(sum)\n\n\n# Driver Code\n\n# Calling function Sum_AP and passing into it the sequence given as input\nap = list(map(int,input(\"Enter elements : \").split()))\nprint(Sum_AP(ap))\n\n'''\nInput description: \n    Line 1 -- Sequence (seperated by spaces)\n\nOutput Description :\n    Sum of AP = Sum\n\nExample Outputs:\n\n    Input 1:\n    Enter elements : 1 2 3 4\n    \n    Output 1:\n    Sum of AP = 10\n    \n    \n    \n    Input 2:\n    Enter elements : 1 3 5\n    \n    Output 2:\n    Sum of AP = 9\n'''"
  },
  {
    "path": "Maths/Series/Sum_of_AP/Sum_of_AP.c",
    "content": "/*C Program to find the Sum of Arithmetic Progression Series */\n#include<stdio.h>\n\nfloat AP( float a, float d, int n){\n return ( ( n / 2)*( ( 2 * a ) + ( ( n - 1 )* d ) ) );\n}\n\nint main(){\n float d = 0, a = 0, result = 0;\n int n = 0;\n printf(\"Enter the First Term [a], Common Difference[d], Number of Terms[n] of an Arithmetic Series :\");\n scanf(\"%f%f%d\", &a, &d, &n );\n\n result =  AP( a, d, n);\n printf(\"The sum of the Series : %0.2f\\n\", result);\n\n return 0;\n}\n"
  },
  {
    "path": "Maths/Series/Sum_of_AP/Sum_of_AP.go",
    "content": "/*\n\tThis code takes input a, d & n and computes sum of Arithmetic Progression .\n\tLanguage : Golang\n\tAuthor : Pulkit Sapra\n*/\n\npackage main\n\n//Package fmt implements formatted I/O with functions analogous to C's printf and scanf. \nimport (\n\t\"fmt\"\n\t)\n\n// Function to compute AP : Return Type : float64\nfunc sum_of_AP(a float64, d float64, n float64) float64{\n\treturn ((n/2)*(2*a + (n-1)*d))\n}\n\n// Main Function\nfunc main() {\n\tfmt.Println(\"Please enter initial element(a) ,common difference(d) and n\")\n\t\n\t// Declaring variables and their types.\n\tvar a,d,n float64\n\n\t// Taking input for a,d & n\n\tfmt.Scan(&a)\n\tfmt.Scan(&d)\n\tfmt.Scan(&n)\n\n\t//Function call\n\tans := sum_of_AP(a,d,n)\n\t\n\tfmt.Println(ans)\n\t\n}\n"
  },
  {
    "path": "Maths/Series/Sum_of_AP/Sum_of_AP.js",
    "content": "/*\nArithmetic progression if a sequence of number has same common difference. \nHere\n    a is first term of series\n    d is common difference\n    n is number of terms\n*/\n\nconst readline = require('readline')\n\nconst rl = readline.createInterface({\n    input: process.stdin,\n    output: process.stdout\n})\n\nconst inputParams = () => new Promise(resolve =>\n    rl.question('\\nEnter first term (a)\\n> ', a =>\n        rl.question('Enter common difference (d)\\n> ', d =>\n            rl.question('Enter the number of elements (n) \\n> ', n => {\n                a = parseInt(a)\n                d = parseInt(d)\n                n = parseInt(n)\n                rl.close()\n                resolve({ a, d, n })\n            })\n        )\n    )\n)\n\nconst sumOfAP = (a, d, n) => {\n    let sum = 0;\n    let i = 0;\n    while (i < n) {\n        sum += a;\n        a += d;\n        i++;\n    }\n    return sum;\n}\n\ninputParams()\n    .then(({ a, d, n }) => {\n        console.log(`\\nSum of arithmetic progression: \\\n  ${sumOfAP(a, d, n)}`)\n    })\n/*\nFor testin purpose\nlet a = 1;\nlet d = 1.5;\nlet n = 10;\n\nconsole.log(sumOfAP(a, d, n));\n*/\n"
  },
  {
    "path": "Maths/Series/Sum_of_AP/Sum_of_AP_JAVA/SumOfAP.ctxt",
    "content": "#BlueJ class context\ncomment0.target=SumOfAP\ncomment1.params=a\\ d\\ n\ncomment1.target=float\\ sumOfAP(float,\\ float,\\ int)\ncomment2.params=args\ncomment2.target=void\\ main(java.lang.String[])\nnumComments=3\n"
  },
  {
    "path": "Maths/Series/Sum_of_AP/Sum_of_AP_JAVA/Sum_of_AP.java",
    "content": "// JAVA Program to find the sum of AP Series\n\nimport java.util.Scanner;\n  \nclass SumOfAP{ \n      \n    // Function to find sum of AP. \n    static float sumOfAP(float a, float d,  \n                                  int n) \n    { \n        float sum = 0; \n        for (int i = 0; i < n; i++) \n        { \n            sum = sum + a; \n            a = a + d; \n        } \n        return sum; \n    } \n      \n    // Driver function \n    public static void main(String args[]) \n    { \n        Scanner sc= new Scanner(System.in);\n        System.out.println(\"Enter the number of elements in the series:\");\n        int n=sc.nextInt();\n        System.out.println(\"Enter the first element of the series:\");\n        float a =sc.nextFloat();\n        System.out.println(\"Enter the common difference of the elements in the series:\");\n        float d =sc.nextFloat(); \n        System.out.println(sumOfAP(a, d, n)); \n    } \n}"
  },
  {
    "path": "Maths/Series/Sum_of_GP/README.md",
    "content": "## This folder is empty.\n"
  },
  {
    "path": "Maths/Series/Sum_of_GP/Sum_Of_GP.c",
    "content": "/***\n\nGuidelines to run this code:\n\t->Ensure you have latest version of c compiler\n\t->Compile and Run either through User Interface or Command Line.\n\t\tExample for gcc compiler,\n\t\t\t\tgcc Sum_Of_GP.c\n\t\t\t\t./a.out(for Linux) or a(for Windows)\n\t\t\t\t\n\n***/\n\n/***\n\nAbout the approach:\n\t->Formula used: a(r^n - 1)/(r - 1)\n\t\t. a is first term\n\t\t. r is common ratio\n\t\t. n is number of terms\n\t\tof the geometric sequence\n\t->some values of common ratio are handled differently\n\t->Time Complexity: O(n) where n is number of terms in the geometric sequence\n\t->Space Complexity: O(1)\n\t->It is considered that a,r and n are given by the user and sum is within double datatype limits\n\n***/\n#include<stdio.h>\n\n/*\narguments:\n\tbase value and the exponent term\nreturns:\n\tresult obtained by calculating the power of the base raised to the exponent term given\n*/\ndouble power(double base,double exponent)\n{\n\tdouble result = 1.0;\n\tfor(int i = 1;i <= exponent;i++)\n\t{\n\t\tresult *= base;\n\t}\n\treturn result;\n}\n\t\n\t\n\nint main()\n{\n\tdouble first_term;\n\tdouble common_ratio;\n\tdouble num_terms;\n\t\n\t//take the first term as input from the user\n\tprintf(\"Enter the first term of the GP Sequence:\");\n\tscanf(\"%lf\",&first_term);\n\t\n\t//take the common ratio as input from the user\n\tprintf(\"Enter the common ratio of the GP Sequence:\");\n\tscanf(\"%lf\",&common_ratio);\n\t\n\t//take the number of terms as input from the user\n\tprintf(\"Enter the number of terms in the GP Sequence:\");\n\tscanf(\"%lf\",&num_terms);\n\t\n\t//wrong case:number_of_terms is negative\n\tif(num_terms < 0)\n\t{\n\t\tprintf(\"Sum of the given Geometric Sequence is not possible due to negative number of terms\\n\");\n\t}\n\t\n\t//case 1:common_ratio is zero,hence the general formula fails as 0/0 is encountered\n\telse if(common_ratio == 0) \n\t{\n\t\tprintf(\"Sum of the given Geometric Sequence is %lf\\n\",first_term);\n\t}\n\t\n\t//case 2:common_ratio is one,hence again the general formula fails as 0/0 is encountered\n\telse if(common_ratio == 1)\n\t{\n\t\tprintf(\"Sum of the given Geometric Sequence is %lf\\n\",first_term * num_terms);\n\t}\n\t\n\t//case 3:other values\n\telse\n\t{\n\t\tdouble result = (first_term * (power(common_ratio,num_terms) - 1)) / (common_ratio - 1);\n\t\t\n\t\tprintf(\"Sum of the given Geometric Sequence is %lf\\n\",result);\n\t}\n\t\t\n\treturn 0;\n}\n\t\n\t\n\t\n\t"
  },
  {
    "path": "Maths/Series/Sum_of_GP/Sum_Of_GP.cpp",
    "content": "#include<iostream>\n#include<math.h>\nusing namespace std;\nint main()\n{  float A,R;\n   int N;\n   A=1;\n   R=2;\n   N=5;\n   float Sum=A*(pow(R,N)-1)/(R-1);\n   cout<<Sum;\n   }\n"
  },
  {
    "path": "Maths/Series/Sum_of_GP/Sum_of_GP.java",
    "content": "import java.util.Scanner;\n\npublic class Sum_of_GP {\n\n    static double sumGP(double firstTerm, double commonRatio, int numberOfTerms) {\n        return firstTerm * ((1 - Math.pow(commonRatio, numberOfTerms)) / (1 - commonRatio));\n    }\n\n    static double sumGPToInfinity(double firstTerm, double commonRatio) {\n        return firstTerm * (1 / (1 - commonRatio));\n    }\n\n    public static void main(String[] args) {\n        Scanner sc = new Scanner(System.in);\n        System.out.println(\"Enter the GP values belows\");\n        System.out.println(\"first term: \");\n        double firstTerm = sc.nextDouble();\n\n        System.out.println(\"number of terms (zero, if you want to get sum to infinity): \");\n        int numberOfTerms = sc.nextInt();\n\n        System.out.println(\"ratio (a non zero number, for sum to infinity, number should be between -1 & 1): \");\n        double commonRatio = sc.nextDouble();\n\n        // common ratio of a GP should not be zero\n        if (commonRatio == 0) {\n            System.out.println(\"common ratio cannot be zero\");\n            return;\n        }\n\n        if (numberOfTerms <= 0) {\n            // if numberOfTerms is 0 or less than, sum to infinity is considered\n            if (commonRatio > -1 && commonRatio < 1) {\n                System.out.println(\"Geometric progression sum to infinity is: \" + sumGPToInfinity(firstTerm, commonRatio));\n            } else {\n                System.out.println(\"Common ratio for sum to infinity should be between -1 and 1\");\n                return;\n            }\n        } else {\n            System.out.println(\"Geometric Progression sum is: \" + sumGP(firstTerm, commonRatio, numberOfTerms));\n        }\n    }\n}\n"
  },
  {
    "path": "Maths/Series/Sum_of_GP/Sum_of_GP.py",
    "content": "\"\"\"A geometric progression, also known as a geometric sequence, \nis a sequence of numbers where each term after the first is found by \nmultiplying the previous one by a fixed, non-zero number called the \ncommon ratio.\na, a*r, a*r*r,.... forms a GP.\nwhere a is the first element and r is the common ratio.\nSum of GP is given by a*(r^n - 1)/(r - 1) where n is the number of terms.\"\"\"\n\ndef sumOfGP(a,r,n):\n    return a*(pow(r,n)-1)/(r-1)\n    \na = 2\nr = 2\nn = 15\nprint(sumOfGP(a,r,n))"
  },
  {
    "path": "Maths/Series/Sum_of_HP/HP_sum.py",
    "content": "def HP(a,d,n): \n    sum=0       \n    curr_term=a \n    for i in range(1,n+1): \n        temp=a+(i-1)*d\n        sum+=(round((1/temp),5))\n    print(sum)\n\n\na = 2   \nd = 1   \nn = 5  \n  \nHP(a, d, n) \n"
  },
  {
    "path": "Maths/Series/Sum_of_HP/Sum_of_HP.cpp",
    "content": "Harmonic progression is a series whose inverse will be an arithmetic progression. i.e. if for a harmonic progression A1, A2, A3.. An, there is an arithmetic\nprogression 1/A1, 1/A2, 1/A3.\n\nSo, a general HP is :\n1/a, 1/(a+d), 1/(a+2d), … 1/(a + nd),where 1/a is the first term and d is the common difference of the reversed AP.\n\nInput:a = 3, d = 2, n = 5\nOutput:The sum of HP is 0.878211\nExecution:Sum = ⅓ + ⅕ + 1/7 + 1/9 + 1/11 = 0.878211\n\nCode:\n#include <iostream>\nusing namespace std;\nfloat findSeriesSum(int a, int d, int n){\n   float sumVal = 0;\n   float term = 0;\n   for(float i = 1; i <= n; i++){\n      term = (1.0)/(float)(a + (i-1)*d);\n      sumVal += term;\n   }\n   return sumVal;\n}\nint main(){\n   int n, a, d ;\n   cin>>n>>a>>d;\n   cout<<\"The sum of HP is \"<<findSeriesSum(a, d, n);\n   return 0;\n}\n"
  },
  {
    "path": "Maths/Series/Sum_of_HP/Sum_of_HP.cs",
    "content": "/***\n\nAbout the approach:\n\t->No particular formula used\n\t\t. 1/a is  reciprocal of first term\n\t\t. d is common difference for reciprocal\n\t\t. n is number of terms\n\t\tof the harmonic sequence\n\t->sum of all terms is found generating each term and adding them\n\t->Time Complexity: O(n) where n is number of terms in the Harmonic sequence\n\t->Space Complexity: O(1)\n\t->It is considered that a,d and n are given by the user and sum is within double datatype limits\n\n***/\nusing System.IO;\nusing System;\n\nclass Program\n{\n    static void Main()\n    {\n        Console.WriteLine(\"Enter the reciprocal of first term in the Harmonic Sequence:\");\n        double firstTerm = Convert.ToDouble(Console.ReadLine());\n        \n        Console.WriteLine(\"Enter the common difference of reciprocal of terms in the Harmonic Sequence:\");\n        double commonDiff = Convert.ToDouble(Console.ReadLine());\n        \n        Console.WriteLine(\"Enter the number of terms in the Harmonic Sequence:\");\n        int numTerms = Convert.ToInt32(Console.ReadLine());\n        \n        double term = 1.0 / (firstTerm * 1.0);\n        double sum = 0;\n        \n        if(firstTerm == 0 || numTerms < 0)\n        {\n            Console.WriteLine(\"Not possible to find sum of terms in the Harmonic Sequence for the given input\");\n            return;\n        }\n        \n        for(int i = 1;i <= numTerms;i++)\n        {\n            sum += term;\n            //1.0 is multiplied in denominator to ensure it doesn't get implicitly converted to int\n            term = 1.0 / (firstTerm + (i * commonDiff)) * 1.0 ;\n        }\n        Console.WriteLine(\"The sum of terms in the Harmonic Sequence are :\" + sum);\n        \n        \n        \n        \n    }\n}"
  },
  {
    "path": "Maths/Series/Sum_of_HP/hpSum.js",
    "content": "const readline = require('readline')\n\nconst rl = readline.createInterface({\n  input: process.stdin,\n  output: process.stdout\n})\n\n// Basic implementation\nconst hpSum = (a, d, n) => {\n  let sum = 0;\n  for (let i = 0; i < n; i++) {\n    sum += 1 / (a + i * d)\n  }\n  return sum\n}\n\n// Recursive implementation\nconst hpSumRecursive = (a, d, limit, sum = 0) =>\n  limit > 0 ?\n    hpSumRecursive(a, d, limit - 1, sum + 1 / (a + (limit - 1) * d)) :\n    sum\n\nconst askQuestions = () => new Promise(resolve  => \n  rl.question('\\nEnter a\\n> ', a =>\n    rl.question('Enter d\\n> ', d =>\n      rl.question('Enter the number of elements\\n> ', n => {\n        a = parseInt(a)\n        d = parseInt(d)\n        n = parseInt(n)\n        rl.close()\n        resolve({ a, d, n })\n      })\n    )\n  )\n)\n\naskQuestions()\n  .then(({ a, d, n }) => {\n    console.log(`\\nA sum of a harmonic progression (basic alg) is \\\n${hpSum(a, d, n)}`)\n    console.log(`A sum of a harmonic progression (recursive alg) is \\\n${hpSum(a, d, n)}\\n`)\n  })\n"
  },
  {
    "path": "Maths/Series/Sum_of_N/Sum_of_n.c",
    "content": "/* Method:-\nSum of first N natural number = (2 * N) * (N + 1);\n*/\n// C Program to find sum \n// of first n natural numbers \n#include <stdio.h>\n\nint main() {\n\t// declaring the variables \n\t// where n is indicating the natural number \n\t// and S the sum of natural number\n\tint n,S;\n\t// taking input n from user\n\tscanf(\"%d\",&n);\n\t// Calculating the sum\n\t// by Arithmetic Progression formula\n\tS = (2*n)*(n+1);\n\t// display the sum\n\tprintf(\"%d\",S);\n}"
  },
  {
    "path": "Maths/Series/Sum_of_N/sumOfNNumbers.sh",
    "content": "echo -n \"Enter number : \"\nread n\n\n# store single digit\ni=1\n# store number of digit\nsum=0\n# use while loop to caclulate the sum of all digits\nwhile [ $i -le $n ]\n  do\n   sum=$(( $sum + $i )) # calculate sum of digit\n        i=$(( $i + 1 ))\n  done\necho  \"Sum of all digit  is $sum\"\n"
  },
  {
    "path": "Maths/Series/Sum_of_N/sum_of_n_natural_no.cpp",
    "content": "// Program to find sum of n natural numbers\n\n#include <bits/stdc++.h>\nusing namespace std;\n\nint main()\n{\n    int n, sum, a=1;\n    cout << \"Enter number of terms: \";\n    cin >> n;\n    sum = (n*(n+a))/2;\n    cout << \"The sum of first \" << n << \" natural numbers are: \" << sum << endl;\n    return 0;\n}"
  },
  {
    "path": "Maths/Series/Sum_of_N/sum_of_n_natural_numbers.go",
    "content": "package main\n\nimport (\n\t\"fmt\"\n)\n\n// Calculate the sum of N natural numbers\n// using the arithmetic progression formula Sn = n/2 * (2*a + (n-1)d)\n// Where:\n// n: numbers of terms\n// a: first term\n// d: common difference\n// for natural numbers the formula becomes: n/2 * (n+1)\nfunc sumNNaturalNumbers(terms uint) uint {\n\treturn (terms * (terms + 1))/2;\n}\n\nfunc main() {\n\tvar numberOfTerms uint;\n\tvar sum uint;\n\n\t// Get user input\n\tfmt.Printf(\"Enter the number of terms: \");\n\t_, err := fmt.Scanf(\"%d\", &numberOfTerms);\n\n\t// make sure the input is/contains a number\n\tif err != nil {\n\t\tfmt.Println(\"Invalid input !\");\n\t\treturn;\n\t}\n\n\t// Calculate and display the sum\n\tsum = sumNNaturalNumbers(numberOfTerms);\n\tfmt.Println(\"The sum of the first\", numberOfTerms, \"natural number(s) is:\", sum);\n\n}"
  },
  {
    "path": "Maths/Series/Sum_of_N/sumn.py",
    "content": "\ndef sumn(n):\n    s=(n*(n+1))/2 # finds the sum of first n natural numbers\n    return s\n\nn=int(input())  # inputs th limit\nprint(sumn(n))\n"
  },
  {
    "path": "Maths/Series/Sum_of_N/sumofNnaturalnums.cs",
    "content": "using System;  \npublic class Exercise3  \n{  \n    public static void Main() \n{\n   int i,n,sum=0;\n   Console.Write(\"\\n\\n\");\n   Console.Write(\"Input Value of terms : \");\n   n= Convert.ToInt32(Console.ReadLine());   \n   for(i=1;i<=n;i++)\n   {\n     sum+=i;\n   }\n   Console.Write(\"\\nThe Sum of Natural Number upto {0} terms : {1} \\n\",n,sum);\n  }\n}"
  },
  {
    "path": "Maths/Series/Sum_of_N/sumofNnaturalnums.py",
    "content": "#  Sum of n natural Number in python3 ..\n\ntry:\n    n=int(input(\"Enter the Nth term upto which you want to calculate the sum: \"))\n    a=1\n    d=1\n    ans = (n/2)*(2*a + (n-1)*d)\n    print(ans)\n\nexcept ValueError:\n    print(\"Please enter a valid integer with base 10.\")\n\n"
  },
  {
    "path": "Maths/Series/Sum_of_N2/SumOf_n^2.C++",
    "content": "/*Method:-\nSum of square of first N natural number = (N * (N + 1) * (2*N + 1)) / 6;\n exmple:-\n  For N =4, Sum = (4 * (4 + 1) * (2 * 4 + 1)) /6;\n                  = (4*5*9)/6\n                  =180/6\n                  = 30\n\n  For N =5, Sum = (5 * (5 + 1) * (2 * 5 + 1)) /6;\n                  = (5*6*11)/6\n                  = 55  */            \n\n// CPP Program to find sum \n// of square of first n \n// natural numbers \n#include <bits/stdc++.h> \nusing namespace std; \n  \n// Return the sum of square of \n// first n natural numbers \nint squaresum(int n) \n{ \n    return (n * (n + 1) * (2 * n + 1)) / 6; \n} \n  \n// Driven Program \nint main() \n{ \n    int n = 4; \n    cout << squaresum(n) << endl; \n    return 0; \n} \n\n/*Output:\n\n30 */"
  },
  {
    "path": "Maths/Series/Sum_of_N2/Sum_Of_n^2.py",
    "content": "'''Python3 Program to find sum of square\n of first n natural numbers\nReturn the sum of square of first n natural numbers.\n'''\ndef squaresum(n) : \n    return (n * (n + 1) * (2 * n + 1)) // 6\n'''\nAvoiding early overflow:\nFor large n,it would overflow.\nWe can avoid overflow using  n*(n+1) must be divisible by 2.\n\nreturn (n * (n + 1) / 2) * (2 * n + 1) / 3 \nuse above code while large numbers\n'''\n\n# Driven Program \nn =int (input(\"Enter the number:::\"))\nprint(squaresum(n)) \n  \n#This code is contributed by Himik Nainwal"
  },
  {
    "path": "Maths/Series/Sum_of_N2/Sum_of_n^2.swift",
    "content": "/*Swift Implementation for sum of n^2*/\n\n//\nfunc squaresum(input: Int) -> Int {\n\n    return (input * (input + 1) * (2 * input + 1)) / 6;\n}\n\n"
  },
  {
    "path": "Maths/Series/Sum_of_N2/square_sum.cs",
    "content": "using System; \n  \nclass GFG  \n{ \n    public static int squaresum(int n) \n    { \n        return (n * (n + 1) *  \n               (2 * n + 1)) / 6; \n    } \n  \n   \n    public static void Main() \n    { \n        int n = 10; \n  \n        Console.WriteLine(squaresum(n)); \n    } \n} \n"
  },
  {
    "path": "Maths/Series/Sum_of_N2/sumOfNSquare.js",
    "content": "// Take Input from user\nvar nTerm = parseInt(\n  prompt(\n    \"Enter the nth term upto which you want to calculate the sum of n sqaure \"\n  )\n);\n\n// Get the Sum of n square\nvar value = () => {\n  return (nTerm * (nTerm + 1) * (2 * nTerm + 1)) / 6;\n};\n\n// Print it\nconsole.log(value());\n"
  },
  {
    "path": "Maths/Series/Sum_of_N2/sumOfn_squared.py",
    "content": "# Taking Input from the user\nn = int(input())\n\n# Sum of n squared natural numbers using the formula - Σn2 = [n(n+1)(2n+1)]/6\nprint((n*(n+1)*(2*n+1))/6)\n"
  },
  {
    "path": "Maths/Series/Sum_of_N2/sumofnsqaure.php",
    "content": "<?php \n\nfunction sum($n) \n{ \n\t$sum = 0; \n\tfor ($i = 1; $i <= $n; $i++) \n\t\t$sum += ($i * $i); \n\n\treturn $sum; \n} \n\n\t// Driver code \n\t$n = 2; \n\techo sum($n); \n\t\n \n?> \n"
  },
  {
    "path": "Maths/Series/Sum_of_N3/Sum of n3.cpp",
    "content": "/*Sum of n³*/\n\n#include <iostream>\n#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n\tint n;\n\n\tcin >> n; // Input\n\n\t/*We have a mathematical formula according to which\n\tsum of cubes of first n natural numbers\n\tis given by ((n*(n+1))/2)*((n*(n+1))/2)*/\n\n\tint ans = ((n*(n+1))/2)*((n*(n+1))/2);\n\n\tcout << ans << endl; // output\n\n\treturn 0;\n}"
  },
  {
    "path": "Maths/Series/Sum_of_N3/sum of n^3.cpp",
    "content": "// Efficient CPP program to find sum of cubes  \n// of first n natural numbers that avoids  \n// overflow if result is going to be withing  \n// limits. \n#include<iostream> \nusing namespace std; \n\n// Returns sum of first n natural \n// numbers \nint sumOfSeries(int n) \n{ \n    int x; \n    if (n % 2 == 0) \n        x = (n/2) * (n+1); \n    else\n        x = ((n + 1) / 2) * n; \n    return x * x;  \n} \n\n// Driver code \nint main() \n{ \n  int n;\n  cout<<\"Enter a number\"<<endl;\n  cin>>n;\n  cout << sumOfSeries(n); \n  return 0; \n}  \n"
  },
  {
    "path": "Maths/Series/Sum_of_N3/sumofncube.php",
    "content": "<?php \n \nfunction sumOfSeries( $n) \n{ \n    $sum = 0; \n    for ($x = 1; $x <= $n; $x++) \n        $sum += $x * $x * $x; \n    return $sum; \n} \n  \n$n = 5; //enter the number here\necho sumOfSeries($n); \n  \n\n?>"
  },
  {
    "path": "Maths/Statistics/Compound_Interest/Compound_Interest.c",
    "content": "#include <stdio.h>\n#include <math.h>\n\nint main(){\n\tdouble principle, rate, timeSpan;\n\n    printf(\"Enter the principle amount\\n\");\n    scanf(\" %lf\", &principle);\n\n    printf(\"Enter the compound rate of interest\\n\");\n    scanf(\" %lf\", &rate);\n\n    printf(\"Enter the time span or number of times the amount gets compounded\\n\");\n    scanf(\" %lf\", &timeSpan);\n  \n    /* Calculate compound interest */\n    /*Formula to calculate final amount after applying compound interest is given by:\n\tFinalAmount = (principle)*((1 + (rate)/100)^(timeSpan))*/\n    double FinalAmount = principle * (pow((1 + rate / 100), timeSpan)); \n\n    printf(\"Final amount after applying Compound interest = %lf\\n\", FinalAmount);\n  \n    return 0;\n}\n\n"
  },
  {
    "path": "Maths/Statistics/Compound_Interest/Compound_Interest.cpp",
    "content": "//  Compound Interest  C.I. = P(1+R/100)^t\n#include <bits/stdc++.h>\nusing namespace std;\n// helper function\ndouble compoundInterest(double p, double r, double t) {\n    return p * pow( (1 + r/100), t );\n}\n// driver function\nint main() {\n    // variables are self-explanatory\n    double principle;\n    double rate;\n    double time;\n\n    cout<<\"Enter the principle \\n\";\n    cin>>principle;\n\n    cout<<\"Enter the rate\\n\";\n    cin>>rate;\n\n    cout<<\"Enter the time\";\n    cin>>time;\n\n    cout<<\"The compound interest is: \"<<compoundInterest(principle, rate, time);\n    return 0;\n}"
  },
  {
    "path": "Maths/Statistics/Compound_Interest/Compound_Interest.cs",
    "content": "using System;\n\nclass Program\n{\n    /// <summary>\n    /// Calculates the compound interest for the given values.\n    /// </summary>\n    private static double CalculateCompoundInterest(double initialAmount, double interestRate, int totalYears, int compundFrequency)\n    {\n        return (initialAmount * Math.Pow((1 + (interestRate / compundFrequency)), (compundFrequency * totalYears)));\n    }\n\n    /// <summary>\n    /// Main application function.\n    /// </summary>\n    static void Main()\n    {\n        double initialAmount, interestRate;\n        int totalYears, compundFrequency;\n        string userInput;\n        \n        Console.WriteLine(\"Enter the initial amount:\");\n        userInput = Console.ReadLine();\n        \n        if ((double.TryParse(userInput, out initialAmount) == false)) { Program.ExitAfterInvalidInput(); }\n        \n        Console.WriteLine(\"Enter the annual interest rate:\");\n        userInput = Console.ReadLine();\n        \n        if ((double.TryParse(userInput, out interestRate) == false)) { Program.ExitAfterInvalidInput(); }\n        \n        Console.WriteLine(\"Enter the number of years:\");\n        userInput = Console.ReadLine();\n        \n        if ((int.TryParse(userInput, out totalYears) == false)) { Program.ExitAfterInvalidInput(); }\n        \n        Console.WriteLine(\"Enter the times per year that interest will be compounded:\");\n        userInput = Console.ReadLine();\n        \n        if ((int.TryParse(userInput, out compundFrequency) == false)) { Program.ExitAfterInvalidInput(); }\n        \n        double totalAmount = Program.CalculateCompoundInterest(initialAmount, interestRate, totalYears, compundFrequency);\n        string yearText    = (totalYears > 1 ? \"years\" : \"year\"); \n        \n        Console.WriteLine();\n        Console.WriteLine(string.Format(\"In {0} {1} the total amount will be {2:#0.000}.\", totalYears, yearText, totalAmount));\n    }\n    \n    /// <summary>\n    /// Informs the user that an invalid value has been entered and exits the program.\n    /// </summary>\n    private static void ExitAfterInvalidInput()\n    {\n        Console.WriteLine(\"You've entered an invalid value. Exiting...\");\n        Environment.Exit(1);\n    }\n}\n"
  },
  {
    "path": "Maths/Statistics/Compound_Interest/Compound_Interest.html",
    "content": "<!DOCTYPE html>\r\n<html>\r\n<head>\r\n\t<title>Calculating Compound Interest using JavaScript</title>\r\n\r\n\t<!--Simple CSS snipets-->\r\n\t<style>\r\n\t\tdiv{\r\n\t\t\tdisplay: table-row; /*to form rows*/\r\n\t\t}\r\n\t\tlabel, input{\r\n\t\t\tdisplay: table-cell; /*to form cells*/\r\n\t\t}\r\n\t</style>\r\n</head>\r\n<body>\r\n\r\n\t<!-- HTML components to acces input dynamically-->\r\n\t<h1>Calculate Compound Interest</h1>\r\n\r\n\t<!-- Takes amount from users-->\r\n\t<div> \r\n\t\t<label> Principle Amount: </label> \r\n\t\t<input id=\"getPrinciple\">\r\n\t</div>\r\n\r\n\t<!-- Takes rate from users-->\r\n\t<div> \r\n\t\t<label> Rate of Interest (in %): </label> \r\n\t\t<input id=\"getRate\">\r\n\t</div>\r\n\r\n\t<!-- Takes time from users-->\r\n\t<div> \r\n\t\t<label> Number of Years: </label> \r\n\t\t<input id=\"getTime\">\r\n\t</div>\r\n\r\n\t<!-- Takes no. of times interested compounded per year-->\r\n\t<div> \r\n\t\t<label> No. of Times Compounded per Year: </label> <!--Interest Compounded daily, weekly, monthly or yearly basis--> \r\n\t\t<input id=\"getCompoundingTimes\">\r\n\t</div>\r\n\r\n\t<button onclick=\"calcCompoundInterest()\">Calculate</button>  <!-- Calls javascript function for calculating amount and compound interest-->\r\n\r\n\r\n\t<p id=\"compoundInterestIs\"></p> <!-- Displays the calculated amount and compound interest-->\r\n\r\n\r\n<script type=\"text/javascript\">\r\n\t\r\n\t// Calculates amount and Compound Interest after given time\r\n\tfunction calcCompoundInterest() {\r\n\t\t\r\n\t\tconst principle = document.getElementById(\"getPrinciple\").value;\r\n\t\tconst compoundedTimes = document.getElementById(\"getCompoundingTimes\").value;\r\n\t\tconst time = document.getElementById(\"getTime\").value;\r\n\t\tconst rate = document.getElementById(\"getRate\").value;\r\n\t\tcompoundInterest = document.getElementById(\"compoundInterestIs\");\r\n\r\n\t\t//Calculates amount = P * ((1 + R/n) ^ (n * t))\r\n\t\tvar amountIs = principle * Math.pow((1 + ( rate /( compoundedTimes * 100))), (compoundedTimes * time));\r\n\r\n\t\t//Calculates CI = amount - P\r\n\t\tvar compoundedInterestIs = amountIs - principle;\r\n\r\n\t\t//Displays Amount and Compound Interest on web page\r\n\t\tcompoundInterest.innerHTML = \"The total Amount is:\" + amountIs.toFixed(2); //toFixed() is used for rounding decimal value upto second place\r\n\t\tcompoundInterest.innerHTML += \"<br>The Compoud Interest is:\" + compoundedInterestIs.toFixed(2);\r\n\r\n\t}\r\n</script>\r\n</body>\r\n</html>"
  },
  {
    "path": "Maths/Statistics/Compound_Interest/Compound_Interest.java",
    "content": "//Calculating Compound Interest\n\nimport java.util.*;\n\nclass Solution\n{\n//function to calculate compound interest\n    double compound_interest(double principle,double rate,double time){\n\t    return principle * Math.pow((1 + rate/100), time);\n\t}\n}\npublic class Compound_Interest\n{\n//main class\n    public static void main(String[] args)\n    {\n      \tScanner scanner = new Scanner(System.in);\n\t      Solution object = new Solution();\n        double principle,rate,time;\n        System.out.println(\"Enter the principle \");\n      \tprinciple = scanner.nextFloat();\n      \tSystem.out.println(\"Enter the rate \");\n      \trate = scanner.nextFloat();\n      \tSystem.out.println(\"Enter the time period \");\n\t      time = scanner.nextFloat();\n      \tSystem.out.println(\"The compound interest is: \"+object.compound_interest(principle, rate, time));\n    }\n} \n"
  },
  {
    "path": "Maths/Statistics/Compound_Interest/Compound_Interest.js",
    "content": "var principle = 1000;\nvar time = 2;\nvar rate = 5;\n\nvar ci = principle * Math.pow( (1 + rate/100), time);\nconsole.log(\"Compound Interest is: \" + ci)\n"
  },
  {
    "path": "Maths/Statistics/Compound_Interest/Compound_Interest.py",
    "content": "# Python3 program to find compound \n# interest for given values. \n  \ndef compound_interest(principle, rate, time): \n  \n    # Calculates compound interest  \n    Amount = principle * (pow((1 + rate / 100), time)) \n    CI = Amount - principle \n    print(\"Compound interest is\", CI) \n  \n# Driver Code  \np = float(input(\"Enter principle amount: \"))\nr = float(input(\"Enter rate: \"))\nt = float(input(\"Enter time: \"))\ncompound_interest(p, r, t) \n"
  },
  {
    "path": "Maths/Statistics/Compound_Interest/Compound_Interest.rb",
    "content": "#!/usr/bin/env ruby\n\ndef calculateCompoundInterest(principle, rate, time)\n  result = principle * ((1 + rate / 100) ** time)\nend\n\nputs \"Enter your principle value:\"\nprinciple = gets.to_f.round(2)\nputs \"Enter your rate value:\"\nrate = gets.to_f.round(2)\nputs \"Enter your time value:\"\ntime = gets.to_i\n\nputs \"Your compound interest is #{calculateCompoundInterest(principle, rate, time)}\""
  },
  {
    "path": "Maths/Statistics/Compound_Interest/Compound_Interest.ts",
    "content": "/*\nA TypeScript program to return Compound Interest\nParameters: \nprincipal amount\ntime \ninterest rate\nnumber of times to compound per time period,\nall numbers\nReturns;\ncompound interest,\na number\n*/\nlet compoundInterest = function (principal: number, time : number, rate : number, n: number) : number {\n    return principal * (Math.pow((1 + (rate / n)), (n * time)));\n}\n\n//Test\nconsole.log(compoundInterest(1000, 2, 0.05, 1));\n\n"
  },
  {
    "path": "Maths/Statistics/Confidence_Interval/Confidence_Interval.cpp",
    "content": "#include <cassert>\n#include <cmath>\n#include <array>\n\n/** calculate the normal quantile (which is the inverse normal CDF, here calculated by Acklam's algorithm, according to https://stackedboxes.org/2017/05/01/acklams-normal-quantile-function/)\n *\t@param p probability\n *\t@return the p-quantile of the standard normal distribution\n */\ndouble normalQuantile(const double p)\n{\n\tassert(0 <= p && p <= 1);\n\n\tdouble result = 0;\n\n\tif (p == 0)\n\t\tresult = -INFINITY;\n\telse if (p == 1)\n\t\tresult = INFINITY;\n\telse\n\t{\n\t\tconst double a[] = {\n\t\t\t\t-3.969683028665376e+01,\n\t\t\t\t2.209460984245205e+02,\n\t\t\t\t-2.759285104469687e+02,\n\t\t\t\t1.383577518672690e+02,\n\t\t\t\t-3.066479806614716e+01,\n\t\t\t\t2.506628277459239e+00\n\t\t};\n\n\t\tconst double b[] = {\n\t\t\t\t-5.447609879822406e+01,\n\t\t\t\t1.615858368580409e+02,\n\t\t\t\t-1.556989798598866e+02,\n\t\t\t\t6.680131188771972e+01,\n\t\t\t\t-1.328068155288572e+01\n\t\t};\n\n\t\tconst double c[] = {\n\t\t\t\t-7.784894002430293e-03,\n\t\t\t\t-3.223964580411365e-01,\n\t\t\t\t-2.400758277161838e+00,\n\t\t\t\t-2.549732539343734e+00,\n\t\t\t\t4.374664141464968e+00,\n\t\t\t\t2.938163982698783e+00\n\t\t};\n\n\t\tconst double d[] = {\n\t\t\t\t7.784695709041462e-03,\n\t\t\t\t3.224671290700398e-01,\n\t\t\t\t2.445134137142996e+00,\n\t\t\t\t3.754408661907416e+00\n\t\t};\n\n\t\tconst double p_low = 0.02425;\n\t\tconst double p_high = 1 - p_low;\n\n\t\tif (p < p_low) // approximation for lower region\n\t\t{\n\t\t\tconst double q = sqrt(-2*log(p));\n\t\t\tresult = (((((c[0]*q+c[1])*q+c[2])*q+c[3])*q+c[4])*q+c[5]) / ((((d[0]*q+d[1])*q+d[2])*q+d[3])*q+1);\n\t\t}\n\t\telse if (p_high < p) // approximation for upper region\n\t\t{\n\t\t\tconst double q = sqrt(-2*log(1-p));\n\t\t\tresult = -(((((c[0]*q+c[1])*q+c[2])*q+c[3])*q+c[4])*q+c[5]) / ((((d[0]*q+d[1])*q+d[2])*q+d[3])*q+1);\n\t\t}\n\t\telse // approximation for central region\n\t\t{\n\t\t\tconst double q = p - 0.5;\n\t\t\tconst double r = q*q;\n\t\t\tresult = (((((a[0]*r+a[1])*r+a[2])*r+a[3])*r+a[4])*r+a[5])*q / (((((b[0]*r+b[1])*r+b[2])*r+b[3])*r+b[4])*r+1);\n\t\t}\n\t}\n\n\treturn result;\n}\n\n/** calculate the confidence interval\n *\t@param estimator estimator of which the CI should be calculated\n *\t@param standardError the estimator's standard error\n *\t@param confidenceLevel confidence level of the CI\n *\t@return the (confidenceLevel*100)% CI\n */\nstd::array<double, 2> confidence_interval(const double estimator, const double standardError, const double confidenceLevel)\n{\n\tassert(0 < confidenceLevel && confidenceLevel < 1);\n\tconst double errorLevel = 1 - confidenceLevel;\n\n\tdouble lower = 0;\n\tdouble upper = 0;\n\n\tconst double error = normalQuantile(1 - errorLevel/2.0) * standardError;\n\n\tlower = estimator - error;\n\tupper = estimator + error;\n\n\tstd::array<double, 2> confidenceInterval{lower, upper};\n\treturn confidenceInterval;\n}\n\n// Test section:\n\n#include <iomanip>\n#include <iostream>\n#include <random>\n#include <vector>\n\nusing namespace std;\n\nint main()\n{\n\tconst double confidenceLevel = 0.99;\n\n\tconst size_t sampleSize = 10000;\n\tvector<double> sample(sampleSize);\n\n\tdouble sampleMean = 0;\n\tdouble sampleVariance = 0;\n\n\t// generate random sample of size sampleSize\n\t{\n\t\tdefault_random_engine generator;\n\t\tnormal_distribution<double> distribution(0.0,1.0);\n\n\t\tfor(size_t i = 0; i < sampleSize; ++i)\n\t\t\tsample[i] = distribution(generator);\n\t}\n\n\t// calculate mean\n\tfor (size_t i = 0; i < sampleSize; ++i)\n\t\tsampleMean += sample[i];\n\tsampleMean /= sampleSize;\n\n\t// calculate variance\n\tfor (size_t i = 0; i < sampleSize; ++i)\n\t\tsampleVariance += (sample[i] - sampleMean)*(sample[i] - sampleMean);\n\tsampleVariance /= sampleSize-1;\n\n\t// our estimator is the sample mean, whose standard deviation is given by\n\tconst double estimatorStandardDeviation = sqrt(sampleVariance/sampleSize);\n\n\tauto confidenceInterval = confidence_interval(sampleMean, estimatorStandardDeviation, confidenceLevel);\n\n\tcout << \"The random sample of \" << sampleSize << \" standard normal points yields the following estimator for the mean:\" << endl\n\t\t << \"   estimator: \" << sampleMean << endl\n\t\t << \"   \" << setprecision(2) << confidenceLevel*100 << \"% confidence interval: (\" << setprecision(6) << confidenceInterval[0] << \", \" << confidenceInterval[1] << \")\" << endl;\n\n\treturn 0;\n}\n"
  },
  {
    "path": "Maths/Statistics/Confidence_Interval/Confidence_Inverval.c",
    "content": "#include <assert.h>\n#include <math.h>\n#include <stdlib.h>\n\n/** calculate the normal quantile (which is the inverse normal CDF, here calculated by Acklam's algorithm, according to https://stackedboxes.org/2017/05/01/acklams-normal-quantile-function/)\n *\t@param p probability\n *\t@return the p-quantile of the standard normal distribution\n */\ndouble normalQuantile(const double p)\n{\n\tassert(0 <= p && p <= 1);\n\n\tdouble result = 0;\n\n\tif (p == 0)\n\t\tresult = -INFINITY;\n\telse if (p == 1)\n\t\tresult = INFINITY;\n\telse\n\t{\n\t\tconst double a[] = {\n\t\t\t\t-3.969683028665376e+01,\n\t\t\t\t2.209460984245205e+02,\n\t\t\t\t-2.759285104469687e+02,\n\t\t\t\t1.383577518672690e+02,\n\t\t\t\t-3.066479806614716e+01,\n\t\t\t\t2.506628277459239e+00\n\t\t};\n\n\t\tconst double b[] = {\n\t\t\t\t-5.447609879822406e+01,\n\t\t\t\t1.615858368580409e+02,\n\t\t\t\t-1.556989798598866e+02,\n\t\t\t\t6.680131188771972e+01,\n\t\t\t\t-1.328068155288572e+01\n\t\t};\n\n\t\tconst double c[] = {\n\t\t\t\t-7.784894002430293e-03,\n\t\t\t\t-3.223964580411365e-01,\n\t\t\t\t-2.400758277161838e+00,\n\t\t\t\t-2.549732539343734e+00,\n\t\t\t\t4.374664141464968e+00,\n\t\t\t\t2.938163982698783e+00\n\t\t};\n\n\t\tconst double d[] = {\n\t\t\t\t7.784695709041462e-03,\n\t\t\t\t3.224671290700398e-01,\n\t\t\t\t2.445134137142996e+00,\n\t\t\t\t3.754408661907416e+00\n\t\t};\n\n\t\tconst double p_low = 0.02425;\n\t\tconst double p_high = 1 - p_low;\n\n\t\tif (p < p_low) // approximation for lower region\n\t\t{\n\t\t\tconst double q = sqrt(-2*log(p));\n\t\t\tresult = (((((c[0]*q+c[1])*q+c[2])*q+c[3])*q+c[4])*q+c[5]) / ((((d[0]*q+d[1])*q+d[2])*q+d[3])*q+1);\n\t\t}\n\t\telse if (p_high < p) // approximation for upper region\n\t\t{\n\t\t\tconst double q = sqrt(-2*log(1-p));\n\t\t\tresult = -(((((c[0]*q+c[1])*q+c[2])*q+c[3])*q+c[4])*q+c[5]) / ((((d[0]*q+d[1])*q+d[2])*q+d[3])*q+1);\n\t\t}\n\t\telse // approximation for central region\n\t\t{\n\t\t\tconst double q = p - 0.5;\n\t\t\tconst double r = q*q;\n\t\t\tresult = (((((a[0]*r+a[1])*r+a[2])*r+a[3])*r+a[4])*r+a[5])*q / (((((b[0]*r+b[1])*r+b[2])*r+b[3])*r+b[4])*r+1);\n\t\t}\n\t}\n\n\treturn result;\n}\n\n/** calculate the confidence interval\n *\t@param[in] estimator estimator of which the CI should be calculated\n *\t@param[in] standardError the estimator's standard error\n *\t@param[in] confidenceLevel confidence level of the CI\n *\t@param[out] confidenceInterval expected to be an array of 2 doubles, in which the lower and upper bounds of the (confidenceLevel*100)% CI are saved\n */\nvoid confidence_interval(const double estimator, const double standardError, const double confidenceLevel, double confidenceInterval[])\n{\n\tassert(0 < confidenceLevel && confidenceLevel < 1);\n\tconst double errorLevel = 1 - confidenceLevel;\n\n\tdouble lower = 0;\n\tdouble upper = 0;\n\n\tconst double error = normalQuantile(1 - errorLevel/2.0) * standardError;\n\n\tlower = estimator - error;\n\tupper = estimator + error;\n\n\tconfidenceInterval[0] = lower;\n\tconfidenceInterval[1] = upper;\n\n\treturn;\n}\n\n/* Test section */\n\n#include <stdio.h>\n\nint main(void)\n{\n\tconst double confidenceLevel = 0.99;\n\n\tdouble confidenceInterval[2];\n\n\tconst size_t sampleSize = 10000;\n\tdouble sample[sampleSize];\n\n\tdouble sampleMean = 0;\n\tdouble sampleVariance = 0;\n\n\t// generate random sample of size sampleSize\n\tsrand(0);\n\tfor(size_t i = 0; i < sampleSize; ++i)\n\t{\n\t\tdouble uniformRandom = rand()/((double)RAND_MAX);\n\t\tsample[i] = normalQuantile(uniformRandom);\n\t}\n\n\t// calculate mean\n\tfor (size_t i = 0; i < sampleSize; ++i)\n\t\tsampleMean += sample[i];\n\tsampleMean /= sampleSize;\n\n\t// calculate variance\n\tfor (size_t i = 0; i < sampleSize; ++i)\n\t\tsampleVariance += (sample[i] - sampleMean)*(sample[i] - sampleMean);\n\tsampleVariance /= sampleSize-1;\n\n\t// our estimator is the sample mean, whose standard deviation is given by\n\tconst double estimatorStandardDeviation = sqrt(sampleVariance/sampleSize);\n\n\tconfidence_interval(sampleMean, estimatorStandardDeviation, confidenceLevel, confidenceInterval);\n\n\tprintf(\"The random sample of %zu standard normal points yields the following estimator for the mean:\\n\", sampleSize);\n\tprintf(\"   estimator: %f\\n\", sampleMean);\n\tprintf(\"   %2.1f %% confidence interval: (%f, %f)\\n\", confidenceLevel*100, confidenceInterval[0], confidenceInterval[1]);\n\n\treturn EXIT_SUCCESS;\n}\n"
  },
  {
    "path": "Maths/Statistics/Confidence_Interval/README.md",
    "content": "## This folder is empty.\n"
  },
  {
    "path": "Maths/Statistics/Confidence_Interval/confidenceInterval.js",
    "content": "// calculate 95 percentile confidence interval\nconst hypothesis = Math.random() * 100; // get a random number in range [0, 100)\nconst data = []\nfor (let i = 0; i < 1000; i++)\n{\n  data.push(Math.random() * 200) // sample a dataset in range [0, 200)\n}\nconst mean = data.reduce ((accumulator, currentValue) => {\n  return accumulator + currentValue\n}, 0) / data.length\n\nconst standardDeviation = Math.sqrt (\n  data.reduce((accumulator, nextElement) =>\n  accumulator + (nextElement - mean)\n  , 0) / data.length\n)\n\nconst percentile = 0.95\n\nfunction percentile_z(p) {\n  if (p > 0.5) return -1\n\n  const a0 = 2.5066282;\n  const a1 = -18.6150006;\n  const a2 = 41.3911977;\n  const a3 = -25.4410605;\n  const b1 = -8.4735109;\n  const b2 = 23.0833674;\n  const b3 = -21.0622410;\n  const b4 = 3.1308291;\n  const c0 = -2.7871893;\n  const c1 = -2.2979648;\n  const c2 = 4.8501413;\n  const c3 = 2.3212128;\n  const d1 = 3.5438892;\n  const d2 = 1.6370678\n  let r;\n  let z;\n\n  if (p > 0.42)\n  {\n      r = Math.sqrt(-Math.log(0.5-p));\n      z = (((c3*r+c2)*r+c1)*r+c0)/((d2*r+d1)*r+1);\n  } else\n  {\n      r = p*p;\n      z = p*(((a3*r+a2)*r+a1)*r+a0)/((((b4*r+b3)*r+b2)*r+b1)*r+1);\n  }\n  return z;\n}\n\nconst confLo = mean - (percentile_z (percentile) * standardDeviation / Math.sqrt(data.length))\nconst confHi = mean + (percentile_z (percentile) * standardDeviation / Math.sqrt(data.length))\nconsole.log(confLo, confHi)"
  },
  {
    "path": "Maths/Statistics/Confidence_Interval/confidence_interval.py",
    "content": "# bootstrap confidence intervals\nfrom numpy.random import seed\nfrom numpy.random import rand\nfrom numpy.random import randint\nfrom numpy import mean\nfrom numpy import median\nfrom numpy import percentile\n# seed the random number generator\nseed(1)\n# generate dataset\ndataset = 0.5 + rand(1000) * 0.5\n# bootstrap\nscores = list()\nfor _ in range(100):\n\t# bootstrap sample\n\tindices = randint(0, 1000, 1000)\n\tsample = dataset[indices]\n\t# calculate and store statistic\n\tstatistic = mean(sample)\n\tscores.append(statistic)\nprint('50th percentile (median) = %.3f' % median(scores))\n# calculate 95% confidence intervals (100 - alpha)\nalpha = 5.0\n# calculate lower percentile (e.g. 2.5)\nlower_p = alpha / 2.0\n# retrieve observation at lower percentile\nlower = max(0.0, percentile(scores, lower_p))\nprint('%.1fth percentile = %.3f' % (lower_p, lower))\n# calculate upper percentile (e.g. 97.5)\nupper_p = (100 - alpha) + (alpha / 2.0)\n# retrieve observation at upper percentile\nupper = min(1.0, percentile(scores, upper_p))\nprint('%.1fth percentile = %.3f' % (upper_p, upper))\n"
  },
  {
    "path": "Maths/Statistics/Exponential_Smoothing/Exponential_Smoothing.cpp",
    "content": "//////////////////////////////////////////////////////////////////////////\n/**\n *   C++ implementation of Exponential Smoothing\n *\n\n *\n *   \n *\n *\n *  \n//////////////////////////////////////////////////////////////////////////\n\n#ifndef HEADER_EXPONENTIAL_SMOOTHING_H\n#define HEADER_EXPONENTIAL_SMOOTHING_H\n\n#include <limits>\n#include <iostream>\n#include <cassert>\n\n/** Class data_vec defines a D-dimensional vector\n *  \\T Data type of vector\n *  \\D Dimension of vector\n */\ntemplate <typename T, size_t D>\nclass es_vec\n{\npublic:\n    /** Default constructor*/\n    es_vec()\n    {\n        for (size_t i = 0; i < D; ++i) esv_data[i] = std::numeric_limits<T>::lowest();\n    }\n\n    /** Create a vector with an initial value _v for all elements */\n    es_vec(const T _v)\n    {\n        for (size_t i = 0; i < D; ++i) esv_data[i] = _v;\n    }\n\n    /** Copy constructor*/\n    es_vec(const es_vec<T, D> & _vec)\n    {\n        for (size_t i = 0; i < D; ++i) esv_data[i] = _vec.esv_data[i];\n    }\n\n    /** Destructor*/\n    ~es_vec()\n    {\n\n    }\n\npublic:\n    /** Reset the vector with a specified value _v */\n    void reset(const T _v = 0)\n    {\n        for (size_t i = 0; i < D; ++i) esv_data[i] = _v;\n    }\n\n    /** Init from a raw vector */\n    void init(const T* _data)\n    {\n        for (size_t i = 0; i < D; ++i) esv_data[i] = _data[i];\n    }\n\n    /** Operator [] */\n    T & operator [] (const size_t _i)\n    {\n        return esv_data[_i];\n    }\n\n    const T & operator [] (const size_t _i) const\n    {\n        return esv_data[_i];\n    }\n\n    /** Operator = */\n    es_vec<T, D> & operator = (const es_vec<T, D> & _vec)\n    {\n        for (size_t i = 0; i < D; ++i) esv_data[i] = _vec.esv_data[i];\n        return *this;\n    }\n\n    /** Operator += */\n    es_vec<T, D> & operator += (const es_vec<T, D> & _vec)\n    {\n        for (size_t i = 0; i < D; ++i) esv_data[i] += _vec[i];\n        return *this;\n    }\n\n    /** Operator -= */\n    es_vec<T, D> & operator -= (const es_vec<T, D> & _vec)\n    {\n        for (size_t i = 0; i < D; ++i) esv_data[i] -= _vec[i];\n        return *this;\n    }\n\n    /** Operator *= */\n    es_vec<T, D> & operator *= (const T _v)\n    {\n        for (size_t i = 0; i < D; ++i) esv_data[i] *= _v;\n        return *this;\n    }\n\n    /** Operator /= */\n    es_vec<T, D> & operator /= (const T _v)\n    {\n        for (size_t i = 0; i < D; ++i) esv_data[i] /= _v;\n        return *this;\n    }\n\n    /** get the raw data vector */\n    T* raw_data()\n    {\n        return esv_data;\n    }\n\n    /** return the 2-norm of this vector */\n    const T norm() const\n    {\n        T norm(0);\n        for (size_t i = 0; i < D; ++i) norm += esv_data[i] * esv_data[i];\n        return sqrt(norm);\n    }\n\n    /** ************* Friend functions to provide more operators ****************************** */\n    /** Operator + */\n    friend es_vec<T, D> operator + (const es_vec<T, D> & _vec1, const es_vec<T, D> & _vec2)\n    {\n        return es_vec<T, D>(_vec1) += _vec2;\n    }\n\n    /** Operator - */\n    friend es_vec<T, D> operator - (const es_vec<T, D> & _vec1, const es_vec<T, D> & _vec2)\n    {\n        return es_vec<T, D>(_vec1) -= _vec2;\n    }\n\n    /** Operator * */\n    friend es_vec<T, D> operator * (const T _v, const es_vec<T, D> & _vec)\n    {\n        return es_vec<T, D>(_vec) *= _v;\n    }\n\n    friend es_vec<T, D> operator * (const es_vec<T, D> & _vec, const T _v)\n    {\n        return es_vec<T, D>(_vec) *= _v;\n    }\n\n    /** Operator / */\n    friend es_vec<T, D> operator / (const es_vec<T, D> & _vec, const T _v)\n    {\n        return es_vec<T, D>(_vec) /= _v;\n    }\n\n    /** Operator == */\n    friend const bool operator == (const es_vec<T, D> & _vec1, const es_vec<T, D> & _vec2)\n    {\n        for (size_t i = 0; i < D; ++i)\n        {\n            if (!_vec1[i] == _vec2[i]) return false;\n        }\n        return true;\n    }\n\n    /** Operator != */\n    friend const bool operator != (const es_vec<T, D> & _vec1, const es_vec<T, D> & _vec2)\n    {\n        for (size_t i = 0; i < D; ++i)\n        {\n            if (!_vec1[i] == _vec2[i]) return true;\n        }\n        return false;\n    }\n\n    /** Operator << */\n    friend std::ostream & operator << (std::ostream & _os, const es_vec<T, D> & _vec)\n    {\n        _os << \"[\";\n        for (size_t i = 0; i < D - 1; ++i) _os << _vec[i] << \" \";\n        _os << _vec[D - 1] << \"]\";\n        return _os;\n    }\n\nprivate:\n    T esv_data[D];\n};\n\n/** Single Exponential Smoothing Method\n *  \\T Data type float/double/double double...\n *  \\D Dimension of this class\n */\ntemplate <typename T, size_t D>\nclass single_exponential_smoothing\n{\npublic:\n    /** Default constructor */\n    single_exponential_smoothing() : ses_smoothing_const(0.5), ses_counter(0), ses_vacillation_tolerance(0)\n    {\n        ses_curr_smoothed_ob.reset();\n    }\n\n    /** Destructor */\n    ~single_exponential_smoothing()\n    {\n\n    }\n\npublic:\n    /** Set the value of smoothing constant in the range (0, 1) */\n    void set_smoothing_constant(const T _val)\n    {\n        assert(_val > 0 && _val < 1);\n        ses_smoothing_const = _val;\n    }\n\n    /** Set the value of vacillation tolerance */\n    void set_vacillation_tolerance(const T _val)\n    {\n        ses_vacillation_tolerance = _val;\n    }\n\n    /** Push a new vec and pop its smoothed value as the return */\n    const es_vec<T, D> push_to_pop(const es_vec<T, D> _curr_raw_ob)\n    {\n        if(0 < ses_counter)\n        {\n            es_vec<T, D> temp_last_smoothed_ob(ses_curr_smoothed_ob);\n\n            ses_curr_smoothed_ob = ses_smoothing_const * _curr_raw_ob + (1 - ses_smoothing_const) * ses_curr_smoothed_ob;\n\n            if ((ses_curr_smoothed_ob - temp_last_smoothed_ob).norm() < ses_vacillation_tolerance)\n            {\n                ses_curr_smoothed_ob = temp_last_smoothed_ob;\n            }\n        }\n        else\n        {\n            ses_curr_smoothed_ob = _curr_raw_ob;\n        }\n\n        ++ses_counter;\n\n        return ses_curr_smoothed_ob;\n    }\n\n    /** Get the current counter */\n    const size_t counter() const { return ses_counter; }\n\n    /** Reset this class to initial state */\n    void reset()\n    {\n        ses_curr_smoothed_ob.reset();\n        ses_smoothing_const = 0.5;\n        ses_counter = 0;\n        ses_vacillation_tolerance = 0;\n    }\n\nprivate:\n    es_vec<T, D> ses_curr_smoothed_ob;\n\n    T ses_smoothing_const;\n\n    size_t ses_counter;\n\n    T ses_vacillation_tolerance;\n};\n\n/** Double Exponential Smoothing Method\n *  \\T Data type float/double/double double...\n *  \\D Dimension of this class\n */\ntemplate <typename T, size_t D>\nclass double_exponential_smoothing\n{\npublic:\n    /** Default constructor */\n    double_exponential_smoothing() :\n            des_1st_smoothing_const(0.5),\n            des_2nd_smoothing_const(0.5),\n            des_counter(0),\n            des_vacillation_tolerance(0)\n    {\n        des_curr_smoothed_ob.reset();\n        des_last_smoothed_ob.reset();\n        des_curr_correction_ob.reset();\n    }\n\n    /** Destructor */\n    ~double_exponential_smoothing()\n    {\n\n    }\n\npublic:\n    /** Set the value of 1st smoothing constant in the range (0, 1) */\n    void set_1st_smoothing_constant(const T _val)\n    {\n        assert(_val > 0 && _val < 1);\n        des_1st_smoothing_const = _val;\n    }\n\n    /** Set the value of 2nd smoothing constant in the range (0, 1) */\n    void set_2nd_smoothing_constant(const T _val)\n    {\n        assert(_val > 0 && _val < 1);\n        des_2nd_smoothing_const = _val;\n    }\n\n    /** Set the value of vacillation tolerance */\n    void set_vacillation_tolerance(const T _val)\n    {\n        des_vacillation_tolerance = _val;\n    }\n\n    /** Push a new vec and pop its smoothed value as the return */\n    const es_vec<T, D> push_to_pop(const es_vec<T, D> _curr_raw_ob)\n    {\n        if (0 == des_counter)\n        {\n            des_curr_smoothed_ob = _curr_raw_ob;\n        }\n        else if (1 == des_counter)\n        {\n            des_curr_correction_ob = _curr_raw_ob - des_curr_smoothed_ob;\n\n            des_last_smoothed_ob = des_curr_smoothed_ob;\n\n            des_curr_smoothed_ob = des_1st_smoothing_const * _curr_raw_ob +\n                    (1 - des_1st_smoothing_const) * (des_curr_smoothed_ob + des_curr_correction_ob);\n\n            if ((des_curr_smoothed_ob - des_last_smoothed_ob).norm() < des_vacillation_tolerance)\n            {\n                des_curr_smoothed_ob = des_last_smoothed_ob;\n            }\n        }\n        else\n        {\n            des_curr_correction_ob = des_2nd_smoothing_const * (des_curr_smoothed_ob - des_last_smoothed_ob) +\n                    (1 - des_2nd_smoothing_const) * des_curr_correction_ob;\n\n            des_last_smoothed_ob = des_curr_smoothed_ob;\n\n            des_curr_smoothed_ob = des_1st_smoothing_const * _curr_raw_ob +\n                    (1 - des_1st_smoothing_const) * (des_curr_smoothed_ob + des_curr_correction_ob);\n\n            if ((des_curr_smoothed_ob - des_last_smoothed_ob).norm() < des_vacillation_tolerance)\n            {\n                des_curr_smoothed_ob = des_last_smoothed_ob;\n            }\n        }\n\n        ++des_counter;\n\n        return des_curr_smoothed_ob;\n    }\n\n    /** Get the current counter */\n    const size_t counter() const { return des_counter; }\n\n    /** Reset this class to initial state */\n    void reset()\n    {\n        des_curr_smoothed_ob.reset();\n        des_last_smoothed_ob.reset();\n        des_curr_correction_ob.reset();\n\n        des_1st_smoothing_const = 0.5;\n        des_2nd_smoothing_const = 0.5;\n\n        des_counter = 0;\n    }\n\nprivate:\n    es_vec<T, D> des_curr_smoothed_ob;\n    es_vec<T, D> des_last_smoothed_ob;\n    es_vec<T, D> des_curr_correction_ob;\n\n    T des_1st_smoothing_const;\n    T des_2nd_smoothing_const;\n\n    size_t des_counter;\n\n    T des_vacillation_tolerance;\n};\n\n#endif // HEADER_EXPONENTIAL_SMOOTHING_H\n"
  },
  {
    "path": "Maths/Statistics/Exponential_Smoothing/Exponential_Smoothing.java",
    "content": "import java.util.Arrays;\n\npublic class DoubleExponentialSmoothingForLinearSeries {\n\n    /**\n     * Performs double exponential smoothing for given time series.\n     * <p/>\n     * This method is suitable for fitting series with linear trend.\n     *\n     * @param data  An array containing the recorded data of the time series\n     * @param alpha Smoothing factor for data (0 < alpha < 1)\n     * @param beta  Smoothing factor for trend (0 < beta < 1)\n     * @return Instance of model that can be used to forecast future values\n     */\n    public static Model fit(double[] data, double alpha, double beta) {\n        validateParams(alpha, beta);                        //validating values of alpha and beta\n\n        double[] smoothedData = new double[data.length];    //array to store smoothed values\n\n        double[] trends = new double[data.length + 1];\n        double[] levels = new double[data.length + 1];\n\n        //initializing values of parameters\n        smoothedData[0] = data[0];\n        trends[0] = data[1] - data[0];\n        levels[0] = data[0];\n\n        for (int t = 0; t < data.length; t++) {\n            smoothedData[t] = trends[t] + levels[t];\n            levels[t+1] = alpha * data[t] + (1 - alpha) * (levels[t] + trends[t]);\n            trends[t+1] = beta * (levels[t+1] - levels[t]) + (1 - beta) * trends[t];\n        }\n        return new Model(smoothedData, trends, levels, calculateSSE(data,smoothedData));\n    }\n\n    private static double calculateSSE(double[] data, double[] smoothedData) {\n        double sse = 0;\n        for (int i = 0; i < data.length; i++) {\n            sse+= Math.pow(smoothedData[i] - data[i],2);\n        }\n        return sse;\n    }\n\n    private static void validateParams(double alpha, double beta) {\n        if (alpha < 0 || alpha > 1) {\n            throw new RuntimeException(\"The value of alpha must be between 0 and 1\");\n        }\n\n        if (beta < 0 || beta > 1) {\n            throw new RuntimeException(\"The value of beta must be between 0 and 1\");\n        }\n    }\n\n    public static void main(String[] args) {\n        double[] testData = {17.55, 21.86, 23.89, 26.93, 26.89, 28.83, 30.08, 30.95, 30.19, 31.58, 32.58, 33.48, 39.02, 41.39, 41.60};\n\n        Model model = DoubleExponentialSmoothingForLinearSeries.fit(testData, 0.8, 0.2);\n\n        System.out.println(\"Input values: \" + Arrays.toString(testData));\n        System.out.println(\"Smoothed values: \" + Arrays.toString(model.getSmoothedData()));\n        System.out.println(\"Trend: \" + Arrays.toString(model.getTrend()));\n        System.out.println(\"Level: \" + Arrays.toString(model.getLevel()));\n        System.out.println(\"Forecast: \" + Arrays.toString(model.forecast(5)));\n        System.out.println(\"Sum of squared error: \" + model.getSSE());\n    }\n\n    static class Model {\n        private final double[] smoothedData;\n        private final double[] trends;\n        private final double[] levels;\n        private final double sse;\n\n        public Model(double[] smoothedData, double[] trends, double[] levels, double sse) {\n            this.smoothedData = smoothedData;\n            this.trends = trends;\n            this.levels = levels;\n            this.sse = sse;\n        }\n\n        /**\n         * Forecasts future values.\n         *\n         * @param size no of future values that you need to forecast\n         * @return forecast data\n         */\n        double[] forecast(int size) {\n            double[] forecastData = new double[size];\n            for (int i = 0; i < size; i++) {\n                forecastData[i] = levels[levels.length - 1] + (i + 1) * trends[trends.length - 1];\n            }\n            return forecastData;\n        }\n\n        public double[] getSmoothedData() {\n            return smoothedData;\n        }\n\n        public double[] getTrend() {\n            return trends;\n        }\n\n        public double[] getLevel() {\n            return levels;\n        }\n\n        public double getSSE() {\n            return sse;\n        }\n    }\n}\n"
  },
  {
    "path": "Maths/Statistics/Exponential_Smoothing/Exponential_Smoothing.rb",
    "content": "#\nmodule HoltWinters\n  class << self\n    #  This method is the entry point. It calculates the initial values and returns the forecast\n    #  for the m periods.\n    #  Calculate initial values and return the forecast for m periods.\n    #\n    #  y - Time series data.\n    #  alpha - Exponential smoothing coefficients for level\n    #  beta - Exponential smoothing coefficients for trend (increasing beta tightens fit)\n    #  gamma - Exponential smoothing coefficients for seasonal\n    #  period - A complete season's data consists of L periods. And we need\n    #    to estimate the trend factor from one period to the next. To\n    #    accomplish this, it is advisable to use two complete seasons;\n    #    that is, 2L periods.\n    #  y           Time series array\n    #  alpha       Level smoothing coefficient.\n    #  beta        Trend smoothing coefficient (increasing beta tightens fit)\n    #  gamma       Seasonal smoothing coefficient\n    #  period      A complete season's data consists of L periods. And we need\n    #              to estimate the trend factor from one period to the next. To\n    #              accomplish this, it is advisable to use two complete seasons;\n    #              that is, 2L periods.\n    #  m           Extrapolated future data points\n    #              - 4 quarterly\n    #              - 7 weekly\n    #              - 12 monthly\n    #\n    #  m - Extrapolated future data points.\n    #    4 quarterly\n    #    7 weekly.\n    #    12 monthly\n    def forecast(y, alpha, beta, gamma, period, m)\n      return nil if y.empty?\n\n      seasons = y.size / period\n      a0 = calculateInitialLevel(y, period)\n      b0 = calculateInitialTrend(y, period)\n      a0 = initial_level(y, period)\n      b0 = initial_trend(y, period)\n\n      seasonal_indices = calculateSeasonalIndices(y, period, seasons)\n      seasonal = seasonal_indicies(y, period, seasons)\n\n      calculateHoltWinters(y, a0, b0, alpha, beta, gamma, seasonal_indices, period, m);\n      holt_winters(y, a0, b0, alpha, beta, gamma, seasonal, period, m);\n    end\n\n    def calculateHoltWinters(y, a0, b0, alpha, beta, gamma, seasonal_indicies, period, m)\n    def holt_winters(y, a0, b0, alpha, beta, gamma, seasonal, period, m)\n      st = Array.new(y.length, 0.0)\n      bt = Array.new(y.length, 0.0)\n      it = Array.new(y.length, 0.0)\n@@ -54,7 +53,7 @@ def calculateHoltWinters(y, a0, b0, alpha, beta, gamma, seasonal_indicies, perio\n      bt[1] = b0\n\n      (0..period - 1).each do |i|\n        it[i] = seasonal_indicies[i]\n        it[i] = seasonal[i]\n      end\n\n      ft[m] = (st[0] + (m * bt[0])) * it[0] # This is actually 0 since bt[0] = 0\n@@ -87,13 +86,13 @@ def calculateHoltWinters(y, a0, b0, alpha, beta, gamma, seasonal_indicies, perio\n\n    # See: http://robjhyndman.com/researchtips/hw-initialization/\n    # 1st period's average can be taken. But y[0] works better.\n    def calculateInitialLevel(y, period)\n    def initial_level(y, period)\n      y.first\n    end\n\n\n    # See: http://www.itl.nist.gov/div898/handbook/pmc/section4/pmc435.htm\n    def calculateInitialTrend(y, period)\n    def initial_trend(y, period)\n      sum = 0\n\n      (0..period - 1).each do |i|\n@@ -105,32 +104,32 @@ def calculateInitialTrend(y, period)\n\n\n    # See: http://www.itl.nist.gov/div898/handbook/pmc/section4/pmc435.htm\n    def calculateSeasonalIndices(y, period, seasons)\n      seasonalAverage = Array.new(seasons, 0.0)\n      seasonalIndices = Array.new(period, 0.0)\n      averagedObservations = Array.new(y.size, 0.0)\n    def seasonal_indicies(y, period, seasons)\n      seasonal_average = Array.new(seasons, 0.0)\n      seasonal_indices = Array.new(period, 0.0)\n      averaged_observations = Array.new(y.size, 0.0)\n\n      (0..seasons - 1).each do |i|\n        (0..period - 1).each do |j|\n          seasonalAverage[i] += y[(i * period) + j]\n          seasonal_average[i] += y[(i * period) + j]\n        end\n        seasonalAverage[i] /= period\n        seasonal_average[i] /= period\n      end\n\n      (0..seasons - 1).each do |i|\n        (0..period - 1).each do |j|\n          averagedObservations[(i * period) + j] = y[(i * period) + j] / seasonalAverage[i]\n          averaged_observations[(i * period) + j] = y[(i * period) + j] / seasonal_average[i]\n        end\n      end\n\n      (0..period - 1).each do |i|\n        (0..seasons - 1).each do |j|\n          seasonalIndices[i] += averagedObservations[(j * period) + i]\n          seasonal_indices[i] += averaged_observations[(j * period) + i]\n        end\n        seasonalIndices[i] /= seasons\n        seasonal_indices[i] /= seasons\n      end\n\n      seasonalIndices\n      seasonal_indices\n    end\n  end\nend\n"
  },
  {
    "path": "Maths/Statistics/Exponential_Smoothing/README.md",
    "content": "## This folder is empty.\n"
  },
  {
    "path": "Maths/Statistics/K-means_Clustering/K-means_Clustering.py",
    "content": "import numpy as np\nimport matplotlib.pyplot as plt\n\nfrom sklearn.datasets import make_blobs\n\nimport random\n\nclass Cluster:\n\n    def __init__(self, center, name):\n        self.center = center\n        self.name = name\n        self.points = []\n\n    def distance(self, point):\n        return np.sqrt(np.sum((self.center - point) ** 2))\n\n    def relocate(self):\n        self.center = np.mean(self.points, axis=0)\n        self.points.clear()\n\n\nclass KMeansCustom:\n\n    def __init__(self, n_clusters=5, max_iters=20, n_init=10):\n        self.max_iters = max_iters\n        self.n_clusters = n_clusters\n        self.n_init = n_init\n\n    def fit(self, X):\n\n        solutions = []\n\n        for init in range(self.n_init):\n\n            clusters = []\n            for i in range(self.n_clusters):\n                cluster = Cluster(center=random.choice(X), name=i)\n                clusters.append(cluster)\n\n            errors = []\n\n            for it in range(self.max_iters):\n\n                # voting\n                labels = []\n\n                for point in X:\n\n                    # collect distance of point to all clusters\n                    distances = []\n                    for cluster in clusters:\n                        distance = cluster.distance(point)\n                        distances.append((distance, cluster.name))\n\n                    # sort and select cluster with min distance\n                    distance, cluster_name = sorted(distances)[0]\n\n                    # point voted which cluster\n                    labels.append(cluster_name)\n\n                    # point which voted the cluster\n                    cluster = clusters[cluster_name]\n                    cluster.points.append(point)\n\n                err = self.error(labels, clusters, X)\n                errors.append(err)\n                # taking mean of all the points in that cluster\n                for cluster in clusters:\n                    cluster.relocate()\n\n            solutions.append([errors[-1], labels, clusters])\n\n        sorted_sols = sorted(solutions, key=lambda item: item[0])\n        err, labels, clusters = sorted_sols[0]\n\n        self.labels_ = np.array(labels)\n        self.cluster_centers_ = np.array([cluster.center for cluster in clusters])\n\n    def error(self, labels, clusters, X):\n\n        err = 0\n\n        for point, label in zip(X, labels):\n            cluster = clusters[label]\n            err += cluster.distance(point)\n\n        return err / len(X)\n\n\n# Running by taking an example from sklearn's blobs\nX, _ = make_blobs(centers=4, random_state=42)\n\nplt.scatter(X[:, 0], X[:, 1])\nmodel = KMeansCustom(4)\nmodel.fit(X)\n\nplt.scatter(X[:, 0], X[:, 1], c=model.labels_)\n\nfor center in model.cluster_centers_:\n    plt.scatter(center[0], center[1], s=120)\nplt.show()\nprint(model.labels_)\nprint(model.cluster_centers_)"
  },
  {
    "path": "Maths/Statistics/Logistic_Function/README.md",
    "content": "## This folder is empty.\n"
  },
  {
    "path": "Maths/Statistics/Mean/mean.cpp",
    "content": "#include <iostream>\nusing namespace std;\n\n\nint mean(int arr[], int n){\n    int m = 0;\n    for(int i=0; i<n; i++){\n        m = m+arr[i];\n    }\n    m = m/n;\n    return m;\n}\n\nint main(){\n    int n;\n    cout << \"How many numbers do you want to enter ?\";\n    cin >> n;\n    cout<<\"Enter the numbers\";\n    int arr[n];\n    for(int i=0; i<n; i++){\n        cin>>arr[i];\n    }\n    int m = mean(arr,n);\n    cout<<\"The mean of numbers is: \"<<m;\n}"
  },
  {
    "path": "Maths/Statistics/Mean/mean.java",
    "content": "package Maths_And_Stats.Statistics.Mean;\n\n\npublic class mean {\n\n   public static void main(String args[]){\n      float mean;\n      int sum, i;\n      int n = 5;\n      int a[] = {2,6,7,4,9};\n      sum = 0;\n\n      for(i = 0; i < n; i++) {\n         sum+=a[i];\n      }\n      System.out.println(\"Mean ::\"+ sum/(float)n);\n   }\n}"
  },
  {
    "path": "Maths/Statistics/Mean/mean.py",
    "content": "\n#Taking Input\nprint(\"Enter the size of list : \")\nsize = int(input())\n\nprint(\"Enter the list elements: \")\narr = list(map(int,input().split()))\n\ntotal_sum = sum(arr)\n\nmean = total_sum /size\n\nprint(\"Mean is : {}\".format(mean))\n\n'''\n    Sample Input :\n        enter the size of list: 5\n        Enter the list elements : 10 30 20 40 50\n    \n    Sample Output:\n        Mean is 30.0\n'''"
  },
  {
    "path": "Maths/Statistics/Mean/meanOfGivenNumbers.c",
    "content": "#include <stdio.h>\n#include <stdlib.h>\n\nint main()\n{\n    int arr[] = {1, 23, 423, 45, 34, 2, 36, 256, 2, 143};\n    int size = sizeof(arr) / sizeof(arr[0]);\n    int sum = 0;\n    float mean;\n    for (int i = 0; i < size; i++)\n        sum = sum + arr[i];\n    mean = (float)sum / size;\n    printf(\"\\nThe mean of %d numbers is %f\\n\", size, mean);\n    return 0;\n}"
  },
  {
    "path": "Maths/Statistics/Mean/meanOfGivenNumbers.cs",
    "content": "using System.IO;\nusing System;\nusing System.Linq;\nclass meanOfGivenNumbers\n{\n    static void Main()\n    {\n        var arr = new int[] { 10, 17, 25, 30, 40, 55, 60, 70 };\n        double avg = Queryable.Average(arr.AsQueryable());\n        Console.WriteLine(\"Average = \" + avg);\n    }\n}"
  },
  {
    "path": "Maths/Statistics/Mean/meanOfGivenNumbers.js",
    "content": "var arr = [10, 17, 25, 30, 40, 55, 60, 70];\nvar total = 0;\nfor (var i = 0; i < arr.length; i++) {\n    total += arr[i];\n}\nvar avg = total / arr.length;\nconsole.log(\"Average of numbers is \" + avg)"
  },
  {
    "path": "Maths/Statistics/Median/Median.c",
    "content": "#include <stdio.h>\n\nvoid swap(int *p,int *q) {\n   int t;\n   \n   t=*p; \n   *p=*q; \n   *q=t;\n}\n\nvoid sort(int a[],int n) { \n   int i,j,temp;\n\n   for(i = 0;i < n-1;i++) {\n      for(j = 0;j < n-i-1;j++) {\n         if(a[j] > a[j+1])\n            swap(&a[j],&a[j+1]);\n      }\n   }\n}\n\nint main() {\n   int a[] = {6,3,8,5,1};\n   int n = 5;\n   int sum,i;\n\n   sort(a,n);\n   \n   n = (n+1) / 2 - 1;      // -1 as array indexing in C starts from 0\n\n   printf(\"Median = %d \", a[n]);\n\n   return 0;\n}\n"
  },
  {
    "path": "Maths/Statistics/Median/Median.java",
    "content": "package Maths_And_Stats.Statistics.Median;\n\nimport java.util.Arrays;\nimport java.util.Scanner;\n\npublic class Median {\n\n    public static void main(String[] args) {\n\n        Scanner sc = new Scanner(System.in);\n\n        System.out.println(\"Enter no of elements: \");\n        int n = sc.nextInt();\n\n        int[] arr = new int[n];\n\n        for (int i = 0; i < n; i++) {\n            arr[i] = sc.nextInt();\n        }\n\n        System.out.println(\"Elements are: \");\n\n        for (int i = 0; i < n; i++) {\n            System.out.print(arr[i]+\" \");\n        }\n        System.out.println();\n\n        System.out.println(\"Median is:\"+ findMedian(arr, n));\n    }\n\n    private static double findMedian(int[] arr, int n) {\n\n        Arrays.sort(arr);\n\n        if(n % 2 != 0) {\n            return (double) arr[n/2];\n        }\n        else {\n             return (double) (arr[(n - 1) / 2] + arr[n / 2] / 2.0);\n\n        }\n    }\n}\n"
  },
  {
    "path": "Maths/Statistics/Median/Median.js",
    "content": "var data = [7, 9, 12, 13, 16];\nvar length = data.length;\nvar position = 0;\nvar median = 0;\ndata.sort(function (a, b) {\n  return a - b;\n});\nif (length % 2 === 0) {\n  position = Math.ceil(length / 2) - 1;\n  median = (data[position] + data[position + 1]) / 2;\n} else {\n  position = Math.floor(length / 2);\n  median = data[position];\n}\nconsole.log(\"Median is : \", median);\n"
  },
  {
    "path": "Maths/Statistics/Median/Median.py",
    "content": "# Python program for finding median \n\n# list of elements to calculate median \ndata = [7, 2, 3, 6, 7] \n\n# length of the list\nlength = len(data) \n\n# Sort list\ndata.sort() \n\n# check if the length of list is odd or even\nif length % 2 == 0: \n\tmedian1 = data[length//2] \n\tmedian2 = data[length//2 - 1] \n\tmedian = (median1 + median2)/2\nelse: \n\tmedian = data[length//2] \n\t\n# Print Median\nprint(\"Median is: \" + str(median)) "
  },
  {
    "path": "Maths/Statistics/Median/README.md",
    "content": "## This folder is empty.\n"
  },
  {
    "path": "Maths/Statistics/Median/meadian.cpp",
    "content": "#include<iostream>\n#include<algorithm>\nusing namespace std;\n#define max 50\nfloat median(int b[],int n)\n{\n    sort(b,b+n);\n    float c;\n    if(n%2!=0)\n    {\n        c=b[n/2];\n        return c;\n    }\n    else\n    {\n        c=(b[(n-1)/2]+b[n/2])/2.0;\n        return c;\n    }\n}\nint main()\n{\n    int a[max];\n    int n;\n    cout<<\"Enter the total number of elements\"<<endl;\n    cin>>n;\n    cout<<\"Enter the elements\"<<endl;\n    for(int i=0;i<n;i++)\n    {\n        cin>>a[i];\n    }\n    cout<<\"Elements are: \"<<endl;\n    for(int i=0;i<n;i++)\n    {\n        cout<<a[i]<<\" \";\n    }\n    cout<<endl;\n    cout<<\"Median= \"<<median(a,n);\n    return 0;\n}\n"
  },
  {
    "path": "Maths/Statistics/Mode/Mode.java",
    "content": "import java.util.*;\r\n\r\npublic class Mode {\r\n\r\n\tprivate static Scanner sc = new Scanner(System.in);\r\n\r\n\tpublic static void main(String[] args) {\r\n\r\n\t\t//Initialize variables\r\n\t\tint mode = 0;\r\n\t\tint maxCount = 0;\r\n\t\tint n;\r\n\t\tint count = 0;\r\n\t\tSet<Integer> multiModalSequence = new HashSet<Integer>();\r\n\t\tint multimodalCount=0;\r\n\t\t\r\n\r\n\t\t//Ask for the size of array\r\n\t\tSystem.out.println(\"Enter the max range of values\");\r\n\t\tn = sc.nextInt();\r\n\r\n\t\t//Initialize the array\r\n\t\tint a[] = new int[n];\r\n\r\n\t\tSystem.out.println(\"Enter the numbers\");\r\n\t\tfor (int i = 0; i < n; i++) {\r\n\t\t\ta[i] = sc.nextInt();\r\n\t\t}\r\n\r\n\t\t//Sort Array (Ascending order)\r\n\t\tArrays.sort(a);\r\n\r\n\r\n\t\t//Find mode (Single and multimodal logic)\r\n\t\tfor (int i = 0; i < n - 1; i++) {\r\n\r\n\t\t\tif (a[i] == a[i + 1]) {\r\n\t\t\t\tcount++;\r\n\t\t\t}else {\r\n\t\t\t\tcount=0;\r\n\t\t\t}\r\n\t\t\tif (count > maxCount) {\r\n\t\t\t\tmaxCount = count;\r\n\t\t\t\tmode = a[i];\r\n\t\t\t\tmultiModalSequence.add(mode);\r\n\t\t\t}else if(maxCount<=count && maxCount>0) {\r\n\t\t\t\tmultiModalSequence.add(a[i]);\r\n\t\t\t\tmultimodalCount=maxCount;\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\t\r\n\t\t}\r\n\t\t\r\n\t\t//Print number sequence for display\r\n\t\tSystem.out.print(\"Sequence:[\");\r\n\t\tfor (int i = 0; i < n; i++) {\r\n\t\t\tif (i == n - 1) {\r\n\t\t\t\tSystem.out.print(a[i]);\r\n\t\t\t} else {\r\n\t\t\t\tSystem.out.print(a[i] + \",\");\r\n\t\t\t}\r\n\t\t}\r\n\t\tSystem.out.println(\"]\");\r\n\t\t\r\n\t\t\r\n\t\t//find occurences\r\n\t\tint occurances = maxCount+1;\r\n\t\t\r\n\t\t\r\n\t\t//Display mode and occurences\r\n\t\tif (maxCount == 0) {\r\n\t\t\tSystem.out.println(\"There is no mode for the entered number sequence!!\");\r\n\t\t} else if(maxCount>multimodalCount) {\r\n\t\t\tSystem.out.println(\"Mode: \" + mode);\r\n\t\t\tSystem.out.println(\"Occurences: \" + occurances);\r\n\t\t}else {\r\n\t\t\tSystem.out.println(\"This is a multimodal sequence\");\r\n\t\t\tSystem.out.print(\"Modes :\");\r\n\t\t\tfor(int x : multiModalSequence) {\r\n\t\t\t\tSystem.out.print(x+\",\");\r\n\t\t\t}\r\n\t\t\tSystem.out.println();\r\n\t\t\tSystem.out.println(\"Occurences(Each Mode): \"+occurances);\r\n\t\t}\r\n\r\n\t}\r\n\r\n}\r\n"
  },
  {
    "path": "Maths/Statistics/Mode/README.md",
    "content": "## This folder is empty.\n"
  },
  {
    "path": "Maths/Statistics/Mode/mode.c",
    "content": "#include<stdio.h>\n#define max 50\nint mode(int b[],int n)\n{\n    int maxcount=0;   \n    int mode=0;\n    for(int i=0;i<n;i++)\n    {\n        int c=0;\n        for(int j=0;j<n;j++)\n        {\n            if(b[j]==b[i])\n                c++;\n        }\n        if(c>maxcount)\n        {\n            maxcount=c;\n            mode=b[i];\n        }\n    }\n    return mode;\n}\nint main()\n{\n    int n;\n    printf(\"Enter total number of elements\\n\");\n    scanf(\"%d\",&n);\n    int a[max];\n    printf(\"Enter the elements \\n\");\n    for(int i=0;i<n;i++)\n    {\n        scanf(\"%d\",&a[i]);\n    }\n    printf(\"Elements are: \");\n    for(int i=0;i<n;i++)\n    {\n        printf(\"%d \",a[i]);\n    }\n    printf(\"\\n\");\n    printf(\"Mode= %d\",mode(a,n));\n}\n"
  },
  {
    "path": "Maths/Statistics/Mode/mode.cpp",
    "content": "// Program to find the mode, i.e., the number which appears most often in a set of numbers\r\n\r\n\r\n#include<bits/stdc++.h>\r\nusing namespace std;\r\n\r\nvoid mode(int [], int);\r\n\r\nint main()\r\n{\r\n    int a[1000], n, i;\r\n    cout << \"Enter no. of elements: \";\r\n    cin >> n;\r\n\r\n    cout << \"Enter data: \";\r\n    for(i=0; i<n; i++)\r\n    {\r\n        cin >> a[i];\r\n    }\r\n\r\n    mode(a, n);\r\n\r\n    return 0;\r\n}\r\n\r\nvoid mode(int arr[], int num)\r\n{\r\n    int i, k, flag=0, mode=0;\r\n\r\n    for(i=0; i<num; i++)\r\n    {\r\n        int count=0;\r\n\r\n        for (k=0; k<i; k++)\r\n        {\r\n            if(arr[k] == arr[i]) {\r\n                count++;\r\n            }\r\n        }\r\n\r\n        if(count > flag) {\r\n            flag = count;\r\n            mode = arr[i];\r\n        }\r\n    }\r\n\r\n    cout << \"Mode is: \" << mode << endl;\r\n}"
  },
  {
    "path": "Maths/Statistics/Mode/mode.js",
    "content": "var arrayOne = [];\r\nvar counter=0,repeater,temp,mode;\r\nvar number1 = prompt(\"Enter Size of Array/Set -> \");\r\n\r\nfor(var i=0;i<number1;i++){\r\n    arrayOne[i] = prompt(\"Enter \" + (i+1) + \" th number of the Set ->\");\r\n}\r\n\r\nfor(var i=0;i<number1;i++){\r\n    temp = arrayOne[i];\r\n    repeater = 0;\r\n    for(var j=0;j<number1;j++){\r\n        if(temp == arrayOne[j]){\r\n            repeater++;\r\n        }\r\n    }\r\n    if(repeater > counter){\r\n        mode = temp;\r\n        counter = repeater;\r\n    }\r\n}\r\nalert(\"Mode of the entered Set is -> \" + mode);"
  },
  {
    "path": "Maths/Statistics/Mode/mode.php",
    "content": "<?php\n\nfunction mode($arr) {\n    $arrCnt = array_count_values($arr);\n    $mode = array_keys($arrCnt, max($arrCnt));\n    return \"The Mode is \" . implode( \", \", $mode) . \"\\n\";\n}\n\necho mode([6, 3, 9, 5, 9, 3]);\necho mode([6, 3, 9, 6, 6, 5, 9, 3]);\n"
  },
  {
    "path": "Maths/Statistics/Mode/mode.py",
    "content": "numbersArray = []\nnumbersSet = set()\nnumbersList = []\ncontinueEntering = True\nwhile continueEntering == True:\n    print('Input a number from your dataset:')\n    number = input()\n    if number.isdigit():\n        pass\n    else:\n        print('Error! You did not enter a number. Try again! What is your number?:')\n        number = input()\n    number = int(number)\n    numbersArray.append(number)\n    numbersSet.add(number)\n    print('Do you have another number to enter - Y/N:')\n    moreNumbers = input()\n    if moreNumbers.lower() == 'y':\n        pass\n    elif moreNumbers.lower() == 'n':\n        continueEntering = False\n    elif (moreNumbers.lower() != 'n') or (moreNumbers.lower() != 'y'):\n        print('Error! You did not enter \"Y\" or \"N\"!')\n        print('Do you have another number to enter - Y/N:')\n        moreNumbers = input()\nnumbersArray = sorted(numbersArray)\n#print(numbersArray)\n#print(numbersSet)\nfor i in numbersSet:\n    numbersList.append([])\n#print(numbersList)\nif len(numbersList)>0:\n    #append first number in array to list\n    numbersList[0].append(numbersArray[0])\n    index = 0\n    for i in range(1,len(numbersArray)):    \n        testNumber = numbersArray[i]\n        compareNumber = numbersArray[i-1]\n        if testNumber == compareNumber:\n            numbersList[index].append(testNumber)\n        else:\n            index += 1\n            numbersList[index].append(testNumber)        \n    #print(numbersList)\nelse:\n    print(\"Error! No numbers in dataset\")\ncounts = []\nfor i in numbersList:\n    count = len(i)\n    counts.append(count)\n#print(counts)\nmaxCounts = max(counts)\nresultList = []\nfor i in range(len(counts)):\n    if counts[i] == maxCounts:\n        resultRow = numbersList[i]\n        result = resultRow[0]\n        resultList.append(result)        \nprint(\"These are your mode(s):\")\nprint(resultList)\n    \n        \n    "
  },
  {
    "path": "Maths/Statistics/README.md",
    "content": "## This folder is empty.\n"
  },
  {
    "path": "Maths/Statistics/Standard_Deviation/README.md",
    "content": "## This folder is empty.\n"
  },
  {
    "path": "Maths/Statistics/Standard_Deviation/Standard_Deviation.c",
    "content": "#include <math.h>\n#include <stdio.h>\n\n//function to calculate standard deviation\nfloat calculateSD(float data[],int n);\nint main() {\n    int i,n;\n    printf(\"Enter total No. of  elements: \");\n    scanf(\"%d\", &n);\n    float data[n];\n    printf(\"Enter %d elements: \",n);\n    for (i = 0; i < n; ++i)\n        scanf(\"%f\", &data[i]);\n    printf(\"\\nStandard Deviation = %.6f\", calculateSD(data,n));\n    return 0;\n}\n\nfloat calculateSD(float data[],int n) {\n    float sum = 0.0, mean, SD = 0.0;\n    int i;\n    for (i = 0; i < n; ++i) {\n        sum += data[i];\n    }\n    mean = sum / n;\n    for (i = 0; i < n; ++i)\n        SD += pow(data[i] - mean, 2);\n    return sqrt(SD / n);\n}\n"
  },
  {
    "path": "Maths/Statistics/Standard_Deviation/Standard_Deviation.cpp",
    "content": "#include <iostream>\n#include <cmath>\nusing namespace std;\n\nfloat standardDeviation(float data[])\n{\n    float sum = 0.0, mean, standardDeviation = 0.0;\n\n    int i;\n\n    for(i = 0; i < 10; ++i)\n    {\n        sum += data[i];\n    }\n\n    mean = sum/10;\n\n    for(i = 0; i < 10; ++i)\n        standardDeviation += pow(data[i] - mean, 2);\n\n    return sqrt(standardDeviation / 10);\n};\n\nint main()\n{\n    int i;\n    float data[10];\n\n    cout << \"Enter 10 elements: \";\n    for(i = 0; i < 10; ++i)\n        cin >> data[i];\n\n    cout << endl << \"Standard Deviation = \" << standardDeviation(data);\n\n    return 0;\n}\n\n"
  },
  {
    "path": "Maths/Statistics/Standard_Deviation/Standard_Deviation.js",
    "content": "var data = [12, 43, 52, 13, 1, 63, 100, 22, 67, 239];\nvar sum = data.reduce((acc, val) => acc + val, 0);\nvar mean = sum / data.length;\n\nvar standardDeviation = data.reduce((acc, val) => acc + Math.pow(val - mean, 2), 0); //Square of the sum of each value minus the mean\nstandardDeviation = Math.sqrt(standardDeviation / data.length); //Square root of the previously obtained value over the size of the population\n\nconsole.log(standardDeviation);"
  },
  {
    "path": "Maths/Statistics/Standard_Deviation/Standard_Deviation.py",
    "content": "# Python code to demonstrate stdev() function \n# importing Statistics module \nimport statistics \n\n# creating a simple data - set \nsample = [1, 2, 3, 4, 5] \n\n# Prints standard deviation \n# xbar is set to default value of 1 \nprint(\"Standard Deviation of sample is % s \" % (statistics.stdev(sample))) \n"
  },
  {
    "path": "Maths/Statistics/Standard_Deviation/Standard_Deviation.swift",
    "content": "\nimport Foundation\n\nfunc getStdDeviation(input:[Int], population: Bool = true) -> Double {\n    var sq_sum = 0.0\n \n    //Calculate Mean of given inout array\n    var sum = 0\n    for number in input {\n        sum += number\n    }\n    let mean = Double(sum) / Double(input.count)\n\n    //calculate the sum of squared difference between mean and each element in the input\n    for number in input {\n        sq_sum = sq_sum + pow(Double(number) - mean, 2)\n    }\n\n    //Divisor depends on if its population stddev or sample stddev\n    let div = population ? input.count : input.count - 1\n    \n    return sqrt(sq_sum / Double(div))\n}\n\nlet input = readLine()!.split(separator: \" \").map { Int(String($0))! }\n\nlet population_stdDev = getStdDeviation(input: input)\nprint(\"Population Standard Deviation for given input series is \\(population_stdDev)\")\n\nlet sample_stdDev = getStdDeviation(input: input, population: false)\nprint(\"Sample Standard Deviation for given input series is \\(sample_stdDev)\")\n"
  },
  {
    "path": "README.md",
    "content": "<p align=\"center\">\n<img width=\"450\" height=\"450\" src=\"https://user-images.githubusercontent.com/54521023/94943180-e676aa80-04f4-11eb-8842-9634c1e66fa4.png\" /><br>\n<img src=\"https://img.shields.io/github/license/ahampriyanshu/algo_ds_101?style=for-the-badge\" />  <img src=\"https://img.shields.io/github/repo-size/ahampriyanshu/algo_ds_101?style=for-the-badge\" />  <img alt=\"GitHub pull requests\" src=\"https://img.shields.io/github/issues-pr/ahampriyanshu/algo_ds_101?style=for-the-badge\" />  <img alt=\"GitHub issues\" src=\"https://img.shields.io/github/issues/ahampriyanshu/algo_ds_101?style=for-the-badge\" />   \n</p>\n\n## Index\n\n* [Data Structures](Data-Structures/)\n* [Algorithms](Algorithms/)\n* [Maths And Stats](Maths/)\n* [Collection](Collection/)\n* [STL](STL/)\n\n## How To Contribute\n\n### 1. Fork The Repo\n![1](https://user-images.githubusercontent.com/54521023/94943081-d19a1700-04f4-11eb-81dc-b5bd1a3b9adb.png)\n\n### 2. Go The Issue Section\n![2](https://user-images.githubusercontent.com/54521023/94943088-d363da80-04f4-11eb-80e5-444999c5fb42.png)\n\n### 3.1 Choose An Existing Issue\n![3](https://user-images.githubusercontent.com/54521023/94943091-d4950780-04f4-11eb-96ce-1bd08c260cbd.png)\n\n### 3.2 Or You Can Create A New One\n![4](https://user-images.githubusercontent.com/54521023/94943089-d3fc7100-04f4-11eb-92a4-51d6363a99b4.png)\n\n* Before opening a new issue make sure that similar kind of issue doesn't already exist.\n\n### 4. Check For The Languages Available\n![5](https://user-images.githubusercontent.com/54521023/135753314-d67a67b5-3e57-48c5-b58e-076e442f3849.png)\n\n### 5. Comment In The Stated Syntax\n![6](https://user-images.githubusercontent.com/54521023/135754330-be6aa099-2ccf-44c7-aebe-e9348c23ae82.png)\n\n* **Language In Which You Will Contribute => Time Required By You To Push The Changes**\n* Ask for the issue that you plan to complete.\n* Do not wait to get assigned.\n* Please try to push the changes in less than or equal to the stated(by you only) time period. Failing to do that, your comment will be discarded and the language will be made available to other participants.\n* Try to avoid any casual communication.\n\n### 6 Create A New Branch \n![7](https://user-images.githubusercontent.com/54521023/94954691-18910800-0507-11eb-95c5-df953d74db3e.png)\n\n### 7. Create A New File with A Relevant Name\n![8](https://user-images.githubusercontent.com/54521023/94943103-d8288e80-04f4-11eb-8839-64eb73bf308a.png)\n\n* Make sure to follow the [naming convection](https://github.com/ahampriyanshu/algo_ds_101/blob/main/CONTRIBUTING.md#naming-convention)\n\n![9](https://user-images.githubusercontent.com/54521023/135753421-9420757f-1a7d-47fa-b5a3-7943ab96ec39.png)\n\n### 8. Commit The File\n![10](https://user-images.githubusercontent.com/54521023/135758806-f9c0a445-4553-475d-a02f-0f1d7e5b802c.png)\n\n### 10. Compare And Pull\n![11](https://user-images.githubusercontent.com/54521023/135753640-38554923-9dd3-43a7-bd5a-ab3c33dbac05.png)\n\n* [Before pulling make sure your branch is up-to-date](#sync-your-forked-repository)\n\n### 11. Give Relevant PR Message\n![12](https://user-images.githubusercontent.com/54521023/135753639-bcf2b0d2-763c-49fd-be9f-9b4175d29c3d.png)\n\n### 12. Enter Related Issue No\n![13](https://user-images.githubusercontent.com/54521023/94943135-dfe83300-04f4-11eb-8db8-639077cf8b9c.png)\n\n### 13. Fill Up The Checkboxe(s)\n![14](https://user-images.githubusercontent.com/54521023/135755940-ef41a77d-2e4b-4518-96f2-2a6643b8def7.png)\n\n### 14. Create A Pull Request\n![15](https://user-images.githubusercontent.com/54521023/94943157-e37bba00-04f4-11eb-8d5e-cd65c93bf842.png)\n\n### 15. Congrats 🎉\n![16](https://user-images.githubusercontent.com/54521023/135753630-0d898e7e-1533-4278-9288-25ec08a3836e.png)\n\n### 20. Wait Till Your PR Gets Merged\n![17](https://user-images.githubusercontent.com/54521023/135753819-76a75d6d-b15e-4096-8f4c-11ad1d5e3e17.png)\n\n## Want To Document The Repo ?\n* Click [here](https://github.com/ahampriyanshu/algo_ds_101/issues/new?assignees=octocat&labels=Hacktoberfest2021%2CHacktoberfest%2Cnew+submssion%2Cfirst+timer%2Cgood+first+issue%2Cdocumentation&template=Documentation.yml&title=Directory+You+Purpose+to+Document) to know more\n\n## How To Commit In CLI\n\n```bash\n$ git clone git@github.com:your_username/algo_ds_101.git\n$ git checkout -b BranchName\n$ git add .\n$ git commit -m 'message'\n$ git push -u origin BranchName\n```\n\n## Sync Your Forked Repository\n\n### CLI\n\n```bash\n$ git fetch --all --prune\n$ git checkout main\n$ git reset --hard upstream/main\n$ git push origin main\n```\n\n### GUI\n\n![18](https://user-images.githubusercontent.com/54521023/135514252-18bab611-4683-4d3c-a8a8-03117292fbb7.png)\n![19](https://user-images.githubusercontent.com/54521023/135514247-020bb6e8-b869-4668-a350-89081a4ed5a8.png)\n![20](https://user-images.githubusercontent.com/54521023/135514235-9e40abdf-ed8c-4954-9bc3-a9e6d41fad49.png)\n\n## Contributing Guidelines\nRead [contributing guidelines](CONTRIBUTING.md/)\n\n## Contributors\nMeet our wonderful [contributors](CONTRIBUTORS.md/)\n\n## Code of Conduct\nRead our [code of conduct](CODE_OF_CONDUCT.md/).\n\n## License\n[MIT License](LICENSE/).\n"
  },
  {
    "path": "STL/Array/Array.cpp",
    "content": "#include <iostream>\n#include <bits/stdc++.h>\nusing namespace std;\n\nint main()\n{\n    // Taking inputs using array template from C++ STL..\n    array<int, 10> arr1 = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; \n    array<int, 10> arr2 = {11, 12, 13, 14, 15, 16, 17, 18, 19, 20};\n\n    cout << \"Before Swap :\" << endl;\n    cout << \"Elements in the first array : \";\n    for (int i = 0; i < 10; i++)\n        cout << arr1.at(i) << \" \"; // This method returns value in the array at the given range.\n    cout << \"\\nElements in the second array : \";\n    for (int i = 0; i < 10; i++)\n        cout << arr2.at(i) << \" \";\n    arr1.swap(arr2); // Swapping two arrays..\n    cout << \"\\n\\nAfter Swap :\" << endl;\n    cout << \"Elements in the first array : \";\n    for (int i = 0; i < 10; i++)\n        cout << arr1.at(i) << \" \";\n    cout << \"\\nElements in the second array : \";\n    for (int i = 0; i < 10; i++)\n        cout << arr2.at(i) << \" \";\n    return 0;\n}"
  },
  {
    "path": "STL/Map/MultiMap/multimap.cpp",
    "content": "#include <iostream> \r\n#include <map> \r\n#include <iterator> \r\n  \r\nusing namespace std; \r\n  \r\nint main() \r\n{ \r\n    multimap <int, int> gquiz1;        // empty multimap container \r\n  \r\n    // insert elements in random order \r\n    gquiz1.insert(pair <int, int> (1, 40)); \r\n    gquiz1.insert(pair <int, int> (2, 30)); \r\n    gquiz1.insert(pair <int, int> (3, 60)); \r\n    gquiz1.insert(pair <int, int> (4, 20)); \r\n    gquiz1.insert(pair <int, int> (5, 50)); \r\n    gquiz1.insert(pair <int, int> (6, 50)); \r\n    gquiz1.insert(pair <int, int> (6, 10)); \r\n  \r\n    // printing multimap gquiz1 \r\n    multimap <int, int> :: iterator itr; \r\n    cout << \"\\nThe multimap gquiz1 is : \\n\"; \r\n    cout << \"\\tKEY\\tELEMENT\\n\"; \r\n    for (itr = gquiz1.begin(); itr != gquiz1.end(); ++itr) \r\n    { \r\n        cout  <<  '\\t' << itr->first \r\n              <<  '\\t' << itr->second << '\\n'; \r\n    } \r\n    cout << endl; \r\n  \r\n    // assigning the elements from gquiz1 to gquiz2 \r\n    multimap <int, int> gquiz2(gquiz1.begin(),gquiz1.end()); \r\n  \r\n    // print all elements of the multimap gquiz2 \r\n    cout << \"\\nThe multimap gquiz2 after assign from gquiz1 is : \\n\"; \r\n    cout << \"\\tKEY\\tELEMENT\\n\"; \r\n    for (itr = gquiz2.begin(); itr != gquiz2.end(); ++itr) \r\n    { \r\n        cout << '\\t' << itr->first \r\n             << '\\t' << itr->second << '\\n'; \r\n    } \r\n    cout << endl; \r\n  \r\n    // remove all elements up to element with value 30 in gquiz2 \r\n    cout << \"\\ngquiz2 after removal of elements less than key=3 : \\n\"; \r\n    cout << \"\\tKEY\\tELEMENT\\n\"; \r\n    gquiz2.erase(gquiz2.begin(), gquiz2.find(3)); \r\n    for (itr = gquiz2.begin(); itr != gquiz2.end(); ++itr) \r\n    { \r\n        cout << '\\t' << itr->first \r\n             << '\\t' << itr->second << '\\n'; \r\n    } \r\n  \r\n    // remove all elements with key = 4 \r\n    int num; \r\n    num = gquiz2.erase(4); \r\n    cout << \"\\ngquiz2.erase(4) : \"; \r\n    cout << num << \" removed \\n\" ; \r\n    cout << \"\\tKEY\\tELEMENT\\n\"; \r\n    for (itr = gquiz2.begin(); itr != gquiz2.end(); ++itr) \r\n    { \r\n        cout << '\\t' << itr->first \r\n             << '\\t' << itr->second << '\\n'; \r\n    } \r\n  \r\n    cout << endl; \r\n  \r\n    //lower bound and upper bound for multimap gquiz1 key = 5 \r\n    cout << \"gquiz1.lower_bound(5) : \" << \"\\tKEY = \"; \r\n    cout << gquiz1.lower_bound(5)->first << '\\t'; \r\n    cout << \"\\tELEMENT = \" << gquiz1.lower_bound(5)->second << endl; \r\n    cout << \"gquiz1.upper_bound(5) : \" << \"\\tKEY = \"; \r\n    cout << gquiz1.upper_bound(5)->first << '\\t'; \r\n    cout << \"\\tELEMENT = \" << gquiz1.upper_bound(5)->second << endl; \r\n  \r\n    return 0; \r\n  \r\n} \r\n"
  },
  {
    "path": "STL/Map/Unodered-Map/unorderedmap.cpp",
    "content": "// C++ program to demonstrate functionality of unordered_map\n#include <iostream>\n#include <unordered_map>\nusing namespace std;\n\nint main()\n{\n\t// Declaring umap to be of <string, int> type\n\t// key will be of string type and mapped value will\n\t// be of int type\n\tunordered_map<string, int> umap;\n\n\t// inserting values by using [] operator\n\tstring s1, s2 ,s3;\n\tcin>>s1>>s2>>s3;\n    \n\tint a,b,c;\n\t\n\tcin>>a>>b>>c;\n\n\tumap[s1] = a;\n\tumap[s2] = b;\n\tumap[s3] = c;\n\n\t// Traversing an unordered map\n\tfor (auto x : umap)\n\tcout << x.first << \" \" << x.second << endl;\n\n}"
  },
  {
    "path": "STL/Map/map.cpp",
    "content": "#include <iostream> \r\n#include <iterator> \r\n#include <map> \r\n  \r\nusing namespace std; \r\n  \r\nint main() \r\n{ \r\n  \r\n    \r\n    map<int, int> gquiz1; \r\n  \r\n    \r\n    gquiz1.insert(pair<int, int>(1, 40)); \r\n    gquiz1.insert(pair<int, int>(2, 30)); \r\n    gquiz1.insert(pair<int, int>(3, 60)); \r\n    gquiz1.insert(pair<int, int>(4, 20)); \r\n    gquiz1.insert(pair<int, int>(5, 50)); \r\n    gquiz1.insert(pair<int, int>(6, 50)); \r\n    gquiz1.insert(pair<int, int>(7, 10)); \r\n  \r\n    \r\n    map<int, int>::iterator itr; \r\n    cout << \"\\nThe map gquiz1 is : \\n\"; \r\n    cout << \"\\tKEY\\tELEMENT\\n\"; \r\n    for (itr = gquiz1.begin(); itr != gquiz1.end(); ++itr) { \r\n        cout << '\\t' << itr->first \r\n             << '\\t' << itr->second << '\\n'; \r\n    } \r\n    cout << endl; \r\n  \r\n     \r\n    map<int, int> gquiz2(gquiz1.begin(), gquiz1.end()); \r\n  \r\n    \r\n    cout << \"\\nThe map gquiz2 after\"\r\n         << \" assign from gquiz1 is : \\n\"; \r\n    cout << \"\\tKEY\\tELEMENT\\n\"; \r\n    for (itr = gquiz2.begin(); itr != gquiz2.end(); ++itr) { \r\n        cout << '\\t' << itr->first \r\n             << '\\t' << itr->second << '\\n'; \r\n    } \r\n    cout << endl; \r\n  \r\n    \r\n    cout << \"\\ngquiz2 after removal of\"\r\n            \" elements less than key=3 : \\n\"; \r\n    cout << \"\\tKEY\\tELEMENT\\n\"; \r\n    gquiz2.erase(gquiz2.begin(), gquiz2.find(3)); \r\n    for (itr = gquiz2.begin(); itr != gquiz2.end(); ++itr) { \r\n        cout << '\\t' << itr->first \r\n             << '\\t' << itr->second << '\\n'; \r\n    } \r\n  \r\n    \r\n    int num; \r\n    num = gquiz2.erase(4); \r\n    cout << \"\\ngquiz2.erase(4) : \"; \r\n    cout << num << \" removed \\n\"; \r\n    cout << \"\\tKEY\\tELEMENT\\n\"; \r\n    for (itr = gquiz2.begin(); itr != gquiz2.end(); ++itr) { \r\n        cout << '\\t' << itr->first \r\n             << '\\t' << itr->second << '\\n'; \r\n    } \r\n  \r\n    cout << endl; \r\n  \r\n    \r\n    cout << \"gquiz1.lower_bound(5) : \"\r\n         << \"\\tKEY = \"; \r\n    cout << gquiz1.lower_bound(5)->first << '\\t'; \r\n    cout << \"\\tELEMENT = \"\r\n         << gquiz1.lower_bound(5)->second << endl; \r\n    cout << \"gquiz1.upper_bound(5) : \"\r\n         << \"\\tKEY = \"; \r\n    cout << gquiz1.upper_bound(5)->first << '\\t'; \r\n    cout << \"\\tELEMENT = \"\r\n         << gquiz1.upper_bound(5)->second << endl; \r\n  \r\n    return 0; \r\n} "
  },
  {
    "path": "STL/Queue/Deque/README.md",
    "content": "# Deque\n\nDeque or double-ended queue is an abstract data type that generalizes a queue, for which elements can be added to or removed from either the front or back. "
  },
  {
    "path": "STL/Queue/Deque/deque.cpp",
    "content": "#include<bits/stdc++.h>\nusing namespace std;\n\nint main(){\n \n    \n    deque<int>q;\n\n    //q={}\n    q.push_back(1); // inserts an element at back\n\n    //q={1}\n\n    q.push_front(2); //inserts an element at front\n    //q={2,1}\n\n   cout<< q.at(1)<<'\\n'; //prints elemant at position 1 {1}\n\n    cout<<q.size()<<'\\n'; //prints no of elements in the deque = 2\n\n    q.resize(4); //resizes the deque to contain 4 elements {1,2,0,0}\n\n    \n    cout<<q.front()<<'\\n'; //prints element at front {2}\n\n    cout<<q.back()<<'\\n'; // prints last element {0}\n\n    q.pop_back();\n    // q={2,1,0}\n\n    q.pop_front();\n    //q={1,0}\n    \n   \n}\n"
  },
  {
    "path": "STL/Queue/PriorityQueue/priority_queue.cpp",
    "content": "#include <bits/stdc++.h>\nusing namespace std;\nint main(int argc, char const *argv[]) {\n  //make a prioity_queue\n  p_queue<int> pq;\n\n  //insert element element in p_queue\n  pq.push(12);\n\n  //find the size of q_queue\n  cout << pq.size();\n\n  //check if p_queue is empty\n  pq.empty();\n\n  //remove element from p-queue\n  pq.pop();\n\n  //print top most element.\n  cout << pq.top();\n\n\n  /*\n    This is by-default max- prioity_queue, to make min-queue, simple multiply -1 to all the elements\n    or use\n\n    p_queue<int,vector<int>, greater<int>> pq;\n  */\n  return 0;\n}\n"
  },
  {
    "path": "STL/Queue/Queue.cpp",
    "content": "/*Functions to demonstrate queue in STL\nOperations: empty(), size(), front(), back(), push(g), pop()*/\n\n#include<bits/stdc++.h>\nusing namespace std;\n//QUEUE is a FIFO data structure, where insertion and deletion of element is done at opposite ends.\n\nvoid print(queue<int> q){\n\twhile(!q.empty()){\n\t\tcout << q.front();\n\t\tq.pop();\n\t}\n}\n\nint main(int argc, char const *argv[]) {\n\n\t//declaration of queue\n\tqueue<int> q;\n\n\t//add element to QUEUE\n\tq.push(1);\n\n\t//print the front item of queue.\n\tq.front();\n\n\t//print the last item of queue.\n\tq.back();\n\n\t//delete item from queue.\n\tq.pop();\n\n\t//check if queue is empty.\n\tq.empty();   //returns 0 or 1.\n\n\t//check the size of queue.\n\tq.size();\n\n\t//iterator to queue.\n\tauto it = q.begin();\n\tqueue<int> it = q.end();\n\n\t//print queue, you can't use a normal for loop and iterator methord to print the queue.\n\tprint(q);\n\treturn 0;\n}\n"
  },
  {
    "path": "STL/README.md",
    "content": "# Index\n\n* [Array](Array/)\n* [Vector](Vector/)\n* [Map](Map/)\n* [Set](Set/)\n* [Stack](Stack/)\n* [Queue](Queue/)"
  },
  {
    "path": "STL/Set/Unodered-Set/UnorderedSet.cpp",
    "content": "#include<bits/stdc++.h>\nusing namespace std ;\n\nint main()\n{\n    // declaring unordered_set for storing int type values\n    unordered_set<int> s ;\n\n    // for inserting an element\n\n    s.insert(1) ; \n    s.insert(2) ;\n    s.insert(3) ;\n    s.insert(4) ;\n\n    // count of an element\n    // count will be either 1 (the element is in the set) or 0 (the element is not in the set)\n    // because set/unordered_set only contain distinct elements\n    cout << s.count(1) << endl  ;  //  1\n    cout << s.count(2) << endl  ;  //  1\n    cout << s.count(5) << endl  ;  //  0\n    cout << s.count(6) << endl  ;  //  0\n\n    // for erasing an element\n    s.erase(1) ;\n    cout << s.count(1) << endl  ;  //  0\n    s.erase(2) ;\n    cout << s.count(2) << endl  ;  //  0\n\n    // insert never adds an element if it is already there\n    cout << s.count(1) << endl  ;  //  0\n    s.insert(1) ;\n    cout << s.count(1) << endl  ;  //  1\n    s.insert(1) ;\n    cout << s.count(1) << endl  ;  //  1 , the count is still one\n\n    // size of an unordered_set\n    cout << s.size() << endl  ;  // 3 , and we know that the elements are 1 , 3 , 4\n\n    // how to access an unordered_set\n    // we can't access an unordered_set or a set by using [] notation\n    // for printing/accessing the elements of set we can simply do this\n    for(auto x:s)\n    {\n        cout << x << \" \" ;  //  it will print the elements of the s\n    }\n    cout << endl ;\n\n    // by using iterators \n    // Iterators are generally used to access elements of an unordered_set/set/vector\n\n    auto x = s.begin() ;  //  this will point to the first element of unordered_set\n\n    // we can access the element by using '*' symbol\n    cout << *x << endl ;\n    // note: the output of the above line is not fixed \n    // it can be a any value from the unordered set elements \n\n    //  it will print the elements of the s\n    // s.end() point towards the next position from last element\n    // that's why will we continue our loop till iterator is not equal to s.end()\n    // once iterator becomes equal to s.end() the loop will stop immediately\n    for (auto it = s.begin(); it != s.end(); it++)\n    {\n        cout << *it << \" \" ;\n    }\n    cout << endl ;\n\n    // search for an element\n    // s.find(x) will tells that whether 'x' is presents in unordered set or not \n    // and if s does not contain x then it will points towards s.end()\n    auto it=s.find(8) ;\n    if(it==s.end()) // means element is not found\n    {\n        cout << \"element is not found\" << endl ;\n    }\n    else\n    {\n        cout << \"element is found\" << endl ;\n    }\n    // above line will print 'element is not found' , because 8 is not presents in s\n\n\n\n    return 0  ;\n}\n"
  },
  {
    "path": "STL/Set/set.cpp",
    "content": "#include <bits/stdc++.h>\nusing namespace std;\n//set is a ordered pair of item, this data structure is used when you need all the\n//elements to be always sorted.\nint main()\n{\n\tset <int, greater <int> > s1;\n\n\ts1.insert(40);\n\ts1.insert(30);\n\ts1.insert(60);\n\ts1.insert(20);\n\ts1.insert(50);\n\ts1.insert(50);\n\ts1.insert(10);\n\n\tset <int, greater <int> > :: iterator itr;\n\tcout << \"\\nThe set s1 is : \";\n\tfor (itr = s1.begin(); itr != s1.end(); ++itr)\n\t{\n\t\tcout << '\\t' << *itr;\n\t}\n\tcout << endl;\n\n\tset <int> s2(s1.begin(), s1.end());\n\n\tcout << \"\\nThe set s2 after assign from s1 is : \";\n\tfor (itr = s2.begin(); itr != s2.end(); ++itr)\n\t{\n\t\tcout << '\\t' << *itr;\n\t}\n\tcout << endl;\n\n\tcout << \"\\ns2 after removal of elements less than 30 : \";\n\ts2.erase(s2.begin(), s2.find(30));\n\tfor (itr = s2.begin(); itr != s2.end(); ++itr)\n\t{\n\t\tcout << '\\t' << *itr;\n\t}\n\n\tint num;\n\tnum = s2.erase (50);\n\tcout << \"\\ns2.erase(50) : \";\n\tcout << num << \" removed \\t\" ;\n\tfor (itr = s2.begin(); itr != s2.end(); ++itr)\n\t{\n\t\tcout << '\\t' << *itr;\n\t}\n\n\tcout << endl;\n\n\tcout << \"s1.lower_bound(40) : \"\n\t\t<< *s1.lower_bound(40) << endl;\n\tcout << \"s1.upper_bound(40) : \"\n\t\t<< *s1.upper_bound(40) << endl;\n\n\tcout << \"s2.lower_bound(40) : \"\n\t\t<< *s2.lower_bound(40) << endl;\n\tcout << \"s2.upper_bound(40) : \"\n\t\t<< *s2.upper_bound(40) << endl;\n\n\t\t// find an item in set. O(logn)\n\t\tauto it = s2.find(1)\n\t\t//if item is not found it returns end() iterator.\n\treturn 0;\n}\n/*\n\tSet is similar to multiset, unordered set except the fact that.\n\tunorderedset is implemented using hash table, hence insert, delete, find is much faster\n\tthan set.\n*/\n"
  },
  {
    "path": "STL/Stack/stack.cpp",
    "content": "#include <bits/stdc++.h>\nusing namespace std;\n//Stack follows FILO\nint main(int argc, char const *argv[]) {\n  //make a stack.\n  stack<int> s;\n\n  //add item to stack\n  s.push(1);\n\n  //remove item from stack.\n  s.pop();\n\n  //find size of stack\n  s.size();\n\n  //find the top most item in stack.\n  s.top();\n\n  //check if stack is empty\n  s.empty();\n  return 0;\n}\n"
  },
  {
    "path": "STL/Vector/Vector.cpp",
    "content": "#include <bits/stdc++.h>\nusing namespace std;\n//Vector are dyanmic arrays, internally they are normal C style arrays.\nint main() {\n\n\t// initilise empty vector\n\tvector<int> empty_vec;  // {} ,empty vector\n\n\t//make a vector with default values\n\tvector<int> empty_vec = {12,23,45};  // {12,23,45}\n\n\t//make a vector with values from vector or array\n\tint arr[] = {1,2,3,4,5};\n\tvector<int> v1(arr,arr+n); //make a vector with array values\n\tvector<int> v2(v1.begin(), v1.end()); //make a new vector with old vector\n\n\tvector<int> v3(10,0);  //vector of size 10 with default value 0.\n\n\t//add a value to vector\n\tv.push_back(45);  //insert value at the vector at end.\n\n\t//remove value from vector\n\tv.pop_back();\n\n\t//insert at a specific position.\n\tv.insert(v.begin(), 101);  //v.insert(position, value)\n\n\t//print the value at ith position.\n\tcout << v.at(i);\n\n\t//insert at a specific position a number of times.\n\tv.insert(v.begin(), 10, 5);  //v.insert(position, number of times to insert,\n\t\t//value this insert 5, 10 times at the begin of vector.\n\n\n\t//copy a vector\n\tvector<int> v1 = {1,2,3,4,5};\n\tvector<int> v1(v1.begin(), v1.end(), v2.begin()); // (start address of copy, end address of copy\n\t\t\t\t\t\t\t\t\t\t\t//starting address of where to copy)\n\n\t//methord-2\n\tvector<int> v5;\n\tint arr[] = {1,2,3,4,5}\n\tv5.assign(arr, arr+n);\n\n\t//methord -3\n\tvector<int> v6;\n\tv6.assign(10,0); //assign 10, 0s to vector v6. (size, value)\n\n\t//delete a value from vector.\n\tv.erase(it); //it = iterator to that delete position.\n\n\t//remove all values.\n\tv.clear();\n\tv = {};  //both methord works\n\n\t//resize an vector.\n\tvector<int> v = {1,2,3,4,4,4};\n\tv.resize(4); //now it only contain 4 items from start rest all delets.\n\tv.resize(10);// {1,2,3,4,4,4,0,0,0,0}\n\n\t//how many items are in between 2 iterator.\n\tauto it = v.begin();\n\tauto it2 = v.end();\n\tcout << distance(it, it2); // print number of items at vector v.\n\n\treturn 0;\n}\n"
  },
  {
    "path": "_config.yml",
    "content": "theme: jekyll-theme-cayman"
  }
]