├── .github └── workflows │ ├── c-cpp.yml │ └── configure ├── CONTRIBUTIONS.md ├── DSA ├── Bit Manipulation │ ├── Clear_Bit.c++ │ ├── Get_Bit.c++ │ ├── Set_Bit.c++ │ └── Update_Bit.c++ ├── DP │ ├── LongestPalindromicSubstring.cpp │ ├── MinimumPathSum.java │ ├── count_the_subset_of_given_diff.cpp │ ├── lcs.cpp │ ├── longest palindromic substring.cpp │ ├── longest_common_subsequence.cpp │ ├── longest_increasing_subsequence.cpp │ ├── longest_palindromic_subsequenece.cpp │ └── minimum_sum_partition.cpp ├── FenwickTree │ └── fenwicktree.cpp ├── HashTable │ └── Hashtable.cpp ├── README.md ├── Recurson Problems │ ├── 2048 problem recursion.cpp │ ├── Mapped strings.cpp │ ├── Tower of hanoi.cpp │ ├── factorial using recursion.cpp │ ├── fast power using recursion.cpp │ ├── freinds problem recursion.cpp │ ├── generate brackets recursion.cpp │ ├── index │ ├── nth fibonacci using recursion.cpp │ ├── optimal binary strings recursion.cpp │ ├── optimal game strategy.cpp │ ├── recursion dictionary order.cpp │ ├── recursion sorted array.cpp │ ├── replace pi using recursion.cpp │ ├── smart keypad.cpp │ ├── string remove duplicates.cpp │ ├── string to int using recursion.cpp │ └── subsequences generation recursion.cpp ├── brute force example │ ├── BuyAShovel.cpp │ ├── DoNotBeDistracted.cpp │ ├── DoNotBeDistracted.java │ └── SpyDetected.cpp ├── fenwickTreeAlgo.cpp ├── floyds_triangle.cpp ├── linkedList │ ├── AddTwoNumberInLL.java │ ├── DjikstraAlgo.cpp │ ├── FloydCycleDetection.cpp │ ├── MergeTwoSortedLinkedList.java │ ├── Middle_Element_of_Linked_List.java │ ├── Odd Even Linked List │ ├── ReverseNodeInKGroup.java │ ├── createBinaryTreeWithInOrderTraversal.java │ ├── insertionInDiffPosinLL.cpp │ ├── palindrome-linked-list.py │ ├── removeNthNodeFromEnd.java │ └── swapTwoNumberInLL.java ├── matrix │ ├── RotateSquareMatrix90clockwise.java │ ├── Search Element in Matrix.c │ ├── SearchElementInMatrix.java │ ├── TransposeOfMatrix.java │ └── TrappingRainwater.java ├── queue.cpp ├── segment-tree │ └── segtree.cpp ├── sorting │ ├── BubbleSorting.java │ ├── CountingSort,java │ ├── HeapSort.java │ ├── Heapsort.java │ ├── InsertionSorting.java │ ├── QuickSort-Hoare-Partition.cpp │ ├── QuickSort-Lomuto-Partition.cpp │ ├── QuickSorting.java │ ├── Radix-Sort.java │ ├── RadixSort.py │ ├── bucket_sort.c │ ├── bucket_sort.cpp │ ├── bucketsort.java │ ├── counting_sort.py │ ├── cyclicSort.cpp │ ├── mergeSorting.java │ ├── selectionSorting.java │ └── sleep-sort.c └── string │ ├── CountSpace.java │ ├── GenerateParentheses.java │ ├── Parenthesis.java │ ├── ReplaceEByI.java │ ├── SwapFirstLastCharacter.java │ ├── ZAlgorithm.java │ ├── convertIntegerToRoman.java │ ├── convertRomanToString.java │ ├── convertStringToInteger.java │ ├── createUsernameByEmail.java │ ├── extractMaximum.java │ ├── findCumulativeLength.java │ └── lexicographically.java ├── README.md ├── algorithms ├── 100-same-tree.cpp ├── AmazonOA.java ├── BASH ├── Basic_Cpp_Template.cpp ├── Bottom View Of Binary Tree.cpp ├── BubbleSort.cpp ├── Bubblesort.cpp ├── CPUScheduler.java ├── CPU_scheduling.java ├── Flip Binary Equivalent Binary Tree.cpp ├── KMP.cpp ├── Knapsack Problem.cpp ├── Longest-Palindromic-Substring.py ├── Longest_Increasing_Subsequence.cpp ├── Mergesort.cpp ├── MinMax.cpp ├── NQueen.c ├── NQueen.java ├── NumberOfWaysInMaze.cpp ├── README.md ├── Searching │ ├── A_Star.py │ ├── A_star.cpp │ ├── Best_First _Search.cpp │ ├── Best_First_Search.py │ ├── BinarySearch.js │ ├── DFS.cpp │ ├── JumpSearch.cpp │ └── Search_In_a_2D_Matrix.cpp ├── Sorting_Algorithms │ └── C++ │ │ ├── C │ │ └── Selection Sort.cpp │ │ ├── Counting_sort.cpp │ │ ├── DNFAlgo.cpp │ │ ├── Merge_sort.cpp │ │ ├── PigeonHole Sort.cpp │ │ ├── QuickSort.cpp │ │ ├── Selection Sort.cpp │ │ ├── bubble sort.cpp │ │ ├── heapsort.cpp │ │ └── insertion sort.cpp ├── Stack │ ├── Applications │ │ ├── Evaluation-Prefix-Postfix(stack).cpp │ │ ├── Reverse_Function(linklist).cpp │ │ ├── Reverse_Function(stack).cpp │ │ └── balacing paraenthesis(stack).cpp │ ├── Stack( with linked-list).cpp │ └── Stack(with array).cpp ├── Topological- Sort │ ├── topologicalSort.py │ └── toposort.cpp ├── Zig_Zag_Traversal.cpp ├── ar-Cpuschpr ├── ar-binsrt │ ├── C# │ │ └── ar-binsrt.cs │ ├── C++ │ │ └── Bin_Sort.cpp │ ├── C │ │ └── bin-sort.c │ ├── java │ │ └── Main.java │ ├── javascript │ │ └── binSort.js │ └── python3 │ │ └── ar_binsrt.py ├── ar-bm │ ├── Java │ │ └── BoyerMoore.java │ └── c++ │ │ └── boyermoree.cpp ├── ar-bogosort │ ├── C++ │ │ └── bogosort.cpp │ ├── elixir │ │ └── bogosort.exs │ ├── java │ │ └── Bogosort.java │ ├── javascript │ │ └── bogosort.js │ ├── python │ │ └── bogosort.py │ └── typescript │ │ └── bogosort.ts ├── ar-bsrh │ ├── Binary Sort in C# │ ├── C++ │ │ └── Binary_search.cpp │ ├── C │ │ └── Binary_search.c │ ├── Java │ │ └── BinarySearch.java │ ├── Javascript │ │ └── BinarySearch.js │ └── python │ │ └── Binary_search.py ├── ar-bsrt │ ├── C# │ │ └── BubbleSort.cs │ ├── C++ │ │ └── main.cpp │ ├── C │ │ └── bubblesort.c │ ├── golang │ │ └── ar-bsrt.go │ ├── java │ │ └── Bubble_sort.java │ ├── javascript │ │ └── ar-bsrt.js │ ├── python2 │ │ └── bubblesort.py │ ├── python3 │ │ ├── ar_bsrt.py │ │ ├── bucket_sort.py │ │ └── test_ar_bsrt.py │ └── typescript │ │ └── ar-bsrt.ts ├── ar-bvwbintr │ ├── C++ │ │ └── BottomView.cpp │ └── java │ │ └── BottomView.java ├── ar-cochprb │ ├── C++ │ │ ├── CoinChangeProblem.cpp │ │ ├── Coin_change_Problem_method2.cpp │ │ └── readme.md │ ├── C │ │ └── ar-cochprb.c │ ├── Java │ │ ├── Main.java │ │ └── coinflip.java │ ├── Javascript │ │ └── coin_change.js │ ├── java │ │ └── coin_change.java │ ├── python2 │ │ └── coinchange.py │ └── python3 │ │ └── CoinChanProblem.py ├── ar-csrt │ ├── C++ │ │ └── count_sort.cpp │ ├── C │ │ └── Count_Sort.c │ ├── Javascript │ │ └── count_sort.js │ ├── Python │ │ └── Count_Sort.py │ └── Python3 │ │ ├── #Main Algorithm For Count Sort in Python.py │ │ ├── Count Sort.py │ │ ├── Counting_Sort.py │ │ ├── Implementation Of counting Sort Algorithm in Python.py │ │ └── count_sort.py ├── ar-expsq │ ├── C++ │ │ └── expsq.cpp │ ├── C │ │ └── expsq.c │ ├── Java │ │ └── axpsq.java │ ├── Python3 │ │ └── expsq.py │ └── readme.md ├── ar-graphtraversal │ └── graphtraversalbfs.cpp ├── ar-grdy │ └── greddy_algorithm.py ├── ar-hsrt │ ├── C │ │ └── ar.hsrt.c │ ├── ar-hsrt.c │ ├── ar-hsrt.java │ ├── c++ │ │ └── ar_hsrt.c++ │ ├── javascript │ │ └── ar-hsrt.js │ └── python │ │ └── ar-hsrt.py ├── ar-isrt │ ├── C │ │ └── InsertionSort.c │ ├── Insertion Sort.c │ ├── cpp │ │ ├── insert.cpp │ │ └── insertion.cpp │ ├── golang │ │ ├── insertion_sort.go │ │ └── insertion_sort_test.go │ ├── java │ │ └── Main.java │ ├── js │ │ └── ar-isrt.js │ ├── python2 │ │ └── insertionsort.py │ ├── python3 │ │ └── ar-isrt.py │ └── typescript │ │ ├── ar-isrt.js │ │ └── ar-isrt.ts ├── ar-kdn │ ├── KadanesAlgo.java │ ├── c++ │ │ └── KadanesAlgo.cpp │ ├── c │ │ └── KadanesAlgo.c │ ├── javascript │ │ └── ar-kdn.js │ └── python │ │ └── kdn.py ├── ar-kmp │ ├── c++ │ │ └── ar_kmp.c++ │ ├── c │ │ └── ar_kmp.c │ ├── javascript │ │ └── ar_kmp.js │ └── python3 │ │ └── ar_kmp.py ├── ar-knn │ ├── c++ │ │ └── K-NN Algorithm.cpp │ ├── js │ │ └── ar-knn.js │ └── readme.md ├── ar-krushkals │ └── krushkalsalgo.cpp ├── ar-lcs │ ├── C │ │ └── LCS.c │ ├── c++ │ │ └── LCS.cpp │ ├── java │ │ └── LongestCommonSubsequence.java │ ├── javascript │ │ └── ar-lcs.js │ └── python3 │ │ └── ar-lcs.py ├── ar-lis │ ├── C++ │ │ └── ar-lis.cpp │ ├── JS │ │ └── lis.js │ ├── Java │ │ └── ar-lis.java │ └── Python3 │ │ └── ar-lis.py ├── ar-lps │ ├── C++ │ │ └── ar-lps.cpp │ ├── JAVA │ │ └── Longest Palindromic.java │ └── Python3 │ │ └── longestPalindromeSubstring.py ├── ar-lscsa │ ├── C++ │ │ └── lscsa.cpp │ ├── C │ │ └── lcsa.c │ ├── Java │ │ └── lscsa.java │ ├── python3 │ │ └── lscsa.py │ └── readme.md ├── ar-lsrh │ ├── JAVA │ │ └── Linear Search.java │ ├── Javascript │ │ └── ar-lsrch.js │ ├── c++ │ │ └── ar_lsrh.cpp │ ├── c │ │ └── ar-lsrh.c │ ├── golang │ │ └── linear-search.go │ └── python │ │ └── ar-lsrh.py ├── ar-lvwbintr │ ├── C │ │ └── leftviewbt.c │ ├── c++ │ │ └── leftviewbt.cpp │ └── python3 │ │ └── leftviewbt.py ├── ar-mexp │ ├── C++ │ │ └── mexp.cpp │ ├── PHP │ │ └── mexp.php │ ├── Python │ │ └── mexp.py │ ├── mexp.c │ └── readme.md ├── ar-min │ ├── c# │ │ └── min_arr.cs │ ├── c++ │ │ └── ar_min.cpp │ ├── c │ │ └── ar_min.c │ ├── golang │ │ └── ar-min.go │ ├── java │ │ └── Main.java │ ├── javascript │ │ └── ar_min.js │ ├── python2 │ │ └── ar_min.py │ ├── python3 │ │ ├── .gitignore │ │ ├── ar_min.py │ │ ├── ar_min2.py │ │ └── test_ar-min.py │ └── typescript │ │ └── ar_min.ts ├── ar-minmax │ └── Min Max.c ├── ar-msrt │ ├── C# │ │ └── MergeSort.cs │ ├── C++ │ │ └── ar-msrt.cpp │ ├── C │ │ └── MergeSort.c │ ├── java │ │ └── merge sort.java │ ├── javascript │ │ └── mergeSort.js │ ├── python2 │ │ └── mergesort.py │ └── python3 │ │ └── ar-msrt.py ├── ar-mxsub │ └── maxsum_subarray.cpp ├── ar-nsrh │ ├── C++ │ │ ├── naive_search.cpp │ │ └── naive_search.exe │ ├── NaiveSearch.java │ └── Python3 │ │ └── naive_search.py ├── ar-pgsrt │ ├── PigeonHoleSort.c │ └── pigeonholesort.cpp ├── ar-prfac │ ├── C++ │ │ └── Prime_Factor.cpp │ ├── C │ │ └── Prime_Factor.c │ ├── JAVA │ │ └── Prime factors.java │ ├── JS │ │ └── prime_factor.js │ ├── PHP │ │ └── prime-factors.php │ └── Python3 │ │ └── Prime_Factor.py ├── ar-pstfix │ ├── C++ │ │ └── Evaluate_Postfix.cpp │ ├── C │ │ └── Evaluate_Postfix.c │ └── Python3 │ │ ├── evaluate_postfix.py │ │ └── test_evaluate_postfix.py ├── ar-qsel │ ├── ar-qsel.cpp │ ├── ar-qsel.cs │ ├── ar-qsel.js │ ├── ar-qsel.py │ └── readme.md ├── ar-qsrt │ ├── C │ │ └── ar-qsrt.c │ ├── Dart │ │ └── ar-qsrt.dart │ ├── Quick_Sort.cpp │ ├── java │ │ └── QuickSort.java │ ├── js │ │ └── ar-qsrt.js │ └── python3 │ │ └── ar-qsrt.py ├── ar-radsrt │ ├── C │ │ └── ar-radsrt.c │ ├── Python │ │ └── radixsort.py │ └── radix_sort.cpp ├── ar-rbtree │ ├── ar-rbtree.c │ └── redblacktree.cpp ├── ar-rcprb │ ├── C++ │ │ └── rcprb.cpp │ ├── c │ │ └── ar-rcprb.c │ ├── cpp │ │ └── rod_cutting.cpp │ ├── js │ │ └── ar-rcprb.js │ └── readme.md ├── ar-rpprscs │ ├── C# │ │ └── RockPaperAndScissor.cs │ ├── c++ │ │ └── rpprscs(c++).cpp │ ├── c │ │ └── Code.c │ ├── java │ │ ├── .gitignore │ │ └── Main.java │ ├── javascript │ │ ├── ar-rpprscs.js │ │ ├── ar-rpprscs.test.js │ │ ├── main.js │ │ ├── package-lock.json │ │ └── package.json │ ├── python │ │ ├── README.md │ │ ├── rpprscs-py3.10.py │ │ └── rpprscs-py3.9.py │ └── typescript │ │ ├── ar-rpprscs.test.ts │ │ ├── ar-rpprscs.ts │ │ ├── main.ts │ │ ├── package-lock.json │ │ └── package.json ├── ar-shsrt │ ├── c │ │ └── ar-shsrt.c │ ├── cpp │ │ └── ar-shsrt.cpp │ ├── js │ │ └── ar-shsrt.js │ └── python3 │ │ └── ar-shsrt.py ├── ar-slpsrt │ ├── c++ │ │ └── Sleep_sort.cpp │ ├── c │ │ └── ar-slpsrt.c │ ├── java │ │ └── Sleep_Sort.java │ ├── js │ │ └── ar-slpsrt.js │ └── python3 │ │ └── Sleep_sort.py ├── ar-soer │ ├── Python3 │ │ └── Sieve.py │ ├── Sieve.cpp │ ├── python2 │ │ └── sieveoferatosthenes.py │ └── seive.java ├── ar-spiralmatrix │ └── spiralmatrix2.cpp ├── ar-spmat │ ├── SpiralMatrix.java │ ├── SpiralMatrix.py │ └── spiralTraversalOfMatrix.cpp ├── ar-ssrt │ ├── C++ │ │ └── selection_sort.cpp │ ├── C │ │ └── selectionsort.c │ ├── java │ │ └── SelectionSort.java │ ├── javascript │ │ └── ar-ssrt.js │ ├── python3 │ │ └── ar-ssrt.py │ └── typescript │ │ └── ar-ssrt.ts ├── ar-strhsg │ └── hashing.cpp ├── ar-tvwbintr │ ├── BinaryTree.java │ └── topViewBinaryTree.py ├── ar-zfnc │ ├── C++ │ │ └── z_function.cpp │ └── Python3 │ │ ├── test_z_function.py │ │ └── z_function.py ├── binary-sort.sh ├── binarySearch.cpp ├── binary_exponentiation.cpp ├── bucket_sort │ ├── bucket_sort.c │ ├── bucket_sort.js │ └── bucket_sort.py ├── exponentialSearch.cpp ├── fractional-knapsack.c ├── gr-bfsrh │ ├── C++ │ ├── Palindrome.cpp │ ├── bfs.cs │ ├── bfs.java │ ├── bfs.js │ ├── gr-bfsrh.c │ └── python3 │ │ ├── gr_bfsrh.py │ │ └── test_gr_bfsrh.py ├── gr-dfsrh │ ├── c++.cpp │ ├── c++ │ │ ├── DFS.cpp │ │ └── gr-dfsrh.c++ │ ├── dfs.java │ ├── dfs.js │ ├── dfsrh.cs │ └── python │ │ └── dfs.py ├── gr-dij │ ├── c │ ├── c++ │ │ ├── c++Dijkstra’s shortest path algorithm.cpp │ │ ├── djikstra.cpp │ │ └── gr-dij.cpp │ ├── java │ │ └── dijkstras.java │ └── python3 │ │ └── dij.py ├── gr-prims │ ├── C++ │ │ ├── RangePrime.cpp │ │ └── is_prime.cpp │ ├── JAVA │ │ └── Prims.java │ ├── javascript │ │ └── isPrime.js │ └── python3 │ │ ├── is_prime.py │ │ └── test_is_prime.py ├── greedy │ ├── greedy.cpp │ └── greedy.py ├── insertion-sort.sh ├── interpolationSearch.cpp ├── jumpSearch.cpp ├── linear-search.sh ├── linearSearching.cpp ├── linkList.cpp ├── matrix_chain.c ├── merge-two-sorted-lists.cpp ├── minPalindrom.cpp ├── n_queens.cpp ├── prims-algo.c ├── prims.c ├── reversing_linkedlist.cpp ├── rightview.cpp ├── scheduling.c ├── simpleCalculator.cpp ├── slidingWindow │ ├── maxSum.cpp │ └── slidingWindowMedian.cpp └── sorting-py │ └── bogosort.py └── matrix-chain-multiplication └── 183aryan.md /.github/workflows/c-cpp.yml: -------------------------------------------------------------------------------- 1 | name: C/C++ CI 2 | 3 | on: 4 | push: 5 | branches: [ main ] 6 | pull_request: 7 | branches: [ main ] 8 | 9 | jobs: 10 | build: 11 | 12 | runs-on: ubuntu-latest 13 | 14 | steps: 15 | - uses: actions/checkout@v2 16 | - name: configure 17 | run: ./configure 18 | - name: make 19 | run: make 20 | - name: make check 21 | run: make check 22 | - name: make distcheck 23 | run: make distcheck 24 | -------------------------------------------------------------------------------- /.github/workflows/configure: -------------------------------------------------------------------------------- 1 | CXX=g++ # The C++ compiler 2 | CXXFLAGS=-g # C++ complilation flags 3 | NATIVE=on # compiles code targeted to current hardware 4 | TUNE=generic # performance-tuning switch 5 | -------------------------------------------------------------------------------- /CONTRIBUTIONS.md: -------------------------------------------------------------------------------- 1 | ## how to contribute 2 | 3 | * Check open issues. 4 | * If you want to add an algorithm, open an issues with the name of algorithm and the language 5 | * Make sure you are assigned 6 | 7 | ## When you are assigned 8 | 9 | * Make a fork, and work on your issues. 10 | * When you have finish, make a pull request, with the # of issues. 11 | -------------------------------------------------------------------------------- /DSA/Bit Manipulation/Clear_Bit.c++: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int clearbit(int n, int pos){ 5 | int mask = ~(1< 2 | using namespace std; 3 | 4 | int getbit(int n, int pos){ 5 | return((n & (1< 2 | using namespace std; 3 | 4 | int setbit(int n, int pos){ 5 | return(n | (1< 2 | using namespace std; 3 | 4 | int updatebit(int n, int pos, int value){ 5 | int mask = ~(1< 3 | using namespace std; 4 | 5 | 6 | struct FenwickTree{ 7 | int siz; 8 | vectortr; 9 | 10 | void init(int n){ 11 | siz = n; 12 | tr.assign(siz, 0ll); 13 | } 14 | 15 | void update(int idx, int val){ 16 | while(idx <= siz){ 17 | tr[idx] += val; 18 | idx += (idx&-idx); 19 | } 20 | } 21 | 22 | long long query(int idx){ 23 | long long ans=0; 24 | while(idx > 0){ 25 | ans += tr[idx]; 26 | idx -= (idx&-idx); 27 | } 28 | return ans; 29 | } 30 | long long query(int l, int r){ 31 | return query(r)-query(l-1); 32 | } 33 | }; 34 | 35 | 36 | int32_t main(){ 37 | int n,q; cin>>n>>q; 38 | vectorv(n+1); 39 | FenwickTree tr; 40 | tr.init(n); 41 | for(int i=1;i<=n;i++){ 42 | int x; cin>>x; 43 | tr.update(i, x-v[i]); 44 | v[i]=x; 45 | } 46 | while(q--){ 47 | int type; cin>>type; 48 | if(type == 1){ 49 | int idx, val; cin>>idx>>val; 50 | tr.update(idx, val-v[idx]); 51 | v[idx] = val; 52 | } 53 | else{ 54 | int l, r; cin>>l>>r; 55 | cout< 2 | using namespace std; 3 | 4 | char words[][10]={"zero","one","two","three","four","five","six","seven","eight","nine"}; 5 | void print_spelling(int n){ 6 | //base case 7 | if(n==0){ 8 | return; 9 | } 10 | //recursive case first print the spellings of (204) 11 | print_spelling(n/10); 12 | //after the function call 13 | int digit=n%10; 14 | cout<>n; 21 | print_spelling(n); 22 | return 0; 23 | } 24 | -------------------------------------------------------------------------------- /DSA/Recurson Problems/Mapped strings.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Knackie/algorithmshacktoberfest2022/7a90f0bf9031e04871b8e8387cae2c4d7a997922/DSA/Recurson Problems/Mapped strings.cpp -------------------------------------------------------------------------------- /DSA/Recurson Problems/Tower of hanoi.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | void move(int n,char src,char helper,char destination){ 5 | //base case 6 | if(n==0){ 7 | return; 8 | } 9 | //recursive case 10 | //move n-1 disks from source to helper 11 | move(n-1,src,destination,helper); 12 | cout<<"shift disk "<>n; 20 | 21 | move(n,'A','B','C'); 22 | 23 | } 24 | -------------------------------------------------------------------------------- /DSA/Recurson Problems/factorial using recursion.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | int factorial(int n){ 4 | //base case 5 | if(n==0){ 6 | return 1; 7 | } 8 | //recursive case 9 | int small_ans=factorial(n-1); 10 | int ans=n*small_ans; 11 | return ans; 12 | /* or simply 13 | return n*factorial(n-1); 14 | */ 15 | 16 | } 17 | int main(){ 18 | int n; 19 | cin>>n; 20 | cout< 2 | using namespace std; 3 | //compute a^n 4 | int power(int a,int n){ 5 | if(n==0){ 6 | return 1; 7 | } 8 | return a*power(a,n-1); 9 | } 10 | //more efficient way in terms of time and space 11 | int fast_power(int a,int n){ 12 | if(n==0){ 13 | return 1; 14 | } 15 | int smaller_ans=fast_power(a,n/2); 16 | smaller_ans*=smaller_ans; 17 | if(n&1){ 18 | return smaller_ans*a; 19 | } 20 | return smaller_ans; 21 | 22 | } 23 | int main(){ 24 | int a,n; 25 | cin>>a>>n; 26 | cout< 16 | using namespace std; 17 | int ways(int N){ 18 | //base case 19 | if(N==0){ 20 | return 1; 21 | 22 | } 23 | if(N==1){ 24 | return 1; 25 | 26 | } 27 | if(N==2){ 28 | return 2; 29 | } 30 | //recursive case 31 | return ways(N-1)+((N-1)*ways(N-2)); 32 | 33 | } 34 | int main(){ 35 | int N; 36 | cin>>N; 37 | cout< 3 | using namespace std; 4 | void generate_brackets(char *out,int n,int idx,int open,int close){ 5 | // base case 6 | if(idx==2*n){ 7 | out[idx]='\0'; 8 | cout<< out <>n; 27 | char out[1000]; 28 | int idx=0; 29 | generate_brackets(out,n,0,0,0); 30 | return 0; 31 | } 32 | -------------------------------------------------------------------------------- /DSA/Recurson Problems/index: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /DSA/Recurson Problems/nth fibonacci using recursion.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | int fibonacci(int n){ 4 | //base case 5 | if(n==0 || n==1){ 6 | return n; //if n=0,return 0 or n=1,return 1 7 | } 8 | //recursive case 9 | int f1=fibonacci(n-2); 10 | int f2=fibonacci(n-1); 11 | return f1+f2; 12 | } 13 | int main(){ 14 | int n; 15 | cin>>n; 16 | cout< 10 | using namespace std; 11 | int f(int n){ 12 | if(n==0){ 13 | return 1; 14 | } 15 | if(n==1){ 16 | return 2; 17 | } 18 | return f(n-1)+f(n-2); 19 | } 20 | int main(){ 21 | int n; 22 | cin>>n; 23 | cout< 4 | using namespace std; 5 | bool is_sorted(int a[],int n){ 6 | //base case 7 | if(n==0 or n==1){ 8 | return true; 9 | 10 | } 11 | //recursive case 12 | if(a[0] 2 | using namespace std; 3 | //replace pi with 3.14 4 | //xpighpimpipi----->x3.14m3.143.14 5 | void replace_pi(char a[],int i){ 6 | if(a[i]=='\0' or a[i+1]=='\0'){ 7 | return ; 8 | 9 | } 10 | //look for pi at current location 11 | if(a[i]=='p' and a[i+1]=='i'){ 12 | //shifting +replacement with 3.14 13 | int j=i+2; 14 | //jake j to the end of the array 15 | while(a[j]!='\0'){ 16 | j++; 17 | } 18 | //shifting(right to left) 19 | while(j>=i+2){ 20 | a[j+2]==a[j]; 21 | j--; 22 | 23 | } 24 | //replacement + recursive call for the remaining part 25 | a[i]='3'; 26 | a[i+1]='.'; 27 | a[i+2]='1'; 28 | a[i+3]='4'; 29 | replace_pi(a,i+4); 30 | 31 | 32 | 33 | 34 | } 35 | else{ 36 | //go to the next position 37 | replace_pi(a,i+1); 38 | 39 | } 40 | return ; 41 | 42 | } 43 | int main(){ 44 | char a[1000]; 45 | cin>>a; 46 | replace_pi(a,0); 47 | cout< 22 | #include 23 | using namespace std; 24 | void remove_duplicates(char a[]){ 25 | int l=strlen(a); 26 | if(l==0 or l==1){ 27 | return; 28 | } 29 | int pre=0; 30 | for(int current=1;current 2 | #include 3 | using namespace std; 4 | 5 | int string_to_int(char *a,int n){ 6 | if(n==0){ 7 | return 0; 8 | 9 | } 10 | int digit=a[n-1]-'0'; 11 | int small_ans=string_to_int(a,n-1); 12 | return small_ans*10+digit; 13 | } 14 | int main(){ 15 | char a[]="1234"; 16 | int n=strlen(a); 17 | int x=string_to_int(a,n); 18 | cout< 2 | using namespace std; 3 | void generate_subsequences(char *in,char *out,int i,int j){ 4 | //base case 5 | if(in[i]=='\0'){ 6 | out[j]='\0'; 7 | cout< 2 | 3 | #define fastio \ 4 | ios_base::sync_with_stdio(false); \ 5 | cin.tie(NULL) 6 | 7 | #define endl "\n" 8 | #define MOD 1000000007 9 | #define ll long long 10 | #define pb push_back 11 | /* notes 12 | You are given an array a consisting of n (n≥3) positive integers. 13 | It is known that in this array, all the numbers except one are the same 14 | ex [4,11,4,4] 15 | https://codeforces.com/contest/1512/problem/A 16 | 17 | */ 18 | 19 | using namespace std; 20 | 21 | 22 | int main() 23 | { 24 | fastio; 25 | int n; 26 | cin >> n; 27 | while (n--) 28 | { 29 | int n; 30 | cin >> n; 31 | vector v(n); 32 | for (int &e : v) 33 | { 34 | cin >> e; 35 | } 36 | vector a = v; 37 | sort(a.begin(), a.end()); 38 | for (int i = 0; i < n; i++) 39 | { 40 | if (v[i] != a[1]) 41 | { 42 | cout << i + 1 << "\n"; 43 | } 44 | } 45 | } 46 | return 0; 47 | } -------------------------------------------------------------------------------- /DSA/floyds_triangle.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | int main() { 4 | int rows, number = 1; 5 | cout << "Enter number of rows: "; cin >> rows; 6 | for(int i = 1; i <= rows; i++) { 7 | for(int j = 1; j <= i; ++j) { 8 | cout << number << " "; 9 | ++number; } 10 | cout << endl; 11 | } 12 | return 0; } 13 | -------------------------------------------------------------------------------- /DSA/linkedList/Middle_Element_of_Linked_List.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/middle-of-the-linked-list/ 2 | 3 | /** 4 | * Definition for singly-linked list. 5 | * struct ListNode { 6 | * int val; 7 | * ListNode *next; 8 | * ListNode() : val(0), next(nullptr) {} 9 | * ListNode(int x) : val(x), next(nullptr) {} 10 | * ListNode(int x, ListNode *next) : val(x), next(next) {} 11 | * }; 12 | */ 13 | class Solution { 14 | public: 15 | ListNode* middleNode(ListNode* head) { 16 | int cnt = 0; 17 | ListNode* tmp = head; 18 | while(tmp != NULL) 19 | { 20 | cnt++; 21 | tmp = tmp->next; 22 | } 23 | 24 | // cout<next; 29 | } 30 | return head; 31 | } 32 | }; 33 | -------------------------------------------------------------------------------- /DSA/linkedList/Odd Even Linked List: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | ListNode* deleteMiddle(ListNode* head) { 4 | ListNode * dummy=new ListNode(); 5 | dummy->next=head; 6 | ListNode * slow=dummy; 7 | ListNode * fast=dummy; 8 | while(fast->next!=NULL && fast->next->next!=NULL){ 9 | slow=slow->next; 10 | fast=fast->next->next; 11 | } 12 | if(slow->next->next==NULL){ 13 | slow=Remove(slow); 14 | return dummy->next; 15 | } 16 | slow=Remove(slow); 17 | return head; 18 | } 19 | ListNode *Remove(ListNode *head){ 20 | ListNode *temp=head->next; 21 | head->next=head->next->next; 22 | temp->next=NULL; 23 | return head; 24 | } 25 | }; 26 | -------------------------------------------------------------------------------- /DSA/matrix/RotateSquareMatrix90clockwise.java: -------------------------------------------------------------------------------- 1 | package matrix; 2 | 3 | public class RotateSquareMatrix90clockwise { 4 | 5 | public static void printMatrix(int a[][]) { 6 | int n=a.length; 7 | for(int i=0;i 2 | #define ROW 10 3 | #define COL 10 4 | 5 | void ReadArray(int [ROW][COL], int, int); 6 | void FindArray(int [ROW][COL], int, int,int); 7 | 8 | main() 9 | { 10 | int r,c,sum,k; 11 | int a[ROW][COL]; 12 | double avg; 13 | printf("Enter the order of 2D matrix: "); 14 | scanf("%d%d",&r,&c); 15 | printf("\nEnter the Elements of Matix:\n"); 16 | ReadArray(a,r,c); 17 | 18 | 19 | printf("\nEnter The Element to search: "); 20 | scanf("%d",&k); 21 | FindArray(a,r,c,k); 22 | } 23 | 24 | void ReadArray(int a[ROW][COL], int r, int c) 25 | { 26 | int i,j; 27 | for(i=0;i=0) { 12 | if(a[row][col]==key) { 13 | return true; 14 | }else if (key>a[row][col]){ 15 | row++; 16 | }else { 17 | col--; 18 | } 19 | } 20 | return false; 21 | } 22 | 23 | public static void main(String[] args) { 24 | 25 | int matrix[][]={ 26 | {1,2,3,4}, 27 | {12,13,15,17}, 28 | {14,16,18,21}, 29 | {22,28,31,32} 30 | }; 31 | int key=32; 32 | // printMatrix(matrix); 33 | // SearchElement(matrix); 34 | System.out.println(SearchElement(matrix,key)); 35 | } 36 | } 37 | 38 | -------------------------------------------------------------------------------- /DSA/matrix/TransposeOfMatrix.java: -------------------------------------------------------------------------------- 1 | package matrix; 2 | 3 | public class TransposeOfMatrix { 4 | public static void printMatrix(int a[][]) { 5 | int n=a.length; 6 | for(int i=0;i=leftMax) leftMax=a[left]; 11 | else ans+=(leftMax-a[left]); 12 | left++; 13 | }else { 14 | if(a[right]>=rightMax) rightMax=a[right]; 15 | else ans+=(rightMax-a[right]); 16 | right--; 17 | } 18 | } 19 | return ans; 20 | } 21 | 22 | public static void main(String[] args) { 23 | // TODO Auto-generated method stub 24 | 25 | int arr[]= {3,4,5,1,7,2,6,5,4,1}; 26 | int ans= TrappingWater(arr); 27 | System.out.println(ans); 28 | } 29 | 30 | } 31 | -------------------------------------------------------------------------------- /DSA/sorting/BubbleSorting.java: -------------------------------------------------------------------------------- 1 | package sorting; 2 | 3 | public class BubbleSorting { 4 | static void swap(int a[],int i,int j) { 5 | int temp=a[i]; 6 | a[i]=a[j]; 7 | a[j]=temp; 8 | } 9 | static void bubbleSort(int arr[]) { 10 | int n=arr.length; 11 | for(int i=0;iarr[j+1]) { 14 | swap(arr,j,j+1); 15 | } 16 | } 17 | } 18 | } 19 | 20 | static void printArray(int a[]) { 21 | for(int e:a) { 22 | System.out.print(e+ " "); 23 | } 24 | } 25 | 26 | public static void main(String[] args) { 27 | // TODO Auto-generated method stub 28 | int a[]=new int[] {9,5,2,-6,3,1,3}; 29 | bubbleSort(a); 30 | printArray(a); 31 | 32 | 33 | } 34 | 35 | } 36 | -------------------------------------------------------------------------------- /DSA/sorting/InsertionSorting.java: -------------------------------------------------------------------------------- 1 | package sorting; 2 | 3 | public class InsertionSorting { 4 | 5 | static void swap(int a[],int i , int j) { 6 | int temp=a[i]; 7 | a[i]=a[j]; 8 | a[j]=temp; 9 | } 10 | static void printArray(int a[]) { 11 | for(int e:a) { 12 | System.out.print(e+ " "); 13 | } 14 | } 15 | 16 | static void insertionSort(int a[]) { 17 | int n=a.length; 18 | for(int i=1;i=0;j--) { 22 | if(temppivot) j--; 17 | if(i 0: 19 | maxLength = False 20 | # empty lists into aList array 21 | a = 0 22 | for b in range( RADIX ): 23 | buck = buckets[b] 24 | for i in buck: 25 | aList[a] = i 26 | a += 1 27 | # move to next digit 28 | placement *= RADIX 29 | 30 | 31 | print(aList) 32 | radixsort(aList) 33 | print(aList) 34 | -------------------------------------------------------------------------------- /DSA/sorting/counting_sort.py: -------------------------------------------------------------------------------- 1 | def countSort(arr): 2 | output = [0 for i in range(len(arr))] 3 | count = [0 for i in range(256)] 4 | ans = ["" for _ in arr] 5 | for i in arr: 6 | count[ord(i)] += 1 7 | for i in range(256): 8 | count[i] += count[i-1] 9 | for i in range(len(arr)): 10 | output[count[ord(arr[i])]-1] = arr[i] 11 | count[ord(arr[i])] -= 1 12 | for i in range(len(arr)): 13 | ans[i] = output[i] 14 | return ans 15 | arr = "geeksforgeeks" 16 | ans = countSort(arr) 17 | print("Sorted character array is % s" %("".join(ans))) 18 | -------------------------------------------------------------------------------- /DSA/sorting/cyclicSort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | void solve(int arr[], int n){ 5 | int i=0; 6 | while(i < n){ 7 | int correct = arr[i] - 1; 8 | if(arr[i] != arr[correct]){ 9 | swap(arr[i] , arr[correct]); 10 | } 11 | else{ 12 | i++; 13 | } 14 | } 15 | } 16 | 17 | int main(){ 18 | int arr[1000],n; 19 | string str; 20 | 21 | cin>>n; 22 | for(int i=0; i>arr[i]; 24 | } 25 | 26 | sort(arr, arr+n); 27 | solve(arr, n); 28 | for(int i=0; imid) { 19 | while(j<=h) { 20 | b[k]=a[j]; 21 | k++; j++; 22 | } 23 | }else { 24 | while(i<=mid) { 25 | b[k]=a[i]; 26 | i++;k++; 27 | } 28 | } 29 | for(i=l;i 2 | #include 3 | #include 4 | void routine(void *a) 5 | { 6 | int n = *(int *) a; 7 | Sleep(n); 8 | printf("%d ", n); 9 | } 10 | void sleepSort(int arr[], int n) 11 | { 12 | HANDLE threads[n]; 13 | for (int i = 0; i < n; i++) 14 | threads[i] = (HANDLE)_beginthread(&routine, 0, &arr[i]); 15 | WaitForMultipleObjects(n, threads, TRUE, INFINITE); 16 | return; 17 | } 18 | 19 | int main() 20 | { 21 | printf("Enter Number of elements"); 22 | scanf("%d",n); 23 | int arr[n]; 24 | for(int i=0;i generateParenthesis(int n) { 9 | List result=new ArrayList<>(); 10 | findAll("(",1,0,result,n); 11 | return result; 12 | } 13 | static void findAll(String current, int openB, int closeB,List result,int n){ 14 | if(current.length()==2*n){ 15 | result.add(current); 16 | return; 17 | } 18 | if(openB stk= new Stack<>(); 11 | for(int i=0;i r) 20 | l = i; r = i + z[i] - 1; 21 | } 22 | 23 | int ans = 0; 24 | 25 | for (int x : z) 26 | if (x == m) ans++; 27 | 28 | return ans ; 29 | } 30 | 31 | } 32 | -------------------------------------------------------------------------------- /DSA/string/convertIntegerToRoman.java: -------------------------------------------------------------------------------- 1 | package string; 2 | 3 | public class convertIntegerToRoman { 4 | 5 | public static String IntegerToRoman(int num) { 6 | int Num[] = {1,4,5,9,10,40,50,90,100,400,500,900,1000}; 7 | String roman[] = {"I","IV","V","IX","X","XL","L","XC","C","CD","D","CM","M"}; 8 | String Roman=""; 9 | StringBuilder sb=new StringBuilder(); 10 | for(int i=Num.length-1;i>=0;i--) { 11 | while(num>=Num[i]) { 12 | sb.append(roman[i]); 13 | num-=Num[i]; 14 | } 15 | } 16 | return sb.toString(); 17 | } 18 | public static void main(String[] args) { 19 | // TODO Auto-generated method stub 20 | int num=18; 21 | System.out.println(IntegerToRoman(num)); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /DSA/string/convertRomanToString.java: -------------------------------------------------------------------------------- 1 | package string; 2 | import java.util.HashMap; 3 | 4 | public class convertRomanToString { 5 | public static int RomanToInteger(String s) { 6 | 7 | HashMap map=new HashMap<>(); 8 | map.put('I',1); 9 | map.put('V',5); 10 | map.put('X',10); 11 | map.put('L',50); 12 | map.put('C',100); 13 | map.put('D',500); 14 | map.put('M',1000); 15 | 16 | int result=map.get(s.charAt(s.length()-1)); 17 | for(int i=s.length()-2;i>=0;i--) { 18 | // result=map.get(s.charAt(i)); 19 | if(map.get(s.charAt(i)) s2.length()) { 19 | return (s1.length() - s2.length()); 20 | } 21 | else { 22 | return 0; 23 | } 24 | 25 | } 26 | 27 | public static void main(String[] args) { 28 | String s1="Ravi"; 29 | String s2="Ravi"; 30 | String s3="Shyam"; 31 | String s4="ABC"; 32 | 33 | System.out.println(s1.compareTo(s2)); 34 | System.out.println(s1.compareTo(s3)); 35 | System.out.println(s1.compareTo(s4)); 36 | System.out.println(s2.compareTo(s4)); 37 | 38 | System.out.println(lexicographically2(s1,s2)); 39 | System.out.println(lexicographically2(s1,s3)); 40 | System.out.println(lexicographically2(s1,s4)); 41 | System.out.println(lexicographically2(s2,s4)); 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /algorithms/100-same-tree.cpp: -------------------------------------------------------------------------------- 1 | /*Leetcode Question: Same Tree 2 | Problem Link: https://leetcode.com/problems/same-tree/ 3 | */ 4 | 5 | class Solution { 6 | public: 7 | bool isSameTree(TreeNode* p, TreeNode* q) { 8 | 9 | if(p == NULL || q == NULL) 10 | return p == q ; 11 | 12 | bool checkLeft = isSameTree(p->left, q->left) ; 13 | bool checkRight = isSameTree(p->right, q->right) ; 14 | 15 | return (p->val == q->val) && checkLeft && checkRight ; 16 | } 17 | }; 18 | -------------------------------------------------------------------------------- /algorithms/BASH: -------------------------------------------------------------------------------- 1 | binary-search.sh 2 | 3 | #!/bin/bash 4 | 5 | declare -a arr 6 | echo "Enter space separated ascendingly sorted integers:" 7 | read -ra arr 8 | 9 | declare -i search 10 | echo -n "Enter the element to be searched for: " 11 | read -r search 12 | 13 | index=-1 14 | beg=0 15 | mid=0 16 | last=${#arr[@]} 17 | last=$((last - 1)) 18 | 19 | while [ $beg -le $last ]; do 20 | echo -e "\nbeg=$beg\nmid=$mid\nlast=$last\n" 21 | mid=$((beg + last)) 22 | mid=$((mid/2)) 23 | if [ "${arr[$mid]}" -eq "$search" ]; then 24 | index=$mid 25 | break 26 | elif [ "${arr[$mid]}" -gt "$search" ]; then 27 | last=$((mid - 1)) 28 | elif [ "${arr[$mid]}" -lt "$search" ]; then 29 | beg=$((mid + 1)) 30 | fi 31 | done 32 | 33 | if [ $index -ne -1 ]; then 34 | echo "Element found at $((index+1))" 35 | else 36 | echo "Element not found" 37 | fi 38 | -------------------------------------------------------------------------------- /algorithms/Basic_Cpp_Template.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | void solve(){ 5 | 6 | } 7 | 8 | int main() { 9 | ios_base::sync_with_stdio(false); cin.tie(NULL); 10 | int t=1; 11 | cin>>t; 12 | while(t--){ 13 | solve(); 14 | } 15 | cout< 2 | using namespace std; 3 | 4 | void swap(int *var1, int *var2) 5 | { 6 | int temp = *var1; 7 | *var1 = *var2; 8 | *var2 = temp; 9 | } 10 | //Here we will implement bubbleSort. 11 | void bubbleSort(int arr[], int n) 12 | { 13 | int i, j; 14 | for (i = 0; i < n-1; i++) 15 | //Since, after each iteration rightmost i elements are sorted. 16 | for (j = 0; j < n-i-1; j++) 17 | if (arr[j] > arr[j+1]) 18 | swap(&arr[j], &arr[j+1]); 19 | } 20 | // Function to print array. 21 | void display(int arr[], int size) 22 | { 23 | int i; 24 | for (i=0; i < size; i++) 25 | cout << arr[i] << "\t"; 26 | 27 | cout< 4 | using namespace std; 5 | 6 | // perform bubble sort 7 | void bubbleSort(int array[], int size) { 8 | 9 | // loop to access each array element 10 | for (int step = 0; step < size; ++step) { 11 | 12 | // loop to compare array elements 13 | for (int i = 0; i < size - step; ++i) { 14 | 15 | // compare two adjacent elements 16 | // change > to < to sort in descending order 17 | if (array[i] > array[i + 1]) { 18 | 19 | // swapping elements if elements 20 | // are not in the intended order 21 | int temp = array[i]; 22 | array[i] = array[i + 1]; 23 | array[i + 1] = temp; 24 | } 25 | } 26 | } 27 | } 28 | 29 | // print array 30 | void printArray(int array[], int size) { 31 | for (int i = 0; i < size; ++i) { 32 | cout << " " << array[i]; 33 | } 34 | cout << "\n"; 35 | } 36 | 37 | int main() { 38 | int data[] = {-2, 45, 0, 11, -9}; 39 | 40 | // find array's length 41 | int size = sizeof(data) / sizeof(data[0]); 42 | 43 | bubbleSort(data, size); 44 | 45 | cout << "Sorted Array in Ascending Order:\n"; 46 | printArray(data, size); 47 | } 48 | -------------------------------------------------------------------------------- /algorithms/Longest-Palindromic-Substring.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def longestPalindrome(self, s): 3 | 4 | def helper(s, l, r): 5 | while l >= 0 and r < len(s) and s[l] == s[r]: 6 | l -= 1 7 | r += 1 8 | l += 1 9 | r -= 1 10 | 11 | return ((r - l) + 1, l, r) 12 | 13 | longest = left = right = 0 14 | 15 | for i in range(len(s)): 16 | for j in range(2): 17 | length, l, r = helper(s, i, i + j) 18 | if length > longest: 19 | longest = length 20 | right = r 21 | left = l 22 | 23 | return s[left : right + 1] 24 | -------------------------------------------------------------------------------- /algorithms/Longest_Increasing_Subsequence.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Solution 5 | { 6 | public: 7 | //Function to find length of longest increasing subsequence. 8 | int longestSubsequence(int n, int nums[]) 9 | { 10 | vector dp(n,0); 11 | dp[0]=1; 12 | int ans=1; 13 | for(int i=1; i=0; j--) 16 | { 17 | if(nums[j]>n; 33 | int a[n]; 34 | 35 | //inserting elements to the array 36 | for(int i=0; i>a[i]; 38 | Solution ob; 39 | //calling method longestSubsequence() 40 | cout << ob.longestSubsequence(n, a) << endl; 41 | } 42 | -------------------------------------------------------------------------------- /algorithms/Mergesort.cpp: -------------------------------------------------------------------------------- 1 | void merge(int arr[], int p, int q, int r) { 2 | 3 | int n1 = q - p + 1; 4 | int n2 = r - q; 5 | 6 | int L[n1], M[n2]; 7 | 8 | for (int i = 0; i < n1; i++) 9 | L[i] = arr[p + i]; 10 | for (int j = 0; j < n2; j++) 11 | M[j] = arr[q + 1 + j]; 12 | int i, j, k; 13 | i = 0; 14 | j = 0; 15 | k = p; 16 | while (i < n1 && j < n2) { 17 | if (L[i] <= M[j]) { 18 | arr[k] = L[i]; 19 | i++; 20 | } else { 21 | arr[k] = M[j]; 22 | j++; 23 | } 24 | k++; 25 | } 26 | while (i < n1) { 27 | arr[k] = L[i]; 28 | i++; 29 | k++; 30 | } 31 | 32 | while (j < n2) { 33 | arr[k] = M[j]; 34 | j++; 35 | k++; 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /algorithms/NumberOfWaysInMaze.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | // Number of ways to end in a maze, where you can move only down or right, using recursion 6 | 7 | int mat[20][20]; 8 | 9 | int c = 0; 10 | 11 | void numWays(int i, int j, int n) 12 | { 13 | if (i == n - 1 && j == n - 1) 14 | { 15 | c++; 16 | return; 17 | } 18 | // down 19 | if (i + 1 < n) 20 | { 21 | numWays(i + 1, j, n); 22 | } 23 | // right 24 | if (j + 1 < n) 25 | { 26 | numWays(i, j + 1, n); 27 | } 28 | } 29 | 30 | int main() 31 | { 32 | cout << "Enter input:"; 33 | int n; 34 | cin >> n; 35 | 36 | numWays(0, 0, n); 37 | 38 | cout << "Number of ways from start to end are " << c << endl; 39 | return 0; 40 | } 41 | -------------------------------------------------------------------------------- /algorithms/README.md: -------------------------------------------------------------------------------- 1 | 2 | # ALGORITHMS 3 | 4 | * This folder is having folders for different algorithms. 5 | * Each folder in this folder is having different files keeping same algorithm in different language such as C++, Java and Python. 6 | 7 | 8 | ## Contributing 9 | 10 | Contributions are always welcome! 11 | 12 | See `contributing.md` for ways to get started. 13 | 14 | 15 | ## Feedback 16 | 17 | If you have any feedback, please reach out to us in comment section. 18 | 19 | ## Good Code 20 | 21 | * Good code quality is appreciated. 22 | * Try to keep comments with your code with proper naming conventions. 23 | 24 | 25 | -------------------------------------------------------------------------------- /algorithms/Searching/Best_First_Search.py: -------------------------------------------------------------------------------- 1 | import collections 2 | 3 | def bfs(graph, root): 4 | 5 | visited, queue = set(), collections.deque([root]) 6 | visited.add(root) 7 | 8 | while queue: 9 | 10 | # Dequeue a vertex from queue 11 | vertex = queue.popleft() 12 | print(str(vertex) + " ", end="") 13 | 14 | # If not visited, mark it as visited, and 15 | # enqueue it 16 | for neighbour in graph[vertex]: 17 | if neighbour not in visited: 18 | visited.add(neighbour) 19 | queue.append(neighbour) 20 | 21 | 22 | if __name__ == '__main__': 23 | graph = {0: [1, 2], 1: [2], 2: [3], 3: [1, 2]} 24 | print("Following is Breadth First Traversal: ") 25 | bfs(graph, 0) 26 | -------------------------------------------------------------------------------- /algorithms/Searching/BinarySearch.js: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /algorithms/Searching/DFS.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Graph { 5 | public: 6 | map visited; 7 | map > adj; 8 | 9 | void addEdge(int v, int w); 10 | 11 | void DFS(int v); 12 | }; 13 | 14 | void Graph::addEdge(int v, int w) 15 | { 16 | adj[v].push_back(w); 17 | } 18 | 19 | void Graph::DFS(int v) 20 | { 21 | visited[v] = true; 22 | cout << v << " "; 23 | 24 | list::iterator i; 25 | for (i = adj[v].begin(); i != adj[v].end(); ++i) 26 | if (!visited[*i]) 27 | DFS(*i); 28 | } 29 | 30 | int main() 31 | { 32 | Graph g; 33 | g.addEdge(0, 1); 34 | g.addEdge(0, 2); 35 | g.addEdge(1, 2); 36 | g.addEdge(2, 0); 37 | g.addEdge(2, 3); 38 | g.addEdge(3, 3); 39 | 40 | cout << "Following is Depth First Traversal" 41 | " (starting from vertex 2) \n"; 42 | 43 | g.DFS(2); 44 | 45 | return 0; 46 | } 47 | 48 | -------------------------------------------------------------------------------- /algorithms/Searching/Search_In_a_2D_Matrix.cpp: -------------------------------------------------------------------------------- 1 | // C++ program to search an element in row-wise 2 | // and column-wise sorted matrix 3 | #include 4 | 5 | using namespace std; 6 | 7 | /* Searches the element x in mat[][]. If the 8 | element is found, then prints its position 9 | and returns true, otherwise prints "not found" 10 | and returns false */ 11 | int search(int mat[4][4], int n, int x) 12 | { 13 | if (n == 0) 14 | return -1; 15 | 16 | // traverse through the matrix 17 | for (int i = 0; i < n; i++) { 18 | for (int j = 0; j < n; j++) 19 | // if the element is found 20 | if (mat[i][j] == x) { 21 | cout << "Element found at (" << i << ", " 22 | << j << ")\n"; 23 | return 1; 24 | } 25 | } 26 | 27 | cout << "n Element not found"; 28 | return 0; 29 | } 30 | 31 | // Driver code 32 | int main() 33 | { 34 | int mat[4][4] = { { 10, 20, 30, 40 }, 35 | { 15, 25, 35, 45 }, 36 | { 27, 29, 37, 48 }, 37 | { 32, 33, 39, 50 } }; 38 | 39 | // Function call 40 | search(mat, 4, 29); 41 | 42 | return 0; 43 | } 44 | -------------------------------------------------------------------------------- /algorithms/Sorting_Algorithms/C++/Counting_sort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | #define RANGE 255 5 | 6 | void countSort(char arr[]) 7 | { 8 | char output[strlen(arr)]; 9 | 10 | int count[RANGE + 1], i; 11 | memset(count, 0, sizeof(count)); 12 | 13 | for (i = 0; arr[i]; ++i) 14 | ++count[arr[i]]; 15 | 16 | for (i = 1; i <= RANGE; ++i) 17 | count[i] += count[i - 1]; 18 | 19 | for (i = 0; arr[i]; ++i) { 20 | output[count[arr[i]] - 1] = arr[i]; 21 | --count[arr[i]]; 22 | } 23 | 24 | for (i = 0; arr[i]; ++i) 25 | arr[i] = output[i]; 26 | } 27 | 28 | int main() 29 | { 30 | char arr[] = "Aforapple"; 31 | 32 | countSort(arr); 33 | 34 | cout << "Sorted character array is " << arr; 35 | return 0; 36 | } 37 | 38 | -------------------------------------------------------------------------------- /algorithms/Sorting_Algorithms/C++/DNFAlgo.cpp: -------------------------------------------------------------------------------- 1 | // DNF : Dutch National Flag algo is used to sort an array consisting three different types elements 2 | 3 | #include 4 | using namespace std; 5 | 6 | void DNF(int nums[], int n) 7 | { 8 | 9 | int low = 0, mid = 0, high = n - 1; 10 | 11 | while (mid <= high) 12 | { 13 | 14 | if (nums[mid] == 0) 15 | { 16 | swap(nums[mid], nums[low]); 17 | mid++; 18 | low++; 19 | } 20 | else if (nums[mid] == 1) 21 | { 22 | mid++; 23 | } 24 | else 25 | { 26 | swap(nums[mid], nums[high]); 27 | 28 | high--; 29 | } 30 | } 31 | } 32 | // Function to print array arr[] 33 | void printArray(int arr[], int arr_size) 34 | { 35 | // Iterate and print every element 36 | for (int i = 0; i < arr_size; i++) 37 | cout << arr[i] << " "; 38 | } 39 | 40 | // Driver Code 41 | int main() 42 | { 43 | int arr[] = {0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1}; 44 | int n = sizeof(arr) / sizeof(arr[0]); 45 | 46 | DNF(arr, n); 47 | 48 | printArray(arr, n); 49 | 50 | return 0; 51 | } -------------------------------------------------------------------------------- /algorithms/Sorting_Algorithms/C++/insertion sort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | void Insertion_sort(int n,int A[]) 5 | // 2 sides ; (1 sotrted ,unsorted/) 6 | { int value; 7 | int hole; 8 | for(int i=0; i0) && (A[hole-1]>value)) 14 | { 15 | A[hole]=A[hole-1]; 16 | hole= hole-1; 17 | 18 | } 19 | A[hole]=value; 20 | } 21 | 22 | 23 | cout<<"\n After sort"; 24 | 25 | for(int i=0; i>size; 38 | int A[10]; 39 | cout<<"Enter the values of aray\n"; 40 | for(int i=0; i>A[i]; 44 | } 45 | Insertion_sort(size,A); 46 | return 0; 47 | } 48 | -------------------------------------------------------------------------------- /algorithms/Stack/Applications/Reverse_Function(stack).cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | void reverse_with_array(char C[] ,int n) 6 | { 7 | //putting all values in stack 8 | stack S; 9 | for(int i=0; i topoSort(int V, vector adj[]) 5 | { 6 | queue q; 7 | vector indegree(V,0); 8 | 9 | for(int i=0; i topo; 19 | while(!q.empty()){ 20 | 21 | int node = q.front(); 22 | q.pop(); 23 | topo.push_back(node); 24 | 25 | for(auto it : adj[node]){ 26 | indegree[it]--; 27 | if(indegree[it] == 0){ 28 | q.push(it); 29 | } 30 | } 31 | 32 | } 33 | return topo; 34 | 35 | } 36 | }; 37 | -------------------------------------------------------------------------------- /algorithms/ar-Cpuschpr: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /algorithms/ar-binsrt/C++/Bin_Sort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | // Function to sort arr[] of 7 | // size n using bucket sort 8 | void bucketSort(float arr[], int n) 9 | { 10 | 11 | // 1) Create n empty buckets 12 | vector b[n]; 13 | 14 | // 2) Put array elements 15 | // in different buckets 16 | for (int i = 0; i < n; i++) { 17 | int bi = n * arr[i]; // Index in bucket 18 | b[bi].push_back(arr[i]); 19 | } 20 | 21 | // 3) Sort individual buckets 22 | for (int i = 0; i < n; i++) 23 | sort(b[i].begin(), b[i].end()); 24 | 25 | // 4) Concatenate all buckets into arr[] 26 | int index = 0; 27 | for (int i = 0; i < n; i++) 28 | for (int j = 0; j < b[i].size(); j++) 29 | arr[index++] = b[i][j]; 30 | } 31 | 32 | int main() 33 | { 34 | float arr[] 35 | = {0.8, 0.2, 0.66, 0.5, 0.1, 0.9, 0.336, 0.982, 0.275, 0.9374, 0.125, 0.8754, 0.925}; 36 | int n = sizeof(arr) / sizeof(arr[0]); 37 | bucketSort(arr, n); 38 | 39 | cout << "Sorted array is \n"; 40 | for (int i = 0; i < n; i++) 41 | cout << arr[i] << " "; 42 | return 0; 43 | } -------------------------------------------------------------------------------- /algorithms/ar-binsrt/C/bin-sort.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | /* Function for bucket sort */ 4 | void bin_sort(int array[], int n) 5 | { 6 | int num_a, num_b; 7 | int count[n]; 8 | for (num_a = 0; num_a < n; num_a++) 9 | count[num_a] = 0; 10 | 11 | for (num_a = 0; num_a < n; num_a++) 12 | (count[array[num_a]])++; 13 | 14 | for (num_a = 0, num_b = 0; num_a < n; num_a++) 15 | for(; count[num_a] > 0; (count[num_a])--) 16 | array[num_b++] = num_a; 17 | } 18 | /* End of Bucket_Sort() */ 19 | 20 | /* The main() begins */ 21 | int main() 22 | { 23 | int array[100], num_a, num; 24 | 25 | printf("Enter the size of array : "); 26 | scanf("%d", &num); 27 | printf("Enter the %d elements to be sorted:\n",num); 28 | for (num_a = 0; num_a < num; num_a++) 29 | scanf("%d", &array[num_a]); 30 | printf("\nThe array of elements before sorting : \n"); 31 | for (num_a = 0; num_a < num; num_a++) 32 | printf("%d ", array[num_a]); 33 | printf("\nThe array of elements after sorting : \n"); 34 | bin_sort(array, num); 35 | for (num_a = 0; num_a < num; num_a++) 36 | printf("%d ", array[num_a]); 37 | printf("\n"); 38 | return 0; 39 | } -------------------------------------------------------------------------------- /algorithms/ar-binsrt/javascript/binSort.js: -------------------------------------------------------------------------------- 1 | const binSort = arr => { 2 | if (arr.length === 0) { 3 | return arr 4 | } 5 | let i, 6 | minValue = arr[0], 7 | maxValue = arr[0], 8 | bucketSize = 5 9 | arr.forEach(function (currentVal) { 10 | if (currentVal < minValue) { 11 | minValue = currentVal 12 | } else if (currentVal > maxValue) { 13 | maxValue = currentVal 14 | } 15 | }) 16 | let bucketCount = Math.floor((maxValue - minValue) / bucketSize) + 1 17 | let allBuckets = new Array(bucketCount) 18 | for (i = 0; i < allBuckets.length; i++) { 19 | allBuckets[i] = [] 20 | } 21 | arr.forEach(function (currentVal) { 22 | allBuckets[Math.floor((currentVal - minValue) / bucketSize)].push( 23 | currentVal, 24 | ) 25 | }) 26 | arr.length = 0 27 | allBuckets.forEach(function (bucket) { 28 | let length = arr.length 29 | let i, j 30 | for (i = 1; i < length; i++) { 31 | let temp = arr[i] 32 | for (j = i - 1; j >= 0 && arr[j] > temp; j--) { 33 | arr[j + 1] = arr[j] 34 | } 35 | arr[j + 1] = temp 36 | } 37 | bucket.forEach(function (element) { 38 | arr.push(element) 39 | }) 40 | }) 41 | return arr 42 | } 43 | 44 | const sampleData = [32, 6, 34, 4, 78, 1, 6767, 4, 65, 34, 879, 7] 45 | console.log(binSort(sampleData)) 46 | -------------------------------------------------------------------------------- /algorithms/ar-binsrt/python3/ar_binsrt.py: -------------------------------------------------------------------------------- 1 | # Bucket Sort Implementation in Python 2 | 3 | def bucketSort(array): 4 | bucket = [] 5 | 6 | # Creating the empty buckets 7 | for i in range(len(array)): 8 | bucket.append([]) 9 | 10 | # Insert elements into their respective buckets 11 | for j in array: 12 | index_b = int(10 * j) 13 | bucket[index_b].append(j) 14 | 15 | # Sort the elements of each bucket 16 | for i in range(len(array)): 17 | bucket[i] = sorted(bucket[i]) 18 | 19 | # Get the sorted elements 20 | k = 0 21 | for i in range(len(array)): 22 | for j in range(len(bucket[i])): 23 | array[k] = bucket[i][j] 24 | k += 1 25 | return array 26 | 27 | #Input array 28 | array = [.42, .32, .33, .52, .37, .47, .51] 29 | print("Sorted Array in descending order is") 30 | print(bucketSort(array)) -------------------------------------------------------------------------------- /algorithms/ar-bm/c++/boyermoree.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | // Function to find majority element 4 | int findMajority(int arr[], int n) 5 | { 6 | int i, candidate = -1, votes = 0; 7 | // Finding majority candidate 8 | for (i = 0; i < n; i++) { 9 | if (votes == 0) { 10 | candidate = arr[i]; 11 | votes = 1; 12 | } 13 | else { 14 | if (arr[i] == candidate) 15 | votes++; 16 | else 17 | votes--; 18 | } 19 | } 20 | int count = 0; 21 | // Checking if majority candidate occurs more than n/2 22 | // times 23 | for (i = 0; i < n; i++) { 24 | if (arr[i] == candidate) 25 | count++; 26 | } 27 | 28 | if (count > n / 2) 29 | return candidate; 30 | return -1; 31 | } 32 | int main() 33 | { 34 | int arr[] = { 1, 1, 1, 1, 2, 3, 4 }; 35 | int n = sizeof(arr) / sizeof(arr[0]); 36 | int majority = findMajority(arr, n); 37 | cout << " The majority element is : " << majority; 38 | return 0; 39 | } 40 | -------------------------------------------------------------------------------- /algorithms/ar-bogosort/elixir/bogosort.exs: -------------------------------------------------------------------------------- 1 | defmodule Bogosort do 2 | def sort(list) when is_list(list) do 3 | list 4 | |> is_sorted?() 5 | |> if do 6 | list 7 | else 8 | list 9 | |> Enum.shuffle() 10 | |> sort() 11 | end 12 | end 13 | 14 | defp is_sorted?(list) do 15 | Enum.reduce(list, {true, nil}, fn 16 | first_num, {true, nil} -> 17 | {true, first_num} 18 | 19 | num, {sorted?, last_num} -> 20 | {num >= last_num and sorted?, num} 21 | end) 22 | |> elem(0) 23 | end 24 | end 25 | 26 | 1..5 27 | |> Enum.shuffle() 28 | |> IO.inspect(label: "Unsorted list") 29 | |> Bogosort.sort() 30 | |> IO.inspect(label: "Sorted list") 31 | -------------------------------------------------------------------------------- /algorithms/ar-bogosort/javascript/bogosort.js: -------------------------------------------------------------------------------- 1 | function bogoSort(list) { 2 | let result = [...list] 3 | while (!isSorted(result)) { 4 | scramble(result) 5 | } 6 | return result 7 | } 8 | 9 | function isSorted(list) { 10 | for (let i = 1; i < list.length; i++) { 11 | if (!(list[i] >= list[i - 1])) { 12 | return false 13 | } 14 | } 15 | return true 16 | } 17 | 18 | function scramble(list) { 19 | for (let i = list.length - 1; i > 0; i--) { 20 | let newIndex = Math.floor(Math.random() * (i)) 21 | let aux = list[i] 22 | list[i] = list[newIndex] 23 | list[newIndex] = aux 24 | } 25 | } 26 | 27 | const list = [3, 5, 6, 2, 5] 28 | 29 | // console.time("sort") 30 | const sortedList = bogoSort(list) 31 | // console.timeEnd("sort") 32 | 33 | console.log({ 34 | list, 35 | sortedList 36 | }) -------------------------------------------------------------------------------- /algorithms/ar-bogosort/python/bogosort.py: -------------------------------------------------------------------------------- 1 | import random 2 | 3 | def bogoSort(a): 4 | n = len(a) 5 | while (is_sorted(a)== False): 6 | shuffle(a) 7 | 8 | def is_sorted(a): 9 | n = len(a) 10 | for i in range(0, n-1): 11 | if (a[i] > a[i+1] ): 12 | return False 13 | return True 14 | 15 | def shuffle(a): 16 | n = len(a) 17 | for i in range (0,n): 18 | r = random.randint(0,n-1) 19 | a[i], a[r] = a[r], a[i] 20 | 21 | a = [] 22 | m = int(input("Enter number of elements : ")) 23 | for i in range(0, m): 24 | ele = int(input()) 25 | a.append(ele) 26 | 27 | bogoSort(a) 28 | print("Sorted array :") 29 | for i in range(len(a)): 30 | print (a[i],end=" ") 31 | -------------------------------------------------------------------------------- /algorithms/ar-bogosort/typescript/bogosort.ts: -------------------------------------------------------------------------------- 1 | let input = [1,2,3,4] 2 | input = shuffle(input) 3 | var shuffleCount = 0; 4 | function bogosort(arr:number[]){ 5 | while (!iSsorted(arr)) { 6 | shuffleCount++; 7 | arr = shuffle(arr); 8 | } 9 | return {shuffleCount, arr} 10 | } 11 | 12 | function iSsorted(array:number[]) { 13 | for (var i = 0; i < array.length - 1; i++) { 14 | if (array[i] <= array[i + 1]) { 15 | continue; 16 | } else { 17 | return false; 18 | } 19 | } 20 | return true 21 | } 22 | 23 | function shuffle(arr:number[]) { 24 | return arr.sort(() => Math.random() - 0.5); 25 | } 26 | 27 | let solve = bogosort(input) 28 | console.log(`Finished within ${solve.shuffleCount} | ${solve.arr.join(",")}`) -------------------------------------------------------------------------------- /algorithms/ar-bsrh/Binary Sort in C#: -------------------------------------------------------------------------------- 1 | // C# Program implementing 2 | // binary insertion sort 3 | using System; 4 | 5 | class GFG { 6 | 7 | public static void Main() 8 | { 9 | int[] arr = { 37, 23, 0, 17, 12, 72, 10 | 31, 46, 100, 88, 54 }; 11 | 12 | sort(arr); 13 | 14 | for (int i = 0; i < arr.Length; i++) 15 | Console.Write(arr[i] + " "); 16 | } 17 | 18 | // Driver Code 19 | public static void sort(int[] array) 20 | { 21 | for (int i = 1; i < array.Length; i++) 22 | { 23 | int x = array[i]; 24 | 25 | // Find location to insert using 26 | // binary search 27 | int j = Math.Abs( 28 | Array.BinarySearch(array, 29 | 0, i, x) + 1); 30 | 31 | // Shifting array to one location right 32 | System.Array.Copy(array, j, 33 | array, j + 1, 34 | i - j); 35 | 36 | // Placing element at its correct 37 | // location 38 | array[j] = x; 39 | } 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /algorithms/ar-bsrh/C++/Binary_search.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | int binary_search(int arr[],int n,int key) 4 | { 5 | int low=0,high=n-1; 6 | while(low<=high) 7 | { 8 | int mid=(low+high)/2; 9 | if(arr[mid]==key) 10 | return mid+1; 11 | else if(arr[mid]>arr[i]; 29 | } 30 | cout<<"Enter key to search in data\n"; 31 | int key; cin>>key; 32 | int x=binary_search(arr,n,key); 33 | if(x==-1) 34 | { 35 | cout<<"Element is not present\n"; 36 | } 37 | else{ 38 | cout<<"Element present at location "< 2 | int binary_search(int arr[],int n,int key) 3 | { 4 | int low=0,high=n-1; 5 | int mid=0; 6 | while(low<=high) 7 | { 8 | mid=(low+high)/2; 9 | if(arr[mid]==key) 10 | return mid+1; 11 | else if(arr[mid]x)r=mid-1; 9 | else l=mid+1; 10 | } 11 | return -1; 12 | } 13 | 14 | public static void main(String args[]) { 15 | int array[] = { 10, 20, 30, 40, 50, 60 }; 16 | int x = 50; 17 | 18 | int result = binarySearch(array, x); 19 | 20 | if (result == -1) 21 | System.out.print("Element not found"); 22 | else 23 | System.out.print("Element found at index: " + result); 24 | } 25 | } -------------------------------------------------------------------------------- /algorithms/ar-bsrh/Javascript/BinarySearch.js: -------------------------------------------------------------------------------- 1 | function binarySearch(arr,x){ 2 | var l=0,r=arr.length-1; 3 | while(l<=r){ 4 | var mid = Math.floor(l+(r-l)/2); 5 | if(arr[mid]===x){ 6 | return mid; 7 | } 8 | else if(arr[mid]>x){ 9 | r=mid-1; 10 | } 11 | else l=mid+1; 12 | } 13 | return -1; 14 | } 15 | 16 | function main(){ 17 | var a = [1,2,3,4,5]; 18 | if(binarySearch(a,4)===-1){ 19 | console.log("Element not found."); 20 | } 21 | else { 22 | console.log(`Element found at ${binarySearch(a,4)}`) 23 | } 24 | } 25 | 26 | main(); -------------------------------------------------------------------------------- /algorithms/ar-bsrh/python/Binary_search.py: -------------------------------------------------------------------------------- 1 | def binary_search(arr,n,key): 2 | low=0 3 | high=n-1 4 | while low<=high: 5 | mid=(low+high)//2 6 | if arr[mid]==key: 7 | return mid+1 8 | elif arr[mid]< key: 9 | low=mid+1 10 | else: 11 | high=mid-1 12 | return -1 13 | 14 | if __name__ == "__main__": 15 | n=int(input('Enter number of Elements: ')) 16 | arr=list(map(int,input('Enter data in sorted order: ').split()))[:n] 17 | key=int(input('Enter key to search: ')) 18 | x=binary_search(arr,n,key) 19 | if x==-1: 20 | print('Element not found') 21 | else: 22 | print("Element found at position ",x) 23 | -------------------------------------------------------------------------------- /algorithms/ar-bsrt/C#/BubbleSort.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace BubbleSort { 4 | public class MySort { 5 | static void Main(string[] args) { 6 | int[] arr = { 78, 55, 45, 98, 13 }; 7 | int temp; 8 | 9 | for (int j = 0; j <= arr.Length - 2; j++) { 10 | for (int i = 0; i <= arr.Length - 2; i++) { 11 | if (arr[i] > arr[i + 1]) { 12 | temp= arr[i + 1]; 13 | arr[i + 1] = arr[i]; 14 | arr[i] = temp; 15 | } 16 | } 17 | } 18 | 19 | Console.WriteLine("Sorted:"); 20 | foreach (int p in arr) 21 | Console.Write(p + " "); 22 | Console.Read(); 23 | } 24 | } 25 | } -------------------------------------------------------------------------------- /algorithms/ar-bsrt/C/bubblesort.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | void bubble_sort( int A[ ], int n ) { 4 | 5 | int temp; 6 | for(int k = 0; k< n-1; k++) { 7 | for(int i = 0; i < n-k-1; i++) { // (n-k-1) is for ignoring comparisons of elements which have already been compared in earlier iterations 8 | if(A[ i ] > A[ i+1] ) { 9 | temp = A[ i ]; // here swapping of positions is being done. 10 | A[ i ] = A[ i+1 ]; 11 | A[ i + 1] = temp; 12 | } 13 | } 14 | } 15 | } 16 | 17 | int main() 18 | { 19 | int n,i; 20 | scanf("%d", &n); 21 | int A[n]; 22 | for(i=0;i nums[i] { 20 | nums[i], nums[i-1] = nums[i-1], nums[i] 21 | swappedVal = true 22 | } 23 | } 24 | if !swappedVal { 25 | sorted = true 26 | } 27 | size = size - 1 28 | } 29 | 30 | return nums 31 | } 32 | -------------------------------------------------------------------------------- /algorithms/ar-bsrt/java/Bubble_sort.java: -------------------------------------------------------------------------------- 1 | class BubbleSort 2 | { 3 | void bubbleSort(int arr[]) 4 | { 5 | int n = arr.length; 6 | for (int i = 0; i < n-1; i++) 7 | for (int j = 0; j < n-i-1; j++) 8 | if (arr[j] > arr[j+1]) 9 | { 10 | int temp = arr[j]; 11 | arr[j] = arr[j+1]; 12 | arr[j+1] = temp; 13 | } 14 | } 15 | 16 | void printArray(int arr[]) 17 | { 18 | int n = arr.length; 19 | for (int i=0; i values[j+1]){ 6 | let temp = values[j] 7 | values[j] = values[j+1]; 8 | values[j+1] = temp; 9 | } 10 | } 11 | } 12 | for(l = 0; l < n; l++) 13 | { 14 | console.log(values[l]) 15 | } 16 | } 17 | let hello = [10, 21,2,4,78] 18 | bubbleSort(hello) -------------------------------------------------------------------------------- /algorithms/ar-bsrt/python2/bubblesort.py: -------------------------------------------------------------------------------- 1 | arr = [int(i) for i in raw_input("Enter elements seperated by space : ").split()] 2 | 3 | for i in range(0,len(arr)-1): 4 | for j in range(0,len(arr)-i-1): 5 | if(arr[j] > arr[j+1]): 6 | arr[j],arr[j+1] = arr[j+1],arr[j]; 7 | print"\n\nfinal array is ",arr; 8 | -------------------------------------------------------------------------------- /algorithms/ar-bsrt/python3/ar_bsrt.py: -------------------------------------------------------------------------------- 1 | def bubble_sort(arr): 2 | for i in range(len(arr)): 3 | for j in range(i + 1, len(arr)): 4 | if arr[i] > arr[j]: 5 | temp = arr[i] 6 | arr[i] = arr[j] 7 | arr[j] = temp 8 | return arr 9 | 10 | 11 | if __name__ == "__main__": 12 | print(bubble_sort([5, 4, 3, 2, 1])) 13 | -------------------------------------------------------------------------------- /algorithms/ar-bsrt/python3/bucket_sort.py: -------------------------------------------------------------------------------- 1 | def insertionSort(b): 2 | for i in range(1, len(b)): 3 | up = b[i] 4 | j = i - 1 5 | while j >= 0 and b[j] > up: 6 | b[j + 1] = b[j] 7 | j -= 1 8 | b[j + 1] = up 9 | return b 10 | 11 | def bucketSort(x): 12 | arr = [] 13 | slot_num = 10 # 10 means 10 slots, each 14 | # slot's size is 0.1 15 | for i in range(slot_num): 16 | arr.append([]) 17 | 18 | # Put array elements in different buckets 19 | for j in x: 20 | index_b = int(slot_num * j) 21 | arr[index_b].append(j) 22 | 23 | # Sort individual buckets 24 | for i in range(slot_num): 25 | arr[i] = insertionSort(arr[i]) 26 | 27 | # concatenate the result 28 | k = 0 29 | for i in range(slot_num): 30 | for j in range(len(arr[i])): 31 | x[k] = arr[i][j] 32 | k += 1 33 | return x 34 | 35 | # Driver Code 36 | x = [0.897, 0.565, 0.656, 37 | 0.1234, 0.665, 0.3434] 38 | print("Sorted Array is") 39 | print(bucketSort(x)) 40 | -------------------------------------------------------------------------------- /algorithms/ar-bsrt/python3/test_ar_bsrt.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | from ar_bsrt import bubble_sort 3 | 4 | 5 | class Test_ar_bsrt(unittest.TestCase): 6 | """docstring for Test_ar_bsrt""" 7 | def test(self): 8 | arr = [5, 4, 3, 2, 1] 9 | self.assertEqual(bubble_sort(arr), [1, 2, 3, 4, 5]) 10 | 11 | 12 | if __name__ == "__main__": 13 | unittest.main() 14 | -------------------------------------------------------------------------------- /algorithms/ar-bsrt/typescript/ar-bsrt.ts: -------------------------------------------------------------------------------- 1 | const bubbleSort = (values: number[]) => { 2 | const n = values.length; 3 | const result = [...values]; 4 | 5 | for (let i = 0; i < n - 1; i++) { 6 | for (let j = 0; j < n - 1; j++) { 7 | if (result[j] > result[j + 1]) { 8 | const temp = result[j]; 9 | result[j] = result[j + 1]; 10 | result[j + 1] = temp; 11 | } 12 | } 13 | } 14 | 15 | return result; 16 | }; 17 | 18 | console.log(bubbleSort([23, 42, 4, 15, 8, 16])); 19 | 20 | -------------------------------------------------------------------------------- /algorithms/ar-cochprb/C++/CoinChangeProblem.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int count( int S[], int m, int n ) 5 | { 6 | int i, j, x, y; 7 | 8 | int table[n + 1][m]; 9 | 10 | for (i = 0; i < m; i++) 11 | table[0][i] = 1; 12 | 13 | for (i = 1; i < n + 1; i++) 14 | { 15 | for (j = 0; j < m; j++) 16 | { 17 | x = (i-S[j] >= 0) ? table[i - S[j]][j] : 0; 18 | 19 | y = (j >= 1) ? table[i][j - 1] : 0; 20 | 21 | table[i][j] = x + y; 22 | } 23 | } 24 | return table[n][m - 1]; 25 | } 26 | 27 | int main() 28 | { 29 | int arr[] = {1, 3, 5,}; 30 | int m = sizeof(arr)/sizeof(arr[0]); 31 | int n = 4; 32 | cout << count(arr, m, n); 33 | return 0; 34 | } 35 | //c++ using dynamic programming is used in this code 36 | -------------------------------------------------------------------------------- /algorithms/ar-cochprb/C++/Coin_change_Problem_method2.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int count(int S[], int m, int n) 5 | { 6 | if (n == 0) 7 | return 1; 8 | 9 | if (n < 0) 10 | return 0; 11 | 12 | if (m <= 0 && n >= 1) 13 | return 0; 14 | 15 | return count(S, m - 1, n) + 16 | count(S, m, n - S[m - 1]); 17 | } 18 | 19 | int main() 20 | { 21 | int i, j; 22 | int arr[] = { 1, 3, 5 }; 23 | int m = sizeof(arr) / sizeof(arr[0]); 24 | 25 | cout << " " << count(arr, m, 4); 26 | 27 | return 0; 28 | } 29 | -------------------------------------------------------------------------------- /algorithms/ar-cochprb/C++/readme.md: -------------------------------------------------------------------------------- 1 | fixed link 2 | -------------------------------------------------------------------------------- /algorithms/ar-cochprb/C/ar-cochprb.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int count( int S[], int m, int n ) 4 | { 5 | int i, j, x, y; 6 | 7 | // We need n+1 rows as the table is constructed in bottom up manner using the base case 0 value case (n = 0) 8 | int table[n+1][m]; 9 | 10 | // Fill the entries for 0 value case (n = 0) 11 | for (i=0; i= 0)? table[i - S[j]][j]: 0; 21 | 22 | // Count of solutions excluding S[j] 23 | y = (j >= 1)? table[i][j-1]: 0; 24 | 25 | // total count 26 | table[i][j] = x + y; 27 | } 28 | } 29 | return table[n][m-1]; 30 | } 31 | 32 | // Driver program to test above function 33 | int main() 34 | { 35 | int arr[] = {1, 2, 3}; 36 | int m = sizeof(arr)/sizeof(arr[0]); 37 | int n = 4; 38 | printf(" %d ", count(arr, m, n)); 39 | return 0; 40 | } -------------------------------------------------------------------------------- /algorithms/ar-cochprb/Java/Main.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | class Main { 4 | /** 5 | *Using Dynamic Programming 6 | *@param int //Amount of value 7 | *@param int[] //Number values to add to amount 8 | **/ 9 | public static int coinChange(int n, int[] coins){ 10 | int[] ways = new int[n+1]; 11 | ways[0] = 1; 12 | for(int i=0; i= coins[i]){ 15 | ways[j] += ways[j-coins[i]]; 16 | } 17 | } 18 | } 19 | return ways[n]; 20 | } 21 | 22 | public static void main(String[] args) { 23 | int value; 24 | Scanner sc = new Scanner(System.in); 25 | System.out.print("Enter change -> "); 26 | value = sc.nextInt(); 27 | System.out.print("Amount of coins -> "); 28 | int[] coins = new int[sc.nextInt()]; 29 | System.out.println("Coin values: "); 30 | for(int i=0; i < coins.length; i++){ 31 | int coin = sc.nextInt(); 32 | coins[i] = coin; 33 | } 34 | System.out.print("Total combinations: "); 35 | System.out.println(coinChange(value, coins)); 36 | } 37 | } -------------------------------------------------------------------------------- /algorithms/ar-cochprb/Java/coinflip.java: -------------------------------------------------------------------------------- 1 | class Main 2 | { 3 | // Function to find the total number of ways to get a change 4 | // of `target` from an unlimited supply of coins in set `S` 5 | public static int count(int[] S, int target) 6 | { 7 | // if the total is 0, return 1 8 | if (target == 0) { 9 | return 1; 10 | } 11 | 12 | // return 0 if total becomes negative 13 | if (target < 0) { 14 | return 0; 15 | } 16 | 17 | // initialize the total number of ways to 0 18 | int result = 0; 19 | 20 | // do for each coin 21 | for (int c: S) 22 | { 23 | // recur to see if total can be reached by including current coin `c` 24 | result += count(S, target - c); 25 | } 26 | 27 | // return the total number of ways 28 | return result; 29 | } 30 | 31 | public static void main(String[] args) 32 | { 33 | // `n` coins of given denominations 34 | int[] S = { 1, 2, 3 }; 35 | 36 | // total change required 37 | int target = 4; 38 | 39 | System.out.println("The total number of ways to get the desired change is " 40 | + count(S, target)); 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /algorithms/ar-cochprb/Javascript/coin_change.js: -------------------------------------------------------------------------------- 1 | function change(coins, i, amount) { 2 | if (amount === 0) { 3 | return 1; 4 | } 5 | if (amount < 0) { 6 | return 0; 7 | } 8 | if (i <= 0) { 9 | return 0; 10 | } 11 | 12 | return ( 13 | change(coins, i - 1, coins[i - 1]) + change(coins, i, amount - coins[i - 1]) 14 | ); 15 | } 16 | let coinArr = [1, 2, 3]; 17 | console.log(change(coinArr, coinArr.length, 4)); 18 | -------------------------------------------------------------------------------- /algorithms/ar-cochprb/python2/coinchange.py: -------------------------------------------------------------------------------- 1 | def countcombo(coins, n, sum):#using DP approach, google for more 2 | if (sum == 0): 3 | return 1 4 | if (sum < 0): 5 | return 0 6 | if (n <= 0): 7 | return 0 8 | return countcombo(coins, n - 1, sum) + countcombo(coins, n, sum-coins[n-1]) 9 | 10 | if __name__=="__main__": 11 | coin_arr = [int(i) for i in raw_input("Enter unique(non repeating ) coins seperated by space :").split()] 12 | #removing duplicates if any 13 | coin_arr = list(set(coin_arr)) 14 | s = int(raw_input("\nEnter needed sum : ")) 15 | print"\n\nAll possible coin change for enter sum ",s," is ",countcombo(coin_arr,len(coin_arr),s) 16 | 17 | -------------------------------------------------------------------------------- /algorithms/ar-cochprb/python3/CoinChanProblem.py: -------------------------------------------------------------------------------- 1 | def count(S, m, n ): 2 | if (n == 0): 3 | return 1 4 | 5 | if (n < 0): 6 | return 0; 7 | 8 | if (m <=0 and n >= 1): 9 | return 0 10 | 11 | return count( S, m - 1, n ) + count( S, m, n-S[m-1] ); 12 | 13 | if __name__ == "__main__": 14 | arr = [1, 2, 3] 15 | m = len(arr) 16 | print(count(arr, m, 4)) -------------------------------------------------------------------------------- /algorithms/ar-csrt/C++/count_sort.cpp: -------------------------------------------------------------------------------- 1 | // C++ Program for counting sort 2 | #include 3 | #include 4 | using namespace std; 5 | #define RANGE 255 6 | 7 | 8 | void countSort(char arr[]) 9 | { 10 | char output[strlen(arr)]; 11 | 12 | // Create a count array to store count of individual characters and initialize count array as 0 13 | int count[RANGE + 1], i; 14 | memset(count, 0, sizeof(count)); 15 | 16 | // Store count of each character 17 | for (i = 0; arr[i]; ++i) 18 | ++count[arr[i]]; 19 | 20 | // Change count[i] so that count[i] now contains actual position of this character in output array 21 | for (i = 1; i <= RANGE; ++i) 22 | count[i] += count[i - 1]; 23 | 24 | // Build the output character array 25 | for (i = 0; arr[i]; ++i) { 26 | output[count[arr[i]] - 1] = arr[i]; 27 | --count[arr[i]]; 28 | } 29 | 30 | 31 | // Copy the output array to arr, so that arr now contains sorted characters 32 | for (i = 0; arr[i]; ++i) 33 | arr[i] = output[i]; 34 | } 35 | 36 | int main() 37 | { 38 | char arr[] = "countsort"; 39 | 40 | countSort(arr); 41 | 42 | cout << "Sorted character array is " << arr; 43 | return 0; 44 | } 45 | 46 | -------------------------------------------------------------------------------- /algorithms/ar-csrt/C/Count_Sort.c: -------------------------------------------------------------------------------- 1 | // C Program for counting sort 2 | #include 3 | #include 4 | 5 | int main() 6 | { 7 | char arr[] = "countsort"; 8 | char temp; 9 | int i,j; 10 | 11 | for(i=0;arr[i]!='\0';i++) 12 | { 13 | for(j=0;jarr[j+1]){ 17 | temp=arr[j]; 18 | arr[j]=arr[j+1]; 19 | arr[j+1]=temp; 20 | 21 | } 22 | } 23 | } 24 | 25 | printf("Sorted character array is = %s",arr); 26 | return 0; 27 | } 28 | -------------------------------------------------------------------------------- /algorithms/ar-csrt/Javascript/count_sort.js: -------------------------------------------------------------------------------- 1 | let countingSort = (arr, min, max) => { 2 | let i = min, 3 | j = 0, 4 | count = []; 5 | for (i; i <= max; i++) { 6 | count[i] = 0; 7 | } 8 | for (i = 0; i < arr.length; i++) { 9 | count[arr[i]] += 1; 10 | } 11 | for (i = min; i <= max; i++) { 12 | while (count[i] > 0) { 13 | arr[j] = i; 14 | j++; 15 | count[i]--; 16 | } 17 | } 18 | return arr; 19 | }; 20 | 21 | let data = [4, 2, 2, 8, 3, 3, 1]; 22 | data = countingSort(data, 1, 8); 23 | console.log(data); 24 | -------------------------------------------------------------------------------- /algorithms/ar-csrt/Python/Count_Sort.py: -------------------------------------------------------------------------------- 1 | # Counting sort in Python programming 2 | 3 | 4 | def countingSort(array): 5 | size = len(array) 6 | output = [0] * size 7 | 8 | # Initialize count array 9 | count = [0] * 10 10 | 11 | # Store the count of each elements in count array 12 | for i in range(0, size): 13 | count[array[i]] += 1 14 | 15 | # Store the cummulative count 16 | for i in range(1, 10): 17 | count[i] += count[i - 1] 18 | 19 | # Find the index of each element of the original array in count array 20 | # place the elements in output array 21 | i = size - 1 22 | while i >= 0: 23 | output[count[array[i]] - 1] = array[i] 24 | count[array[i]] -= 1 25 | i -= 1 26 | 27 | # Copy the sorted elements into original array 28 | for i in range(0, size): 29 | array[i] = output[i] 30 | 31 | 32 | data = [4, 2, 2, 8, 3, 3, 1] 33 | countingSort(data) 34 | print("Sorted Array in Ascending Order: ") 35 | print(data) 36 | -------------------------------------------------------------------------------- /algorithms/ar-csrt/Python3/Count Sort.py: -------------------------------------------------------------------------------- 1 | #Program for Count Sort by Animesh Tiwari 2 | def countingSort(inputArray): 3 | maxElement= max(inputArray) 4 | countArrayLength = maxElement+1 5 | countArray = [0] * countArrayLength 6 | for el in inputArray: 7 | countArray[el] += 1 8 | 9 | for i in range(1, countArrayLength): 10 | countArray[i] += countArray[i-1] 11 | outputArray = [0] * len(inputArray) 12 | i = len(inputArray) - 1 13 | while i >= 0: 14 | currentEl = inputArray[i] 15 | countArray[currentEl] -= 1 16 | newPosition = countArray[currentEl] 17 | outputArray[newPosition] = currentEl 18 | i -= 1 19 | 20 | return outputArray 21 | 22 | inputArray = [4,2,8,0,1,6,9,7] 23 | print("Input array = ", inputArray) 24 | 25 | sortedArray = countingSort(inputArray) 26 | print("Counting sort result = ", sortedArray) -------------------------------------------------------------------------------- /algorithms/ar-csrt/Python3/Counting_Sort.py: -------------------------------------------------------------------------------- 1 | # Python program for counting sort 2 | def countSort(arr): 3 | output = [0 for i in range(len(arr))] 4 | count = [0 for i in range(256)] 5 | ans = ["" for _ in arr] 6 | 7 | for i in arr: 8 | count[ord(i)] += 1 9 | 10 | for i in range(256): 11 | count[i] += count[i-1] 12 | 13 | for i in range(len(arr)): 14 | output[count[ord(arr[i])]-1] = arr[i] 15 | count[ord(arr[i])] -= 1 16 | 17 | for i in range(len(arr)): 18 | ans[i] = output[i] 19 | return ans 20 | 21 | arr = "Hactoberfestcontributions" 22 | ans = countSort(arr) 23 | print("Sorted character array is % s" %("".join(ans))) 24 | 25 | # This code is contributed by Animesh Tiwari 26 | -------------------------------------------------------------------------------- /algorithms/ar-csrt/Python3/Implementation Of counting Sort Algorithm in Python.py: -------------------------------------------------------------------------------- 1 | #Implentation Of COUNT SORT Algorithm by Animesh Tiwari 2 | def counting(data): 3 | # Creates 2D list of size max number in the array 4 | counts = [0 for i in range(max(data)+1)] 5 | print(counts) 6 | 7 | # Finds the "counts" for each individual number 8 | for value in data: 9 | counts[value] += 1 10 | print(counts) 11 | 12 | # Finds the cumulative sum counts 13 | for index in range(1, len(counts)): 14 | counts[index] = counts[index-1] + counts[index] 15 | print(counts) 16 | 17 | # Sorting Phase 18 | arr = [0 for loop in range(len(data))] 19 | for value in data: 20 | index = counts[value] - 1 21 | arr[index] = value 22 | counts[value] -= 1 23 | 24 | return arr 25 | 26 | data = [9, 4, 16, 20, 8, 1, 5, 10] 27 | print(counting(data)) -------------------------------------------------------------------------------- /algorithms/ar-csrt/Python3/count_sort.py: -------------------------------------------------------------------------------- 1 | # Counting sort in Python programming 2 | 3 | def countSort(array): 4 | size = len(array) 5 | output = [0] * size 6 | 7 | # Initialize count array 8 | count = [0] * size 9 | 10 | # Store the count of each elements in count array 11 | for i in range(0, size): 12 | count[array[i]] += 1 13 | 14 | # Store the cummulative count 15 | for i in range(0, size): 16 | count[i] += count[i - 1] 17 | 18 | # Find the index of each element of the original array in count array 19 | # place the elements in output array 20 | i = size - 1 21 | while i >= 0: 22 | output[count[array[i]] - 1] = array[i] 23 | count[array[i]] -= 1 24 | i -= 1 25 | 26 | # Copy the sorted elements into original array 27 | for i in range(0, size): 28 | array[i] = output[i] 29 | 30 | return array 31 | -------------------------------------------------------------------------------- /algorithms/ar-expsq/C++/expsq.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | int expo(int base,int exp) 6 | { 7 | int res=1; 8 | while(exp>0) 9 | { 10 | if(exp%2==1) 11 | res=res*base; 12 | base=base*base; 13 | exp=exp/2; 14 | } 15 | return res; 16 | } 17 | 18 | int main() 19 | { 20 | cout< 2 | 3 | int expo(int base, int exp) 4 | { 5 | int res = 1; 6 | while (exp > 0) 7 | { 8 | if (exp % 2 == 1) 9 | res = res * base; 10 | base = base * base; 11 | exp = exp / 2; 12 | } 13 | return res; 14 | } 15 | int main() 16 | { 17 | int ans = expo(3, 3); 18 | printf("%d", ans); 19 | } -------------------------------------------------------------------------------- /algorithms/ar-expsq/Java/axpsq.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | import java.lang.*; 3 | import java.io.*; 4 | 5 | class exponentiation_by_squaring{ 6 | public static void main(String[] args){ 7 | long base=5; 8 | long exp=10; 9 | long ans=exponentiation(base, exp); 10 | System.out.println(ans); 11 | } 12 | 13 | static long exponentiation(long base, long exp){ 14 | long ans=1; 15 | while(exp>0){ 16 | if(exp%2==1) 17 | ans=ans*base; 18 | base=base*base; 19 | exp=exp/2; 20 | } 21 | return ans; 22 | } 23 | } -------------------------------------------------------------------------------- /algorithms/ar-expsq/Python3/expsq.py: -------------------------------------------------------------------------------- 1 | def expo(base, exp): 2 | res=1 3 | while(exp>0): 4 | if(exp%2==1): 5 | res=res*base 6 | base=base*base 7 | exp=exp//2 8 | return res 9 | 10 | x=int(input("Enter the base")) 11 | y=int(input("Enter the exponent")) 12 | 13 | print(x, "raised to power", y, "is",expo(x,y)) 14 | -------------------------------------------------------------------------------- /algorithms/ar-expsq/readme.md: -------------------------------------------------------------------------------- 1 | fixed link 2 | -------------------------------------------------------------------------------- /algorithms/ar-hsrt/javascript/ar-hsrt.js: -------------------------------------------------------------------------------- 1 | function heapify(arr, n, i) { 2 | let largest = i; 3 | let left = 2 * i + 1; 4 | let right = 2 * i + 2; 5 | 6 | if (left < n && arr[left] > arr[i]) { 7 | largest = left; 8 | } 9 | 10 | if (right < n && arr[right] > arr[largest]) { 11 | largest = right; 12 | } 13 | 14 | if (largest != i) { 15 | aux = arr[i]; 16 | arr[i] = arr[largest]; 17 | arr[largest] = aux; 18 | heapify(arr, n, largest); 19 | } 20 | } 21 | 22 | function heapsort(arr) { 23 | let n = arr.length; 24 | 25 | for (i = Math.floor(n / 2) - 1; i >= 0; i--) { 26 | heapify(arr, n, i); 27 | } 28 | 29 | for (i = n - 1; i > 0; i--) { 30 | aux = arr[i]; 31 | arr[i] = arr[0]; 32 | arr[0] = aux; 33 | heapify(arr, i, 0); 34 | } 35 | } 36 | 37 | let arr = [12, 11, 13, 5, 6, 7, 22]; 38 | heapsort(arr); 39 | 40 | for (i = 0; i < arr.length; i++) { 41 | console.log(arr[i]); 42 | } 43 | -------------------------------------------------------------------------------- /algorithms/ar-hsrt/python/ar-hsrt.py: -------------------------------------------------------------------------------- 1 | def heapify(arr, n, i): 2 | largest = i 3 | left = 2 * i + 1 4 | right = 2 * i + 2 5 | 6 | if left < n and arr[left] > arr[i]: 7 | largest = left 8 | 9 | if right < n and arr[right] > arr[largest]: 10 | largest = right 11 | 12 | if largest != i: 13 | arr[i], arr[largest] = arr[largest], arr[i] 14 | heapify(arr, n, largest) 15 | 16 | 17 | def heapsort(arr): 18 | n = len(arr) 19 | for i in range(n // 2 - 1, -1, -1): 20 | heapify(arr, n, i) 21 | 22 | for i in range(n - 1, 0, -1): 23 | arr[i], arr[0] = arr[0], arr[i] 24 | heapify(arr, i, 0) 25 | 26 | 27 | arr = [12, 11, 13, 5, 6, 7] 28 | heapsort(arr) 29 | for i in arr: 30 | print(i, end=" ") 31 | -------------------------------------------------------------------------------- /algorithms/ar-isrt/C/InsertionSort.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | void insertionSort(int arr[], int n) 5 | { 6 | int i, key, j; 7 | for (i = 1; i < n; i++) { 8 | key = arr[i]; 9 | j = i - 1; 10 | 11 | while (j >= 0 && arr[j] > key) { 12 | arr[j + 1] = arr[j]; 13 | j = j - 1; 14 | } 15 | arr[j + 1] = key; 16 | } 17 | } 18 | 19 | void printArray(int arr[], int n) 20 | { 21 | int i; 22 | for (i = 0; i < n; i++) 23 | printf("%d ", arr[i]); 24 | printf("\n"); 25 | } 26 | 27 | int main() 28 | { 29 | int n; 30 | scanf("%d", &n); 31 | int arr[n]; 32 | for(int i=0;i= 0 && arr[j] > key) { 20 | arr[j + 1] = arr[j]; 21 | j = j - 1; 22 | } 23 | arr[j + 1] = key; 24 | } 25 | } 26 | 27 | // A utility function to print 28 | // array of size n 29 | static void printArray(int[] arr) 30 | { 31 | int n = arr.Length; 32 | for (int i = 0; i < n; ++i) 33 | Console.Write(arr[i] + " "); 34 | 35 | Console.Write("\n"); 36 | } 37 | 38 | // Driver Code 39 | public static void Main() 40 | { 41 | int[] arr = { 12, 11, 13, 5, 6 }; 42 | InsertionSort ob = new InsertionSort(); 43 | ob.sort(arr); 44 | printArray(arr); 45 | } 46 | } 47 | 48 | // This code is contributed by halmoside. 49 | -------------------------------------------------------------------------------- /algorithms/ar-isrt/cpp/insert.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | void insertionsort(int A[],int n) 4 | { 5 | for(int i=1;i=0 && A[j]>p) 10 | { 11 | A[j+1]=A[j]; 12 | j--; 13 | 14 | } 15 | A[j+1]=p; 16 | } 17 | } 18 | int main() 19 | { 20 | int N; 21 | cout<<"Enter the size:\n"; 22 | cin>>N; 23 | int *A=new int[N]; 24 | cout<<"Enter the elements:\n"; 25 | for(int i=0;i>A[i]; 28 | } 29 | cout<<"Before Sorting:\n"; 30 | for(int i=0;i 2 | using namespace std; 3 | void insertionsort(int A[],int n) 4 | { 5 | for(int i=1;i=0 && A[j]>p) 10 | { 11 | A[j+1]=A[j]; 12 | j--; 13 | 14 | } 15 | A[j+1]=p; 16 | } 17 | } 18 | int main() 19 | { 20 | int N; 21 | cout<<"Enter the size:\n"; 22 | cin>>N; 23 | int *A=new int[N]; 24 | cout<<"Enter the elements:\n"; 25 | for(int i=0;i>A[i]; 28 | } 29 | cout<<"Before Sorting:\n"; 30 | for(int i=0;i=0 && sortedArr[j]>key { 9 | sortedArr[j+1] = sortedArr[j] 10 | j -= 1 11 | } 12 | sortedArr[j+1] = key 13 | } 14 | return sortedArr 15 | } 16 | -------------------------------------------------------------------------------- /algorithms/ar-isrt/golang/insertion_sort_test.go: -------------------------------------------------------------------------------- 1 | package golang 2 | 3 | import ( 4 | "testing" 5 | "reflect" 6 | ) 7 | 8 | func TestInsertionSort(t *testing.T){ 9 | tcs := []struct { 10 | in []int 11 | want []int 12 | }{ 13 | { 14 | in: []int{5, 2, 6, 3, 1, 4}, 15 | want: []int{1, 2, 3, 4, 5, 6}, 16 | }, 17 | } 18 | for _, tc := range tcs { 19 | got := insertionSort(tc.in) 20 | if !reflect.DeepEqual(tc.want, got) { 21 | t.Errorf("want %v, but got %v\n", tc.want, got) 22 | } 23 | } 24 | } -------------------------------------------------------------------------------- /algorithms/ar-isrt/js/ar-isrt.js: -------------------------------------------------------------------------------- 1 | function insertionSort(inputArr) { 2 | let n = inputArr.length; 3 | for (let i = 1; i < n; i++) { 4 | // Choosing the first element in our unsorted subarray 5 | let current = inputArr[i]; 6 | // The last element of our sorted subarray 7 | let j = i-1; 8 | while ((j > -1) && (current < inputArr[j])) { 9 | inputArr[j+1] = inputArr[j]; 10 | j--; 11 | } 12 | inputArr[j+1] = current; 13 | } 14 | return inputArr; 15 | } -------------------------------------------------------------------------------- /algorithms/ar-isrt/python2/insertionsort.py: -------------------------------------------------------------------------------- 1 | arr = [int(i) for i in raw_input("Enter elements seperated by space : ").split()] 2 | 3 | for i in range(1,len(arr)): 4 | j = i-1 5 | key = arr[i] 6 | while(arr[j]>key and j>=0): 7 | arr[j+1] = arr[j] 8 | j-=1 9 | if(j != i-1): 10 | arr[j+1] = key; 11 | 12 | print"\n\nfinal array is ",arr; 13 | 14 | -------------------------------------------------------------------------------- /algorithms/ar-isrt/python3/ar-isrt.py: -------------------------------------------------------------------------------- 1 | def insertion_sort(input_list): 2 | len_list = len(input_list) 3 | for i in range(1, len_list): 4 | index = i 5 | # Making the value down to its position 6 | while index > 0 and input_list[index] < input_list[index-1]: 7 | # Swapping values 8 | input_list[index], input_list[index-1] = input_list[index-1], input_list[index] 9 | index -= 1 10 | return input_list 11 | 12 | 13 | example = [1, 5, 2, 4, 6, 3] 14 | print(insertion_sort(example)) 15 | -------------------------------------------------------------------------------- /algorithms/ar-isrt/typescript/ar-isrt.js: -------------------------------------------------------------------------------- 1 | function insSort(arr) { 2 | var size = arr.length; 3 | for (var i = 1; i < size; i++) { 4 | var current = arr[i]; 5 | var j = i - 1; 6 | while ((j > -1) && (current < arr[j])) { 7 | arr[j + 1] = arr[j]; 8 | j--; 9 | } 10 | arr[j + 1] = current; 11 | } 12 | return arr; 13 | } 14 | var array = [3, 1, 7, 4, 6, 2, 3, 0]; 15 | console.log(insSort(array)); 16 | -------------------------------------------------------------------------------- /algorithms/ar-isrt/typescript/ar-isrt.ts: -------------------------------------------------------------------------------- 1 | function insSort(arr:Array):Array{ 2 | let size = arr.length 3 | for (let i = 1; i < size; i++) { 4 | let current = arr[i]; 5 | let j = i-1; 6 | while ((j > -1) && (current < arr[j])) { 7 | arr[j+1] = arr[j]; 8 | j--; 9 | } 10 | arr[j+1] = current; 11 | } 12 | return arr 13 | } 14 | 15 | let array = [3,1,7,4,6,2,3,0] 16 | console.log(insSort(array)) -------------------------------------------------------------------------------- /algorithms/ar-kdn/c++/KadanesAlgo.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int kadanes (int array[],int length) { 5 | int highestMax = 0; 6 | int currentElementMax = 0; 7 | for(int i = 0; i < length; i++){ 8 | currentElementMax =max(array[i],currentElementMax + array[i]) ; 9 | highestMax = max(highestMax,currentElementMax); 10 | } 11 | return highestMax; 12 | } 13 | 14 | int main() { 15 | cout << "Enter the array length: "; 16 | int l; 17 | cin >> l; 18 | int arr[l]; 19 | cout << "Enter the elements of array: "; 20 | for (int i = 0; i < l; i++) { 21 | cin >> arr[i]; 22 | } 23 | 24 | cout << "The Maximum Sum is: "< 2 | #include 3 | 4 | int max(int a1, int a2){ 5 | if(a1>a2) 6 | return a1; 7 | return a2; 8 | } 9 | 10 | int kadanes (int array[],int length) { 11 | int highestMax = 0; 12 | int currentElementMax = 0; 13 | for(int i = 0; i < length; i++){ 14 | currentElementMax =max(array[i],currentElementMax + array[i]) ; 15 | highestMax = max(highestMax,currentElementMax); 16 | } 17 | return highestMax; 18 | } 19 | 20 | int main() { 21 | printf("Enter the array length: "); 22 | int l; 23 | scanf("%d", &l); 24 | int arr[l]; 25 | printf("Enter the elements of array: "); 26 | for (int i = 0; i < l; i++) { 27 | scanf("%d", &arr[i]); 28 | } 29 | 30 | printf("The Maximum Sum is: %d\n", kadanes(arr,l)); 31 | return 0; 32 | } -------------------------------------------------------------------------------- /algorithms/ar-kdn/javascript/ar-kdn.js: -------------------------------------------------------------------------------- 1 | function kadane(arr) { 2 | let max = 0; 3 | let maxSoFar = 0; 4 | for (let i = 0; i < arr.length; i++) { 5 | maxSoFar = Math.max(0, maxSoFar + arr[i]); 6 | max = Math.max(max, maxSoFar); 7 | } 8 | return max; 9 | } 10 | 11 | const arr = [-2, 1, -3, 4, -1, 2, 1, -5, 4]; 12 | console.log(kadane(arr)); -------------------------------------------------------------------------------- /algorithms/ar-kdn/python/kdn.py: -------------------------------------------------------------------------------- 1 | def maxSubArraySum(arr,size): 2 | 3 | max_till_now = arr[0] 4 | max_ending = 0 5 | 6 | for i in range(0, size): 7 | max_ending = max_ending + arr[i] 8 | if max_ending < 0: 9 | max_ending = 0 10 | 11 | 12 | elif (max_till_now < max_ending): 13 | max_till_now = max_ending 14 | 15 | return max_till_now 16 | 17 | arr = [-2, -3, 4, -1, -2, 5, -3] 18 | print("Maximum Sub Array Sum Is" , maxSubArraySum(arr,len(arr))) 19 | -------------------------------------------------------------------------------- /algorithms/ar-knn/readme.md: -------------------------------------------------------------------------------- 1 | fixed link 2 | -------------------------------------------------------------------------------- /algorithms/ar-lcs/C/LCS.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int max(int a, int b); 5 | 6 | 7 | int lcs( char *X, char *Y, int m, int n ) 8 | { 9 | if (m == 0 || n == 0) 10 | return 0; 11 | if (X[m-1] == Y[n-1]) 12 | return 1 + lcs(X, Y, m-1, n-1); 13 | else 14 | return max(lcs(X, Y, m, n-1), lcs(X, Y, m-1, n)); 15 | } 16 | 17 | int max(int a, int b) 18 | { 19 | return (a > b)? a : b; 20 | } 21 | 22 | // Driver program 23 | int main() 24 | { 25 | char X[] = "AGGTAB"; 26 | char Y[] = "GXTXAYB"; 27 | 28 | int m = strlen(X); 29 | int n = strlen(Y); 30 | 31 | printf("Length of LCS is %d", lcs( X, Y, m, n ) ); 32 | 33 | return 0; 34 | } 35 | -------------------------------------------------------------------------------- /algorithms/ar-lcs/c++/LCS.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int max(int a, int b); 4 | 5 | int lcs(char* X, char* Y, int m, int n) 6 | { 7 | int L[m + 1][n + 1]; 8 | int i, j; 9 | 10 | for (i = 0; i <= m; i++) { 11 | for (j = 0; j <= n; j++) { 12 | if (i == 0 || j == 0) 13 | L[i][j] = 0; 14 | 15 | else if (X[i - 1] == Y[j - 1]) 16 | L[i][j] = L[i - 1][j - 1] + 1; 17 | 18 | else 19 | L[i][j] = max(L[i - 1][j], L[i][j - 1]); 20 | } 21 | } 22 | 23 | return L[m][n]; 24 | } 25 | 26 | int max(int a, int b) 27 | { 28 | return (a > b) ? a : b; 29 | } 30 | 31 | int main() 32 | { 33 | char X[] = "AGGTAB"; 34 | char Y[] = "GXTXAYB"; 35 | 36 | int m = strlen(X); 37 | int n = strlen(Y); 38 | 39 | printf("Length of LCS is %d\n", lcs(X, Y, m, n)); 40 | 41 | return 0; 42 | } 43 | -------------------------------------------------------------------------------- /algorithms/ar-lcs/javascript/ar-lcs.js: -------------------------------------------------------------------------------- 1 | 2 | function lcs(a, b){ 3 | var m = a.length, n = b.length, i, j, l = []; 4 | for(i = 0; i <= m; i++){ 5 | l[i] = []; 6 | for(j = 0; j <= n; j++){ 7 | if(i == 0 || j == 0){ 8 | l[i][j] = 0; 9 | }else if(a[i-1] == b[j-1]){ 10 | l[i][j] = l[i-1][j-1] + 1; 11 | }else{ 12 | l[i][j] = Math.max(l[i-1][j], l[i][j-1]); 13 | } 14 | } 15 | } 16 | return l[m][n]; 17 | } 18 | 19 | let a = [1,2,3,4,5,6,7,8,9,0]; 20 | let b = [2,4,6,7,9,10]; 21 | 22 | console.log(lcs(a, b)); -------------------------------------------------------------------------------- /algorithms/ar-lcs/python3/ar-lcs.py: -------------------------------------------------------------------------------- 1 | def lcs(string1, string2, get_string=False): 2 | m = len(string1) 3 | n = len(string2) 4 | 5 | dp = [[0]*(n+1) for i in range(m+1)] 6 | 7 | for i in range(1, m+1): 8 | for j in range(1, n+1): 9 | if string1[i-1] == string2[j-1]: 10 | dp[i][j] = dp[i-1][j-1] + 1 11 | else: 12 | dp[i][j] = max(dp[i-1][j] , dp[i][j-1]) 13 | 14 | if not get_string: 15 | return dp[m][n] 16 | 17 | idx = dp[m][n] 18 | lcs = [""] * (idx + 1) 19 | lcs[idx] = "" 20 | 21 | # Backtrack 22 | i = m 23 | j = n 24 | while i > 0 and j > 0: 25 | if string1[i-1] == string2[j-1]: 26 | lcs[idx-1] = string1[i-1] 27 | i -= 1 28 | j -= 1 29 | idx -= 1 30 | elif dp[i-1][j] > dp[i][j-1]: 31 | i -= 1 32 | else: 33 | j -= 1 34 | 35 | return "".join(lcs) 36 | 37 | if __name__ == '__main__': 38 | print(lcs('AGGTAB', 'GXTXAYB')) 39 | print(lcs('AGGTAB', 'GXTXAYB', get_string=True)) -------------------------------------------------------------------------------- /algorithms/ar-lis/C++/ar-lis.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int lengthOfLIS(vector& nums) { 4 | int l = nums.size(); 5 | if (nums.empty()) return 0; 6 | vector d(l, -1); 7 | int ans = 0; 8 | d[0] = 0; 9 | for (int i = 1 ; i < l ; i++) { 10 | if (nums[i] > nums[d[ans]]) { 11 | ans++; 12 | d[ans] = i; 13 | } else if (nums[i] <= nums[d[0]]) { 14 | d[0] = i; 15 | } else { 16 | int l = 0; 17 | int r = ans; 18 | while ((r - l) > 1) { 19 | int m = l + (r - l) / 2; 20 | if (nums[i] <= nums[d[m]]) { 21 | r = m; 22 | } else { 23 | l = m; 24 | } 25 | } 26 | d[r] = i; 27 | } 28 | } 29 | return ans + 1; 30 | } 31 | }; -------------------------------------------------------------------------------- /algorithms/ar-lis/JS/lis.js: -------------------------------------------------------------------------------- 1 | let arr = [10, 22, 9, 33, 21, 50, 41, 60, 80] 2 | let Ln = arr.length-1; 3 | let LIS = [] 4 | 5 | for(let i = 0; i<=Ln; i++){ 6 | LIS[i] = 1; 7 | } 8 | 9 | for(let i =1; i<=Ln; i++){ 10 | for(let j=0; j <= i; j++){ 11 | if(arr[j] < arr[i] && LIS[i] < LIS[j]+1 ){ 12 | LIS[i] = LIS[j]+1; 13 | } 14 | } 15 | } 16 | 17 | console.log(`Max Length is ${Math.max.apply(null,LIS)}`) -------------------------------------------------------------------------------- /algorithms/ar-lis/Python3/ar-lis.py: -------------------------------------------------------------------------------- 1 | seq=list(map(int,input().split())) 2 | ans=0 3 | count=1 4 | length=len(seq) 5 | if length==0: 6 | ans=0 7 | elif length==1: 8 | ans=1 9 | else: 10 | for i in range(1,length): 11 | if seq[i]>seq[i-1]: 12 | count+=1 13 | else: 14 | ans=max(ans,count) 15 | count=1 16 | ans=max(ans,count) 17 | print(ans) 18 | 19 | 20 | -------------------------------------------------------------------------------- /algorithms/ar-lps/C++/ar-lps.cpp: -------------------------------------------------------------------------------- 1 | class LongestPalindromicSubstring { 2 | public: 3 | string lps(string s) { 4 | ios::sync_with_stdio(0); 5 | int mx = 1; 6 | int st = 0; 7 | int len = s.length(); 8 | for (int i = 1 ; i < len ; i++) { 9 | int l = i - 1; 10 | int h = i; 11 | while (l >= 0 && h < len && s[l] == s[h]) { 12 | if (h - l + 1 > mx) { 13 | mx = h - l + 1; 14 | st = l; 15 | } 16 | l--; 17 | h++; 18 | } 19 | l = i - 1; 20 | h = i + 1; 21 | while (l >= 0 && h < len && s[l] == s[h]) { 22 | if (h - l + 2 > mx) { 23 | st = l; 24 | mx = h - l + 1; 25 | } 26 | l--; 27 | h++; 28 | } 29 | } 30 | return s.substr(st, mx); 31 | } 32 | }; -------------------------------------------------------------------------------- /algorithms/ar-lps/JAVA/Longest Palindromic.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | class LongestPalindromicSubstring { 4 | private static String findLongestPalindromicSubstring(String input) { 5 | if(input.isEmpty()) { 6 | return ""; 7 | } 8 | int n = input.length(); 9 | int longestSoFar = 0, startIndex = 0, endIndex = 0; 10 | boolean[][] palindrom = new boolean[n][n]; 11 | 12 | for(int j = 0; j < n; j++) { 13 | palindrom[j][j] = true; 14 | for(int i = 0; i < j; i++) { 15 | if(input.charAt(i) == input.charAt(j) && (j-i <= 2 || palindrom[i+1][j-1])) { 16 | palindrom[i][j] = true; 17 | if(j-i+1 > longestSoFar) { 18 | longestSoFar = j-i+1; 19 | startIndex = i; 20 | endIndex = j; 21 | } 22 | } 23 | } 24 | } 25 | return input.substring(startIndex, endIndex+1); 26 | } 27 | public static void main(String[] args) { 28 | Scanner keyboard = new Scanner(System.in); 29 | String input = keyboard.next(); 30 | System.out.println(findLongestPalindromicSubstring(input)); 31 | } 32 | } -------------------------------------------------------------------------------- /algorithms/ar-lps/Python3/longestPalindromeSubstring.py: -------------------------------------------------------------------------------- 1 | s = input() 2 | dp = [[False]*len(s) for _ in range(len(s))] 3 | longest = '' 4 | for i in range(len(s)): 5 | for j in range(i+1): 6 | if s[i] == s[j] and ((i+1-j) <= 3 or dp[i-1][j+1]): 7 | dp[i][j] = True 8 | if i+1-j > len(longest): 9 | longest = s[j:i+1] 10 | print(longest) -------------------------------------------------------------------------------- /algorithms/ar-lscsa/C++/lscsa.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | int largest_sum_cont_subarray(vector&arr) 6 | { 7 | int ans=0; 8 | int sum=0; 9 | for(int i=0;i v; 23 | v.push_back(1); 24 | v.push_back(-1); 25 | v.push_back(2); 26 | v.push_back(3); 27 | cout< 2 | 3 | int lcsa(int a[], int s) 4 | { 5 | int largest_sum=a[0]; 6 | for(int i=0;ilargest_sum) 13 | largest_sum=sum; 14 | } 15 | } 16 | return largest_sum; 17 | } 18 | 19 | int main() 20 | { 21 | int size; 22 | printf("What is the lenght of your array\n"); 23 | scanf("%d",&size); 24 | int array[size]; 25 | printf("Type your elements one by one\n"); 26 | for(int i=0;i 8 | using namespace std; 9 | 10 | int linearSearch(int arr[], int key, int size) { 11 | for (int i = 0; i < size; i++) { 12 | if (arr[i] == key) { 13 | return i; 14 | } 15 | } 16 | 17 | return -1; 18 | } 19 | 20 | int main() { 21 | int arr[] = {1, 6, 2, 4, 4, 9, 78, 7, 78}; 22 | int size = sizeof(arr)/sizeof(arr[0]); 23 | 24 | int key = 78; 25 | 26 | int res = linearSearch(arr, key, size); 27 | if (res == -1) { 28 | cout << "Key not found" << endl; 29 | } else { 30 | cout << "The element " << key << " was found at the index of " << res << endl; 31 | } 32 | return 0; 33 | } -------------------------------------------------------------------------------- /algorithms/ar-lsrh/c/ar-lsrh.c: -------------------------------------------------------------------------------- 1 | #include 2 | int main() 3 | { 4 | int n, arr[10000], key = 0, i, found = 0; 5 | printf("Enter Size of Array\n"); 6 | scanf("%d", &n); 7 | printf("Enter Array elements\n"); 8 | for (i = 0; i < n; i++) 9 | { 10 | scanf("%d", &arr[i]); 11 | } 12 | printf("Enter Key to Search\n"); 13 | scanf("%d", &key); 14 | for (i = 0; i < n; i++) 15 | { 16 | if (arr[i] == key) 17 | { 18 | found = 1; 19 | printf("found at position %d", i + 1); 20 | } 21 | } 22 | if (found == 0) 23 | printf("Not Found\n"); 24 | 25 | return 0; 26 | } 27 | -------------------------------------------------------------------------------- /algorithms/ar-lsrh/golang/linear-search.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func linearsearch(datalist []int, key int) bool { 6 | for _, item := range datalist { 7 | if item == key { 8 | return true 9 | } 10 | } 11 | return false 12 | } 13 | 14 | func main() { 15 | items := []int{32, 13, 123, 56, 34} 16 | // If element found print element found 17 | if linearsearch(items, 56) { 18 | fmt.Println("Element found.") 19 | } else { 20 | fmt.Println("Element not found.") 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /algorithms/ar-lsrh/python/ar-lsrh.py: -------------------------------------------------------------------------------- 1 | def linear_search(arr, key): 2 | n = len(arr) 3 | for i in range(n): 4 | if arr[i] == key: 5 | return i 6 | return -1 7 | 8 | 9 | arr = [1, 2, 5, 3, 7, 8, 89, 34, 23, 56, 99] 10 | key = 1 11 | ans = linear_search(arr, key) 12 | if ans == -1: 13 | print("Key not found.") 14 | else: 15 | print("Key " + str(key) + " found at index " + str(ans)) 16 | -------------------------------------------------------------------------------- /algorithms/ar-mexp/C++/mexp.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | int modular_exponentiation(int base,int power,int mod) 6 | { 7 | int result=1; 8 | while(power>0) 9 | { 10 | if(power&1) 11 | { 12 | result=(result*base)%mod; 13 | } 14 | base=(base*base)%mod; 15 | power>>=1; 16 | } 17 | return result; 18 | } 19 | 20 | int main() 21 | { 22 | cout< 0 ) { 6 | if( $power & 1 ) { 7 | $iResult = ( $iResult * $base ) % $mod; 8 | } 9 | $base = ( $base * $base ) % $mod; 10 | $power >>= 1; 11 | } 12 | return $iResult; 13 | } 14 | 15 | var_dump( mod_ex( 2,6,5 ) ); -------------------------------------------------------------------------------- /algorithms/ar-mexp/Python/mexp.py: -------------------------------------------------------------------------------- 1 | def mexp(base: int, exp: int, m: int) -> int: 2 | result = 1 3 | 4 | while exp > 0: 5 | if (exp & 1) > 0: 6 | result = (result * base) % m 7 | exp >>= 1 8 | base = (base * base) % m 9 | 10 | return result 11 | 12 | 13 | assert mexp(3, 3, 5), 2 14 | -------------------------------------------------------------------------------- /algorithms/ar-mexp/mexp.c: -------------------------------------------------------------------------------- 1 | // Modular Exponential in C 2 | #include 3 | int power(int x,int y,int p); 4 | /* Iterative Function to calculate (x^y)%p in O(log y) */ 5 | int power(int x, int y, int p) 6 | { 7 | int res = 1; // Initialize result 8 | x = x % p; // Update x if it is more than or equal to p 9 | if (x == 0) return 0; // In case x is divisible by p; 10 | while (y > 0) 11 | { 12 | // If y is odd, multiply x with result 13 | if (y & 1) 14 | res = (res*x) % p; 15 | // y must be even now 16 | y = y>>1; // y = y/2 17 | x = (x*x) % p; 18 | } 19 | return res; 20 | } 21 | int main() 22 | { 23 | int x = 2,y=5,p=13; 24 | clrscr(); 25 | printf("Power is %d",power(x, y, p)); 26 | return 0; 27 | } 28 | -------------------------------------------------------------------------------- /algorithms/ar-mexp/readme.md: -------------------------------------------------------------------------------- 1 | fixed link 2 | -------------------------------------------------------------------------------- /algorithms/ar-min/c#/min_arr.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Linq; 3 | 4 | class min_arr 5 | { 6 | static void Main() 7 | { 8 | int[] test_array = { 3, 12, 16, 1, -1, -5, 2, -10, 18, 0 }; 9 | 10 | int min_number = test_array.Min(); 11 | Console.WriteLine(min_number); 12 | 13 | } 14 | } -------------------------------------------------------------------------------- /algorithms/ar-min/c++/ar_min.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | int main() 4 | { 5 | int n; 6 | cout<<"Enter number of element in array - "; 7 | cin >> n; 8 | vector arr(n); 9 | for(int i=0;i< n;i++) 10 | cin>>arr[i]; 11 | 12 | int ans=INT_MAX; 13 | for(auto x:arr) 14 | { 15 | ans=min(x,ans); 16 | } 17 | cout<<"Minimun number is "< 2 | 3 | int main(){ 4 | int arr[7] = {2,4,7,1,3,6,5}; 5 | int len = sizeof arr / sizeof arr[0]; 6 | int min = arr[0]; 7 | for(int i=1;i):number{ 2 | return Math.min(...arr) 3 | } 4 | let array:Array = [1,2,3,4,5] 5 | console.log(arrMin(array)) 6 | 7 | -------------------------------------------------------------------------------- /algorithms/ar-minmax/Min Max.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | void readArray(int[],int); 4 | void displayArray(int[],int); 5 | void minmaxArray(int[],int); 6 | 7 | int main() 8 | { 9 | int n,s ; 10 | int arr[100]; 11 | printf("Enter the size of Array: "); 12 | scanf("%d",&n); 13 | printf("Enter the elements of array: \n"); 14 | readArray(arr,n); 15 | minmaxArray(arr,n); 16 | } 17 | 18 | void readArray(int arr[],int n) 19 | { 20 | int i; 21 | for(i=0;iarr[i]) 43 | min=arr[i]; 44 | if(max { 2 | if(nums.length<2){ 3 | return nums; 4 | } 5 | 6 | const length = nums.length; 7 | const middle = Math.floor(length/2); 8 | const left = nums.slice(0,middle); 9 | const right = nums.slice(middle,length); 10 | console.log(middle); 11 | return stitch (mergeSort(left) , mergeSort(right)); 12 | 13 | }; 14 | 15 | const stitch = (left , right) =>{ 16 | const results = []; 17 | while(left.length && right.length){ 18 | if(left[0] <= right[0]){ 19 | results.push(left.shift()); 20 | } 21 | else{ 22 | results.push(right.shift()); 23 | } 24 | } 25 | return results.concat(left,right); 26 | } -------------------------------------------------------------------------------- /algorithms/ar-msrt/python3/ar-msrt.py: -------------------------------------------------------------------------------- 1 | def merge_list(input_list1, input_list2): 2 | if not input_list1: 3 | return input_list2 4 | elif not input_list2: 5 | return input_list1 6 | else: 7 | a, b = input_list1[0], input_list2[0] 8 | if a <= b: 9 | return [a] + merge_list(input_list1[1:], input_list2) 10 | else: 11 | return [b] + merge_list(input_list1, input_list2[1:]) 12 | 13 | 14 | def merge_sort(input_list): 15 | if not input_list: 16 | return input_list 17 | elif not input_list[1:]: 18 | return input_list 19 | else: 20 | n = len(input_list) 21 | begin, end = input_list[0: n//2], input_list[n//2:] 22 | return merge_list(merge_sort(begin), merge_sort(end)) 23 | 24 | 25 | example = [1, 5, 2, 4, 6, 3] 26 | print(merge_sort(example)) 27 | -------------------------------------------------------------------------------- /algorithms/ar-mxsub/maxsum_subarray.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | int main() 3 | { int n, a[1000],sum=0,csum[1000],max_sum=0; 4 | //int max_sum=0; 5 | //int sum=0; 6 | // int csum[1000]; 7 | 8 | cout<<"enter the value of n"; 9 | cin>>n; 10 | cout<<"enter the array"; 11 | for(int i=0;i>a[i]; 14 | } 15 | csum[0]=a[0]; 16 | for(int j=1;jmax_sum) 26 | { 27 | max_sum=sum; 28 | } 29 | } 30 | } 31 | cout<<"max sum of the subarray"< 2 | using namespace std; 3 | int index(int *x,int length,int target) 4 | { 5 | for (int i=0;i 2 | #include 3 | 4 | int* pigeonholeSort(int nums[], int size) 5 | { 6 | int i, j, min = nums[0], max = nums[0], range; 7 | 8 | for (i = 1; i < size; i++) 9 | { 10 | if (nums[i] < min) 11 | min = nums[i]; 12 | if (nums[i] > max) 13 | max = nums[i]; 14 | } 15 | range = max - min + 1; 16 | 17 | int *tmp = (int *)malloc(sizeof(int) * range); 18 | for (i = 0; i < range; i++) 19 | tmp[i] = 0; 20 | for (i = 0; i < size; i++) 21 | tmp[nums[i] - min]++; 22 | j = 0; 23 | for (i = 0; i < range; i++) 24 | { 25 | while (tmp[i] > 0) 26 | { 27 | nums[j] = i + min; 28 | tmp[i]--; 29 | j++; 30 | } 31 | } 32 | return nums; 33 | } 34 | -------------------------------------------------------------------------------- /algorithms/ar-prfac/C++/Prime_Factor.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | void primefactor(int n) 4 | { 5 | for (int i = 2; i <= n; i++) 6 | { 7 | if (n % i == 0) 8 | { 9 | while (n % i == 0) 10 | { 11 | cout << i << " "; //printing i till n is divisible by i 12 | n = n / i; 13 | 14 | } 15 | } 16 | 17 | } 18 | 19 | } 20 | int main() 21 | { 22 | int n; cin >> n;//taking input from user 23 | primefactor(n);// calling function to print prime factor 24 | cout << "\n"; 25 | return 0; 26 | } 27 | 28 | 29 | // input : 100005 30 | // output: 3 5 59 113 31 | -------------------------------------------------------------------------------- /algorithms/ar-prfac/C/Prime_Factor.c: -------------------------------------------------------------------------------- 1 | #include 2 | int main() 3 | { 4 | int n, i; 5 | scanf("%d", &n);// taking input from user 6 | for (i = 2; i <= n; i++) // starting from 2 because prime number starts from 2 7 | { 8 | if (n % i == 0) 9 | { 10 | while (n % i == 0) 11 | { 12 | printf("%d ", i); 13 | n = n / i; 14 | 15 | } 16 | } 17 | 18 | } 19 | return 0; 20 | } 21 | 22 | // input : 100005 23 | // output: 3 5 59 113 24 | -------------------------------------------------------------------------------- /algorithms/ar-prfac/JAVA/Prime factors.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | public class PrimeFactors { 4 | public static void main(String args[]){ 5 | int number; 6 | Scanner sc = new Scanner(System.in); 7 | System.out.println("Enter a number ::"); 8 | number = sc.nextInt(); 9 | 10 | for(int i = 2; i< number; i++) { 11 | while(number%i == 0) { 12 | System.out.println(i+" "); 13 | number = number/i; 14 | } 15 | } 16 | if(number >2) { 17 | System.out.println(number); 18 | } 19 | } 20 | } -------------------------------------------------------------------------------- /algorithms/ar-prfac/JS/prime_factor.js: -------------------------------------------------------------------------------- 1 | const primeFactor = num => { 2 | for (let i = 2; i <= num; i++) { 3 | if (num % i == 0) { 4 | while (num % i == 0) { 5 | console.log(i) 6 | num /= i; 7 | } 8 | } 9 | } 10 | } 11 | 12 | var num = 10005; 13 | primeFactor(num); 14 | -------------------------------------------------------------------------------- /algorithms/ar-prfac/PHP/prime-factors.php: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | 4 | using namespace std; 5 | 6 | int partition(int *arr, int low, int high) { 7 | int pivot = arr[high]; 8 | int i = low - 1; 9 | for (int j = low; j <= high - 1; j++) { 10 | if (arr[j] <= pivot) { 11 | i++; 12 | swap(arr[i], arr[j]); 13 | } 14 | } 15 | swap(arr[i + 1], arr[high]); 16 | return i + 1; 17 | } 18 | 19 | int quickselect(int *arr, int n, int k) { 20 | int left = 0, right = n - 1; 21 | while (left < right) { 22 | int pivot = partition(arr, left, right); 23 | if (pivot == k) { 24 | return arr[pivot]; 25 | } else if (pivot < k) { 26 | left = pivot + 1; 27 | } else { 28 | right = pivot - 1; 29 | } 30 | } 31 | return arr[left]; 32 | } 33 | 34 | int main() { 35 | int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; 36 | int k = 5; 37 | cout << quickselect(arr, 10, k) << endl; 38 | return 0; 39 | } 40 | -------------------------------------------------------------------------------- /algorithms/ar-qsel/ar-qsel.js: -------------------------------------------------------------------------------- 1 | function quickSelect(arr, k) { 2 | if (k < 0 || k > arr.length - 1) { 3 | return null; 4 | } 5 | return quickSelectHelper(arr, 0, arr.length - 1, k); 6 | } 7 | 8 | function quickSelectHelper(arr, left, right, k) { 9 | if (left === right) { 10 | return arr[left]; 11 | } 12 | const pivot = partition(arr, left, right); 13 | if (pivot === k) { 14 | return arr[pivot]; 15 | } else if (pivot > k) { 16 | return quickSelectHelper(arr, left, pivot - 1, k); 17 | } else { 18 | return quickSelectHelper(arr, pivot + 1, right, k); 19 | } 20 | } 21 | 22 | function partition(arr, left, right) { 23 | const pivot = arr[right]; 24 | let i = left; 25 | for (let j = left; j < right; j++) { 26 | if (arr[j] <= pivot) { 27 | swap(arr, i, j); 28 | i++; 29 | } 30 | } 31 | swap(arr, i, right); 32 | return i; 33 | } 34 | 35 | function swap(arr, i, j) { 36 | const temp = arr[i]; 37 | arr[i] = arr[j]; 38 | arr[j] = temp; 39 | } 40 | 41 | arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; 42 | console.log(quickSelect(arr, 5)); 43 | -------------------------------------------------------------------------------- /algorithms/ar-qsel/ar-qsel.py: -------------------------------------------------------------------------------- 1 | def quickselect(arr, l, h): 2 | if l == h: 3 | return arr[l] 4 | pivot = arr[h] 5 | i = l 6 | for j in range(l, h): 7 | if arr[j] <= pivot: 8 | arr[i], arr[j] = arr[j], arr[i] 9 | i += 1 10 | arr[i], arr[h] = arr[h], arr[i] 11 | if i == k-1: 12 | return arr[i] 13 | elif i < k-1: 14 | return quickselect(arr, i + 1, h) 15 | else: 16 | return quickselect(arr, l, i - 1) 17 | 18 | 19 | if __name__ == "__main__": 20 | arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] 21 | k = 5 22 | print(quickselect(arr, 0, len(arr) - 1)) 23 | -------------------------------------------------------------------------------- /algorithms/ar-qsel/readme.md: -------------------------------------------------------------------------------- 1 | fixed link 2 | -------------------------------------------------------------------------------- /algorithms/ar-qsrt/Quick_Sort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | void swap(int arr[], int i, int j) 5 | { 6 | int temp=arr[i]; 7 | arr[i]=arr[j]; 8 | arr[j]=temp; 9 | } 10 | 11 | int partition(int arr[], int l, int r) 12 | { 13 | int pivot=arr[r]; 14 | int i=l-1; 15 | 16 | for(int j=l; j{ 2 | 3 | const length = list.length; 4 | const pivot = list[length-1]; 5 | const left = []; 6 | const right = [] 7 | 8 | if(list.length <= 1) return list ; 9 | 10 | for(let i = 0 ; i < length-1 ; i++){ 11 | 12 | if(list[i] < pivot){ 13 | left.push(list[i]); 14 | } 15 | 16 | else{ 17 | right.push(list[i]) 18 | } 19 | } 20 | 21 | return [...QuickSort(left) , pivot , ...QuickSort(right)]; 22 | } -------------------------------------------------------------------------------- /algorithms/ar-qsrt/python3/ar-qsrt.py: -------------------------------------------------------------------------------- 1 | def partition(lst, low, high): 2 | idx = low - 1 3 | pivot = lst[high] 4 | for i in range(low, high): 5 | if lst[i] <= pivot: 6 | idx += 1 7 | lst[idx], lst[i] = lst[i], lst[idx] 8 | 9 | lst[idx + 1], lst[high] = lst[high], lst[idx + 1] 10 | return idx + 1 11 | 12 | def quick_sort(lst, low, high): 13 | if low < high: 14 | pi = partition(lst, low, high) 15 | quick_sort(lst, low, pi - 1) 16 | quick_sort(lst, pi + 1, high) 17 | return lst 18 | 19 | 20 | arr = [23, 76, 12, 7, 29, 43, 65, 1] 21 | print(quick_sort(arr, 0, len(arr) - 1)) -------------------------------------------------------------------------------- /algorithms/ar-radsrt/Python/radixsort.py: -------------------------------------------------------------------------------- 1 | def counting_Sort(arr, p): 2 | s = len(arr) 3 | result = [0] * s 4 | c = [0] * 10 5 | 6 | # count of elements 7 | for i in range(0, s): 8 | index = arr[i] // p 9 | c[index % 10] += 1 10 | 11 | # cumulative count 12 | for i in range(1, 10): 13 | c[i] += c[i - 1] 14 | 15 | # sorted order 16 | i = s - 1 17 | while i >= 0: 18 | index = arr[i] // p 19 | result[c[index % 10] - 1] = arr[i] 20 | c[index % 10] -= 1 21 | i -= 1 22 | 23 | for i in range(0, s): 24 | arr[i] = result[i] 25 | 26 | 27 | # radix sort 28 | def radix_Sort(arr): 29 | maximum = max(arr) 30 | 31 | p = 1 32 | while maximum // p > 0: 33 | counting_Sort(arr, p) 34 | p *= 10 35 | 36 | array = [170, 45, 75, 90, 802, 24, 2, 66] 37 | print("Array:\n ", array) 38 | radix_Sort(array) 39 | print("Sorted array:\n", array) -------------------------------------------------------------------------------- /algorithms/ar-rcprb/C++/rcprb.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | int rod_cutting(vector&val) 6 | { 7 | int n=val.size(); 8 | vectordp(n+1,0); 9 | for(int i=1;i<=n;i++) 10 | { 11 | int max_val=INT_MIN; 12 | for(int j=1;j<=i;j++) 13 | { 14 | max_val=max(max_val,val[j-1]+dp[i-j]); 15 | } 16 | dp[i]=max_val; 17 | } 18 | return dp[n]; 19 | } 20 | 21 | int main() 22 | { 23 | int n; 24 | cin>>n; 25 | vector v(n); 26 | for(int i=0;i>v[i]; 29 | } 30 | cout< 3 | #include 4 | 5 | // A utility function to get the maximum of two integers 6 | int max(int a, int b) { return (a > b)? a : b;} 7 | 8 | /* Returns the best obtainable price for a rod of length n and price[] as prices of different pieces */ 9 | int cutRod(int price[], int n) 10 | { 11 | int val[n+1]; 12 | val[0] = 0; 13 | int i, j; 14 | 15 | // Build the table val[] in bottom up manner and return the last entry from the table 16 | for (i = 1; i<=n; i++) 17 | { 18 | int max_val = INT_MIN; 19 | for (j = 0; j < i; j++) 20 | max_val = max(max_val, price[j] + val[i-j-1]); 21 | val[i] = max_val; 22 | } 23 | 24 | return val[n]; 25 | } 26 | 27 | int main() 28 | { 29 | int arr[] = {1, 5, 8, 9, 10, 17, 17, 20}; 30 | int size = sizeof(arr)/sizeof(arr[0]); 31 | printf("Maximum Profit Obtained is %d", cutRod(arr, size)); 32 | getchar(); 33 | return 0; 34 | } -------------------------------------------------------------------------------- /algorithms/ar-rcprb/js/ar-rcprb.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @function cutRod Function that determines the maximum value obtainable by cutting 3 | * the rods into different pieces. 4 | * @param {Array} price : An array containing prices of the rod at lengths 1 to n. 5 | * @param {Number} n : The length of the given rod 6 | * @returns {Number} The maximum anount obtainable by cutting the rod into 7 | * different pieces. 8 | */ 9 | function cutRod(price, n) { 10 | let val = new Array(n + 1); 11 | val[0] = 0; 12 | 13 | // Build the table val[] in 14 | // bottom up manner and return 15 | // the last entry from the table 16 | for (let i = 1; i <= n; i++) { 17 | let max_val = Number.MIN_VALUE; 18 | for (let j = 0; j < i; j++) 19 | max_val = Math.max(max_val, price[j] + val[i - j - 1]); 20 | val[i] = max_val; 21 | } 22 | 23 | return val[n]; 24 | } 25 | 26 | // driver code 27 | let arr = [1, 5, 8, 9, 10, 17, 17, 20]; 28 | let size = arr.length; 29 | console.log("Cutting Rod Problem: "); 30 | console.log("Highest amount that can be obtained = " + cutRod(arr, size)); -------------------------------------------------------------------------------- /algorithms/ar-rcprb/readme.md: -------------------------------------------------------------------------------- 1 | fixed link 2 | -------------------------------------------------------------------------------- /algorithms/ar-rpprscs/java/.gitignore: -------------------------------------------------------------------------------- 1 | *.class -------------------------------------------------------------------------------- /algorithms/ar-rpprscs/javascript/main.js: -------------------------------------------------------------------------------- 1 | const {play} = require('./ar-rpprscs') 2 | 3 | play() 4 | -------------------------------------------------------------------------------- /algorithms/ar-rpprscs/javascript/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "ar-rpprscs", 3 | "version": "1.0.0", 4 | "description": "", 5 | "main": "main.js", 6 | "scripts": { 7 | "start": "node .", 8 | "test": "ava" 9 | }, 10 | "private": true, 11 | "license": "ISC", 12 | "devDependencies": { 13 | "ava": "^3.15.0" 14 | }, 15 | "dependencies": { 16 | "inquirer": "^8.2.0" 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /algorithms/ar-rpprscs/python/README.md: -------------------------------------------------------------------------------- 1 | A computer version of rock, paper, scissors. 2 | 3 | Contains Versions: 4 | Python3.9 5 | Python3.10 -------------------------------------------------------------------------------- /algorithms/ar-rpprscs/python/rpprscs-py3.10.py: -------------------------------------------------------------------------------- 1 | # A Rock, Paper, Scissors Game in Python3.10 2 | 3 | # Include Needed Modules. 4 | import random, os 5 | 6 | # Choices to pick. 7 | choices = ["R", "P", "S"] 8 | 9 | # Main Game loop. 10 | while True: 11 | # Get userChoice. 12 | while True: 13 | userChoice = input("R | P | S >> ").upper() 14 | 15 | if userChoice in choices: 16 | break 17 | 18 | # Get compChoice. 19 | compChoice = choices[random.randint(0, 2)] 20 | 21 | print(f"You picked {userChoice} and the Computer chose {compChoice}!\n") 22 | 23 | # Compare userChoice to compChoice. 24 | compare = (userChoice, compChoice) 25 | 26 | match compare: 27 | case ('R', 'R') | ('P', 'P') | ('S', 'S'): 28 | print("Tie!") 29 | case ('R', 'S') | ('P', 'R') | ('S', 'P'): 30 | print("You win!") 31 | case ('R', 'P') | ('P', 'S') | ('S', 'R'): 32 | print("Sorry, you lose!") 33 | -------------------------------------------------------------------------------- /algorithms/ar-rpprscs/python/rpprscs-py3.9.py: -------------------------------------------------------------------------------- 1 | # Rock, Paper, Scissors in Python3.9 2 | 3 | # Import Needed Modules. 4 | import random, os 5 | 6 | # Choices to pick. 7 | choices = ["R", "P", "S"] 8 | 9 | # Main Game Loop. 10 | while True: 11 | 12 | # Get Users Choice. 13 | while True: 14 | userChoice = input("R | P | S >> ").upper() 15 | 16 | if userChoice.upper() in choices: 17 | break 18 | 19 | # Get Computers Choice. 20 | compChoice = choices[random.randint(0, 2)] 21 | 22 | print(f"You picked {userChoice} and the Computer picked {compChoice}!\n") 23 | 24 | # Check userChoice against compChoice. 25 | compare = (userChoice, compChoice) 26 | 27 | if compare[0] == compare[1]: 28 | print("Tie!") 29 | elif compare in [('R', 'S'), ('P', 'R'), ('S', 'P')]: 30 | print("You win!") 31 | elif compare in [('R', 'P'), ('P', 'S'), ('S', 'R')]: 32 | print("Sorry, you lose!") 33 | -------------------------------------------------------------------------------- /algorithms/ar-rpprscs/typescript/main.ts: -------------------------------------------------------------------------------- 1 | const {play} = require('./ar-rpprscs') 2 | 3 | play() 4 | -------------------------------------------------------------------------------- /algorithms/ar-rpprscs/typescript/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "ar-rpprscs", 3 | "version": "1.0.0", 4 | "description": "", 5 | "main": "main.ts", 6 | "scripts": { 7 | "start": "ts-node main.ts", 8 | "test": "ava" 9 | }, 10 | "private": true, 11 | "license": "ISC", 12 | "devDependencies": { 13 | "@ava/typescript": "^2.0.0", 14 | "@types/inquirer": "^8.1.3", 15 | "ava": "^3.15.0", 16 | "ts-node": "^10.4.0", 17 | "typescript": "^4.4.4" 18 | }, 19 | "dependencies": { 20 | "inquirer": "^8.2.0" 21 | }, 22 | "ava": { 23 | "extensions": [ 24 | "ts" 25 | ], 26 | "require": [ 27 | "ts-node/register" 28 | ] 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /algorithms/ar-shsrt/c/ar-shsrt.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int shellSort(int arr[], int n) 4 | { 5 | for (int gap = n/2; gap > 0; gap /= 2) 6 | { 7 | for (int i = gap; i < n; i += 1) 8 | { 9 | int temp = arr[i],j; 10 | for (j = i; j >= gap && arr[j - gap] > temp; j -= gap) 11 | arr[j] = arr[j - gap]; 12 | arr[j] = temp; 13 | } 14 | } 15 | return 0; 16 | } 17 | 18 | 19 | int main() 20 | { 21 | int arr[20],n; 22 | 23 | printf("Enter the no. of elements to be inserted:"); 24 | scanf("%d",&n); 25 | 26 | for (int i=0; i 3 | using namespace std; 4 | 5 | int main() { 6 | 7 | int n; 8 | cin >> n; 9 | int arr[n]; 10 | 11 | for (int i = 0; i < n; i++) 12 | { 13 | cin >> arr[i]; 14 | } 15 | 16 | int interval = n / 2; 17 | //taking the interval as a geometric progression with r = 1/2 18 | while (interval > 0) 19 | { 20 | for (int i = interval; i < n; i++) 21 | { 22 | for (int k = i - interval; k >= 0; k -= interval) 23 | { 24 | if (arr[k + interval] < arr[k]) 25 | { 26 | swap(arr[k], arr[k + interval]); 27 | } 28 | } 29 | } 30 | 31 | interval = interval / 2; 32 | } 33 | 34 | for (int i = 0; i < n; i++) 35 | { 36 | cout << arr[i] << ' '; 37 | } 38 | 39 | return 0; 40 | } 41 | -------------------------------------------------------------------------------- /algorithms/ar-shsrt/js/ar-shsrt.js: -------------------------------------------------------------------------------- 1 | const shellSort = (arr) => { 2 | let n = arr.length; 3 | 4 | for (let gap = Math.floor(n/2); gap > 0; gap = Math.floor(gap/2)) { 5 | for (let i = gap; i < n; i += 1) { 6 | let temp = arr[i]; 7 | 8 | let j; 9 | for (j = i; j >= gap && arr[j-gap] > temp; j-=gap) { 10 | arr[j] = arr[j-gap]; 11 | } 12 | 13 | arr[j] = temp; 14 | } 15 | } 16 | 17 | return arr; 18 | } 19 | 20 | const array = [1, 5, 6, 2, 0, 100, 15, 12, 19] 21 | 22 | const preSorted = `Unsorted array = ${array}` 23 | const sorted = `Sorted array = ${shellSort(array)}` 24 | 25 | console.log(preSorted + "\n" + sorted); -------------------------------------------------------------------------------- /algorithms/ar-shsrt/python3/ar-shsrt.py: -------------------------------------------------------------------------------- 1 | def shell_sort(nums): 2 | size = len(nums) 3 | 4 | # starting gap 5 | gap = size // 2 6 | 7 | while gap > 0: 8 | for x in range(gap, size): 9 | temp_val = nums[x] 10 | temp_position = x 11 | 12 | # sort everything in the gap 13 | while temp_position >= gap and nums[temp_position - gap] > temp_val: 14 | nums[temp_position] = nums[temp_position - gap] 15 | temp_position -= gap 16 | 17 | nums[temp_position] = temp_val 18 | 19 | # next gap to sort 20 | gap //= 2 21 | 22 | return nums 23 | 24 | 25 | arr = [198, 65, 2, 3, 36, 200, 55, 4, 0] 26 | print(f'pre shell sort: {arr}') 27 | print(f'post shell sort: {shell_sort(arr)}') -------------------------------------------------------------------------------- /algorithms/ar-slpsrt/c++/Sleep_sort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | static const int num_threads = 20; 7 | void sleep_and_print(int x) 8 | { 9 | // sleep for time x 10 | std::this_thread::sleep_for(std::chrono::milliseconds(x)); 11 | std::cout< num_list; 18 | std::cout<> threads_vec(num_list.size()); 29 | 30 | for (int i = 0; i < num_list.size(); ++i) { 31 | threads_vec[i] = std::make_shared(sleep_and_print, num_list[i]); 32 | } 33 | 34 | std::cout << "\nSorted list: \n"; 35 | 36 | //Join the threads with the main thread. 37 | for (int i = 0; i < num_threads; ++i) { 38 | threads_vec[i]->join(); 39 | } 40 | 41 | return 0; 42 | } -------------------------------------------------------------------------------- /algorithms/ar-slpsrt/c/ar-slpsrt.c: -------------------------------------------------------------------------------- 1 | // Implement sleep sort in C 2 | 3 | #include 4 | #include 5 | #include 6 | 7 | void *SleepAndPrint(void *duration) 8 | { 9 | int int_duration = *(int *)duration; 10 | sleep(int_duration); 11 | printf("%i ", int_duration); 12 | fflush(stdout); 13 | return NULL; 14 | } 15 | 16 | void SleepSort(int *arr, size_t size) 17 | { 18 | pthread_t threads[size]; 19 | 20 | for (size_t i = 0; i < size; i++) 21 | { 22 | pthread_create(&threads[i], NULL, SleepAndPrint, &arr[i]); 23 | } 24 | 25 | for (size_t i = 0; i < size; i++) 26 | { 27 | pthread_join(threads[i], NULL); 28 | } 29 | printf("\n"); 30 | } 31 | 32 | int main(int argc, const char *argv[]) 33 | { 34 | if (argc < 2) 35 | { 36 | printf("usage: ./ar-slpsrt [num num ...]\n", argv[0]); 37 | return 1; 38 | } 39 | 40 | const size_t arr_size = argc - 1; 41 | int arr[arr_size]; 42 | 43 | for (size_t i = 0; i < arr_size; i++) 44 | { 45 | sscanf(argv[i + 1], "%i", &arr[i]); 46 | } 47 | 48 | SleepSort(arr, arr_size); 49 | } -------------------------------------------------------------------------------- /algorithms/ar-slpsrt/java/Sleep_Sort.java: -------------------------------------------------------------------------------- 1 | import java.util.concurrent.CountDownLatch; 2 | 3 | public class SleepSort { 4 | public static void sleepSortAndPrint(int[] nums) { 5 | final CountDownLatch doneSignal = new CountDownLatch(nums.length); 6 | for (final int num : nums) { 7 | new Thread(new Runnable() { 8 | public void run() { 9 | doneSignal.countDown(); 10 | try { 11 | doneSignal.await(); 12 | Thread.sleep(num * 500); 13 | System.out.println(num); 14 | } catch (InterruptedException e) { 15 | e.printStackTrace(); 16 | } 17 | } 18 | }).start(); 19 | } 20 | } 21 | public static void main(String[] args) { 22 | int[] nums ={25, 20, 5, 3, 16}; 23 | for (int i = 0; i < args.length; i++) 24 | nums[i] = Integer.parseInt(args[i]); 25 | sleepSortAndPrint(nums); 26 | } 27 | } -------------------------------------------------------------------------------- /algorithms/ar-slpsrt/js/ar-slpsrt.js: -------------------------------------------------------------------------------- 1 | const sleep = (time) => new Promise((res) => setTimeout(res, time * 1000)); 2 | const sleepSort = async (arr) => { 3 | const response = []; 4 | await Promise.all( 5 | arr.map(async (element) => { 6 | await sleep(element); 7 | response.push(element); 8 | }) 9 | ); 10 | console.log(response); 11 | }; 12 | // Example 13 | sleepSort([9, 1, 2, 3, 5, 4, 7]); 14 | -------------------------------------------------------------------------------- /algorithms/ar-slpsrt/python3/Sleep_sort.py: -------------------------------------------------------------------------------- 1 | from time import sleep 2 | from threading import Timer 3 | 4 | def sleep_sort(l): 5 | res = [] 6 | def add1(x): 7 | res.append(x) 8 | mx = l[0] 9 | for i in l: 10 | if mx < i: 11 | mx = i 12 | Timer(i, add1, [i]).start() 13 | sleep(mx+1) 14 | return res 15 | 16 | l1 = [4,1,2,8,5,18,7,21] 17 | print("Initial Array") 18 | print(l1) 19 | 20 | print("Final Array is Arriving! Please wait..") 21 | r = sleep_sort(l1) 22 | print(r) -------------------------------------------------------------------------------- /algorithms/ar-soer/Python3/Sieve.py: -------------------------------------------------------------------------------- 1 | n = 10000 2 | is_prime = [] 3 | 4 | 5 | def sieve(): 6 | for i in range(n+1): 7 | is_prime.append(1) 8 | is_prime[0] = 0 9 | is_prime[1] = 0 10 | i = 2 11 | while((i*i) <= n): 12 | if(is_prime[i]): 13 | for j in range((i*i), n+1, i): 14 | is_prime[j] = 0 15 | i += 1 16 | 17 | 18 | sieve() 19 | # enter start as well as end 20 | start, end = map(int, input("Enter Range: ").split()) 21 | for i in range(start, end+1): 22 | if is_prime[i]: 23 | print(i, end=" ") # printing prime numbers using sieve 24 | print() 25 | 26 | # Enter Range: 25 65 27 | # 29 31 37 41 43 47 53 59 61 28 | -------------------------------------------------------------------------------- /algorithms/ar-soer/Sieve.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | // Sieve of Eratosthenes is a method to find whether a number is prime or not in O(1) time 4 | bool is_prime[1000001]; 5 | void sieve() 6 | { 7 | int MaxN = 1000000; 8 | for (int i = 0; i <= MaxN; i++) 9 | is_prime[i] = 1; 10 | is_prime[0] = is_prime[1] = 0; //number 0 and 1 is not prime we know that 11 | for (int i = 2; i * i <= MaxN; i++) 12 | { 13 | if (is_prime[i]) 14 | { 15 | for (int j = i * i; j <= MaxN; j += i) 16 | { 17 | is_prime[j] = 0; 18 | } 19 | } 20 | } 21 | 22 | } 23 | int main() 24 | { 25 | 26 | sieve();//preprocessing 27 | //enter range 28 | int start, end; cin >> start >> end; 29 | for (int i = start; i <= end; i++) 30 | { 31 | if (is_prime[i]) 32 | cout << i << " "; 33 | } 34 | cout << "\n"; 35 | 36 | return 0; 37 | } 38 | 39 | input: 1 10 40 | output: 2 3 5 7 41 | -------------------------------------------------------------------------------- /algorithms/ar-soer/python2/sieveoferatosthenes.py: -------------------------------------------------------------------------------- 1 | def sieveOfEratosthenes(n):#finds all prime numbers from 2 till n 2 | primes = [0,0] + [1]*(n-1) 3 | # 0 and 1 not prime 4 | p = 2 5 | while(p**2 <= n): 6 | if primes[p]:#if true 7 | for i in range(p**2, n+1, p):#update all multiples of p to 0 8 | primes[i] = 0; 9 | p+=1 10 | return primes 11 | 12 | 13 | if __name__ == '__main__': 14 | #insert range 15 | n = int(raw_input("Enter range till which primes is required(>0) : ")) 16 | ans = sieveOfEratosthenes(n) 17 | if(ans == [0]*(n+1)): 18 | print"no primes" 19 | else: 20 | for i in range(2,n+1): 21 | if ans[i]: 22 | print " ",i 23 | 24 | 25 | -------------------------------------------------------------------------------- /algorithms/ar-soer/seive.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | public class seive { 4 | public static void main(String args[]) { 5 | Scanner sc = new Scanner(System.in); 6 | System.out.println("Enter a number"); 7 | int num = sc.nextInt(); 8 | boolean[] a = new boolean[num]; 9 | 10 | for (int i = 0; i< a.length; i++) { 11 | a[i] = true; 12 | } 13 | for (int i = 2; i< Math.sqrt(num); i++) { 14 | if(a[i] == true) { 15 | for(int j = (i*i); j 2 | using namespace std; 3 | 4 | vector spiralOrder(vector >& matrix) 5 | { 6 | vector ans; 7 | 8 | if (matrix.size() == 0) 9 | return ans; 10 | 11 | int R = matrix.size(), C = matrix[0].size(); 12 | vector > seen(R, vector(C, false)); 13 | int dr[] = { 0, 1, 0, -1 }; 14 | int dc[] = { 1, 0, -1, 0 }; 15 | int r = 0, c = 0, di = 0; 16 | 17 | // Iterate from 0 to R * C - 1 18 | for (int i = 0; i < R * C; i++) { 19 | ans.push_back(matrix[r]); 20 | seen[r] = true; 21 | int cr = r + dr[di]; 22 | int cc = c + dc[di]; 23 | 24 | if (0 <= cr && cr < R && 0 <= cc && cc < C 25 | && !seen[cr][cc]) { 26 | r = cr; 27 | c = cc; 28 | } 29 | else { 30 | di = (di + 1) % 4; 31 | r += dr[di]; 32 | c += dc[di]; 33 | } 34 | } 35 | return ans; 36 | } 37 | 38 | // Driver code 39 | int main() 40 | { 41 | vector > a{ { 1, 2, 3, 4 }, 42 | { 5, 6, 7, 8 }, 43 | { 9, 10, 11, 12 }, 44 | { 13, 14, 15, 16 } }; 45 | 46 | for (int x : spiralOrder(a)) { 47 | cout << x << " "; 48 | } 49 | return 0; 50 | } 51 | 52 | // This code is contributed by Yashvendra Singh 53 | -------------------------------------------------------------------------------- /algorithms/ar-spmat/SpiralMatrix.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | class SpiralMatrix{ 4 | 5 | // Function to print in spiral order 6 | public static List spiralOrder(int[][] matrix) 7 | { 8 | List ans = new ArrayList(); 9 | 10 | if (matrix.length == 0) 11 | return ans; 12 | 13 | int R = matrix.length, C = matrix[0].length; 14 | boolean[][] seen = new boolean[R][C]; 15 | int[] dr = { 0, 1, 0, -1 }; 16 | int[] dc = { 1, 0, -1, 0 }; 17 | int r = 0, c = 0, di = 0; 18 | 19 | // Iterate from 0 to R * C - 1 20 | for (int i = 0; i < R * C; i++) { 21 | ans.add(matrix[r]); 22 | seen[r] = true; 23 | int cr = r + dr[di]; 24 | int cc = c + dc[di]; 25 | 26 | if (0 <= cr && cr < R && 0 <= cc && cc < C 27 | && !seen[cr][cc]) { 28 | r = cr; 29 | c = cc; 30 | } 31 | else { 32 | di = (di + 1) % 4; 33 | r += dr[di]; 34 | c += dc[di]; 35 | } 36 | } 37 | return ans; 38 | } 39 | 40 | // Driver Code 41 | public static void main(String[] args) 42 | { 43 | int a[][] = { { 1, 2, 3, 4 }, 44 | { 5, 6, 7, 8 }, 45 | { 9, 10, 11, 12 }, 46 | { 13, 14, 15, 16 } }; 47 | 48 | System.out.println(spiralOrder(a)); 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /algorithms/ar-spmat/spiralTraversalOfMatrix.cpp: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | using namespace std; 4 | 5 | 6 | int findK(vector> &a, int n, int m, int k) 7 | { 8 | int top=0,down=n-1,left=0,right=m-1; 9 | int d=0; 10 | int counter=0; 11 | while(top<=down && left<=right) 12 | { 13 | for(int i=left;i<=right && counter=left && counter=top && counter 2 | using namespace std; 3 | 4 | void swap(int *a,int *b) 5 | { 6 | int tmp=*a; 7 | *a=*b; 8 | *b=tmp; 9 | 10 | } 11 | int Selection_Sort(int arr[],int n) 12 | { 13 | int i,j,min=arr[0]; 14 | for(i=0;i>SIZE; 41 | int arr[SIZE]; 42 | int n=sizeof(arr)/sizeof(arr[0]); 43 | cout<<"Enter elements for an array"<>arr[i]; 47 | } 48 | cout<<"Unsorted Array elements are:"< 2 | 3 | void swap(int n,int arr[n], int t1, int t2){ 4 | int temp; 5 | temp = arr[t1]; 6 | arr[t1] = arr[t2]; 7 | arr[t2] = temp; 8 | } 9 | 10 | int main() 11 | { 12 | int n,iter,i,j,minimum; 13 | scanf("%d", &n); 14 | int arr[n]; 15 | for(i=0;i arr[j]) 26 | { 27 | temp = arr[i]; 28 | arr[i] = arr[j]; 29 | arr[j] = temp; 30 | } 31 | } 32 | } 33 | 34 | System.out.print("Now the Array after Sorting is :\n"); 35 | for(i=0; i inputArr[j]) { 10 | lowestIdx = j 11 | } 12 | } 13 | 14 | if (lowestIdx !== i) { 15 | // swap array value 16 | let temp = inputArr[i] 17 | inputArr[i] = inputArr[lowestIdx] 18 | inputArr[lowestIdx] = temp 19 | } 20 | } 21 | return inputArr 22 | } 23 | let arrExample = [1, 5, 2, 4, 6, 3] 24 | console.log(selectionSort(arrExample)) // [1, 2, 3, 4, 5, 6]s -------------------------------------------------------------------------------- /algorithms/ar-ssrt/python3/ar-ssrt.py: -------------------------------------------------------------------------------- 1 | def selection_sort(input_list): 2 | len_list = len(input_list) 3 | for i in range(len_list-1): 4 | # Finding the lowest value 5 | lower_index = i 6 | for j in range(i+1, len_list): 7 | if input_list[j] < input_list[lower_index]: 8 | lower_index = j 9 | 10 | # Swapping values 11 | input_list[i], input_list[lower_index] = input_list[lower_index], input_list[i] 12 | 13 | return input_list 14 | 15 | 16 | example = [1, 5, 2, 4, 6, 3] 17 | print(selection_sort(example)) 18 | -------------------------------------------------------------------------------- /algorithms/ar-ssrt/typescript/ar-ssrt.ts: -------------------------------------------------------------------------------- 1 | function selectionSortTS(inputArr: number[]): number[] { 2 | const arrLength = inputArr.length 3 | 4 | for (let i = 0; i < arrLength; i++) { 5 | let lowestIdx: number = i 6 | 7 | // find the lowest 8 | for (let j = i + 1; j < arrLength; j++) { 9 | if (inputArr[lowestIdx] > inputArr[j]) { 10 | lowestIdx = j 11 | } 12 | } 13 | 14 | if (lowestIdx !== i) { 15 | // swap array value 16 | let temp: number = inputArr[i] 17 | inputArr[i] = inputArr[lowestIdx] 18 | inputArr[lowestIdx] = temp 19 | } 20 | } 21 | return inputArr 22 | } 23 | const arrExampleTS: number[] = [1, 5, 2, 4, 6, 3] 24 | console.log(selectionSort(arrExample)) // [1, 2, 3, 4, 5, 6] -------------------------------------------------------------------------------- /algorithms/ar-zfnc/C++/z_function.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | typedef long long ll; 4 | 5 | ll z[2000005]; 6 | 7 | int main() { 8 | string s; 9 | cin>>s; 10 | ll n=s.size(); 11 | 12 | for (ll i = 1, l = 0, r = 0; i < n; ++i) { 13 | if (i <= r) 14 | z[i] = min (r - i + 1, z[i - l]); 15 | while (i + z[i] < n && s[z[i]] == s[i + z[i]]) 16 | ++z[i]; 17 | if (i + z[i] - 1 > r) 18 | l = i, r = i + z[i] - 1; 19 | } 20 | 21 | for(ll i=1;i right: 21 | left = pos 22 | right = pos + res[pos] - 1 23 | 24 | return res 25 | -------------------------------------------------------------------------------- /algorithms/binary-sort.sh: -------------------------------------------------------------------------------- 1 | 2 | binary-sort.sh 3 | 4 | #!/bin/bash 5 | 6 | declare -a arr 7 | echo "Enter the elements of the array: " 8 | read -ra arr 9 | 10 | n=${#arr[@]} 11 | for((i=0;i 2 | using namespace std; 3 | 4 | int binarySearch(int arr[], int l, int r, int x) 5 | { 6 | if (r >= l) { 7 | int mid = l + (r - l) / 2; 8 | 9 | if (arr[mid] == x) 10 | return mid; 11 | 12 | if (arr[mid] > x) 13 | return binarySearch(arr, l, mid - 1, x); 14 | 15 | return binarySearch(arr, mid + 1, r, x); 16 | } 17 | return -1; 18 | } 19 | 20 | int main(void) 21 | { 22 | int arr[] = { 2, 3, 4, 10, 40 }; 23 | int x = 10; 24 | int n = sizeof(arr) / sizeof(arr[0]); 25 | int result = binarySearch(arr, 0, n - 1, x); 26 | (result == -1) 27 | ? cout << "Element is not present in array" 28 | : cout << "Element is present at index " << result; 29 | return 0; 30 | } 31 | -------------------------------------------------------------------------------- /algorithms/binary_exponentiation.cpp: -------------------------------------------------------------------------------- 1 | ll binPow(ll fst, ll scnd){ 2 | ll ans=1; 3 | while(scnd>0){ 4 | if(scnd&1)ans = ans*fst%mod; 5 | fst = fst*fst%mod; 6 | scnd>>=1; 7 | } 8 | return ans; 9 | } 10 | -------------------------------------------------------------------------------- /algorithms/bucket_sort/bucket_sort.py: -------------------------------------------------------------------------------- 1 | # Sort an array using bucket sort 2 | def insertionSort(b): 3 | for i in range(1, len(b)): 4 | up = b[i] 5 | j = i - 1 6 | while j >= 0 and b[j] > up: 7 | b[j + 1] = b[j] 8 | j -= 1 9 | b[j + 1] = up 10 | return b 11 | 12 | def bucketSort(x): 13 | arr = [] 14 | slot_num = 10 # 10 slots 15 | for i in range(slot_num): 16 | arr.append([]) 17 | 18 | # Put array elements in different buckets 19 | for j in x: 20 | index_b = int(slot_num * j) 21 | arr[index_b].append(j) 22 | 23 | # Sort individual buckets 24 | for i in range(slot_num): 25 | arr[i] = insertionSort(arr[i]) 26 | 27 | # concatenate the result 28 | k = 0 29 | for i in range(slot_num): 30 | for j in range(len(arr[i])): 31 | x[k] = arr[i][j] 32 | k += 1 33 | return x 34 | 35 | # Test Code 36 | x = [0.795, 0.583, 0.646, 37 | 0.1234, 0.685, 0.3534] 38 | print("After sorting array elements are") 39 | print(bucketSort(x)) -------------------------------------------------------------------------------- /algorithms/exponentialSearch.cpp: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | using namespace std; 4 | 5 | int binarySearch(int arr[], int, int, int); 6 | 7 | int exponentialSearch(int arr[], int n, int x) 8 | { 9 | if (arr[0] == x) 10 | return 0; 11 | 12 | int i = 1; 13 | while (i < n && arr[i] <= x) 14 | i = i*2; 15 | 16 | return binarySearch(arr, i/2, 17 | min(i, n-1), x); 18 | } 19 | 20 | int binarySearch(int arr[], int l, int r, int x) 21 | { 22 | if (r >= l) 23 | { 24 | int mid = l + (r - l)/2; 25 | 26 | if (arr[mid] == x) 27 | return mid; 28 | 29 | if (arr[mid] > x) 30 | return binarySearch(arr, l, mid-1, x); 31 | 32 | return binarySearch(arr, mid+1, r, x); 33 | } 34 | 35 | return -1; 36 | } 37 | 38 | int main(void) 39 | { 40 | int arr[] = {2, 3, 4, 10, 40}; 41 | int n = sizeof(arr)/ sizeof(arr[0]); 42 | int x = 10; 43 | int result = exponentialSearch(arr, n, x); 44 | (result == -1)? cout <<"Element is not present in array" 45 | : cout <<"Element is present at index " << result; 46 | return 0; 47 | } 48 | 49 | -------------------------------------------------------------------------------- /algorithms/gr-bfsrh/C++: -------------------------------------------------------------------------------- 1 | // BFS Implementation using C++ 2 | #include 3 | using namespace std; 4 | 5 | vector v; 6 | vector> g; 7 | 8 | void edge(int a, int b) 9 | { 10 | g[a].push_back(b); 11 | // for undirected graph add this line 12 | // g[b].pb(a); 13 | } 14 | 15 | void bfs(int u) 16 | { 17 | queue q; 18 | 19 | q.push(u); 20 | v[u] = true; 21 | 22 | while (!q.empty()) 23 | { 24 | int f = q.front(); 25 | q.pop(); 26 | cout << f << " "; 27 | for (auto i = g[f].begin(); i != g[f].end(); i++) 28 | { 29 | if (!v[*i]) 30 | { 31 | q.push(*i); 32 | v[*i] = true; 33 | } 34 | } 35 | } 36 | } 37 | 38 | int main() 39 | { 40 | int n, e; 41 | cin >> n >> e; 42 | v.assign(n, false); 43 | g.assign(n, vector()); 44 | int a, b; 45 | for (int i = 0; i < e; i++) 46 | { 47 | cin >> a >> b; 48 | edge(a, b); 49 | } 50 | for (int i = 0; i < n; i++) 51 | { 52 | if (!v[i]) 53 | { 54 | bfs(i); 55 | } 56 | } 57 | return 0; 58 | } 59 | // Sample Input: 60 | // 8 10 61 | // 0 1 62 | // 0 2 63 | // 0 3 64 | // 0 4 65 | // 1 5 66 | // 2 5 67 | // 3 6 68 | // 4 6 69 | // 5 7 70 | // 6 7 71 | 72 | // Output: 73 | // 0 1 2 3 4 5 6 7 74 | -------------------------------------------------------------------------------- /algorithms/gr-bfsrh/Palindrome.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | int main() 6 | 7 | { 8 | 9 | int n, num, digit, rev = 0; 10 | 11 | cout << "Enter a positive number: "; 12 | 13 | cin >> num; 14 | 15 | n = num; 16 | 17 | do 18 | 19 | { 20 | 21 | digit = num % 10; 22 | 23 | rev = (rev * 10) + digit; 24 | 25 | num = num / 10; 26 | 27 | } while (num != 0); 28 | 29 | cout << " The reverse of the number is: " << rev << endl; 30 | 31 | if (n == rev) 32 | 33 | cout << " The number is a palindrome."; 34 | 35 | else 36 | 37 | cout << " The number is not a palindrome."; 38 | 39 | return 0; 40 | 41 | } 42 | -------------------------------------------------------------------------------- /algorithms/gr-bfsrh/gr-bfsrh.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int a[20][20], q[20], visited[20], n, i, j, f = 0, r = -1; 4 | 5 | void bfs(int v) 6 | { 7 | 8 | for (i = 1; i <= n; i++) 9 | if (a[v][i] && !visited[i]) 10 | q[++r] = i; 11 | 12 | if (f <= r) 13 | { 14 | visited[q[f]] = 1; 15 | bfs(q[f++]); 16 | } 17 | } 18 | 19 | int main() 20 | { 21 | int v; 22 | printf("\n Enter the number of vertices:"); 23 | scanf("%d", &n); 24 | 25 | for (i = 1; i <= n; i++) 26 | { 27 | q[i] = 0; 28 | visited[i] = 0; 29 | } 30 | 31 | printf("\n Enter the vertex values in matrix form:\n"); 32 | 33 | for (i = 1; i <= n; i++) 34 | for (j = 1; j <= n; j++) 35 | scanf("%d", &a[i][j]); 36 | 37 | printf("\n Enter the starting vertex:"); 38 | scanf("%d", &v); 39 | 40 | bfs(v); 41 | printf("\n Output :\n"); 42 | 43 | for (i = 1; i <= n; i++) 44 | if (visited[i]) 45 | printf("%d ", i); 46 | else 47 | printf("\n BFS not valid!! "); 48 | 49 | printf("\n"); 50 | } 51 | -------------------------------------------------------------------------------- /algorithms/gr-bfsrh/python3/gr_bfsrh.py: -------------------------------------------------------------------------------- 1 | from queue import Queue 2 | 3 | def bfs(graph): 4 | queue = Queue() 5 | visited = {} 6 | distance = {} 7 | parent = {} 8 | bfs_list = [] 9 | 10 | for node in graph.keys(): 11 | visited[node] = False 12 | distance[node] = -1 13 | parent[node] = None 14 | 15 | start = "A" #sourse 16 | visited[start] = True #marking starting node as visited 17 | distance[start] = 0 #setting level as 0 18 | queue.put(start) 19 | 20 | while not queue.empty(): 21 | visit = queue.get() 22 | bfs_list.append(visit) 23 | 24 | for v in graph[visit]: 25 | if not visited[v]: 26 | visited[v] = True 27 | distance[v] = distance[visit] + 1 28 | parent[v] = visit 29 | queue.put(v) 30 | return bfs_list 31 | 32 | 33 | if __name__ == "__main__": 34 | 35 | graph = { 36 | "A":["B", "D"], 37 | "B":["A","C"], 38 | "C":["B"], 39 | "D":["A", "E", "F"], 40 | "E":["D","F","G"], 41 | "F":["D","E","H"], 42 | "G":["E","H"], 43 | "H":["G","F"] 44 | } 45 | 46 | print(bfs(graph)) -------------------------------------------------------------------------------- /algorithms/gr-bfsrh/python3/test_gr_bfsrh.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | from gr_bfsrh import bfs 3 | 4 | class Test_ar_bsrt(unittest.TestCase): 5 | """docstring for Test_gr_bfsrh""" 6 | def test(self): 7 | arr = { 8 | "A":["B", "D"], 9 | "B":["A","C"], 10 | "C":["B"], 11 | "D":["A", "E", "F"], 12 | "E":["D","F","G"], 13 | "F":["D","E","H"], 14 | "G":["E","H"], 15 | "H":["G","F"] 16 | } 17 | self.assertEqual(bfs(arr), ['A', 'B', 'D', 'C', 'E', 'F', 'G', 'H']) 18 | 19 | if __name__ == "__main__": 20 | unittest.main() -------------------------------------------------------------------------------- /algorithms/gr-dfsrh/c++.cpp: -------------------------------------------------------------------------------- 1 | //Implementing dfs on graphs in c++ 2 | 3 | 4 | #include 5 | using namespace std; 6 | typedef long long int ll ; 7 | 8 | static int n; 9 | static int vis[n+1]; 10 | 11 | //Dfs function 12 | void dfs(int cur ,vector *adj) 13 | { 14 | 15 | vis[cur]= 1; 16 | cout<>n; //no of nodes 37 | 38 | vector adj[n+1]; 39 | 40 | for (int i = 0 ; i>u>>v; 42 | adj[u].push_back(v); 43 | adj[v].push_back(u); 44 | } 45 | 46 | dfs(1,adj); 47 | 48 | return 0; 49 | 50 | } 51 | -------------------------------------------------------------------------------- /algorithms/gr-dfsrh/c++/DFS.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | #define MAXSIZE 1000000 4 | 5 | vector > graph(MAXSIZE); 6 | bool vis[MAXSIZE]; 7 | 8 | 9 | void dfs(int start) 10 | { 11 | stack s; 12 | cout<>n; 37 | for(int i=0;i>u>>v; 40 | graph[u].push_back(v); 41 | graph[v].push_back(u); 42 | } 43 | 44 | //to check adjacency list 45 | // for(int i=1;i<=n;i++) 46 | // { 47 | // cout< "; 48 | // for(int j=0;j 1 -> 3 -> 4 -> 5 -> 2 13 | graph = { 14 | '0' : ['1','2'], 15 | '1' : ['3', '4'], 16 | '2' : ['5'], 17 | '3' : [], 18 | '4' : ['5'], 19 | '5' : [] 20 | } 21 | 22 | 23 | def dfs(graph: Dict[str, List[str]], root: str, visited = []) -> List[str]: 24 | if root in visited: 25 | return visited 26 | 27 | visited.append(root) 28 | [dfs(graph, k, visited) for k in graph[root]] 29 | return visited 30 | 31 | 32 | if __name__ == '__main__': 33 | dfs_result = dfs(graph, '0') 34 | print(f'Depth-First Search result: {" -> ".join(dfs_result)}') 35 | -------------------------------------------------------------------------------- /algorithms/gr-dij/c++/djikstra.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | int main() 4 | { 5 | int v,e; 6 | cin>>v>>e; 7 | vector< pair > adj[v]; 8 | for(int i=0;i>src>>dest>>w; 12 | adj[src].push_back({dest,w}); 13 | } 14 | int src; 15 | cin>>src; 16 | vector sptset; 17 | vectordist; 18 | for(int i=0;i:: iterator it = min_element(dist.begin(),dist.end()); 30 | int idx = it - dist.begin(); 31 | sptset[idx] = true; 32 | for(int i = 0;idist[idx]+w) 37 | { 38 | dist[v] = dist[idx] + w; 39 | } 40 | } 41 | } 42 | for(int i=0;i 4 | 5 | // Function for print prime 6 | // number in given range 7 | void primeInRange(int L, int R) 8 | { 9 | int i, j, flag; 10 | 11 | // Traverse each number in the 12 | // interval with the help of for loop 13 | for (i = L; i <= R; i++) { 14 | 15 | // Skip 0 and 1 as they are 16 | // neither prime nor composite 17 | if (i == 1 || i == 0) 18 | continue; 19 | 20 | // flag variable to tell 21 | // if i is prime or not 22 | flag = 1; 23 | 24 | // Iterate to check if i is prime 25 | // or not 26 | for (j = 2; j <= i / 2; ++j) { 27 | if (i % j == 0) { 28 | flag = 0; 29 | break; 30 | } 31 | } 32 | 33 | // flag = 1 means i is prime 34 | // and flag = 0 means i is not prime 35 | if (flag == 1) 36 | printf("%d ", i); 37 | } 38 | } 39 | 40 | // Driver Code 41 | int main() 42 | { 43 | // Given Range 44 | int L = 1; 45 | int R = 10; 46 | 47 | // Function Call 48 | primeInRange(L, R); 49 | 50 | return 0; 51 | } 52 | -------------------------------------------------------------------------------- /algorithms/gr-prims/C++/is_prime.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | 5 | bool is_prime(int n) { 6 | int d = 2; 7 | bool primo; 8 | if (n <= 1) return false; 9 | else { 10 | primo = true; 11 | while (primo && d <= n/2) { 12 | if (n % d == 0) { 13 | primo =false; 14 | } 15 | d++; 16 | } return primo; 17 | } 18 | } 19 | 20 | 21 | int main() 22 | { 23 | int n; 24 | cout<<"Enter the number: "; 25 | cin>>n; 26 | if (is_prime(n)) { 27 | cout<<"Prime"< 3 | using namespace std; 4 | int notes[] = { 1, 2, 5, 10, 20, 50, 100, 200, 500, 2000 }; 5 | int n = sizeof(notes) / sizeof(notes[0]); 6 | void minchange(int sum){ 7 | vector coins; 8 | for (int i = n - 1; i >= 0; i--) { 9 | while (sum >= notes[i]) { 10 | sum -= notes[i]; 11 | coins.push_back(notes[i]); 12 | } 13 | } 14 | for (int i = 0; i < coins.size(); i++) 15 | cout << coins[i] << "\t"; 16 | } 17 | int main(){ 18 | int n = 3253; 19 | cout << "The minimum number of coins/notes that sum up " << n << " is \t "; 20 | minchange(n); 21 | return 0; 22 | -------------------------------------------------------------------------------- /algorithms/insertion-sort.sh: -------------------------------------------------------------------------------- 1 | ines (15 sloc) 328 Bytes 2 | #!/bin/bash 3 | 4 | declare -a arr 5 | echo "Enter the elements of the array: " 6 | read -ra arr 7 | 8 | n=${#arr[@]} 9 | 10 | for((i=1;i 3 | using namespace std; 4 | 5 | 6 | int interpolationSearch(int arr[], int lo, int hi, int x) 7 | { 8 | int pos; 9 | 10 | if (lo <= hi && x >= arr[lo] && x <= arr[hi]) { 11 | 12 | pos = lo 13 | + (((double)(hi - lo) / (arr[hi] - arr[lo])) 14 | * (x - arr[lo])); 15 | 16 | if (arr[pos] == x) 17 | return pos; 18 | 19 | if (arr[pos] < x) 20 | return interpolationSearch(arr, pos + 1, hi, x); 21 | 22 | if (arr[pos] > x) 23 | return interpolationSearch(arr, lo, pos - 1, x); 24 | } 25 | return -1; 26 | } 27 | 28 | // Driver Code 29 | int main() 30 | { 31 | int arr[] = { 10, 12, 13, 16, 18, 19, 20, 21, 32 | 22, 23, 24, 33, 35, 42, 47 }; 33 | 34 | int n = sizeof(arr) / sizeof(arr[0]); 35 | 36 | int x = 18; 37 | int index = interpolationSearch(arr, 0, n - 1, x); 38 | 39 | if (index != -1) 40 | cout << "Element found at index " << index; 41 | else 42 | cout << "Element not found."; 43 | 44 | return 0; 45 | } 46 | -------------------------------------------------------------------------------- /algorithms/jumpSearch.cpp: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | using namespace std; 4 | 5 | int jumpSearch(int arr[], int x, int n) 6 | { 7 | int step = sqrt(n); 8 | 9 | int prev = 0; 10 | while (arr[min(step, n)-1] < x) 11 | { 12 | prev = step; 13 | step += sqrt(n); 14 | if (prev >= n) 15 | return -1; 16 | } 17 | 18 | 19 | while (arr[prev] < x) 20 | { 21 | prev++; 22 | 23 | if (prev == min(step, n)) 24 | return -1; 25 | } 26 | if (arr[prev] == x) 27 | return prev; 28 | 29 | return -1; 30 | } 31 | 32 | int main() 33 | { 34 | int arr[] = { 0, 1, 1, 2, 3, 5, 8, 13, 21, 35 | 34, 55, 89, 144, 233, 377, 610 }; 36 | int x = 55; 37 | int n = sizeof(arr) / sizeof(arr[0]); 38 | 39 | int index = jumpSearch(arr, x, n); 40 | 41 | cout << "\nNumber " << x << " is at index " << index; 42 | return 0; 43 | } -------------------------------------------------------------------------------- /algorithms/linear-search.sh: -------------------------------------------------------------------------------- 1 | linear-search.sh 2 | 3 | #!/bin/bash 4 | 5 | # Delcare array 6 | declare -a arr 7 | 8 | echo "Enter space separated integers" 9 | read -a arr 10 | 11 | totalElements=${#arr[@]} 12 | 13 | echo "Enter element to be searched for:" 14 | read search 15 | 16 | index=-1 17 | for ((i = 0; i < totalElements; i++)); do 18 | if [ ${arr[i]} -eq $search ]; then 19 | index=$i 20 | fi 21 | done 22 | 23 | if [ $index -ne -1 ]; then 24 | echo "Element found at index $((index + 1))" 25 | else 26 | echo "Element not found" 27 | fi 28 | -------------------------------------------------------------------------------- /algorithms/linearSearching.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int search(int arr[], int N, int x) 5 | { 6 | int i; 7 | for (i = 0; i < N; i++) 8 | if (arr[i] == x) 9 | return i; 10 | return -1; 11 | } 12 | 13 | int main(void) 14 | { 15 | int arr[] = { 2, 3, 4, 10, 40 }; 16 | int x = 10; 17 | int N = sizeof(arr) / sizeof(arr[0]); 18 | 19 | int result = search(arr, N, x); 20 | (result == -1) 21 | ? cout << "Element is not present in array" 22 | : cout << "Element is present at index " << result; 23 | return 0; 24 | } 25 | -------------------------------------------------------------------------------- /algorithms/minPalindrom.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | bool checkPalindrome(string word) 6 | { 7 | int start = 0; 8 | int end = word.length() - 1; 9 | while (start < end) 10 | { 11 | if (word[start] != word[end]) 12 | { 13 | return false; 14 | } 15 | start++; 16 | end--; 17 | } 18 | return true; 19 | } 20 | 21 | int main() 22 | { 23 | string input; 24 | cout << "Enter string : "; 25 | cin >> input; 26 | int n = input.length(); 27 | 28 | string temp = ""; 29 | for (int i = 0; i < input.length(); i++) 30 | { 31 | string sub = input.substr(i, n - i); 32 | if (checkPalindrome(sub)) 33 | { 34 | // if the string is a palidrome at this point, we need to append the reverse of previous substr to this string 35 | input += temp; 36 | break; 37 | } 38 | temp = input[i] + temp; // reverse 39 | } 40 | 41 | // output final palindromic work 42 | 43 | cout << "Palindromic string is " << (input) << endl; 44 | return 0; 45 | } 46 | -------------------------------------------------------------------------------- /algorithms/simpleCalculator.cpp: -------------------------------------------------------------------------------- 1 | # include 2 | using namespace std; 3 | 4 | int main() { 5 | 6 | char op; 7 | float num1, num2; 8 | 9 | cout << "Enter operator: +, -, *, /: "; 10 | cin >> op; 11 | 12 | cout << "Enter two operands: "; 13 | cin >> num1 >> num2; 14 | 15 | switch(op) { 16 | 17 | case '+': 18 | cout << num1 << " + " << num2 << " = " << num1 + num2; 19 | break; 20 | 21 | case '-': 22 | cout << num1 << " - " << num2 << " = " << num1 - num2; 23 | break; 24 | 25 | case '*': 26 | cout << num1 << " * " << num2 << " = " << num1 * num2; 27 | break; 28 | 29 | case '/': 30 | cout << num1 << " / " << num2 << " = " << num1 / num2; 31 | break; 32 | 33 | default: 34 | // If the operator is other than +, -, * or /, error message is shown 35 | cout << "Error! operator is not correct"; 36 | break; 37 | } 38 | 39 | return 0; 40 | } 41 | -------------------------------------------------------------------------------- /algorithms/slidingWindow/slidingWindowMedian.cpp: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | #include 4 | #include 5 | #include 6 | using namespace std; 7 | 8 | vector medianSlidingWindow(vector& nums, int k) { 9 | multiset window(nums.begin(), nums.begin() + k); 10 | auto mid = next(window.begin(), k / 2); 11 | vector medians; 12 | for (int i=k; ; i++) { 13 | 14 | // Push the current median. 15 | medians.push_back((double(*mid) + *prev(mid, 1 - k%2)) / 2); 16 | 17 | // If all done, return. 18 | if (i == nums.size()) 19 | return medians; 20 | 21 | // Insert nums[i]. 22 | window.insert(nums[i]); 23 | if (nums[i] < *mid) 24 | mid--; 25 | 26 | // Erase nums[i-k]. 27 | if (nums[i-k] <= *mid) 28 | mid++; 29 | window.erase(window.lower_bound(nums[i-k])); 30 | } 31 | } -------------------------------------------------------------------------------- /algorithms/sorting-py/bogosort.py: -------------------------------------------------------------------------------- 1 | import random 2 | 3 | def bogosort(nums): 4 | def isSorted(nums): 5 | if len(nums) < 2: 6 | return True 7 | for i in range(len(nums) - 1): 8 | if nums[i] > nums[i + 1]: 9 | return False 10 | return True 11 | 12 | while not isSorted(nums): 13 | random.shuffle(nums) 14 | return nums 15 | num1 = input('Input comma separated numbers:\n').strip() 16 | nums = [int(item) for item in num1.split(',')] 17 | print(bogosort(nums)) --------------------------------------------------------------------------------