Repository: ahampriyanshu/algo_ds_101 Branch: main Commit: ea880b13c09d Files: 1380 Total size: 1.9 MB Directory structure: gitextract_qpjjgosa/ ├── .github/ │ ├── ISSUE_TEMPLATE/ │ │ ├── Documentation.yml │ │ ├── New-Submission.yml │ │ └── config.yml │ ├── pull_request_template.md │ └── workflows/ │ ├── contributors.yml │ └── welcome.yml ├── 404.md ├── Algorithms/ │ ├── Array/ │ │ ├── Arr4 right shift.c │ │ ├── InsertArray.c │ │ ├── LinearSearch.java │ │ ├── Merge-Sorted-Array.c │ │ ├── Merge-Sorted-Array.cpp │ │ ├── Merge-Sorted-Array.js │ │ ├── Merge-Sorted-Array.py │ │ ├── Merge_Sorted_Arrays.rb │ │ ├── Rearrange-High-Low.js │ │ ├── Rearrange-High-Low.kt │ │ ├── Remove-Dublicate.js │ │ ├── Remove-Duplicates-from-Sorted-Array.c │ │ ├── Remove-Duplicates-from-Sorted-Array.cpp │ │ ├── Shuffle.c │ │ ├── Two-Arrays-And-Swaps.c │ │ ├── check_two_equal_array.cpp │ │ ├── copyarray.c │ │ ├── counting_frequency_of_char_in_string.c │ │ ├── findpos.py │ │ ├── high-low-rearrangement.c │ │ ├── high-low-rearrangement.c++ │ │ ├── high-low-rearrangement.py │ │ ├── largest-smallest-number-and-sum-of-all-elements-in-array.java │ │ ├── merge-sorted-arrays-algo-only.py │ │ ├── merge_without_extraspace.cpp │ │ ├── merging_2_arrays.c │ │ ├── rearrange-high-low.java │ │ ├── revering_array.c │ │ ├── rotate_matrix_90degree.cpp │ │ ├── rotated_sorted_array_search.cpp │ │ ├── twoSum.cpp │ │ ├── twoSum.kt │ │ └── wave_form_array │ ├── Backtracking/ │ │ ├── Crossword/ │ │ │ └── Crossword.cpp │ │ ├── Nqueen/ │ │ │ ├── N_Queen.java │ │ │ ├── Nqueens.c │ │ │ ├── Nqueens.cpp │ │ │ ├── Nqueens_optimized.cpp │ │ │ ├── nqueen.cpp │ │ │ └── nqueens.py │ │ ├── Permutation/ │ │ │ ├── Permutations.c │ │ │ ├── permutation.py │ │ │ ├── permutations.cpp │ │ │ └── permutations.js │ │ ├── README.md │ │ └── Rat-In-A-Maze/ │ │ └── Rat-In-A-Maze.cpp │ ├── Cryptography/ │ │ ├── AES_Cipher/ │ │ │ ├── AES_Cipher.py │ │ │ └── README.md │ │ ├── Affine_Cipher/ │ │ │ ├── Affine_Cipher.cpp │ │ │ ├── Affine_Cipher.py │ │ │ ├── README.md │ │ │ └── affine_cipher.c │ │ ├── Bifid_Cipher/ │ │ │ ├── Bifid_Cipher.py │ │ │ └── README.md │ │ ├── CIA_Triad_Ciper/ │ │ │ └── README.md │ │ ├── Caesar_Cipher/ │ │ │ ├── Caesar Cypher.cpp │ │ │ ├── Caesar Cypher.py │ │ │ ├── CaesarCipher.java │ │ │ ├── Caesar_Cipher.c │ │ │ ├── Caesar_Cipher.cs │ │ │ ├── Caesar_Cipher.js │ │ │ ├── Caesar_Cipher.php │ │ │ ├── Caesar_Cypher.rb │ │ │ └── README.md │ │ ├── README.md │ │ ├── RSA_Cipher/ │ │ │ ├── README.md │ │ │ ├── RSA_Cipher.py │ │ │ ├── RSA_cipher.cpp │ │ │ └── RSA_cipher.java │ │ ├── Shamir_Cipher/ │ │ │ ├── Shamir_Cipher.c │ │ │ └── Shamir_Cipher.cpp │ │ ├── Vernam_Cipher/ │ │ │ ├── README.md │ │ │ ├── Vernam_Cipher.cpp │ │ │ ├── Vernam_Cipher.js │ │ │ └── Vernam_Cipher.py │ │ └── Vigenere_Cipher/ │ │ ├── README.md │ │ ├── Vigenere_Cipher.cpp │ │ ├── Vigenere_Cipher.py │ │ ├── Vignere_Cipher.cs │ │ └── vigenereCipher.py │ ├── DP/ │ │ ├── 0-1_Knapsack_Problem/ │ │ │ ├── 0-1 Knapsack Problem.java │ │ │ ├── Branch_And_Bound/ │ │ │ │ └── 0-1_knapsack.cpp │ │ │ ├── knapsackProblem.java │ │ │ ├── knapsack_problem_0_1.cpp │ │ │ └── knapsack_problem_0_1.py │ │ ├── AdjacentBitCounts.cpp │ │ ├── AdjacentBitCounts.js │ │ ├── Bitmask DP/ │ │ │ └── TravellingSalesman.cpp │ │ ├── Branch_And_Bound/ │ │ │ ├── 0_1_KnapSack.py │ │ │ └── Knapsack_Branch_and_Bound.java │ │ ├── Count_Square_Matrices.cpp │ │ ├── Count_Square_Matrices.py │ │ ├── Edit_Distance/ │ │ │ ├── Edit_Distance.js │ │ │ ├── Edit_distance.cpp │ │ │ ├── README.md │ │ │ └── edit_distance.py │ │ ├── Egg_Drop/ │ │ │ ├── Egg_Drop.cpp │ │ │ ├── Egg_Drop.cs │ │ │ ├── egg drop.java │ │ │ ├── egg_drop.py │ │ │ └── egg_drop.ts │ │ ├── Fibonacci_Series/ │ │ │ ├── Fibonacci.c │ │ │ ├── Fibonacci.php │ │ │ ├── fibonacci.go │ │ │ ├── fibonacci.js │ │ │ └── fibonacci.py │ │ ├── Gauss_Easter_Date/ │ │ │ ├── CalculateEasterDate.java │ │ │ ├── Gauss_Easter_Date.cpp │ │ │ ├── Gauss_Easter_Date.php │ │ │ ├── Gauss_Easter_Date.py │ │ │ ├── Gauss_Easter_Date.rb │ │ │ ├── easterDate.cpp │ │ │ ├── easterDate.go │ │ │ ├── easterDate.java │ │ │ └── easterDate.js │ │ ├── Generate_ATM_Codes.py │ │ ├── Gold_Mine_Problem/ │ │ │ ├── goldmine.java │ │ │ └── goldmine.py │ │ ├── Golomb_Sequence/ │ │ │ ├── Golomb Sequence.cpp │ │ │ ├── Golomb.cpp │ │ │ ├── Golomb.java │ │ │ └── golomb.py │ │ ├── Knight_Probability/ │ │ │ ├── Knight_Probability_in_a_ChessBoard.cpp │ │ │ └── Problem_Statement.md │ │ ├── LCS/ │ │ │ ├── LCS_of_three_strings.py │ │ │ ├── LongestCommonSubsequence.cpp │ │ │ ├── LongestCommonSubsequenceLength.java │ │ │ ├── Longest_Common_Subsequence_of_Three_String.java │ │ │ ├── Longest_Common_Subsequence_of_Two_Sequences.c │ │ │ ├── Longest_Common_Subsequence_of_Two_Sequences.cpp │ │ │ ├── lcs.py │ │ │ └── lcs_of_3_strings.cpp │ │ ├── LIS/ │ │ │ ├── LIS.c │ │ │ ├── LIS.cpp │ │ │ ├── LIS.go │ │ │ ├── LIS.java │ │ │ ├── LongestIncreaseSubSequence.cpp │ │ │ ├── README.md │ │ │ └── lis.py │ │ ├── LSCS/ │ │ │ ├── LSCS.c │ │ │ ├── LSCS.cpp │ │ │ ├── lscs.go │ │ │ ├── lscs.py │ │ │ └── shortest_common_supersequence.c │ │ ├── Largest Divisible Subset.cpp │ │ ├── Largest divisible subset in array/ │ │ │ └── file.py │ │ ├── Largest_Divisible_Subset.js │ │ ├── Largest_Divisible_Subsets.java │ │ ├── Largest_Divisible_Subsets.py │ │ ├── Largest_Sum_Contiguous_Subarray/ │ │ │ ├── .vscode/ │ │ │ │ ├── c_cpp_properties.json │ │ │ │ ├── launch.json │ │ │ │ └── tasks.json │ │ │ ├── C++_Implementation/ │ │ │ │ ├── Kadane │ │ │ │ ├── makefile │ │ │ │ ├── obj/ │ │ │ │ │ ├── functions.o │ │ │ │ │ └── main.o │ │ │ │ └── src/ │ │ │ │ ├── functions.cpp │ │ │ │ ├── include/ │ │ │ │ │ └── functions.h │ │ │ │ └── main.cpp │ │ │ ├── Kadane's Algorithm.cpp │ │ │ ├── LSCS.cpp │ │ │ ├── LSCS.js │ │ │ ├── LSCS.swift │ │ │ └── lscs.c │ │ ├── MOS_Algorithm.cpp │ │ ├── Max_Product_Subarray/ │ │ │ └── max_product_subarray.py │ │ ├── Maximum_Achievable_Coins/ │ │ │ ├── Maximum_Achievable_Coins.php │ │ │ ├── Maximum_Achievable_coins.c │ │ │ ├── Maximum_Achievable_coins.java │ │ │ ├── Maximum_Achievable_coins.py │ │ │ └── maximum_achievable_coins.cpp │ │ ├── Minimum_Sum_Descent/ │ │ │ ├── min-sum.c │ │ │ ├── minsum.cs │ │ │ ├── minsum.go │ │ │ └── minsum.ts │ │ ├── Partition_Sum/ │ │ │ ├── DP_PartitionSum.java │ │ │ ├── partition_sum.c │ │ │ ├── partition_sum.cpp │ │ │ ├── partition_sum.cs │ │ │ └── partition_sum.php │ │ ├── README.md │ │ ├── Recaman's Sequence.c │ │ ├── Scramble Strings/ │ │ │ └── ScrambleString.cpp │ │ ├── Shortest_Common_Supersequence/ │ │ │ ├── shortest_common_sequence.java │ │ │ ├── shortest_common_supersequence.cpp │ │ │ ├── shortest_common_supersequence.cs │ │ │ ├── shortest_common_supersequence.js │ │ │ └── shortest_common_supersequence.py │ │ ├── Sudoku_Solver/ │ │ │ ├── README.md │ │ │ ├── SudokuSolver.java │ │ │ ├── SudokuSolver.py │ │ │ ├── Sudoku_Solver.cpp │ │ │ ├── Sudoku_Solver.cs │ │ │ └── Sudoku_Solver.js │ │ ├── Target_Sum/ │ │ │ ├── Target_Sum.c │ │ │ ├── Target_Sum.cpp │ │ │ ├── Target_Sum.java │ │ │ ├── Target_Sum.js │ │ │ └── Target_Sum.py │ │ ├── Tower_Of_Hanoi/ │ │ │ ├── README.md │ │ │ ├── TOH.java │ │ │ ├── Tower_Of_Hanoi.cs │ │ │ ├── Tower_Of_Hanoi.js │ │ │ ├── Tower_of_hanoi.ts │ │ │ ├── tower_of_hanoi.c │ │ │ ├── tower_of_hanoi.cpp │ │ │ ├── tower_of_hanoi.go │ │ │ └── tower_of_hanoi.py │ │ ├── TrappingWater/ │ │ │ └── TrappingWater.cpp │ │ ├── Water_Area/ │ │ │ ├── QUESTION.md │ │ │ ├── Water-area.py │ │ │ └── water_area.rb │ │ ├── Z_Algorithm/ │ │ │ ├── README.md │ │ │ ├── Z-Algorithm.c++ │ │ │ └── Z_Algo.py │ │ ├── creating an string input function in C.c │ │ ├── partition_sum.py │ │ └── rod-cutting-problem.cpp │ ├── Graph/ │ │ ├── A_Star/ │ │ │ ├── A_star.cpp │ │ │ ├── A_star.cs │ │ │ ├── A_star.py │ │ │ ├── A_star.ts │ │ │ └── astar.py │ │ ├── BFS/ │ │ │ ├── BFS.c │ │ │ ├── BFS.cpp │ │ │ ├── BFS.go │ │ │ ├── BFS.java │ │ │ ├── BFS.py │ │ │ ├── BFS.rb │ │ │ ├── README.md │ │ │ └── bfs.js │ │ ├── Bellman_Ford/ │ │ │ ├── BellMan_Ford.py │ │ │ ├── README.md │ │ │ ├── bellmanFord.cpp │ │ │ └── bellman_ford.c │ │ ├── Bidirectional_search/ │ │ │ ├── Bidirectional_Search.py │ │ │ └── Bidirectional_search.cpp │ │ ├── Bidirectional_search_algo.py │ │ ├── DFS/ │ │ │ ├── DFS.cpp │ │ │ ├── DFS.java │ │ │ ├── Depth First Search[DFS].cpp │ │ │ ├── README.md │ │ │ ├── dfs.js │ │ │ └── dfs.py │ │ ├── DSU/ │ │ │ ├── dsu.cpp │ │ │ └── dsu.py │ │ ├── Depth First Transversal/ │ │ │ └── DFT.py │ │ ├── Dijkstra/ │ │ │ ├── Dijikstra.java │ │ │ ├── Dijkstra.c │ │ │ ├── Dijkstra.cpp │ │ │ ├── Dijkstra.cs │ │ │ ├── Dijkstra.go │ │ │ ├── Dijkstra.js │ │ │ ├── Dijkstra.php │ │ │ ├── README.md │ │ │ ├── dijkstra_leftist_heap/ │ │ │ │ ├── README.txt │ │ │ │ ├── WDGraph.cpp │ │ │ │ ├── WDGraph.h │ │ │ │ ├── dijkstra.cpp │ │ │ │ ├── leftistHeap.cpp │ │ │ │ └── leftistHeap.h │ │ │ └── djikstra.py │ │ ├── Flood_Fill/ │ │ │ ├── Flood_Fill.cpp │ │ │ ├── Flood_Fill.java │ │ │ ├── Flood_Fill.js │ │ │ └── flood_fill_algorithm.cs │ │ ├── Floyd_Warshall/ │ │ │ ├── Floyd_Warshall.c │ │ │ ├── Floyd_Warshall.cpp │ │ │ ├── Floyd_Warshall.java │ │ │ ├── Floyd_Warshall.py │ │ │ └── README.md │ │ ├── Hopcroft_Karp/ │ │ │ └── Hopcroft_Karp_algorithm.cpp │ │ ├── Hungarian_algorithm/ │ │ │ └── Hungarian_algorithm.cpp │ │ ├── Johnson_algorithm/ │ │ │ └── Johnson_algorithm.cpp │ │ ├── Karger_algorithm/ │ │ │ ├── Karger_algorithm.cpp │ │ │ └── sample.txt │ │ ├── Kosarajus_Algorithm/ │ │ │ ├── kosajaru.rs │ │ │ ├── kosaraju.ts │ │ │ └── kosaraju_algorithm_strongly_connected_components.cpp │ │ ├── Kruskal's_MST/ │ │ │ ├── KruskalMST.c │ │ │ ├── Kruskal_Algorithm.cpp │ │ │ ├── README.md │ │ │ ├── cpp/ │ │ │ │ └── kruskal.cpp │ │ │ ├── python/ │ │ │ │ └── KruskalMST.py │ │ │ └── rust/ │ │ │ └── kruskal.rs │ │ ├── LIS/ │ │ │ └── README.md │ │ ├── Level order traversal.cpp │ │ ├── Lowest_Common_Manager/ │ │ │ ├── Lowest_Common_Manager.py │ │ │ └── QUESTION.md │ │ ├── Prim's_MST/ │ │ │ ├── Prim's_MST.py │ │ │ ├── Prims_MST.java │ │ │ └── README.md │ │ ├── README.md │ │ ├── Tarjan's Algorithm/ │ │ │ └── StronglyConnectedComponents.cpp │ │ ├── Topological Sort/ │ │ │ ├── QUESTION.md │ │ │ └── topo_sort.py │ │ ├── Topological sort/ │ │ │ ├── README.md │ │ │ └── Topological_sort.cpp │ │ ├── Youngest_Common_Ancestor/ │ │ │ ├── QUESTION.md │ │ │ ├── YoungerCommonAncestor.cpp │ │ │ ├── YoungestCommonAncestor.java │ │ │ └── youngest-comm-anc.py │ │ ├── articulation_points.py │ │ ├── flood_fill.py │ │ ├── lagrange_interpolation.cpp │ │ ├── lowest_common_manager/ │ │ │ └── lowest_common_manager.java │ │ └── newton_raphson_method.c │ ├── Hashing/ │ │ ├── Amicable/ │ │ │ ├── Amicable_Number.rb │ │ │ ├── Amicable_Numbers..c │ │ │ ├── Amicable_Numbers.cpp │ │ │ ├── Amicable_Numbers.java │ │ │ ├── amicable.cs │ │ │ ├── amicable.js │ │ │ ├── amicable.swift │ │ │ ├── amicable_numbers.php │ │ │ └── amicable_numbers.py │ │ ├── Brick_Wall/ │ │ │ ├── Brick_wall.cpp │ │ │ └── QUESTION.md │ │ ├── Chaining/ │ │ │ └── chainingHashing.cpp │ │ ├── Cuckoo_Hashing/ │ │ │ ├── Cuckoo_Hashing.cpp │ │ │ └── Cuckoo_Hashing.java │ │ ├── Divisible_Pair_Count/ │ │ │ ├── DivisiblePairCount.c │ │ │ ├── DivisiblePairCount.go │ │ │ ├── DivisiblePairCount.java │ │ │ ├── DivisiblePairCount.js │ │ │ ├── DivisiblePairCount.py │ │ │ └── DivsiblePairCount.cpp │ │ ├── Group_Anagrams/ │ │ │ ├── Group_Anagrams.cpp │ │ │ ├── QUESTIONS.md │ │ │ ├── group_anagrams.js │ │ │ └── group_anagrams.py │ │ ├── Open Addressing/ │ │ │ ├── doubleHashHashingTable.cpp │ │ │ ├── linearProbingHashTable.cpp │ │ │ └── quadraticProbingHashTable.cpp │ │ └── Recaman_Sequence/ │ │ ├── Recamans_Sequence.java │ │ ├── Recamans_Sequence.ts │ │ ├── recaman.py │ │ ├── recaman_sequence.cpp │ │ └── recamans_sequence.cs │ ├── Heap/ │ │ └── README.md │ ├── LinkedList/ │ │ └── Floyd_Cylce_detection/ │ │ ├── floyd_cycle_detection.cpp │ │ ├── floyd_cycle_detection.java │ │ ├── floyd_cycle_detection.kt │ │ ├── floyd_cycle_detection.py │ │ └── floyd_cycle_detection.swift │ ├── Matrix/ │ │ ├── README.md │ │ └── Spiral-Matrix/ │ │ └── Spiral-Matrix.cpp │ ├── Merging-Interval/ │ │ ├── #999 merging_intervals.py │ │ ├── Merging_Intervals.java │ │ ├── README.md │ │ ├── merge_intervals.cpp │ │ └── merge_intervals.js │ ├── Pattern-Searching/ │ │ ├── Aho-Corasick/ │ │ │ └── Readme.md │ │ ├── Binary_Search/ │ │ │ └── search_in_2D_matrix.java │ │ ├── README.md │ │ └── Substring_Check/ │ │ └── search.php │ ├── Queue/ │ │ ├── first_negative_integer_in_window.cpp │ │ ├── first_nonrepeating_char_in_stream.cpp │ │ └── reversing a queue.cpp │ ├── README.md │ ├── Recursion/ │ │ ├── All_Subsets.c │ │ ├── Combination_Sum/ │ │ │ ├── Combination_Sum.php │ │ │ └── combination_sum.cpp │ │ ├── Factorial/ │ │ │ ├── Factorial.c │ │ │ ├── Factorial.cs │ │ │ ├── Factorial.go │ │ │ ├── Factorial_Algorithm.cpp │ │ │ ├── Factorial_Algorithm.py │ │ │ ├── factorial.js │ │ │ └── factorial.py │ │ ├── Josephus/ │ │ │ ├── Josephus.c │ │ │ ├── Josephus.cs │ │ │ ├── Josephus.java │ │ │ ├── josephus.cpp │ │ │ └── josephus.kt │ │ ├── Keypadcodes.cpp │ │ ├── Permutation/ │ │ │ ├── Permutation.cs │ │ │ ├── Permutation.js │ │ │ ├── Permutation.ts │ │ │ ├── Permutations_Recursion.cpp │ │ │ └── Permutations_Recursion.py │ │ └── README.md │ ├── Searching/ │ │ ├── A-Star Search/ │ │ │ ├── A_Star.ipynb │ │ │ └── README.md │ │ ├── Binary-Search/ │ │ │ ├── Binary_Search_CubicRoot.cpp │ │ │ ├── Binary_search_javascript.js │ │ │ ├── Koko_Eating_Bananas/ │ │ │ │ ├── KEB.java │ │ │ │ ├── Koko_Eating_Bananas.cpp │ │ │ │ ├── Koko_Eating_Bananas.py │ │ │ │ └── QUESTION.md │ │ │ ├── README.md │ │ │ ├── Rotated-Sorted-Array-Search.cs │ │ │ ├── Rotated-Sorted-Array-Search.js │ │ │ ├── Rotated-Sorted-Array-Search.py │ │ │ ├── binarySearch.c │ │ │ ├── binarySearch.cpp │ │ │ ├── binarySearch.js │ │ │ ├── binarySearch.kt │ │ │ ├── binarySearch.scala │ │ │ ├── binary_search.cpp │ │ │ ├── binary_search.java │ │ │ ├── binarysearch.java │ │ │ ├── binarysearch.js │ │ │ ├── binarysearch.php │ │ │ ├── binarysearch.py │ │ │ ├── binarysearch.sh │ │ │ ├── matrix_binary_search.py │ │ │ └── search_in_2d_matrix.cpp │ │ ├── Exponential-Search/ │ │ │ ├── exponential_search.cpp │ │ │ ├── exponential_search.php │ │ │ └── exponential_search.py │ │ ├── Fibonacci-Search/ │ │ │ ├── Fibonacci_Search.cpp │ │ │ ├── Fibonacci_search.java │ │ │ ├── Fibonacci_search.php │ │ │ ├── Fibonacci_search_in_C.c │ │ │ ├── fibonacciSearch.py │ │ │ ├── fibonacci_search.c │ │ │ └── fibonacci_search.js │ │ ├── Interpolation-Search/ │ │ │ ├── IS.cpp │ │ │ └── IS.py │ │ ├── Jump-Search/ │ │ │ ├── JumpSearch.java │ │ │ ├── Jump_Search.cpp │ │ │ ├── jumpSearch.cs │ │ │ ├── jumpSearch.go │ │ │ ├── jumpSearch.js │ │ │ ├── jumpSearch.ts │ │ │ └── jump_search.py │ │ ├── Linear-Search/ │ │ │ ├── LINEAR_SEARH.cpp │ │ │ ├── LinearSearch.js │ │ │ ├── Linear_Search.cpp │ │ │ ├── Linear_Search.go │ │ │ ├── Linear_Search.py │ │ │ ├── Linearsearch.c │ │ │ ├── README.md │ │ │ ├── linear_search.java │ │ │ └── linear_search.sh │ │ ├── README.md │ │ ├── Sublist-Search/ │ │ │ ├── Sublist_Search.php │ │ │ ├── sublist_search.cpp │ │ │ ├── sublist_search.cs │ │ │ ├── sublist_search.java │ │ │ ├── sublist_search.js │ │ │ └── sublist_search.py │ │ ├── Ternary-Search/ │ │ │ ├── README.md │ │ │ ├── Ternary-String.c │ │ │ ├── ternarySearch.cpp │ │ │ ├── unimodal_func.cpp │ │ │ ├── unimodal_func.java │ │ │ ├── unimodal_func.js │ │ │ └── unimodal_func.py │ │ └── Trie-Search/ │ │ ├── Trie Data Structure.cpp │ │ ├── Trie1_HashMap.java │ │ ├── TrieDataStructure.java │ │ ├── Trie_Search.cpp │ │ ├── Trie_Search.go │ │ └── Trie_Search.py │ ├── Sorting/ │ │ ├── 3-Way_Quick_Sort/ │ │ │ ├── 3-Way_Quick_Sort.cpp │ │ │ ├── 3-Way_Quick_Sort.cs │ │ │ ├── 3-Way_Quick_Sort.java │ │ │ └── 3_Way_Quick_Sort.c │ │ ├── Bead_Sort/ │ │ │ ├── Bead_Sort.php │ │ │ ├── Bead_Sort.rb │ │ │ ├── Bead_sort.cpp │ │ │ ├── README.md │ │ │ └── bead_sort.py │ │ ├── Binary_Insertion_Sort/ │ │ │ ├── Binary Insertion Sort.c │ │ │ ├── Binary_Insertion_Sort.cpp │ │ │ ├── Binary_Insertion_Sort.py │ │ │ └── Readme.md │ │ ├── Bitonic_Search/ │ │ │ ├── BitonicSort.java │ │ │ ├── Bitonic_sort.c │ │ │ ├── Readme.md │ │ │ └── bitonic_search.py │ │ ├── Brick_Sort/ │ │ │ ├── BrickSort.js │ │ │ ├── Brick_Sort.c │ │ │ ├── Readme.md │ │ │ └── brickSort.py │ │ ├── Bubble_Sort/ │ │ │ ├── BubbleSort.js │ │ │ ├── BubbleSort.scala │ │ │ ├── Bubble_Sort.c │ │ │ ├── Bubble_Sort.cs │ │ │ ├── Bubble_Sort.py │ │ │ ├── Bubble_sort_optimised.cpp │ │ │ ├── bubbleSort.cpp │ │ │ ├── bubble_sort.java │ │ │ ├── bubble_sort.sh │ │ │ └── readme.md │ │ ├── Bucket_Sort/ │ │ │ ├── BucketSort.c │ │ │ ├── BucketSort.java │ │ │ ├── BucketSort.js │ │ │ ├── BucketSort.py │ │ │ ├── README.md │ │ │ ├── bucket_sort.cpp │ │ │ ├── bucketsort.php │ │ │ ├── bucketsort.rb │ │ │ └── bucketsortinC.c │ │ ├── Circle_Sort/ │ │ │ ├── Circle_Sort.c │ │ │ ├── Circle_Sort.cs │ │ │ ├── Circle_Sort.java │ │ │ ├── Circle_Sort.rb │ │ │ └── README.md │ │ ├── Cocktail_Sort/ │ │ │ ├── Cocktail_Sort.c │ │ │ ├── Cocktail_Sort.cpp │ │ │ ├── Cocktail_Sort.java │ │ │ ├── Cocktail_Sort.py │ │ │ ├── README.md │ │ │ └── cocktail_sort.js │ │ ├── Comb_Sort/ │ │ │ ├── Comb_Sort.c │ │ │ ├── Comb_Sort.cpp │ │ │ ├── README.md │ │ │ ├── comb.py │ │ │ └── comb_sort.rb │ │ ├── Counting_Sort/ │ │ │ ├── Count_sort.py │ │ │ ├── Counting_Sort.c │ │ │ ├── Counting_Sort.cs │ │ │ ├── Counting_Sort.java │ │ │ ├── Counting_sort.js │ │ │ ├── README.md │ │ │ ├── counting_sort.py │ │ │ └── countingsort.py │ │ ├── Cycle_Sort/ │ │ │ ├── CYCLESort.cs │ │ │ ├── Cyclesort.py │ │ │ ├── README.md │ │ │ ├── cyclesort.c │ │ │ └── stoogesort.java │ │ ├── Gnome_Sort/ │ │ │ ├── Gnome_Sort.cs │ │ │ ├── Gnome_Sort.java │ │ │ ├── Gnome_Sort.php │ │ │ ├── Gnome_Sort.py │ │ │ └── gnomeSort.java │ │ ├── Heap_Sort/ │ │ │ ├── Heap_Sort.js │ │ │ ├── Heap_Sort.swift │ │ │ ├── Max_heap_sort.cpp │ │ │ ├── README.md │ │ │ ├── heap-sort.c │ │ │ ├── heap-sort.php │ │ │ ├── heap-sort.py │ │ │ ├── heap-sort.rb │ │ │ ├── heap_sort.cpp │ │ │ ├── heap_sort.go │ │ │ ├── heap_sort.java │ │ │ └── heapsorting.py │ │ ├── Insertion_Sort/ │ │ │ ├── InsertSort.py │ │ │ ├── Insertion Sort.cpp │ │ │ ├── InsertionSort.java │ │ │ ├── InsertionSort.py │ │ │ ├── InsertionSort.scala │ │ │ ├── Insertion_Sort.cpp │ │ │ ├── Insertion_Sort.swift │ │ │ ├── Insertion_sort_2.cpp │ │ │ ├── README.md │ │ │ ├── insertion_sort.py │ │ │ └── insertion_sort.ts │ │ ├── Merge_Sort/ │ │ │ ├── Application of Merge Sort/ │ │ │ │ ├── Count_Inversions.c │ │ │ │ └── Count_Inversions.cpp │ │ │ ├── MERGE_SORT.c │ │ │ ├── MERGE_SORT.cpp │ │ │ ├── MERGE_SORT.java │ │ │ ├── MERGE_SORT.js │ │ │ ├── MergeSort.scala │ │ │ ├── Non_recursive_merge_sort.cpp │ │ │ ├── README.md │ │ │ ├── mergeSort.py │ │ │ ├── merge_Sort.rb │ │ │ ├── mergesort.sh │ │ │ ├── non_recursive_merge_sort.c │ │ │ ├── non_recursive_merge_sort.cs │ │ │ └── non_recursive_merge_sort.py │ │ ├── Merge_Sort_on_Doubly_Linked_List/ │ │ │ ├── Mergesort_doubly.c │ │ │ ├── Mergesort_doubly.cpp │ │ │ ├── Mergesort_doubly.java │ │ │ └── Mergesort_doubly.py │ │ ├── Pancake_Sort/ │ │ │ ├── PancakeSort.java │ │ │ ├── Pancake_Sort.c │ │ │ ├── Pancake_Sort.c++ │ │ │ ├── Pancake_Sort.cs │ │ │ ├── Pancake_Sort.js │ │ │ ├── Pancake_Sort.py │ │ │ ├── Pancake_Sort.rb │ │ │ └── README.md │ │ ├── Patience_Sort/ │ │ │ ├── PatienceSort.cs │ │ │ ├── Patience_sort.cpp │ │ │ └── README.md │ │ ├── Patience_sort.py │ │ ├── Pigeonhole_Sort/ │ │ │ ├── PigeonholeSort.cpp │ │ │ ├── PigeonholeSort.ts │ │ │ ├── Pigeonhole_Sort.c │ │ │ ├── Pigeonhole_Sort.java │ │ │ └── pigeonhole.py │ │ ├── Quick_Select/ │ │ │ ├── QuickSelect.cpp │ │ │ ├── Quick_Select.js │ │ │ ├── Quick_Select.php │ │ │ ├── Quick_select.py │ │ │ ├── README.md │ │ │ ├── quick_select.java │ │ │ └── quick_select.rb │ │ ├── Quick_Sort/ │ │ │ ├── QuickSort.java │ │ │ ├── QuickSort.js │ │ │ ├── QuickSort.py │ │ │ ├── Quick_Sort.cpp │ │ │ ├── Quick_Sort.go │ │ │ ├── Quick_Sort.sh │ │ │ ├── README.md │ │ │ ├── quicksort.C │ │ │ └── quicksort.c │ │ ├── README.md │ │ ├── Radix_Sort/ │ │ │ ├── README.md │ │ │ ├── Radix Sort With C (Mayukh Mitra)/ │ │ │ │ ├── Radix_sort.c │ │ │ │ └── r │ │ │ ├── RadixSort.java │ │ │ ├── RadixSort.py │ │ │ ├── Radix_Sort.js │ │ │ ├── Radix_Sort.rb │ │ │ ├── Radix_sort.cs │ │ │ ├── radixSort.php │ │ │ └── radixsort.cpp │ │ ├── Selection_Algorithms.cpp │ │ ├── Selection_Sort/ │ │ │ ├── README.md │ │ │ ├── Selection Sort.py │ │ │ ├── SelectionSort.java │ │ │ ├── SelectionSort.py │ │ │ ├── SelectionSort.scala │ │ │ ├── Selection_Sort.cpp │ │ │ ├── Selection_Sort.go │ │ │ ├── selection sort.cs │ │ │ ├── selection_sort.c │ │ │ └── selection_sort.rb │ │ ├── Shell_Sort/ │ │ │ ├── README.md │ │ │ ├── Shell_Sort.c │ │ │ ├── Shell_Sort.cpp │ │ │ ├── Shell_Sort.cs │ │ │ ├── Shell_Sort.java │ │ │ ├── Shell_Sort.js │ │ │ ├── Shell_Sort.swift │ │ │ ├── shell_sort.py │ │ │ └── shell_sort.sh │ │ ├── Stooge_Sort/ │ │ │ ├── README.md │ │ │ ├── Stooge_Sort.cs │ │ │ ├── Stooge_Sort.go │ │ │ └── Stooge_Sort.py │ │ ├── Strand_Sort/ │ │ │ ├── README.md │ │ │ ├── Strand_Sort.cpp │ │ │ ├── Strand_sort.java │ │ │ ├── strand_sort.c │ │ │ └── strand_sort.ts │ │ ├── Tim_Sort/ │ │ │ ├── README.md │ │ │ ├── Tim_Sort.c │ │ │ ├── Tim_Sort.java │ │ │ └── Tim_Sort.py │ │ ├── Topological_Sort/ │ │ │ ├── README.md │ │ │ ├── Topological_Sort.cpp │ │ │ ├── Topological_sort.cs │ │ │ └── Topological_sort.py │ │ ├── Tree_Sort/ │ │ │ ├── README.md │ │ │ ├── Tree_Sort.c │ │ │ ├── tree sort.cpp │ │ │ └── treesort.java │ │ └── Wave_Sort/ │ │ ├── Wave_Sort.py │ │ ├── wave_sort.c │ │ └── wave_sort.cpp │ ├── Stack-Algorithm/ │ │ ├── Next_Greater_Element.cpp │ │ ├── RemoveKDigitsToGetSmallestPossibleInteger.java │ │ ├── Simplify-Path/ │ │ │ ├── QUESTION.md │ │ │ └── Simplify_Path.cpp │ │ ├── balanced_brackets_stack.cpp │ │ ├── immediate_smaller_element.cpp │ │ └── longest_valid_substring.cpp │ ├── String/ │ │ ├── Anagram/ │ │ │ ├── AnagramChecker.c │ │ │ ├── anagram c#.cs │ │ │ ├── anagram.c │ │ │ ├── anagram.java │ │ │ ├── anagram.py │ │ │ ├── anagram.swift │ │ │ └── anagrams.sh │ │ ├── Isomorphic/ │ │ │ ├── Isomorphic-String.java │ │ │ └── isomorphic.cpp │ │ ├── KMP/ │ │ │ ├── KMP_Algorithm.php │ │ │ ├── kmp.cpp │ │ │ └── kmp.js │ │ ├── LCS/ │ │ │ ├── LCS.py │ │ │ └── lcs.cpp │ │ ├── LPS/ │ │ │ ├── longest_palindromic_substring.c │ │ │ ├── longest_palindromic_substring.cpp │ │ │ ├── longest_palindromic_substring.java │ │ │ ├── longest_palindromic_substring.js │ │ │ ├── longest_palindromic_substring.py │ │ │ └── longest_palindromic_substring.rb │ │ ├── Palindrome/ │ │ │ ├── Palindrome.c │ │ │ ├── Palindrome.cs │ │ │ ├── Palindrome.java │ │ │ ├── isPalindrome.cpp │ │ │ ├── isPalindrome.py │ │ │ ├── palindrome.go │ │ │ ├── palindrome.java │ │ │ ├── palindrome.js │ │ │ ├── palindrome.php │ │ │ ├── palindrome.py │ │ │ ├── palindrome.swift │ │ │ ├── palindrome.ts │ │ │ └── palindromecheck.go │ │ ├── README.md │ │ ├── Rabin-Karp/ │ │ │ ├── RabinKarpAlgo.java │ │ │ ├── Rabin_Karp.cpp │ │ │ ├── Rabin_Karp.ts │ │ │ ├── Rabin_karp.c │ │ │ └── rabin_karp.py │ │ ├── SCS/ │ │ │ └── SCS.cpp │ │ ├── ScrambleString.java │ │ └── suffix_array.cpp │ └── Tree/ │ ├── Binary_Lifting/ │ │ ├── Binary Lifting.py │ │ └── Binary-Lifting.cpp │ ├── GenericTreeImplementation/ │ │ ├── GenericTree.c │ │ ├── GenericTree.cpp │ │ └── GenericTree.java │ ├── LCA/ │ │ ├── LCA.cpp │ │ ├── LCA.cs │ │ ├── LCA.js │ │ └── LCA.py │ ├── Max_Heap_Construction/ │ │ └── minmaxheap.cpp │ ├── Max_Path_Sum_BST/ │ │ ├── Max_Path_Sum_BST.cpp │ │ └── Max_Path_Sum_BST.py │ ├── Min_Heap_Construction/ │ │ ├── README.md │ │ ├── min-heap-construc.cpp │ │ └── min-heap-construc.py │ ├── README.md │ ├── Sorted-Array-To-BST/ │ │ └── Sorted-Array-To-BST.cpp │ ├── Sorted_Array_To_BST/ │ │ └── SortedArrayToBST.java │ ├── Validate_BST/ │ │ ├── Validate_BST.cpp │ │ ├── Validate_BST.cs │ │ └── Validate_BST.java │ └── level_traversing/ │ ├── level_traversing.php │ └── level_traversing.py ├── CNAME ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── CONTRIBUTORS.md ├── Collection/ │ ├── ArrayDeque/ │ │ ├── ArrayDeque.java │ │ └── README.md │ ├── ArrayList/ │ │ ├── ArrayList .java │ │ └── README.md │ ├── HashMap/ │ │ ├── HashMap.java │ │ └── README.md │ ├── HashSet/ │ │ ├── HashSet.java │ │ └── README.md │ ├── LinkedList/ │ │ ├── LinkedHashSet/ │ │ │ └── README.md │ │ ├── LinkedList.java │ │ └── README.md │ ├── Queue/ │ │ ├── Deque/ │ │ │ ├── Deque.java │ │ │ └── README.md │ │ ├── PriorityQueue/ │ │ │ ├── PriorityQueue.java │ │ │ └── README.md │ │ ├── Queue.java │ │ └── README.md │ ├── README.md │ ├── Stack/ │ │ ├── README.md │ │ └── StackCollection.java │ └── Vector/ │ ├── README.md │ └── Vector.java ├── DOCUMENTATION.md ├── Data-Structures/ │ ├── Array/ │ │ ├── Array.c │ │ ├── Array.cpp │ │ ├── Array.go │ │ ├── Array.java │ │ ├── Array.js │ │ ├── Array.py │ │ ├── Array.ts │ │ ├── README.md │ │ └── array_menudriven.cpp │ ├── Graph/ │ │ ├── GraphUsingList.kt │ │ ├── README.md │ │ ├── UsingList.cpp │ │ ├── UsingList.py │ │ ├── UsingMatrix.cpp │ │ └── graph_implementation_in_C_bfs_dfs.c │ ├── HashMap/ │ │ └── README.md │ ├── HashSet/ │ │ ├── Hash-Set.c │ │ └── README.md │ ├── Heap/ │ │ └── README.md │ ├── LinkedList/ │ │ ├── Circular_Linked_List/ │ │ │ ├── CircularLinkedList.c │ │ │ ├── CircularLinkedList.java │ │ │ ├── Circular_Link_List.cpp │ │ │ ├── README.md │ │ │ ├── circularLinkedList.js │ │ │ ├── circularLinkedList.py │ │ │ └── csharp/ │ │ │ └── CircularLinkedList.cs │ │ ├── Doubly_Linked_List/ │ │ │ ├── Double linked List circular with double headers C++/ │ │ │ │ ├── LDLCCED.cbp │ │ │ │ ├── LDLCCED.layout │ │ │ │ ├── dllist.cpp │ │ │ │ ├── dllist.h │ │ │ │ ├── dlnode.cpp │ │ │ │ ├── dlnode.h │ │ │ │ ├── listexception.h │ │ │ │ ├── main.cpp │ │ │ │ └── nodeexception.h │ │ │ ├── DoubleLinkedList.java │ │ │ ├── DoublyLinkedList.cs │ │ │ ├── DoublyLinkedList.hs │ │ │ ├── DoublyLinkedList_C++_Template/ │ │ │ │ ├── DLL.h │ │ │ │ └── DLLtest.cpp │ │ │ ├── Doubly_Linked_List.py │ │ │ ├── README.md │ │ │ ├── double_linked_list.c │ │ │ ├── doubly.c │ │ │ ├── doubly_ll.py │ │ │ └── simple linked list circular without header/ │ │ │ ├── LSLCSE.cbp │ │ │ ├── LSLCSE.layout │ │ │ ├── main.cpp │ │ │ ├── sllist.cpp │ │ │ ├── sllist.h │ │ │ ├── slnode.cpp │ │ │ └── slnode.h │ │ ├── README.md │ │ ├── Singly_Linked_List/ │ │ │ ├── Delete_Kth_Node_From_End/ │ │ │ │ ├── Delete_Kth_Node_From_End.cpp │ │ │ │ ├── Delete_Kth_Node_From_End.java │ │ │ │ ├── Delete_Kth_Node_From_End.py │ │ │ │ └── Delete_Kth_Node_From_End.rb │ │ │ ├── Detect_Cycle/ │ │ │ │ ├── CycleDetection.c │ │ │ │ ├── CycleDetection.java │ │ │ │ ├── DetectCycle.cpp │ │ │ │ ├── DetectCycle.py │ │ │ │ ├── DetectCycle.ts │ │ │ │ ├── Detect_Cycle.js │ │ │ │ ├── detect_cycle.cs │ │ │ │ └── detect_cycle.go │ │ │ ├── Java/ │ │ │ │ └── PalindromeLinkedList.java │ │ │ ├── LinkedList.cs │ │ │ ├── LinkedList.java │ │ │ ├── LinkedList.py │ │ │ ├── LinkedListAndOperations.cpp │ │ │ ├── LoopDetection.cpp │ │ │ ├── MiddleElementLL.cpp │ │ │ ├── MiddleElementLinkedList.java │ │ │ ├── Palindrome.ts │ │ │ ├── PalindromeLinkedList.cpp │ │ │ ├── PalindromeLinkedList.js │ │ │ ├── README.md │ │ │ ├── Remove duplicates from linked_list.c │ │ │ ├── Remove duplicates in a Linked List.cpp │ │ │ ├── Remove_Duplicates_in_LL.py │ │ │ ├── Reversed_Linked_List/ │ │ │ │ ├── ReversedLinkedList.js │ │ │ │ └── reverseLinkedList.c │ │ │ ├── Sublist_Search.rb │ │ │ ├── linked list.c │ │ │ ├── linked.cpp │ │ │ ├── linkedlist.cpp │ │ │ ├── merge2sortedlinkedlists.cpp │ │ │ ├── middle.ts │ │ │ └── singly_linked_list.hs │ │ ├── detect_cycle.rb │ │ └── sparce matrix/ │ │ └── sparce addition.cpp │ ├── Queue/ │ │ ├── Circular-Queue/ │ │ │ ├── circular_queue.c │ │ │ ├── circular_queue.cs │ │ │ ├── circular_queue_LL.c │ │ │ ├── circular_queue_array_implementation.c │ │ │ └── cirqueue.cpp │ │ ├── Deque/ │ │ │ ├── Deque.cpp │ │ │ ├── Deque.java │ │ │ ├── Deque.js │ │ │ ├── Deque.py │ │ │ ├── Deque.ts │ │ │ └── README.md │ │ ├── Priority-Queue/ │ │ │ ├── Priority-Queue.cpp │ │ │ ├── PriorityQueue.php │ │ │ ├── README.md │ │ │ └── priorityQueue.js │ │ ├── QueueUsingArray.c │ │ ├── QueueUsingArray.cpp │ │ ├── QueueUsingArray.go │ │ ├── QueueUsingArray.java │ │ ├── QueueUsingArray.js │ │ ├── QueueUsingArray.py │ │ ├── QueueUsingArray.rb │ │ ├── QueueUsingArray.swift │ │ ├── QueueUsingLL.c │ │ ├── QueueUsingLL.cpp │ │ ├── QueueUsingLL.cs │ │ ├── QueueUsingLL.php │ │ ├── QueueUsingStacks.cpp │ │ └── README.md │ ├── README.md │ ├── Stack/ │ │ ├── Infix_to_prefix_postfix.cpp │ │ ├── README.md │ │ ├── StackUsingArray.c │ │ ├── StackUsingArray.cpp │ │ ├── StackUsingArray.cs │ │ ├── StackUsingArray.go │ │ ├── StackUsingArray.hs │ │ ├── StackUsingArray.java │ │ ├── StackUsingArray.js │ │ ├── StackUsingArray.php │ │ ├── StackUsingArray.rb │ │ ├── StackUsingArray.swift │ │ ├── StackUsingLL.cpp │ │ ├── StackUsingLL.go │ │ ├── StackUsingLL.java │ │ ├── StackUsingLL.js │ │ ├── StackUsingLL.py │ │ ├── stackUsingLinkedList.c │ │ └── stackusingLL.c │ └── Tree/ │ ├── 23-Tree/ │ │ ├── 23Tree.cpp │ │ └── 23Tree.py │ ├── AVL-Tree/ │ │ ├── AVL_Tree.java │ │ ├── AVL_Tree.py │ │ ├── AVLtree.c │ │ ├── README.md │ │ └── avl_tree.py │ ├── Binary-Indexed-Tree/ │ │ ├── Binary-Indexed-Tree.c │ │ ├── Binary-Indexed-Tree.go │ │ ├── Binary-Indexed-Tree.java │ │ └── Binary-Indexed-Tree.py │ ├── Binary-Search-Tree/ │ │ ├── BST.cs │ │ ├── BST_balanced.cpp │ │ ├── BinarySearchTree.go │ │ ├── BinarySearchTree.java │ │ ├── Binary_Search_Tree.cpp │ │ ├── Binary_Search_Tree.py │ │ ├── Binary_Search_Tree_operations.cpp │ │ ├── LCA.py │ │ ├── README.md │ │ ├── Validate_BST.py │ │ ├── Vertcal_order_traversal.py │ │ ├── inorder_transversal.c │ │ ├── operationBST.cpp │ │ ├── postorder_transversal.c │ │ └── valid BST │ ├── Binary-Tree/ │ │ ├── BTree.cpp │ │ ├── Binary tree using C.c │ │ ├── Btree.java │ │ ├── Check_duplicates_in _BTree.java │ │ ├── Density/ │ │ │ ├── DensityBtree.c │ │ │ └── DensityBtree.cpp │ │ ├── Deserialize/ │ │ │ └── Deserialize.rb │ │ ├── Duplicate_values.cs │ │ ├── Invert_Binary_Tree/ │ │ │ ├── Invert_Binary_Tree.py │ │ │ ├── invertBinTree.rb │ │ │ └── invert_binary_tree.cpp │ │ ├── Invert_Binary_tree/ │ │ │ └── invert_btree.swift │ │ ├── Right_View/ │ │ │ ├── RightViewBTree.java │ │ │ ├── rightViewBinTree.rb │ │ │ ├── right_view.py │ │ │ ├── right_view.swift │ │ │ └── right_view_of_binary_tree.cpp │ │ ├── Serialize/ │ │ │ ├── Serialize.cpp │ │ │ └── Serialize.py │ │ ├── Subtree_check/ │ │ │ └── Subtree_check.cpp │ │ ├── SymmetricBTree.java │ │ ├── SymmetryBTree/ │ │ │ └── SymmetryBTree.rb │ │ ├── SymmetryBTree.cs │ │ ├── SymmetryBTree.py │ │ ├── Two_level_Node/ │ │ │ └── two_level_Node.cpp │ │ ├── Two_level_Node.java │ │ ├── VerticalOrderTraversal.java │ │ ├── VerticalOrderTraversal.py │ │ ├── Vertical_Sum/ │ │ │ ├── Verticle_sum_of_BinaryTree.java │ │ │ └── Verticle_sum_of_Binary_Tree.cpp │ │ ├── b_tree.cpp │ │ ├── b_tree.java │ │ ├── b_tree.js │ │ ├── b_tree.py │ │ ├── binary_tree_trans.cpp │ │ ├── duplicate_values.cpp │ │ ├── duplicate_values.py │ │ ├── duplicate_values.rb │ │ ├── subtree_check.cpp │ │ ├── symmetry_bTree.cpp │ │ └── two_level_node.py │ ├── Expression Tree/ │ │ └── Expression_Tree.cpp │ ├── Fibonacci-Heap/ │ │ └── Fibonacci-Heap.c │ ├── Generic Tree/ │ │ └── GenericTree.cpp │ ├── README.md │ ├── Red-Black-Tree/ │ │ ├── Red-Black-Tree.c │ │ ├── Red-Black-Tree.cpp │ │ ├── Red-Black-Tree.java │ │ └── Red-Black-Tree.py │ ├── Segment-Tree/ │ │ └── Segment-Tree.c │ ├── Splay-Tree/ │ │ └── Splay-Tree.c │ ├── Threaded Binary Tree/ │ │ └── Threaded_Binary_Tree.cpp │ └── Trie/ │ ├── README.md │ ├── Trie.c │ ├── trie.cpp │ └── trie.py ├── LICENSE ├── Maths/ │ ├── Algebra/ │ │ ├── Babylionian/ │ │ │ ├── Babylionian.cs │ │ │ ├── Babylionian.go │ │ │ └── Babylonian.java │ │ ├── Babylonian/ │ │ │ ├── Babylonian.js │ │ │ └── babylonian_square_root.c │ │ ├── Derivative_Of_Polynomial/ │ │ │ ├── Matrix_Multiplication.c │ │ │ └── README.md │ │ ├── Diophantine/ │ │ │ └── README.md │ │ ├── Factorial/ │ │ │ ├── Factorial.hs │ │ │ ├── Factorial.java │ │ │ ├── README.md │ │ │ ├── factorial.c │ │ │ ├── factorial.cpp │ │ │ ├── factorial.cs │ │ │ ├── factorial.go │ │ │ ├── factorial.js │ │ │ ├── factorial.php │ │ │ ├── factorial.py │ │ │ ├── factorial.rb │ │ │ ├── factorial.sh │ │ │ ├── factorial.swift │ │ │ └── factorial.ts │ │ ├── Factorial_of_Large_Number/ │ │ │ ├── Factorial_of_Large_Number.cs │ │ │ ├── Factorial_of_Large_Number.hs │ │ │ ├── Factorial_of_Large_Number.js │ │ │ ├── Factorial_of_Large_Number.php │ │ │ ├── Factorial_of_large_number.c │ │ │ ├── README.md │ │ │ ├── bigfactorial.cpp │ │ │ └── largeFactorial.java │ │ ├── GCD/ │ │ │ ├── EuclidGCD.swift │ │ │ ├── Euclidean_gcd.py │ │ │ ├── EuclidianGCD.py │ │ │ ├── GCD.cpp │ │ │ ├── GCD.cs │ │ │ ├── GCD.js │ │ │ ├── GCD.php │ │ │ ├── GCD.py │ │ │ ├── GCD.rb │ │ │ ├── GCD.sh │ │ │ ├── README.md │ │ │ └── gcd.java │ │ ├── Inverse_of_a_Matrix/ │ │ │ └── README.md │ │ ├── LCM/ │ │ │ ├── LCM.c │ │ │ ├── LCM.cpp │ │ │ ├── LCM.java │ │ │ ├── LCM.js │ │ │ ├── LCM.py │ │ │ ├── LCM.sh │ │ │ ├── LCM_GCD.c │ │ │ ├── LCM_python.py │ │ │ └── README.md │ │ ├── Markov_Matrix/ │ │ │ ├── MarkovMatrix.java │ │ │ ├── Markov_Matrix.c++ │ │ │ ├── Markov_Matrix.cs │ │ │ └── Markov_Matrix.js │ │ ├── Matrix_Multipication/ │ │ │ ├── MatMul.cpp │ │ │ ├── MatrixMultipication.py │ │ │ ├── MatrixMultiply.java │ │ │ ├── Matrix_Multiplication.js │ │ │ ├── README.md │ │ │ ├── multiply.c │ │ │ ├── multiply.cpp │ │ │ ├── multiply.java │ │ │ ├── multiply.php │ │ │ └── multiply.py │ │ ├── Permutation_And_Combination/ │ │ │ ├── Permutations_Combinations.ipynb │ │ │ ├── README.md │ │ │ ├── permutation_combination.cpp │ │ │ └── permutation_combination.js │ │ ├── Prime_Factorization/ │ │ │ ├── PrimeFactorisation.cpp │ │ │ ├── Prime_Factor.c │ │ │ ├── Prime_Factorisation.cpp │ │ │ ├── Prime_Factorization.cs │ │ │ ├── README.md │ │ │ ├── prime-factorisation.js │ │ │ ├── prime.cpp │ │ │ ├── prime_factorization.cpp │ │ │ ├── prime_factorization.java │ │ │ ├── prime_factorization.py │ │ │ └── prime_factorization.ts │ │ ├── Quadratic_Formula/ │ │ │ ├── Quadratic_Formula.cpp │ │ │ ├── Quadratic_Formula.hs │ │ │ ├── Quadratic_Formula.sh │ │ │ ├── README.md │ │ │ └── quadraticformula.py │ │ ├── README.md │ │ ├── Sieve of Eratosthenes/ │ │ │ ├── SieveOfEratosthenes.cpp │ │ │ ├── SieveOfEratosthenes.py │ │ │ ├── SieveOfEratosthens.c │ │ │ └── SieveofEratosthenes.java │ │ ├── Strassens_Algorithm/ │ │ │ ├── README.md │ │ │ ├── Strassen.java │ │ │ ├── Strassens_Algorithm.c++ │ │ │ └── strassens.py │ │ ├── Taylor-Expansion/ │ │ │ └── README.md │ │ └── Vertex_Formula/ │ │ └── README.md │ ├── Calculus/ │ │ ├── Euler_Approximation/ │ │ │ ├── Euler_Approximation.c │ │ │ ├── Euler_Approximation.cpp │ │ │ ├── Euler_Approximation.java │ │ │ ├── Euler_Approximation.py │ │ │ └── README.md │ │ ├── Leibniz_formula/ │ │ │ ├── LeibnizFormula.py │ │ │ ├── Leibniz_Formula.java │ │ │ ├── Leibniz_formula.cpp │ │ │ └── README.md │ │ ├── Probability_Density_Functions/ │ │ │ └── README.md │ │ ├── README.md │ │ ├── Riemann_Sum/ │ │ │ ├── README.md │ │ │ ├── Riemann.py │ │ │ ├── Riemann_Sum.cpp │ │ │ ├── Riemann_Sum.cs │ │ │ └── riemann_sum.py │ │ └── Runge–Kutta_Method/ │ │ ├── Range-Kutta.c │ │ ├── Runge-Kutta.cpp │ │ └── Runge-Kutta.py │ ├── Discrete/ │ │ ├── Ackermann_Peter/ │ │ │ ├── Ackermann_Peter.c │ │ │ ├── Ackermann_Peter.cpp │ │ │ ├── Ackermann_Peter.js │ │ │ ├── Ackermann_Peter.py │ │ │ ├── Python/ │ │ │ │ └── ackermann.py │ │ │ └── README.md │ │ └── README.md │ ├── Geometry/ │ │ ├── Clock_Angle/ │ │ │ ├── ClockAngle.cs │ │ │ ├── Clock_Angle.c │ │ │ ├── Clock_Angle.cpp │ │ │ ├── Clock_Angle.hs │ │ │ ├── Clock_Angle.java │ │ │ ├── Clock_Angle.js │ │ │ ├── README.md │ │ │ ├── clock_angle.go │ │ │ └── clock_angle.py │ │ ├── Distance_Formula/ │ │ │ ├── Distance_Formula.c │ │ │ ├── Distance_Formula.cpp │ │ │ ├── Distance_Formula.cs │ │ │ ├── Distance_Formula.go │ │ │ ├── Distance_Formula.hs │ │ │ ├── Distance_Formula.java │ │ │ ├── Distance_Formula.js │ │ │ ├── Distance_Formula.php │ │ │ ├── Distance_Formula.py │ │ │ └── README.md │ │ ├── Manhattan_Distance/ │ │ │ ├── ManhattanDistance.java │ │ │ ├── ManhattanDistance.js │ │ │ ├── Manhattan_Distance.c │ │ │ ├── Manhattan_Distance.hs │ │ │ ├── README.md │ │ │ ├── manhattan_dist.cpp │ │ │ ├── manhattan_dist.go │ │ │ ├── manhattan_dist.py │ │ │ └── manhattan_distance.py │ │ ├── N_Dimensional_Distance/ │ │ │ └── N_Dimensional_Distance.c │ │ ├── Polar_Cartesian_Conversion/ │ │ │ ├── Polar_Cartesian_Conversion.go │ │ │ ├── Polar_Cartesian_Conversion.hs │ │ │ ├── Polar_Cartesian_Conversion.java │ │ │ └── Polar_Cartesian_Conversion.py │ │ ├── Pythagorean_theorem/ │ │ │ ├── PythagoreanTheorem.cs │ │ │ ├── Pythagorean_theorem.cpp │ │ │ ├── Pythagorean_theorem.hs │ │ │ ├── Pythagorean_theorem.js │ │ │ ├── Pythagorean_theorem.py │ │ │ ├── Pythagorean_theorem.rb │ │ │ ├── Pythagorean_theorem.swift │ │ │ ├── README.md │ │ │ └── pythogoras_theorem.java │ │ ├── README.md │ │ ├── Radians_Degrees_Conversion/ │ │ │ ├── README.md │ │ │ ├── Radians_Degree_Conversion.c │ │ │ ├── Radians_Degrees_Conversion.c │ │ │ ├── Radians_Degrees_Conversion.cpp │ │ │ ├── Radians_Degrees_Conversion.hs │ │ │ ├── Radians_Degrees_Conversion.java │ │ │ ├── Radians_Degrees_Conversion.js │ │ │ └── Radians_Degrees_Conversion.py │ │ ├── Scalar_Product/ │ │ │ ├── README.md │ │ │ ├── Scalar_Product.c │ │ │ ├── Scalar_Product.hs │ │ │ ├── Scalar_Product.java │ │ │ ├── Scalar_Product.js │ │ │ ├── Scalar_Product.py │ │ │ ├── scalar_product.cpp │ │ │ └── scalar_product.rb │ │ └── Vector_Product/ │ │ ├── README.md │ │ ├── Vector_Product.c │ │ ├── Vector_Product.cpp │ │ ├── Vector_Product.hs │ │ ├── Vector_Product.js │ │ ├── Vector_Product.py │ │ └── Vector_Product.ts │ ├── MOs-Algorithm/ │ │ ├── Mos_Algorithm.c │ │ ├── Mos_Algorithm.cpp │ │ └── README.md │ ├── Number-Theory/ │ │ ├── Armstrong_Number/ │ │ │ ├── ArmstrongNumber.java │ │ │ ├── Armstrong_Number.c │ │ │ ├── armstrong.py │ │ │ ├── armstrongin.java │ │ │ ├── armstrongnumber.cpp │ │ │ └── armstrongnumber.js │ │ ├── Extended Euclidean Algorithm/ │ │ │ ├── extendEuclid.cpp │ │ │ └── extendEuclid.py │ │ ├── Fibonacci_Number/ │ │ │ ├── Fibonacci.cs │ │ │ ├── FibonacciNumbers.java │ │ │ ├── Fibonacci_Number.clj │ │ │ ├── Fibonacci_Number.cpp │ │ │ ├── Fibonacci_Number.py │ │ │ └── fibonacci.sh │ │ ├── Perfect_Number/ │ │ │ ├── Perfect Number.cpp │ │ │ ├── PerfectNumber.py │ │ │ ├── Perfect_Number,sh │ │ │ ├── Perfect_Number.java │ │ │ ├── perfec_numper.py │ │ │ ├── perfectnumber.cpp │ │ │ ├── perfectnumber.js │ │ │ └── perfectnumber.php │ │ ├── README.md │ │ ├── Segmented_Sieve/ │ │ │ ├── README.md │ │ │ ├── Segmented_Sieve.php │ │ │ ├── segmented_sieve.js │ │ │ └── segmented_sieve.py │ │ ├── Sieve_of_Eratosthenes/ │ │ │ ├── SieveOfEratosthenes.c │ │ │ ├── SieveOfEratosthenes.cs │ │ │ ├── Sieve_of_Erastosthenes.rb │ │ │ ├── Sieve_of_Erastosthenes.ts │ │ │ ├── Sieve_of_Eratosthenes.c │ │ │ ├── Sieve_of_Eratosthenes.cpp │ │ │ ├── Sieve_of_Eratosthenes.go │ │ │ ├── SieveofErastosthenes.java │ │ │ └── prime_and_base.py │ │ ├── Smith_number/ │ │ │ ├── SmithNumber.py │ │ │ └── smith_numbers_till_n.cpp │ │ ├── Strong_Number/ │ │ │ ├── strong_number.c │ │ │ ├── strong_number.cpp │ │ │ ├── strong_number.java │ │ │ ├── strong_number.py │ │ │ └── strong_number.sh │ │ ├── Tribonacci_Number/ │ │ │ └── nthTribonacci.kt │ │ └── Ugly_Number/ │ │ ├── README.md │ │ ├── UglyNumber.go │ │ ├── UglyNumbers.sh │ │ ├── Ugly_Number.c │ │ ├── Ugly_Number.java │ │ ├── Ugly_Number.js │ │ ├── Ugly_Number.php │ │ ├── Ugly_Number.py │ │ ├── Ugly_Number.rb │ │ ├── Ugly_Number_Till_N.cpp │ │ └── Ugly_Numbers.sh │ ├── README.md │ ├── Series/ │ │ ├── Arithmetic_Progression/ │ │ │ ├── AP.py │ │ │ ├── Arithematic_Progression.cpp │ │ │ ├── Arithmetic_Progression.c │ │ │ ├── Arithmetic_Progression.java │ │ │ ├── Arithmetic_Progression.js │ │ │ ├── Arithmetic_Progression.php │ │ │ ├── Arithmetic_Progression.sh │ │ │ ├── Arithmetic_Progression.ts │ │ │ └── README.md │ │ ├── Fibonacci/ │ │ │ ├── Fibonacci.c │ │ │ ├── Fibonacci.cpp │ │ │ ├── Fibonacci.sh │ │ │ ├── Fiboncci.py │ │ │ ├── README.md │ │ │ ├── fibonacci.cpp │ │ │ └── fibonacci.java │ │ ├── Geometric_Progression/ │ │ │ ├── Geometric Progression.py │ │ │ ├── GeometricProgression.cs │ │ │ ├── GeometricProgression.java │ │ │ ├── Geometric_Progression.sh │ │ │ └── README.md │ │ ├── Harmonic_Progression/ │ │ │ ├── Harmonic Progression.cpp │ │ │ ├── HarmonicProgresion.c │ │ │ ├── Harmonic_Expression.java │ │ │ ├── README.md │ │ │ ├── SumOfHP.swift │ │ │ └── harmonic_progression.py │ │ ├── Lucas_Series/ │ │ │ ├── Lucas_Series.c │ │ │ ├── Lucas_Series.cpp │ │ │ ├── Lucas_Series.go │ │ │ ├── Lucas_Series.php │ │ │ ├── README.md │ │ │ ├── lucas_series.cs │ │ │ ├── lucas_series.py │ │ │ └── lucas_series.ts │ │ ├── Modular_Exponentiation/ │ │ │ ├── Modular_Exponentiation.cpp │ │ │ ├── Modular_Exponentiation.py │ │ │ ├── README.md │ │ │ ├── modular_exponentiation.c │ │ │ ├── modular_exponentiation.cpp │ │ │ └── modular_exponentiation.java │ │ ├── README.md │ │ ├── Relative_Primes/ │ │ │ ├── README.md │ │ │ ├── RelativePrimes.c │ │ │ ├── RelativePrimes.java │ │ │ ├── RelativePrimes.php │ │ │ ├── RelativePrimes.py │ │ │ ├── Relative_Prime.cpp │ │ │ └── Relative_Primes.go │ │ ├── Sum_of_AP/ │ │ │ ├── Sum_Of_AP.CPP │ │ │ ├── Sum_Of_AP.py │ │ │ ├── Sum_of_AP.c │ │ │ ├── Sum_of_AP.go │ │ │ ├── Sum_of_AP.js │ │ │ └── Sum_of_AP_JAVA/ │ │ │ ├── SumOfAP.ctxt │ │ │ └── Sum_of_AP.java │ │ ├── Sum_of_GP/ │ │ │ ├── README.md │ │ │ ├── Sum_Of_GP.c │ │ │ ├── Sum_Of_GP.cpp │ │ │ ├── Sum_of_GP.java │ │ │ └── Sum_of_GP.py │ │ ├── Sum_of_HP/ │ │ │ ├── HP_sum.py │ │ │ ├── Sum_of_HP.cpp │ │ │ ├── Sum_of_HP.cs │ │ │ └── hpSum.js │ │ ├── Sum_of_N/ │ │ │ ├── Sum_of_n.c │ │ │ ├── sumOfNNumbers.sh │ │ │ ├── sum_of_n_natural_no.cpp │ │ │ ├── sum_of_n_natural_numbers.go │ │ │ ├── sumn.py │ │ │ ├── sumofNnaturalnums.cs │ │ │ └── sumofNnaturalnums.py │ │ ├── Sum_of_N2/ │ │ │ ├── SumOf_n^2.C++ │ │ │ ├── Sum_Of_n^2.py │ │ │ ├── Sum_of_n^2.swift │ │ │ ├── square_sum.cs │ │ │ ├── sumOfNSquare.js │ │ │ ├── sumOfn_squared.py │ │ │ └── sumofnsqaure.php │ │ └── Sum_of_N3/ │ │ ├── Sum of n3.cpp │ │ ├── sum of n^3.cpp │ │ └── sumofncube.php │ └── Statistics/ │ ├── Compound_Interest/ │ │ ├── Compound_Interest.c │ │ ├── Compound_Interest.cpp │ │ ├── Compound_Interest.cs │ │ ├── Compound_Interest.html │ │ ├── Compound_Interest.java │ │ ├── Compound_Interest.js │ │ ├── Compound_Interest.py │ │ ├── Compound_Interest.rb │ │ └── Compound_Interest.ts │ ├── Confidence_Interval/ │ │ ├── Confidence_Interval.cpp │ │ ├── Confidence_Inverval.c │ │ ├── README.md │ │ ├── confidenceInterval.js │ │ └── confidence_interval.py │ ├── Exponential_Smoothing/ │ │ ├── Exponential_Smoothing.cpp │ │ ├── Exponential_Smoothing.java │ │ ├── Exponential_Smoothing.rb │ │ └── README.md │ ├── K-means_Clustering/ │ │ └── K-means_Clustering.py │ ├── Logistic_Function/ │ │ └── README.md │ ├── Mean/ │ │ ├── mean.cpp │ │ ├── mean.java │ │ ├── mean.py │ │ ├── meanOfGivenNumbers.c │ │ ├── meanOfGivenNumbers.cs │ │ └── meanOfGivenNumbers.js │ ├── Median/ │ │ ├── Median.c │ │ ├── Median.java │ │ ├── Median.js │ │ ├── Median.py │ │ ├── README.md │ │ └── meadian.cpp │ ├── Mode/ │ │ ├── Mode.java │ │ ├── README.md │ │ ├── mode.c │ │ ├── mode.cpp │ │ ├── mode.js │ │ ├── mode.php │ │ └── mode.py │ ├── README.md │ └── Standard_Deviation/ │ ├── README.md │ ├── Standard_Deviation.c │ ├── Standard_Deviation.cpp │ ├── Standard_Deviation.js │ ├── Standard_Deviation.py │ └── Standard_Deviation.swift ├── README.md ├── STL/ │ ├── Array/ │ │ └── Array.cpp │ ├── Map/ │ │ ├── MultiMap/ │ │ │ └── multimap.cpp │ │ ├── Unodered-Map/ │ │ │ └── unorderedmap.cpp │ │ └── map.cpp │ ├── Queue/ │ │ ├── Deque/ │ │ │ ├── README.md │ │ │ └── deque.cpp │ │ ├── PriorityQueue/ │ │ │ └── priority_queue.cpp │ │ └── Queue.cpp │ ├── README.md │ ├── Set/ │ │ ├── Unodered-Set/ │ │ │ └── UnorderedSet.cpp │ │ └── set.cpp │ ├── Stack/ │ │ └── stack.cpp │ └── Vector/ │ └── Vector.cpp └── _config.yml ================================================ FILE CONTENTS ================================================ ================================================ FILE: .github/ISSUE_TEMPLATE/Documentation.yml ================================================ name: Documentation description: Select this to document the repo title: "Directory You Purpose to Document" labels: ["Hacktoberfest2021", "Hacktoberfest", "new submssion", "first timer", "good first issue", "documentation"] assignees: - octocat body: - type: markdown attributes: value: | Before starting please take a look at [this](https://github.com/ahampriyanshu/algo_ds_101/tree/main/DOCUMENTATION.md), [this](https://dsa.ahampriyanshu.com/DOCUMENTATION) and [this](https://dsa.ahampriyanshu.com/Data-Structures/Queue/). - type: input id: directory attributes: label: Directory description: Path to the readme file placeholder: Algorithm => Sorting => Merge-Sort => README.md validations: required: true - type: checkboxes id: language attributes: label: Things To Remember description: Please check the following options: - label: The content added isn't directly copied from any sources like gfg, tutorialpoint, etc. For theory, use open-source alternatives like WikiPedia. - label: I have used github flavoured md syntax only. - label: All the relative links are working. - label: All the absolute links are working. - label: I have synced-up my forked repo. - label: Ain't pushing from the main branch. ================================================ FILE: .github/ISSUE_TEMPLATE/New-Submission.yml ================================================ name: New Submission description: Select this to submit new Algorithm/Data-Structure/STL/... title: "Title of the Submission" labels: ["Hacktoberfest", "new submission", "first timer", "good first issue"] assignees: - octocat body: - type: markdown attributes: value: | I have verified that this issue doesn't already exist. - type: dropdown id: type attributes: label: Type description: Type of the submission options: - Algorithm - Data-Structure - Maths - STL - Collection validations: required: true - type: input id: directory attributes: label: Directory description: Location of the new file placeholder: Algorithm => Sorting => Merge-Sort => Merge-Sort.ext validations: required: true - type: textarea id: description attributes: label: Description description: Describe the submission placeholder: A linked list is a linear collection of data elements whose ... validations: required: true - type: checkboxes id: language attributes: label: Programming Language description: programming language options: - label: c++ - label: c - label: python - label: java - label: kotlin - label: javascript - label: typescript - label: c# - label: swift - label: ruby - label: scala - label: go - label: php - label: haskell - label: bash ================================================ FILE: .github/ISSUE_TEMPLATE/config.yml ================================================ blank_issues_enabled: false ================================================ FILE: .github/pull_request_template.md ================================================ ## Assigned Issue Number ? #Issue_Number ## Location of the file(s) ? Folder => Sub-Folder => ... => File.extension ### Checklist - [ ] **I've followed the [contributing guidelines](https://github.com/ahampriyanshu/algo_ds_101/blob/main/CONTRIBUTING.md)** - [ ] The content added isn't directly copied from any sources like gfg, tutorialpoint, etc. - [ ] Input has been taken dynamically. - [ ] I've referred the correct issue number. - [ ] Comments have been added - [ ] I've synced-up my forked repo. - [ ] Ain't pushing from the main branch. ================================================ FILE: .github/workflows/contributors.yml ================================================ name: Add contributors on: schedule: - cron: '0 0 * * *' jobs: add-contributors: runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - uses: BobAnkh/add-contributors@master with: REPO_NAME: 'ahampriyanshu/algo_ds_101' CONTRIBUTOR: '### Contributors' COLUMN_PER_ROW: '6' ACCESS_TOKEN: ${{secrets.GITHUB_TOKEN}} IMG_WIDTH: '100' FONT_SIZE: '14' PATH: '/CONTRIBUTORS.md' COMMIT_MESSAGE: 'Updating Contributors' AVATAR_SHAPE: 'square' ================================================ FILE: .github/workflows/welcome.yml ================================================ name: Welcome on: pull_request: types: [opened, closed] issues: types: [opened] jobs: run: runs-on: ubuntu-latest steps: - uses: bubkoo/welcome-action@v1 with: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} FIRST_ISSUE: | 👋 @{{ author }} Thanks for opening your first issue here! Be sure to follow the issue template! Regards @ahampriyanshu :v: FIRST_PR: | 👋 @{{ author }} Thanks for opening this pull request! Please check out our contributing guidelines. Regards @ahampriyanshu :v: FIRST_PR_MERGED: | 🎉 @{{ author }} Congrats on merging your first pull request! Happy contributing! Regards @ahampriyanshu :v: ================================================ FILE: 404.md ================================================ --- title: 404! permalink: /404.html ---
404
================================================ FILE: Algorithms/Array/Arr4 right shift.c ================================================ #include #define MAX 5 void AcceptArray(int *Arr1 , int n) { int cnt ; int x ; int *ptr = Arr1 ; printf("Accept an array"); for(cnt=0;cnt0 ; cnt--) { printf("cnt=%d ptr =%x ptr -1 %x \n ",cnt ,ptr ,(ptr-1)); x=*(ptr-1); *ptr=x; // printf("%d",*ptr); ptr--; } *ptr=-1; } void main(void) { int Arr[MAX]; int cnt ; int x ; printf("in main %x ",&Arr[0]); printf("\n enter your array \n"); AcceptArray(Arr,MAX); printf("\n you have entered \n "); DisplayArray(Arr,MAX ); } ================================================ FILE: Algorithms/Array/InsertArray.c ================================================ #include #define max 10 int main() { int array[max], pos, i, n, value; printf("Enter number of elements in array: "); scanf("%d", &n); if (n <= max) { printf("Enter %d elements:\n", n); for (i = 0; i < n; i++) { scanf("%d\n", &array[i]); } printf("Enter the location where you want to insert an element: "); scanf("%d", &pos); printf("Enter the value to insert: "); scanf("%d", &value); for (i = n - 1; i >= pos - 1; i--) array[i + 1] = array[i]; array[pos - 1] = value; printf("Resultant array:\n"); for (i = 0; i <= n; i++) printf("%d\n", array[i]); } else { printf("Array out of bound."); } return 0; } ================================================ FILE: Algorithms/Array/LinearSearch.java ================================================ public class Main { { public static void main(String[] args) { // Validate command line arguments count. if (args.length != 2) { System.err.println("usage: java LinearSearch integers integer"); return; } // Read integers from first command-line argument. Return if integers // could not be read. int[] ints = readIntegers(args[0]); if (ints == null) return; // Read search integer; NumberFormatException is thrown if the integer // isn't valid. int srchint = Integer.parseInt(args[1]); // Perform the search and output the result. System.out.println(srchint + (search(ints, srchint) ? " found" : " not found")); } private static int[] readIntegers(String s) { String[] tokens = s.split(","); int[] integers = new int[tokens.length]; for (int i = 0; i < tokens.length; i++) integers[i] = Integer.parseInt(tokens[i]); return integers; } private static boolean search(int[] x, int srchint) { for (int i = 0; i < x.length; i++) if (srchint == x[i]) return true; return false; } } } ================================================ FILE: Algorithms/Array/Merge-Sorted-Array.c ================================================ #include #include int cmpfunc (const void * a, const void * b) { return ( *(int*)a - *(int*)b ); } int main() { int aSize, bSize, cSize, mSize, i, j; int a[10], b[10], c[10], Merged[20]; printf("\n Please Enter the First Array Size : "); scanf("%d", &aSize); printf("\nPlease Enter the First Array Elements : "); for(i = 0; i < aSize; i++) { scanf("%d", &a[i]); } printf("\n Please Enter the Second Array Size : "); scanf("%d", &bSize); printf("\nPlease Enter the Second Array Elements : "); for(i = 0; i < bSize; i++) { scanf("%d", &b[i]); } printf("\n Please Enter the Third Array Size : "); scanf("%d", &cSize); printf("\nPlease Enter the Third Array Elements : "); for(i = 0; i < cSize; i++) { scanf("%d", &c[i]); } for(i = 0; i < aSize; i++) { Merged[i] = a[i]; } mSize = aSize + bSize; for(i = 0, j = aSize; j < mSize && i < bSize; i++, j++) { Merged[j] = b[i]; } mSize = aSize + bSize + cSize; for(i = 0, j = aSize + bSize; j < mSize && i < cSize; i++, j++) { Merged[j] = c[i]; } qsort(Merged,mSize,sizeof(int),cmpfunc); printf("\n a[%d] Array Elements After Merging \n", mSize); for(i = 0; i < mSize; i++) { printf(" %d \t ",Merged[i]); } return 0; } ================================================ FILE: Algorithms/Array/Merge-Sorted-Array.cpp ================================================ #include using namespace std; #define n 4 void printArray(int arr[], int size) { for (int i=0; i < size; i++) cout << arr[i] << " "; } void mergeKArrays(int arr[][n], int a, int output[]) { int c=0; for(int i=0; i arr[i]) { swap(arr, i - 1, i); } // if the next element is greater than the current element, // swap the elements if (i + 1 < n && arr[i + 1] > arr[i]) { swap(arr, i + 1, i); } } } const arr = [ 1, 2, 3, 4, 5, 6, 7 ]; const n = arr.length; rearrangeArray(arr, n); // print output array for (let i = 0; i < n; i++) { console.log(arr[i]); } /* Output: 1 3 2 5 4 7 6 */ ================================================ FILE: Algorithms/Array/Rearrange-High-Low.kt ================================================ // main function fun main(args: Array) { // pre defined array val arr=arrayOf(3, 6, 5, 10, 7, 20) // size of array val n=arr.size // sort the array arr.sort() // swap the alternate positions and increment in steps of 2 for (i in 0 until n step 2) { arr[i]=arr[i]+arr[i+1]; arr[i+1]=arr[i]-arr[i+1]; arr[i]=arr[i]-arr[i+1]; } // output the array for(i in 0 until n) println(arr[i]) } /* Output: 5 3 7 6 20 10 */ ================================================ FILE: Algorithms/Array/Remove-Dublicate.js ================================================ // RemoveDuplicateItem function RemoveDuplicateItem(arr) { let newAr = []; arr.forEach((item) => { if (!newAr.includes(item)) { newAr.push(item) } }) return newAr } ================================================ FILE: Algorithms/Array/Remove-Duplicates-from-Sorted-Array.c ================================================ /* Given a sorted array nums, remove the duplicates in-place such that each element appears only once and returns the new length. Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory. */ #include #include #include #include #include #include #include #include #include #include using namespace std; #define ll long long #define len length() #define vi vector #define vl vector #define fr(i,n) for(ll i=0;ij?i:j; } int removeDuplicates(vector& nums) { int ind=1; int n=nums.size(); if (n<=1) return n; for(int i=0;i>n; vector v(n,0); fr(i,n){ int x; cin>>x; v[i]=x; } sort(v.begin(),v.end()); removeDuplicates(v); for(int u =0;u using namespace std; int removeDuplicates(int arr[], int n) { if (n==0 || n==1) return n; int j = 0; for (int i=0; i < n-1; i++) if (arr[i] != arr[i+1]) arr[j++] = arr[i]; arr[j++] = arr[n-1]; return j; } int main() { int n; cin>>n; int arr[n]; for(int i=0;i>a[i]; } n = removeDuplicates(arr, n); for (int i=0; i #include #include #include #include #include #include #include #include #include using namespace std; #define ll long long #define len length() #define vi vector #define vl vector #define fr(i,n) for(ll i=0;ij?i:j; } int main(){ int t; //t=1; cin>>t; while(t--){ ll n,x,m; cin>>n>>x>>m; ll mx=x, mn=x; while(m--){ ll l,r; cin>>l>>r; if(mn>=l&&mn<=r || mx>=l&&mx<=r){ mn=min(mn,l); mx=max(mx,r); } } ll ans=(mx-mn)+1; cout< #include #include #include #include #include #include #include #include #include using namespace std; #define ll long long #define len length() #define vi vector #define vl vector #define fr(i,n) for(ll i=0;i>t; while(t--){ ll n,k; cin>>n>>k; vl a(n,0),b(n,0); fr(i,n){ cin>>a[i]; } fr(i,n){ cin>>b[i]; } sort(a.begin(),a.end()); sort(b.begin(),b.end(),greater()); ll s=0,ans=0; ll j=0; fr(i,n){ if(s using namespace std; #define LL long long #define F first #define S second #define fast_io ios::sync_with_stdio(false);cin.tie(NULL) int main() { int t; cin >> t; while(t--) { int n,ans=1; cin >> n; int a[n+5],b[n+5]; int h1[10005]={0},h2[10005]={0}; for(int i=0;i> a[i]; h1[a[i]]++; } for(int i=0;i> b[i]; h2[b[i]]++; } for(int i=0;i<=10000;i++) { if(h1[i] != h2[i]) { ans = 0; break; } } cout << ans << endl; } } ================================================ FILE: Algorithms/Array/copyarray.c ================================================ #include int main() { int arr1[40],n,i,arr2[40]; printf("How many number :"); scanf("%d",&n); // scan array_1 Elements; for (i=0;i int main() { char str[1000], ch; int i,count = 0; printf("Enter a string: "); fgets(str, sizeof(str), stdin); printf("Enter a character to find its frequency: "); scanf("%c", &ch); for ( i = 0; str[i] != '\0'; ++i) { if (ch == str[i]) ++count; } printf("Frequency of %c = %d", ch, count); return 0; } ================================================ FILE: Algorithms/Array/findpos.py ================================================ def findposition(arr, x) : flag = True for i in range(0, len(arr)) : if (x != arr[i]) : continue if (flag==True) : first = i last = i flag = False if (flag==False) : print( "First Occurrence in array = ", first , "\n" + " Last Occurrence in array = ", last) else : print("Element Not Found") arr = [1, 2, 2, 2, 2, 3, 4, 7, 8, 8 ] x=int(input("Enter the Element : ")) findposition(arr, x) ================================================ FILE: Algorithms/Array/high-low-rearrangement.c ================================================ #include //swap of elements void swap(int arr[], int i, int j) { int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } //arrange the array in high low order void rearrange(int arr[], int n) { for (int i = 1; i < n; i += 2) { if (arr[i - 1] > arr[i]) { swap(arr, i - 1, i); } if (i + 1 < n && arr[i + 1] > arr[i]) { swap(arr, i + 1, i); } } } int main(void) { //take input from user int n; printf("Enter array length : \n"); scanf("%d",&n); int arr[n]; printf("Enter array elements:\n"); for(int i = 0; i < n; i++){ scanf("%d", &arr[i]); } rearrange(arr, n); for (int i = 0; i < n; i++) { printf("%d ", arr[i]); } return 0; } ================================================ FILE: Algorithms/Array/high-low-rearrangement.c++ ================================================ #include using namespace std; //swap of elements void swap(int arr[], int i, int j) { int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } //rearrange elements high and low void rearrange(int arr[], int n) { for (int i = 1; i < n; i += 2) { if (arr[i - 1] > arr[i]) { swap(arr, i - 1, i); } if (i + 1 < n && arr[i + 1] > arr[i]) { swap(arr, i + 1, i); } } } int main() { //enter array by user int n; cout<<"Enter the number of elements:"<>n; int arr[n]; cout<<"Enter array elements:"<>arr[i]; } rearrange(arr, n); for (int i = 0; i < n; i++) { cout< A[i]: swap(A, i - 1, i) if i + 1 < len(A) and A[i + 1] > A[i]: swap(A, i + 1, i) if __name__ == '__main__': A = [] n = int(input("Enter number of elements : ")) A = list(map(int,input("\nEnter the numbers:").strip().split()))[:n] rearrangeArray(A) print(A) ================================================ FILE: Algorithms/Array/largest-smallest-number-and-sum-of-all-elements-in-array.java ================================================ import java.io.*; class t17question7 { public static void main(String args[])throws IOException { InputStreamReader in = new InputStreamReader(System.in); BufferedReader y = new BufferedReader(in); int i,ln=0,sn=0,s=0; int n[]=new int[20]; System.out.println("Input 20 integers"); for(i=0;i<20;i++) { n[i]=Integer.parseInt(y.readLine()); } ln=n[0]; for(i=1;i<20;i++) { if(n[i]>ln) ln=n[i]; } System.out.println(" The largest number is "+ln); sn=n[0]; for(i=1;i<20;i++) { if(n[i] using namespace std; /* Author : codewithmini */ /* Problem Statement We are given two sorted arrays. We need to merge these two arrays such that the initial numbers (after complete sorting) are in the first array and the remaining numbers are in the second array. Extra space allowed in O(1). */ int main() { int m,n; // input as length of array 1 cout<<"Enter the length of array 1 : "; cin>>m; // input as length of array 2 cout<<"\nEnter the length of array 2 : "; cin>>n; int arr1[m],arr2[n]; // array 1 cout<<"\nEnter the values of array 1 \n"; for(int i=0;i>arr1[i]; } // array 2 cout<<"\nEnter the values of array 2 \n"; for(int i=0;i>arr2[i]; } int i = 0, j = 0, k = m - 1; // Till when i less than equal to k or j is less tha m // while traversing the two sorted arrays parallelly, if we encounter the jth second array element is smaller than ith first array element, then jth element is to be included and replace some kth element in the first array while (i <= k && j < n) { if (arr1[i] < arr2[j]) { i++; } else { swap(arr2[j++], arr1[k--]); } } // sort both arr1 and arr2 sort(arr1, arr1 + m); sort(arr2, arr2 + n); cout << "After Merging \nFirst Array: "; for (int i = 0; i < m; i++) cout << arr1[i] << " "; cout << "\nSecond Array: "; for (int i = 0; i < n; i++) cout << arr2[i] << " "; return 0; } /* OUTPUT : Enter the length of array 1 : 6 Enter the length of array 2 : 4 Enter the values of array 1 1 5 9 10 15 20 Enter the values of array 2 2 3 8 13 After Merging First Array: 1 2 3 5 8 9 Second Array: 10 13 15 20 */ ================================================ FILE: Algorithms/Array/merging_2_arrays.c ================================================ #include int main() { int n1, n2, n3, i, j; printf("\n Enter the number of elements for First Array : "); scanf("%d", &n1); //Array Size Declaration int a[n1]; //Array Declaration printf("\nEnter the elements for First Array : "); for(i = 0; i < n1; i++) { scanf("%d", &a[i]); } printf("\n Enter the number of elements for Second Array : "); scanf("%d", &n2); //Array Size Declaration int b[n2]; //Array Declaration printf("\nEnter the elements for Second Array : "); for(i = 0; i < n2; i++) { scanf("%d", &b[i]); } n3 = n1 + n2; //Array Size Declaration int c[n3]; //Array Declaration for(i = 0; i < n1; i++) { c[i] = a[i]; } for(i = 0, j = n1; j < n3 && i < n2; i++, j++) { c[j] = b[i]; } printf("\n a[%d] Array Elements After Merging \n", n3); for(i = 0; i < n3; i++) { printf(" %d \t ",c[i]); } return 0; } ================================================ FILE: Algorithms/Array/rearrange-high-low.java ================================================ import java.util.Scanner; class Main { // swap private static void swap(int[] A, int i, int j) { int temp = A[i]; A[i] = A[j]; A[j] = temp; } // rearrange public static void rearrangeArray(int[] A) { for (int i = 1; i < A.length; i += 2) { if (A[i - 1] > A[i]) { swap(A, i - 1, i); } if (i + 1 < A.length && A[i + 1] > A[i]) { swap(A, i + 1, i); } } } public static void main (String[] args) { int n; Scanner sc = new Scanner(System.in); System.out.println("Enter no. of elements in array:"); n = sc.nextInt(); int A[] = new int[n]; System.out.println("Enter all the elements:"); for(int i = 0; i < n; i++) { A[i] = sc.nextInt(); } rearrangeArray(A); System.out.println(Arrays.toString(A)); } } ================================================ FILE: Algorithms/Array/revering_array.c ================================================ #include #include struct Array { int A[10]; int size; int length; }; void Display(struct Array arr) { int i; printf("\nElements are\n"); for(i=0;ilength*sizeof(int)); for(i=arr->length-1,j=0;i>=0;i--,j++) B[j]=arr->A[i]; for(i=0;ilength;i++) arr->A[i]=B[i]; } void Reverse2(struct Array *arr) { int i,j; for(i=0,j=arr->length-1;iA[i],&arr->A[j]); } } int main() { struct Array arr1={{2,3,9,16,18,21,28,32,35},10,9}; Reverse(&arr1); Display(arr1); return 0; } ================================================ FILE: Algorithms/Array/rotate_matrix_90degree.cpp ================================================ #include using namespace std; /* Author : codewithrathi */ /* Problem Statement : Rotate a matrix by 90 degree in clockwise or anticlockwise direction without using any extra space */ int main() { int n; // Dimension of square matrix cout<<"\nEnter the dimension of Matrix : "; cin>>n; int arr[n][n],ch; // matrix cout<<"\nEnter the values of Matrix \n"; for(int i=0;i>arr[i][j]; } } cout<<"Enter your choice (1 or 2) : \n"; cout<<"[1] anti-clockwise rotation \n"; cout<<"[2] clockwise rotation \n"; cin>>ch; cout<<"Matrix before rotation :\n\n"; for(int i=0;i using namespace std; int rotatedSearch(vector &A, int B) { //low and high are the indices between which we search- int low=0; int high=A.size()-1; //finding the pivot of rotation- for(int i=0; iA[i+1]){ if(B>=A[0]) high=i; //search only in the left of pivot else if(B<=A[A.size()-1]) low=i+1; //search only in the right of pivot break; } } //implementing Binary Search- while(high>=low){ int mid=low+(high-low)/2; if(A[mid]==B) return mid; //B is found else if(A[mid]>B) high=mid-1; else if(A[mid] using namespace std; /*Naive Approach: Check for all pairs if they adds up to the target or not TC: O(n*n) SC: O(1) */ pair findTwoSumNaive(vector nums, int target){ int n = nums.size(); for(int i = 0; i < n; i++){ for(int j = i + 1; j < n; j++){ if(nums[i] + nums[j] == target) return {nums[i], nums[j]}; } } return {-1, -1}; } /*Better Approach: Sort the given array ->create two pointers one of which points to the first element and another one to the last element. ->check if both the values pointed to by these pointers adds up to the target or not. ->if yes, return the result. ->otherwise, if the sum is lesser than the target increment left pointer -> otherwise decrement the right pointer. ->The above intuition works because the array is sorted. TC: O(nlogn) SC: O(n) */ pair findTwoSumBetter(vector nums, int target){ sort(nums.begin(), nums.end()); int lo = 0; int hi = nums.size() - 1; while(lo < hi){ if(nums[lo] + nums[hi] == target) return {nums[lo],nums[hi]}; nums[lo] + nums[hi] < target ? lo++ : hi--; } return {-1, -1}; } /*Optimal Approach: ->Use a hashmap to store the numbers as you traverse. ->At any point if you had added a value equal to the target - current_number in the hashmap. ->Then we have our ans as {current_number, target - current_number} which adds up to the target value. ->otherwise return {-1, -1} as the result. TC: O(n) SC: O(n) considering the hashmap works in O(1) on an average. */ pair findTwoSumOptimal(vector nums, int target){ unordered_mapmp; for(auto &a : nums){ if(mp[target - a]) return {target - a, a}; mp[a]++; } return {-1, -1}; } int main(){ //get the input array as a line of string string s; getline(cin, s); //get the target value int target; cin >> target; stringstream ss(s); vector nums; int value; //string values to integer values and add it the nums array while(ss >> value)nums.push_back(value); //a pair of values to store the result pair values = findTwoSumOptimal(nums, target); //if both the values of the result are -1 //it means no such pair exists that adds up to the target value //otherwise, print a valid pair of values if(values.first == -1 and values.second == -1){ cout << "No such pair exists" << endl; } else{ cout << values.first <<" and " << values.second <<" adds up to " << target << endl; } } ================================================ FILE: Algorithms/Array/twoSum.kt ================================================ import java.util.* /*Naive Approach: Check for all pairs if they adds up to the target or not TC: O(n*n) SC: O(1) */ fun findTwoSumNaive(nums: List, target: Int): IntArray{ val n = nums.size for(i in 0 until n){ for(j in (i+1) until n){ if(nums[i] + nums[j] == target) return intArrayOf(nums[i], nums[j]) } } return intArrayOf(-1, -1) } /*Better Approach: Sort the given array ->create two pointers one of which points to the first element and another one to the last element. ->check if both the values pointed to by these pointers adds up to the target or not. ->if yes, return the result. ->otherwise, if the sum is lesser than the target increment left pointer -> otherwise decrement the right pointer. ->The above intuition works because the array is sorted. TC: O(nlogn) SC: O(n) */ fun findTwoSumBetter(nums: List, target: Int): IntArray{ Collections.sort(nums) var (lo, hi) = Pair(0, nums.size - 1) while(lo < hi){ val sum = nums[lo] + nums[hi] if(sum == target){ return intArrayOf(nums[lo], nums[hi]); } if(sum < target) lo++ else hi-- } return intArrayOf(-1, -1) } /*Optimal Approach: ->Use a hashmap to store the numbers as you traverse. ->At any point if you had added a value equal to the target - current_number in the hashmap. ->Then we have our ans as {current_number, target - current_number} which adds up to the target value. ->otherwise return {-1, -1} as the result. TC: O(n) SC: O(n) considering the hashmap works in O(1) on an average. */ fun findTwoSumOptimal(nums: List, target: Int): IntArray{ val map = mutableMapOf() for(num in nums){ if(map.containsKey(target - num)) return intArrayOf(target - num, num) map[num] = true } return intArrayOf(-1, -1) } //main function fun main(){ //get the input array val nums = readLine()!!.split(' ').map{it.toInt()} //get the target value val target = readLine()!!.toInt() //a pair of values to store the result val values = findTwoSumOptimal(nums, target) //if both the values of the result are -1 //it means no such pair exists that adds up to the target value //otherwise, print a valid pair of values if(values[0] == -1 && values[1] == -1) println("No such pair exists") else println("${values[0]} and ${values[1]} adds up to $target") } ================================================ FILE: Algorithms/Array/wave_form_array ================================================ //Print a 2d array in wave form i.e. \/\/\/\/ #include using namespace std; int main() { int a[1000][1000]; int m,n; cin>>m>>n; for(int i=0;i>a[i][j]; } } cout<<"The 2-D Array is:"<=0;i--){ cout< using namespace std; #define N 10 //Return index of word which is not filled in crossword bool findString(vector &visited, int &index) { int n = visited.size(); for (int i = 0; i < n; i++) if (visited[i] == 0) { index = i; return false; } return true; } //check if word can be filled in a column bool isPossible_col(vector> &grid, int row, int col, string word) { int len = word.size(); for (int i = 0; i < len; i++) { if ((col + i) >= 10) return false; if (grid[row][col + i] != '-' && grid[row][col + i] != word[i]) return false; } return true; } //check if word can be filled in a row. bool isPossible_row(vector> &grid, int row, int col, string word) { int len = word.size(); for (int i = 0; i < len; i++) { if ((row + i) >= 10) return false; if (grid[row + i][col] != '-' && grid[row + i][col] != word[i]) return false; } return true; } // Fill all words in crossword & return true if all words can be filled in the grid. bool crossword(vector> &grid, vector &visited, vector &words) { int index; if (findString(visited, index)) return true; for (int i = 0; i < 10; i++) { for (int j = 0; j < 10; j++) { if (grid[i][j] == '-' || grid[i][j] == words[index][0]) { if (isPossible_col(grid, i, j, words[index])) { string prev_state = ""; for (int k = 0; k < words[index].size(); k++) prev_state += grid[i][j + k], grid[i][j + k] = words[index][k]; visited[index] = 1; bool flag = crossword(grid, visited, words); if (flag) return true; visited[index] = 0; for (int k = 0; k < words[index].size(); k++) grid[i][j + k] = prev_state[k]; } if (isPossible_row(grid, i, j, words[index])) { string prev_state = ""; for (int k = 0; k < words[index].size(); k++) prev_state += grid[i + k][j], grid[i + k][j] = words[index][k]; visited[index] = 1; bool flag = crossword(grid, visited, words); if (flag) return true; visited[index] = 0; for (int k = 0; k < words[index].size(); k++) grid[i + k][j] = prev_state[k]; } } } } return false; } int main() { //1. given crossword grid vector> grid(N, vector(N)); for (int i = 0; i < N; i++) for (int j = 0; j < N; j++) cin >> grid[i][j]; //2. given words to be filled in Crossword int num_of_words; vector words; string word; cin>>num_of_words; for(int i=0;i>word; words.push_back(word); } //3. calling function crossword to fill the grid vector visited(num_of_words, 0); if (crossword(grid, visited, words)) { for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) cout << grid[i][j]; cout << endl; } } else { cout << "We Cannot fill all the words in the grid" << endl; } } ================================================ FILE: Algorithms/Backtracking/Nqueen/N_Queen.java ================================================ import java.util.*; public class N_Queen { final int N=4; public boolean solveNQUtil(int board[][],int col) { if(col>=N) return true; for(int i=0;i=0&&j>=0;i--,j--) if(board[i][j]==1) return false; return true; } boolean solveNQ() { int board[][]= {{0,0,0,0},{0,0,0,0},{0,0,0,0},{0,0,0,0} }; if(solveNQUtil(board,0)==false) { System.out.println("solution does nor exist"); return false; } printsolution(board); return true; } void printsolution(int board[][]) { for(int i=0;i #include char a[10][10]; int n; void printmatrix() { int i, j; printf("\n"); for (i = 0; i < n; i++) { for (j = 0; j < n; j++) printf("%c\t", a[i][j]); printf("\n\n"); } } int getmarkedcol(int row) { int i; for (i = 0; i < n; i++) if (a[row][i] == 'Q') { return (i); break; } } int feasible(int row, int col) { int i, tcol; for (i = 0; i < n; i++) { tcol = getmarkedcol(i); if (col == tcol || abs(row - i) == abs(col - tcol)) return 0; } return 1; } void nqueen(int row) { int i, j; if (row < n) { for (i = 0; i < n; i++) { if (feasible(row, i)) { a[row][i] = 'Q'; nqueen(row + 1); a[row][i] = '.'; } } } else { printf("\nThe solution is:- "); printmatrix(); } } int main() { int i, j; printf("\nEnter the no. of queens:- "); scanf("%d", &n); for (i = 0; i < n; i++) for (j = 0; j < n; j++) a[i][j] = '.'; nqueen(0); return (0); } ================================================ FILE: Algorithms/Backtracking/Nqueen/Nqueens.cpp ================================================ #include #define ll long long #define mod 1000000007; using namespace std; bool isvalid(int board[][10],int i,int j,int n) { for(int k=0;k=0&&y>=0) { if(board[x][y]==1) { return false; } x--; y--; } x=i; y=j; while(x>=0&&y>n; bool f=showNqueen(board,0,n); return 0; } ================================================ FILE: Algorithms/Backtracking/Nqueen/Nqueens_optimized.cpp ================================================ #include #define ll long long #define mod 1000000007; using namespace std; int c=0; int column[100]={0},d1[100]={0},d2[100]={0}; void solve(int i,int n) { if(i==n) { c++; return ; } for(int j=0;j>n; solve(0,n); cout< using namespace std; int grid[10][10]; //print the solution void print(int n) { for (int i = 0;i <= n-1; i++) { for (int j = 0;j <= n-1; j++) { cout <= 0 && j >= 0; i--,j--) { if (grid[i][j]) { return false; } } for (int i = row, j = col; i >= 0 && j < n; j++, i--) { if (grid[i][j]) { return false; } } return true; } bool solve (int n, int row) { if (n == row) { print(n); return true; } bool res = false; for (int i = 0;i <=n-1;i++) { if (isSafe(i, row, n)) { grid[row][i] = 1; res = solve(n, row+1) || res;//if res ==false then backtracking will occur grid[row][i] = 0; } } return res; } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); int n; cout<<"Enter the number of queen"<> n; for (int i = 0;i < n;i++) { for (int j = 0;j < n;j++) { grid[i][j] = 0; } } bool res = solve(n, 0); if(res == false) { cout << -1 << endl; } else { cout << endl; } return 0; } ================================================ FILE: Algorithms/Backtracking/Nqueen/nqueens.py ================================================ global N N = 4 def printSolution(board): for i in range(N): for j in range(N): print(board[i][j],end=",") print(" ") def isSafe(board, row, col): # Check this row on left side for i in range(col): if board[row][i] == 1: return False # Check upper diagonal on left side for i, j in zip(range(row, -1, -1), range(col, -1, -1)): if board[i][j] == 1: return False # Check lower diagonal on left side for i, j in zip(range(row, N, 1), range(col, -1, -1)): if board[i][j] == 1: return False return True def solveNQUtil(board, col): if col >= N: return True for i in range(N): if isSafe(board, i, col): # Place this queen in board[i][col] board[i][col] = 1 # recur to place rest of the queens if solveNQUtil(board, col + 1) == True: return True board[i][col] = 0 return False def solveNQ(): board = [ [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0] ] if solveNQUtil(board, 0) == False: print("Solution does not exist") return False printSolution(board) return True # driver program to test above function solveNQ() ================================================ FILE: Algorithms/Backtracking/Permutation/Permutations.c ================================================ #include #include #include void swap(int *ar, int i, int j) { int temp = ar[i]; ar[i] = ar[j]; ar[j] = temp; } void printar(int *ar, int n) { for (int i = 0; i < n; i++) printf("%d ", ar[i]); printf("\n"); } void permute(int *ar, int i, int n) { if (n == i) { printar(ar, n); return; } int j = i; for (j = i; j < n; j++) { swap(ar, i, j); permute(ar , i + 1, n); swap(ar, i, j); } return; } int main() { int n; scanf("%d", &n); int ar[n]; for (int i = 0; i < n; i++) scanf("%d", &ar[i]); permute(ar, 0, n); } ================================================ FILE: Algorithms/Backtracking/Permutation/permutation.py ================================================ def permutation(arr): if(len(arr) == 1): return [arr] result = [] for i in arr: #Array excluding i element sub_arr = [j for j in arr if j != i] p = permutation(sub_arr) for k in p: temp = [i]+k result.append(temp) return result ================================================ FILE: Algorithms/Backtracking/Permutation/permutations.cpp ================================================ #include using namespace std; void solve(vector& nums, vector& curr, vector> &res, int i){ if(curr.size()==nums.size()) //one possible permutation obtained- res.push_back(curr); else { //backtracking algorithm implementation- for(int j=i; j> permute(vector& nums) { vector>res; vectorcurr; solve(nums, curr, res, 0); return res; } int main() { int n; cin >> n; vectorarr(n); for(int i=0; i> arr[i]; vector> answer = permute(arr); //printing all the possible permutation arrays - for(int i=0; i using namespace std; //function that returns the list of paths in lexicographically increasing order void rat_in_a_maze(int i, int j, int n, vector> &grid, vector &paths, string &path) { //base case if (i == n - 1 && j == n - 1) { paths.push_back(path); return; } //if grid[0][0] is -1, no recursion takes place... if (grid[i][j] == 0) { return; } //moving down('D') if ((i + 1) < n && grid[i + 1][j] == 1) { int x = grid[i][j]; path.push_back('D'); grid[i][j] = -1; //indicates this to be visited rat_in_a_maze(i + 1, j, n, grid, paths, path); path.pop_back(); //undoing change grid[i][j] = x; //restoring the grid } //moving down('L') if ((j - 1) >= n && grid[i][j - 1] == 1) { int x = grid[i][j]; path.push_back('L'); grid[i][j] = -1; //indicates this to be visited rat_in_a_maze(i, j - 1, n, grid, paths, path); path.pop_back(); //undoing change grid[i][j] = x; //restoring the grid } //moving down('R') if ((j + 1) < n && grid[i][j + 1] == 1) { int x = grid[i][j]; path.push_back('R'); grid[i][j] = -1; //indicates this to be visited rat_in_a_maze(i, j + 1, n, grid, paths, path); path.pop_back(); //undoing change grid[i][j] = x; //restoring the grid } //moving down('U') if ((i - 1) >= 0 && grid[i - 1][j] == 1) { int x = grid[i][j]; path.push_back('U'); grid[i][j] = -1; //indicates this to be visited rat_in_a_maze(i - 1, j, n, grid, paths, path); path.pop_back(); //undoing change grid[i][j] = x; //restoring the grid } } int main() { int n;//size of the grid (n * n) cin >> n; vector> grid(n, vector (n, 0)); for (int i = 0; i < n; ++i) { for (int j = 0; j < n; ++j) { cin >> grid[i][j]; } } vector paths; string path; rat_in_a_maze(0, 0, n, grid, paths, path); cout<<"The Paths from the Top Right to Bottom Left are : \n"; for (string s : paths) { cout << s << " "; } cout << endl; } ================================================ FILE: Algorithms/Cryptography/AES_Cipher/AES_Cipher.py ================================================ import sys, base64, json, math try: from Crypto.Cipher import AES except ImportError: print ("Error!! Module AES is required. Run either or following commands") print("pip install pycrypto") print("---------OR--------") print("pip3 install pycrypto") sys.exit() KEY="" PADDING_CHARACTER="S" VECTOR_FOR_AES="SUDESH1611GITHUB" def GetKey(): global KEY tempKey = input("Enter password(min length: 8, max length: 32)") while(len(tempKey.strip())<8 or len(tempKey.strip())>32 or ' ' in tempKey): if(' ' in tempKey): print("White spaces are not allowed!") else: print("Password must be at least 8 characters long and at max 32 characters long. Try Again!") while(len(tempKey)%8!=0): tempKey+=PADDING_CHARACTER KEY=tempKey def AES_Encryption(cleartext): if(len(KEY)<8 or len(KEY)%8!=0): print("Password is corrupted. Exiting!") sys.exit() return AES_Encryptor = AES.new(KEY,AES.MODE_CBC,VECTOR_FOR_AES) cleartext_length = len(cleartext) nearest_multiple_of_16 = 16 * math.ceil(cleartext_length/16) padded_cleartext = cleartext.rjust(nearest_multiple_of_16) raw_ciphertext = AES_Encryptor.encrypt(padded_cleartext) return base64.b64encode(raw_ciphertext).decode('utf-8') def AES_Decryption(ciphertext): if(len(KEY)<8 or len(KEY)%8!=0): print("Password is corrupted. Exiting!") sys.exit() return AES_Decryptor = AES.new(KEY,AES.MODE_CBC,VECTOR_FOR_AES) raw_ciphertext = base64.b64decode(ciphertext) decrypted_message_with_padding = AES_Decryptor.decrypt(raw_ciphertext) return decrypted_message_with_padding.decode('utf-8').strip() if __name__ == "__main__": type="S" while(type not in "ed"): type = input("Encrypt or Decrypt the text(e/d): ") type = type.strip().lower() if(len(type)!=1): type="S" GetKey() if(type=="e"): print("NOTE: If you forget this password, you will not be able to decrypt text correctly. So, DO NOT FORGET PASSWORD!!") message = input("Enter message in single line: ") ciphertext = AES_Encryption(message) print("Encrypted Message: %s" % ciphertext) else: encText = input("Enter encrypted message: ") message = AES_Decryption(encText) print("Original Message: %s" % message) ================================================ FILE: Algorithms/Cryptography/AES_Cipher/README.md ================================================ ## AES The Advanced Encryption Standard (AES), also known by its original name Rijndael is a specification for the encryption of electronic data with different key and block sizes. ================================================ FILE: Algorithms/Cryptography/Affine_Cipher/Affine_Cipher.cpp ================================================ // In the affine cipher the letters of an alphabet of size m are first mapped to the integers in the range 0 … m − 1. // It then uses modular arithmetic to transform the integer that each plaintext letter corresponds to into another // integer that correspond to a ciphertext letter. // ENCYPTION // E(x) = (a*x + b) % 26 // DECRYPTION // D(x) = a^-1(x - b) % 26 // where a^-1 is modular multiplicative inverse of a #include using namespace std; int a = 5; int b = 8; int inv_a; // encryptMessage: encrypt the given text using affine ciper // param text: the text which need to pe encrypted // type test: string // param func: custom func can be passed by the user which will be used in affine cipher // type func: function (int) ->int // default func: x: a*x + b string encryptMessage(string text, int (*func)(int)=NULL) { string encrypted_text = ""; if(func==NULL){ func = [](int x){ return a*x + b; }; } int mod = 26; for(const char character : text) { //to check the case and convert the character in that specific case //else if characte is not a alphabet don't change it int ascii_val, new_ascii_val; if (isupper(character)) { ascii_val = int(character) - int('A'); new_ascii_val = func(ascii_val) % mod; new_ascii_val += int('A'); } else if (islower(character)) { ascii_val = int(character) - int('a'); new_ascii_val = func(ascii_val) % mod; new_ascii_val += int('a'); } else { ascii_val = int(character); new_ascii_val = ascii_val; } encrypted_text = encrypted_text + char(new_ascii_val); } return encrypted_text; } // decryptMessage: decrypt the given text using affine ciper // param text: the encrypted text which need to pe decrypted // type test: str // param func: custom func can be passed by the user which will be used in affine cipher // type func: function // default func: x: inv_a*(x - b) string decryptMessage(string text, int (*func)(int)=NULL) { // finding modular multiplicative inverse of a for(int i = 0; i < 26; i++) { if((i*a)%26 == 1){ inv_a = i; break; } } string decyrpted_text = ""; if(func==NULL){ func = [](int x){ return inv_a*(x - b); }; } int mod = 26; for(const char character : text) { //to check the case and convert the character in that specific case //else if characte is not a alphabet don't change it int ascii_val, new_ascii_val; if (isupper(character)) { ascii_val = int(character) - int('A'); new_ascii_val = func(ascii_val) % mod; new_ascii_val = new_ascii_val<0 ? mod + new_ascii_val : new_ascii_val; new_ascii_val += int('A'); } else if (islower(character)) { ascii_val = int(character) - int('a'); new_ascii_val = func(ascii_val) % mod; new_ascii_val = new_ascii_val<0 ? mod + new_ascii_val : new_ascii_val; new_ascii_val += int('a'); } else { ascii_val = int(character); new_ascii_val = ascii_val; } decyrpted_text = decyrpted_text + char(new_ascii_val); } return decyrpted_text; } int main(void) { string msg; getline(cin,msg); // custom function can also be used string cipherText = encryptMessage(msg); cout << "Encrypted Message is : " << cipherText< #include #include #include #include #define MAX 100000 int CalcGCD(int); int CalcGCD(int alpha) { int x; int temp1 = alpha; int temp2 = 26; while (temp2 != 0) { x = temp2; temp2 = temp1 % temp2; temp1 = x; } return (temp1); } int main() { int i, j, k, gcd, alpha, beta, numstr[100], numcipher[100]; char str[100], cipher[100]; printf("Enter a string\n"); fgets(str, MAX, stdin); for (i = 0, j = 0; i < strlen(str); i++) { if (str[i] != ' ') { str[j] = toupper(str[i]); j++; } else { str[j] = ' '; j++; } } str[j] = '\0'; printf("Enter Alpha value and must be between 1 and 25 both included\n"); scanf("%d", &alpha); if (alpha < 1 || alpha > 25) { printf("Alpha should lie in between 1 and 25\nSorry Try again !\n"); exit(0); } gcd = CalcGCD(alpha); if (gcd != 1) { printf("gcd(alpha,26)=1 but \n gcd(%d,26)=%d\nSorry Try again !\n", alpha, gcd); exit(0); } printf("Enter Beta value and must be between 0 and 25 both included\n"); scanf("%d", &beta); if (beta < 0 || beta > 25) { printf("Beta value should lie between 0 and 25\nSorry Try again !\n"); exit(0); } for (i = 0; i < strlen(str); i++) { if (str[i] != ' ') numstr[i] = str[i] - 'A'; else numstr[i] = -20; } printf("Affine Cipher text is: "); for (i = 0; i < strlen(str); i++) { if (numstr[i] != -20) { numcipher[i] = ((alpha * numstr[i]) + beta) % 26; printf("%c", (numcipher[i] + 'A')); } else { printf(" "); } } printf("\n"); } ================================================ FILE: Algorithms/Cryptography/Bifid_Cipher/Bifid_Cipher.py ================================================ """ @author: Abhinav Tiwari @github: abhinav-idle """ """ Bifid Cipher was invented in 1901 by Felix Delastelle. Bifid cipher is a cipher in which we combine polybius square with transposition and fractionation i.e we use regular system to shift the letters of input-text so that the cipher-text constitutes of permutaion of different plaintext(transposition) as in here we replace each letter of input text with respect to it co-ordinates in polybius square (fractionation). the co-ordinates are stored in row by column arrays respectively. After performing these steps for every letter in input text we have two arrays of equal length constituting of rows and columns of each letter, we then concatinate both the arrays making one array, then we make couples of two and get the character according to the polybius square and concatinate each character to the encrypted text. Voila, we have done bifid encryption, to cross verify you can decrypt the encrypted message to get back the originat text, by reverting each step and using the same polybius square. In this cipher I'll use a custom 8x8 polybis square to cover complex encryption/decryption that includes any alpha-numeric combination of the following characters i.e A-Z, a-z, 0-9, ?, @ One can use their own customized polybius square to encrypt even more complex input text. """ def find_pos(polybius_square, character): #returns the co-ordinates of character according to polybius square created as a #tuple of co-ordinates, indexing is done from 1 and not from 0. for i in range(8): #to avoid error we've used try exceplt block, as index function raises ValueError #when elemnt is not found in list. try: j = polybius_square[i].index(character) return i + 1, j + 1 except ValueError: pass def get_word(a, b, polybius_square): #returns the character present at (a - 1, b - 1) co-ordinate #indexing is from 1 so, we're substracting 1 to get actual co-ordinates. return polybius_square[a-1][b-1] def create_polybius_square(): #create and return polybius square as a list arr = [] num = 48 #for numeric characters 0-9. upper_case = 63 #for uppercase alphabets A-Z and ?,@. lower_case = 97 #for lowercase alphabets a-z. for i in range(8): sub_arr = [] cnt = 0 while(cnt<8): if num<=57 and cnt<8: sub_arr.append(chr(num)) num += 1 cnt += 1 if upper_case<=90 and cnt<8: sub_arr.append(chr(upper_case)) upper_case += 1 cnt+=1 if lower_case<=122 and cnt<8: sub_arr.append(chr(lower_case)) lower_case += 1 cnt+=1 arr.append(sub_arr) return arr def bifid_encryption(polybius_square, text): #implementing bifid-encryption #to store co-ordinates row = [] column = [] for letter in text: i,j = find_pos(polybius_square, letter) row.append(i) column.append(j) array = [] array.extend(row) array.extend(column) encrypted_text = "" for i in range(0,len(array),2): character = get_word(array[i], array[i+1], polybius_square) encrypted_text += character return encrypted_text def decryption(polybius_square, encrypted_text): #decrypt message array = [] for text in encrypted_text: array.extend(list(find_pos(polybius_square,text))) row = array[:len(array)//2] column = array[len(array)//2:] original_text = "" for i in range(len(row)): original_text += get_word(row[i],column[i],polybius_square) return original_text def main(): #Enter text to encrypt text = input() #created polybius square polybius_square = create_polybius_square() print("Encrypted text : ",bifid_encryption(polybius_square, text)) print("Original text : ",decryption(polybius_square, bifid_encryption(polybius_square, text))) main() ================================================ FILE: Algorithms/Cryptography/Bifid_Cipher/README.md ================================================ ## This folder is empty. ================================================ FILE: Algorithms/Cryptography/CIA_Triad_Ciper/README.md ================================================ ## This folder is empty. ================================================ FILE: Algorithms/Cryptography/Caesar_Cipher/Caesar Cypher.cpp ================================================ #include #include using namespace std; int main() { cout<<"Enter the message:\n"; char msg[100]; cin.getline(msg,100); //take the message as input int i, j, length,choice,key; cout << "Enter key: "; cin >> key; //take the key as input length = strlen(msg); cout<<"Enter your choice \n1. Encryption \n2. Decryption \n"; cin>>choice; if (choice==1) //for encryption{ char ch; for(int i = 0; msg[i] != '\0'; ++i) { ch = msg[i]; //encrypt for lowercase letter If (ch >= 'a' && ch <= 'z'){ ch = ch + key; if (ch > 'z') { ch = ch - 'z' + 'a' - 1; } msg[i] = ch; } //encrypt for uppercase letter else if (ch >= 'A' && ch <= 'Z'){ ch = ch + key; if (ch > 'Z'){ ch = ch - 'Z' + 'A' - 1; } msg[i] = ch; } } printf("Encrypted message: %s", msg); } else if (choice == 2) { //for decryption char ch; for(int i = 0; msg[i] != '\0'; ++i) { ch = msg[i]; //decrypt for lowercase letter if(ch >= 'a' && ch <= 'z') { ch = ch - key; if(ch < 'a'){ ch = ch + 'z' - 'a' + 1; } msg[i] = ch; } //decrypt for uppercase letter else if(ch >= 'A' && ch <= 'Z') { ch = ch - key; if(ch < 'A') { ch = ch + 'Z' - 'A' + 1; } msg[i] = ch; } } cout << "Decrypted message: " << msg; } } ================================================ FILE: Algorithms/Cryptography/Caesar_Cipher/Caesar Cypher.py ================================================ def encrypt(text,s): result = "" # transverse the plain text for i in range(len(text)): char = text[i] # Encrypt uppercase characters in plain text if (char.isupper()): result += chr((ord(char) + s-65) % 26 + 65) # Encrypt lowercase characters in plain text else: result += chr((ord(char) + s - 97) % 26 + 97) return result #check the above function text = input() s = input() print "Plain Text : " + text print "Shift pattern : " + str(s) print "Cipher: " + encrypt(text,s) ================================================ FILE: Algorithms/Cryptography/Caesar_Cipher/CaesarCipher.java ================================================ import java.util.Scanner; public class CaesarCipher { public static final int SHIFT_MAX = 26; public static int shiftChar(int c, int shift) { shift = (shift+SHIFT_MAX)%SHIFT_MAX; if ('a' <= c && c <= 'z') { return ((c - 'a' + shift)%SHIFT_MAX + 'a'); } else if ('A' <= c && c <= 'Z') { return ((c - 'A' + shift)%SHIFT_MAX + 'A'); } else { return c; } } public static String cipher(String str, int shift) { return str.chars().map(c->shiftChar(c, shift)).collect( StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append).toString(); } public static String cipher(String str) { return cipher(str, 13); } public static String decipher(String str, int shift) { return cipher(str, SHIFT_MAX - shift); } public static String decipher(String str) { return decipher(str, 13); } public static void main(String [] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter shift (Caesar's = 13): "); int shift = scanner.nextInt(); System.out.println("Enter text to be encrypted:"); System.out.print("> "); String text = scanner.nextLine(); // We read empty newline text = scanner.nextLine(); String crypt = cipher(text, shift); System.out.println(crypt); System.out.println(decipher(crypt, shift)); } } ================================================ FILE: Algorithms/Cryptography/Caesar_Cipher/Caesar_Cipher.c ================================================ #include int main() { char message[100], ch; int i, key; printf("Message to encrypt: "); gets(message); do { printf("Key: "); scanf("%d", & key); } while (key < 0 || key > 26); for (i = 0; message[i] != '\0'; ++i) { ch = message[i]; if (ch >= 'a' && ch <= 'z') { ch = ch + key; if (ch > 'z') { ch = ch - 'z' + 'a' - 1; } message[i] = ch; } else if (ch >= 'A' && ch <= 'Z') { ch = ch + key; if (ch > 'Z') { ch = ch - 'Z' + 'A' - 1; } message[i] = ch; } } printf("Encrypted message: %s\n", message); return 0; } ================================================ FILE: Algorithms/Cryptography/Caesar_Cipher/Caesar_Cipher.cs ================================================ using System; class Program { /// /// Shifts every character of a given string by a specified amount /// and returns the shifted string. /// private static string CaesarCipher(string text, int shiftAmount) { char[] characters = text.ToCharArray(); for (int i = 0; i < characters.Length; i++) { char character = characters[i]; if (char.IsLetter(character) == false) { continue; } int offsetCharacter = (char.IsLower(character) ? 'a' : 'A'); characters[i] = (char)((((character + shiftAmount) - offsetCharacter) % 26) + offsetCharacter); } return string.Join(string.Empty, characters); } /// /// Encrypts the given text using the Caesar cipher. /// private static string Encrypt(string text, int shiftAmount) { return Program.CaesarCipher(text, shiftAmount); } /// /// Decrypts the given text using the Caesar cipher. /// private static string Decrypt(string text, int shiftAmount) { return Program.CaesarCipher(text, (26 - shiftAmount)); } /// /// Main application function. /// static void Main() { bool shouldEncrpyt; int shiftAmount; string textToProcess, userInput; Console.WriteLine("Do you want to [E]ncrypt or [D]ecrypt? (Enter \"E\" or \"D\"):"); userInput = Console.ReadLine().ToLower(); if ((userInput != "e") && (userInput != "d")) { Program.ExitAfterInvalidInput(); } shouldEncrpyt = (userInput == "e"); Console.WriteLine(string.Format("Enter the text to {0}:", (shouldEncrpyt ? "encrypt" : "decrypt"))); userInput = Console.ReadLine(); if (string.IsNullOrWhiteSpace(userInput)) { Program.ExitAfterInvalidInput(); } textToProcess = userInput; Console.WriteLine("Enter an integer for the shift amount (key):"); userInput = Console.ReadLine(); if (int.TryParse(userInput, out shiftAmount) == false) { Program.ExitAfterInvalidInput(); } string result = (shouldEncrpyt ? Program.Encrypt(textToProcess, shiftAmount) : Program.Decrypt(textToProcess, shiftAmount)); Console.WriteLine(); Console.WriteLine(string.Format("Result: {0}", result)); } /// /// Informs the user that an invalid value has been entered and exits the program. /// private static void ExitAfterInvalidInput() { Console.WriteLine("You've entered an invalid value. Exiting..."); Environment.Exit(1); } } ================================================ FILE: Algorithms/Cryptography/Caesar_Cipher/Caesar_Cipher.js ================================================ var caesarEncypt = function(str, key) { if (key < 0) { return caesarEncypt(str, key + 26); } var encrypted = ""; for (var i = 0; i < str.length; i++) { var c = str[i]; if (c.match(/[a-z]/i)) { var code = str.charCodeAt(i); if (code >= 65 && code <= 90) { c = String.fromCharCode(((code - 65 + key) % 26) + 65); } else if (code >= 97 && code <= 122) { c = String.fromCharCode(((code - 97 + key) % 26) + 97); } } encrypted += c; } return encrypted; }; ================================================ FILE: Algorithms/Cryptography/Caesar_Cipher/Caesar_Cipher.php ================================================ 64 && $char < 91) { return chr(65 + ($char + $k) % 65 % 26); } else if($char > 96 && $char < 123) { return chr(97 + ($char + $k) % 97 % 26); } else { return chr($char); } }, $input); return implode($res); } ?> ================================================ FILE: Algorithms/Cryptography/Caesar_Cipher/Caesar_Cypher.rb ================================================ class CaesarCipher ORDER_ALPHABET = ("a".."z").to_a # Array of valid letter rotation (Only english alphabet letters) class << self def encrypt(sentence, times = 3) # Converts to_s allowing to map through each char of it sentence.to_s.chars.map.with_index {|char, index| # If char is not included in the array, return the char without rotate ORDER_ALPHABET.include?(char.downcase) ? rotate(times, char, index) : char }.join("") end private # Rotates the n times assigned by the user def rotate(times,current_char, index) ORDER_ALPHABET.rotate(times)[ORDER_ALPHABET.index(current_char.downcase)] end end end puts CaesarCipher.encrypt("Hello World", 13) # uryyb jbeyq puts CaesarCipher.encrypt("Uryyb jbeyq", -13) # hello world puts CaesarCipher.encrypt("Th1s 1s @ compl3x w0rd", 5) # ym1x 1x @ htruq3c b0wi puts CaesarCipher.encrypt(["Also", "Works", "for", "complex", "structures"], 7) # ["hszv", "dvyrz", "mvy", "jvtwsle", "zaybjabylz"] puts CaesarCipher.encrypt(nil) puts CaesarCipher.encrypt("Nothing change", 0) # nothing change ================================================ FILE: Algorithms/Cryptography/Caesar_Cipher/README.md ================================================ ## This folder is empty. ================================================ FILE: Algorithms/Cryptography/README.md ================================================ # This folder is empty. ================================================ FILE: Algorithms/Cryptography/RSA_Cipher/README.md ================================================ ## This folder is empty. ================================================ FILE: Algorithms/Cryptography/RSA_Cipher/RSA_Cipher.py ================================================ # -*- coding: utf-8 -*- import random from math import gcd plaintext = (input('Enter the value of text = ')) pt = "" if (plaintext.isnumeric()) : pt = plaintext else : for i in range(0,len(plaintext)): pt += str(ord(plaintext[i])) print(pt) def modInverse(e, phin) : e = e % phin; for d in range(1, phin) : if ((e * d) % phin == 1) : return d return 1 import sympy p=sympy.randprime(1000, 2000) q=sympy.randprime(1000, 2000) n=p*q phin=(p-1)*(q-1) list=[] for i in range(2,phin): if gcd(phin,i)==1: list.append(i) e = random.choice(list) d = modInverse(e,phin) ciphertext = pow(int(pt),e)%n decrypttext = pow(ciphertext,d)%n print('n = '+str(n)+' e = '+str(e)+' phi(n) = '+str(phin)+' d = '+str(d)+' cipher text = '+str(ciphertext)+' decrypted text = '+str(decrypttext)) ================================================ FILE: Algorithms/Cryptography/RSA_Cipher/RSA_cipher.cpp ================================================ #include #include #include #include #include #include using namespace std; #define LIMIT 10000 int log_power(int n, int p, int mod) { int result = 1; for (; p; p >>= 1) { if (p & 1) result = (1LL * result * n) % mod; n = (1LL * n * n) % mod; } return result; } bool new_func(int n) { bool ok = true; for (int i = 1; i <= 5 && ok; i++) { int a = rand() + 1; int result = log_power(a, n - 1, n); ok &= (result == 1); } return ok; } int generate_prime() { int generated = rand() % LIMIT; while (!new_func(generated)) generated = rand() % LIMIT; return generated; } int gcd(int a, int b) { while (b) { int r = a % b; a = b; b = r; } return a; } int generate_coprime(int n) { int generated = rand() % LIMIT; while (gcd(n, generated) != 1) generated = rand() % LIMIT; return generated; } pair euclid_extended(int a, int b) { if(!b) { return {1, 0}; } auto result = euclid_extended(b, a % b); return { result.second, result.first - (a / b) * result.second }; } int modular_inverse(int n, int mod) { int inverse = euclid_extended(n, mod).first; while(inverse < 0) inverse += mod; return inverse; } typedef pair PublicKey; typedef pair PrivateKey; struct Keys { PublicKey public_key; PrivateKey private_key; }; Keys generate_keys() { Keys result; int p, q; p = generate_prime(); q = generate_prime(); int n = p * q; int phi = (p -1) * (q - 1); int e = generate_coprime(phi); result.public_key = make_pair(n, e); int d = modular_inverse(e, phi); result.private_key = make_pair(n, d); return result; } int encrypt(PublicKey key, int value) { return log_power(value, key.second, key.first); } int decrypt(PrivateKey key, int value) { return log_power(value, key.second, key.first); } int main() { string s; srand(time(NULL)); Keys keys = generate_keys(); cout << "Public key: " << keys.public_key.first << " " << keys.public_key.second << "\n"; cout << "Private key: " << keys.private_key.first << " " << keys.private_key.second << "\n"; cout << "Enter your message\n"; cin >> s; int len = s.size(); cout << "Initial string: " << s << "\n"; int enc[100] = {0}; int dec[100] = {0}; for (int i = 0; i < len; i++) enc[i] = encrypt(keys.public_key, s[i]); for (int i = 0; i < len; i++) dec[i] = decrypt(keys.private_key, enc[i]); cout << "Encrypted string\n"; for(int i = 0; i < len; i++) cout << (int)enc[i]; cout << "\n"; cout << "Decrypted string: \n"; for (int i = 0; i < len; i++) cout << (char)dec[i]; cout << "\n"; return 0; } ================================================ FILE: Algorithms/Cryptography/RSA_Cipher/RSA_cipher.java ================================================ /* * RSA algorithm is asymmetric cryptography algorithm. * Asymmetric actually means that it works on two different keys i.e. Public Key and Private Key. * As the name describes that the Public Key is given to everyone and Private key is kept private. */ import java.io.DataInputStream; import java.io.IOException; import java.math.BigInteger; import java.util.Random; class Algorithm { private BigInteger P; private BigInteger Q; public BigInteger N; private BigInteger PHI; public BigInteger e; private BigInteger d; private int maxLength = 1024; private Random R; public Algorithm() { R = new Random(); //prime numbers P = BigInteger.probablePrime(maxLength, R); Q = BigInteger.probablePrime(maxLength, R); //N = P*Q N = P.multiply(Q); //(|)(N) = (P-1)*(Q-1) PHI = P.subtract(BigInteger.ONE).multiply( Q.subtract(BigInteger.ONE)); e = BigInteger.probablePrime(maxLength / 2, R); while (PHI.gcd(e).compareTo(BigInteger.ONE) > 0 && e.compareTo(PHI) < 0) { e.add(BigInteger.ONE); } //e relatively prime to PHI d = e.modInverse(PHI); } public Algorithm(BigInteger e, BigInteger d, BigInteger N) { this.e = e; this.d = d; this.N = N; } // Encrypting the data public byte[] encryptMessage(byte[] data) { // returns (data^e)%N return (new BigInteger(data)).modPow(e, N).toByteArray(); } // Decrypting the data public byte[] decryptMessage(byte[] data) { //returns (data^d)%N //remember d is our private key, we never share that //otherwise our security will be compromised. return (new BigInteger(data)).modPow(d, N).toByteArray(); } } public class RSA_cipher { //return all the bytes concatenated in a string private static String byte2String(byte[] cipher) { String temp = ""; for (byte b : cipher) { temp += Byte.toString(b); } return temp; } public static void main (String [] arguments) throws IOException { Algorithm algorithm = new Algorithm(); DataInputStream input = new DataInputStream(System.in); String inputString; System.out.println("Enter data to send."); inputString = input.readLine(); System.out.println("Encrypting the data: " + inputString); System.out.println("The data in bytes is:: " + byte2String(inputString.getBytes())); System.out.printf("Shared public key:\nN: %d \ne: %d \n\n",algorithm.N, algorithm.e); // encryption byte[] cipher = algorithm.encryptMessage(inputString.getBytes()); // decryption byte[] plain = algorithm.decryptMessage(cipher); System.out.println("Decrypting Bytes: " + byte2String(plain)); System.out.println("Original data is: " + new String(plain)); } } ================================================ FILE: Algorithms/Cryptography/Shamir_Cipher/Shamir_Cipher.c ================================================ #include #include #include #include #include #include const int N = 4; const int K = 2; const int prime = 256; size_t size = 1024; int mod_expo(int base, int exp, int mod) { if (exp == 0) { return 1; } else if (exp % 2 == 0) { int mysqrt = mod_expo(base, exp / 2, mod); return (mysqrt * mysqrt) % mod; } else { return (base * mod_expo(base, exp - 1, mod)) % mod; } } void free_heap_mem(char **shares, int n) { int i; for (i = 0; i < n; ++i) { free(shares[i]); } free(shares); } int *gcdD(int a, int b) { int *xyz = malloc(sizeof(int) * 3); if (b == 0) { xyz[0] = a; xyz[1] = 1; xyz[2] = 0; } else { int n = floor(a / b); int c = a % b; int *r = gcdD(b, c); xyz[0] = r[0]; xyz[1] = r[2]; xyz[2] = r[1] - r[2] * n; free(r); } return xyz; } int modInverse(int k) { k = k % prime; int r; int *xyz; if (k < 0) { xyz = gcdD(prime, -k); r = -xyz[2]; } else { xyz = gcdD(prime, k); r = xyz[2]; } free(xyz); return (prime + r) % prime; } int *split_number(int number, int n, int t) { int *shares = malloc(sizeof(int) * n); int *coef = malloc(sizeof(int) * t); int x; int i; coef[0] = number; for (i = 1; i < t; ++i) { #ifdef HAVE_ARC4RANDOM coef[i] = arc4random_uniform(prime); #else coef[i] = rand() % (prime); #endif } for (x = 0; x < n; ++x) { int y = coef[0]; for (i = 1; i < t; ++i) { int temp = mod_expo(x + 1, i, prime); y = (y + (coef[i] * temp % prime)) % prime; } y = (y + prime) % prime; shares[x] = y; } free(coef); return shares; } char **split_string(char *secret, int n, int t) { int len = strlen(secret); char **shares = malloc(sizeof(char *) * n); int i; for (i = 0; i < n; ++i) { shares[i] = (char *)malloc(2 * len + 6 + 1); sprintf(shares[i], "%02X%02XAA", (i + 1), t); } for (i = 0; i < len; ++i) { int letter = secret[i]; if (letter < 0) { letter = prime + letter; } int *chunks = split_number(letter, n, t); int j; for (j = 0; j < n; ++j) { if (chunks[j] == prime) { sprintf(shares[j] + 6 + i * 2, "G0"); } else { sprintf(shares[j] + 6 + i * 2, "%02X", chunks[j]); } } free(chunks); } return shares; } int join_shares(int *xy_pairs, int n) { int secret = 0; long numerator; long denominator; long startposition; long nextposition; long value; int i; int j; for (i = 0; i < n; ++i) { numerator = 1; denominator = 1; for (j = 0; j < n; ++j) { if (i != j) { startposition = xy_pairs[i * 2]; nextposition = xy_pairs[j * 2]; numerator = (numerator * -nextposition) % prime; denominator = (denominator * (startposition - nextposition)) % prime; } } value = xy_pairs[i * 2 + 1]; secret = (secret + (value * numerator * modInverse(denominator))) % prime; } secret = (secret + prime) % prime; return secret; } char *decode(char **shares, int n) { if ((n == 0) || (shares == NULL) || (shares[0] == NULL)) { return NULL; } int len = (strlen(shares[0]) - 6) / 2; char *result = malloc(len + 1); char codon[3]; codon[2] = '\0'; int x[n]; int i; int j; for (i = 0; i < n; ++i) { if (shares[i] == NULL) { free(result); return NULL; } codon[0] = shares[i][0]; codon[1] = shares[i][1]; x[i] = strtol(codon, NULL, 16); } for (i = 0; i < len; ++i) { int *chunks = malloc(sizeof(int) * n * 2); for (j = 0; j < n; ++j) { chunks[j * 2] = x[j]; codon[0] = shares[j][6 + i * 2]; codon[1] = shares[j][6 + i * 2 + 1]; if (memcmp(codon, "G0", 2) == 0) { chunks[j * 2 + 1] = prime; } else { chunks[j * 2 + 1] = strtol(codon, NULL, 16); } } char letter = join_shares(chunks, n); free(chunks); sprintf(result + i, "%c", letter); } return result; } char *encode(char *secret, int n, int t) { char **result = split_string(secret, n, t); int len = strlen(secret); int key_len = 6 + 2 * len + 1; int i; char *shares = malloc(key_len * n + 1); for (i = 0; i < n; ++i) { sprintf(shares + i * key_len, "%s\n", result[i]); } free_heap_mem(result, n); return shares; } // Driver Code int main(void) { srand(time(NULL)); int M; char **codes = malloc(sizeof(char *) * prime); char *code = malloc(sizeof(char) * prime); char *str = malloc(sizeof(char) * size); getline(&str, &size, stdin); char *shares = encode(str, N, K); puts(shares); printf("Enter the number of shares you want to enter to decode the orginal secret\n"); scanf("%d", &M); for (int i = 0; i < M; i++) { printf("Enter the %d share\n", i+1); scanf("%s", code); codes[i] = strdup(code); } char *secret = decode(codes, M); printf("The secret is : "); puts(secret); free_heap_mem(codes, M); free(shares); free(secret); free(code); free(str); return 0; } ================================================ FILE: Algorithms/Cryptography/Shamir_Cipher/Shamir_Cipher.cpp ================================================ #include using namespace std; int calculate_Y(int x, vector &poly) { int y = 0; int temp = 1; for (auto coeff : poly) { y = (y + (coeff * temp)); temp = (temp * x); } return y; } void secret_sharing(int S, vector> &points, int N, int K) { vector poly(K); poly[0] = S; for (int j = 1; j < K; ++j) { int p = 0; while (p == 0) p = (rand() % 997); poly[j] = p; } for (int j = 1; j <= N; ++j) { int x = j; int y = calculate_Y(x, poly); points[j - 1] = {x, y}; } } struct fraction { int num, den; fraction(int n, int d) { num = n, den = d; } void reduce_fraction(fraction &f) { int gcd = __gcd(f.num, f.den); f.num /= gcd, f.den /= gcd; } fraction operator*(fraction f) { fraction temp(num * f.num, den * f.den); reduce_fraction(temp); return temp; } fraction operator+(fraction f) { fraction temp(num * f.den + den * f.num, den * f.den); reduce_fraction(temp); return temp; } }; int Generate_Secret(int x[], int y[], int M) { fraction ans(0, 1); for (int i = 0; i < M; ++i) { fraction l(y[i], 1); for (int j = 0; j < M; ++j) { if (i != j) { fraction temp(-x[j], x[i] - x[j]); l = l * temp; } } ans = ans + l; } return ans.num; } void solve(int S, int N, int K) { vector> points(N); secret_sharing(S, points, N, K); int M = 2; if (M < K) { cout << "Points are less than threshold " << K << " Points Required" << endl; } int *x = new int[M]; int *y = new int[M]; for (int i = 0; i < M; ++i) { x[i] = points[i].first; y[i] = points[i].second; } cout << "Your Secret Code is " << Generate_Secret(x, y, M) << endl; } int main() { int S, N; printf("Enter the Secret Code\n"); scanf("%d", &S); printf("Enter the number of Parts\n"); scanf("%d", &N); solve(S, N, 2); return 0; } ================================================ FILE: Algorithms/Cryptography/Vernam_Cipher/README.md ================================================ ## This folder is empty. ================================================ FILE: Algorithms/Cryptography/Vernam_Cipher/Vernam_Cipher.cpp ================================================ #include #include /** * Encrypts/decrypts data using vernam cipher * @param[in/out] data data to which Vernam cipher is applied * @param[in] key key, is expected to have the same size as data * @param[in] size memory size (in bytes) of data */ void apply_vernam(void *data, void const * key, const size_t size) { static_assert(sizeof(char) == 1); const unsigned sizeTypeSize = sizeof(size_t); const size_t numberOfIterations = size / sizeTypeSize; size_t *currentDataPosition = static_cast(data); size_t const * currentKeyPosition = static_cast(key); for (size_t i = 0; i < numberOfIterations; ++i) { *currentDataPosition = *currentDataPosition ^ *currentKeyPosition; // XOR ++currentDataPosition; ++currentKeyPosition; } const unsigned numberOfRemainingOperations = size % sizeTypeSize; char *currentRemainingDataPosition = reinterpret_cast(currentDataPosition); char const * currentRemainingKeyPosition = reinterpret_cast(currentKeyPosition); for (unsigned i = 0; i < numberOfRemainingOperations; ++i) { *currentRemainingDataPosition = *currentRemainingDataPosition ^ *currentRemainingKeyPosition; // XOR ++currentRemainingDataPosition; ++currentRemainingKeyPosition; } return; } /** Generates a random uniformly distributed key. The key has to be allocated with at least size byte of memory. * @param[out] key generated key * @param[in] size size of key */ void generate_key(void *key, const size_t size) { std::random_device rd; std::uniform_real_distribution distribution(0.0, 0.1); const unsigned doubleSize = sizeof(double); const size_t numberOfIterations = size / doubleSize; double *currentKeyPosition = static_cast(key); for (size_t i = 0; i < numberOfIterations; ++i) { *currentKeyPosition = distribution(rd); ++currentKeyPosition; } const unsigned numberOfRemainingOperations = size % doubleSize; char * currentRemainingKeyPosition = reinterpret_cast(currentKeyPosition); for (unsigned i = 0; i < numberOfRemainingOperations; ++i) { const double randomNumber = distribution(rd); memcpy(currentRemainingKeyPosition, &randomNumber, sizeof(char)); ++currentRemainingKeyPosition; } return; } // Test section: #include using namespace std; int main() { string data; cout << "Enter plaintext:" << endl; getline(cin, data); // Generate random key: string key(data); generate_key(&key[0], sizeof(char)*key.size()); cout << "Random key:" << endl << key << endl; apply_vernam(&data[0], &key[0], sizeof(char)*data.size()); cout << endl << "Ciphertext:" << endl << data << endl; apply_vernam(&data[0], &key[0], sizeof(char)*data.size()); cout << endl << "Decrypted text:" << endl << data << endl; return 0; } ================================================ FILE: Algorithms/Cryptography/Vernam_Cipher/Vernam_Cipher.js ================================================ xin = "Shubham"; treshold = 150; c = { 0: [], // input encoded 1: [], // key encoded 2: [], // cipher encoded 3: [] // decoded encoded }; for (i=0;i<=xin.length;++i) c[0].push((xin[i]+"").charCodeAt(0)); console.log("Encoded input: " + c[0].join(", ")); // c[0] is input // generate challenge key for (i=0;i<=c[0].length;++i) c[1].push(Math.round(Math.random()*treshold)); console.log("Generated Challenge Pad: " + c[1].join(", ")); // generate cipher for (i=0;i<=c[0].length;++i) c[2].push(c[0][i] ^ c[1][i]); console.log("Resulting Cipher: " + c[2].join(", ")); for (i=0;i<=c[0].length - 1;++i) c[3].push(c[2][i] ^ c[1][i]); console.log("Recalculated Pad: " + c[3].join(", ")); console.log("Has decoding been successful? " + ( c[0].join() == c[3].join() ? "Yes" : "No" )); ================================================ FILE: Algorithms/Cryptography/Vernam_Cipher/Vernam_Cipher.py ================================================ #!/usr/bin/env python import random import string from operator import xor def vernam_enc(msg): #Generate Random Key randomKey = ''.join([random.choice(string.ascii_letters) for i in range(len(msg))]) print("Random Key: "+randomKey) #Convert string to decimal convdecimal = [] for i in range(len(msg)): convdecimal.append(str(ord(msg[i]))) decimal = ' '.join(convdecimal) #Convert decimal to biner convbiner = [] for i in range(len(convdecimal)): convbiner.append(str(bin(int(convdecimal[i]))[2:].zfill(8))) biner = ''.join(convbiner) #Convert key to decimal convkeydecimal = [] for i in range(len(randomKey)): convkeydecimal.append(str(ord(randomKey[i]))) keydecimal = ' '.join(convkeydecimal) #Convert key decimal to biner convkeybiner = [] for i in range(len(convkeydecimal)): convkeybiner.append(str(bin(int(convkeydecimal[i])))) binerkey = ''.join(convkeybiner) binermsg =biner.replace("b","") binerkey =binerkey.replace("b","") #XOR Function ciphertext = [] for i in range(len(binermsg)): ciphertext.append(xor(int(binermsg[i]),int(binerkey[i]))) cipherfix =''.join(map(str,ciphertext)) splits=[cipherfix[x:x+8] for x in range(0,len(cipherfix),8)] #convert biner to decimal hexa = [] for i in range(len(splits)): hexa.append(hex(int(splits[i],2))) #convert hex to desimal dec = [] for i in range(len(hexa)): dec.append(int(hexa[i], 16)) print("Ciphertext-Num : \n"+str(dec)) #final convert to text teks = [] for i in range(len(dec)): teks.append(chr(dec[i])) print("Ciphertext : \n"+''.join(teks)) def main(): print("Vernam Cipher") msg = input("Enter Text : ") vernam_enc(msg) if __name__ == '__main__': main() ================================================ FILE: Algorithms/Cryptography/Vigenere_Cipher/README.md ================================================ ## This folder is empty. ================================================ FILE: Algorithms/Cryptography/Vigenere_Cipher/Vigenere_Cipher.cpp ================================================ #include #include #include /** * Returns the mathematical (unsigned) modulus * @param x number * @param div divisor * @return the unsigned modulus x % div */ unsigned positive_modulo(const int x, const int div) { return (x % div + div) % div; } /** * Returns, wheter character is a letter of the alphabet * @param ch character * @return true if ch is a letter. false otherwise */ bool is_letter(const unsigned char ch) { bool result = false; if (('A' <= ch && ch <= 'Z') || ('a' <= ch && ch <= 'z')) result = true; return result; } /** * Encrypts a string using Vigenere cipher * @input plaintext plaintext * @input keyword keyword * @return the encrypted plaintext */ std::string encrypt_vigenere(const std::string &plaintext, const std::string &keyword) { std::string ciphertext(plaintext); std::string cleanKeyword(keyword); ciphertext.erase(std::remove_if(ciphertext.begin(), ciphertext.end(), [](const unsigned char ch){ return !is_letter(ch); }), ciphertext.end()); cleanKeyword.erase(std::remove_if(cleanKeyword.begin(), cleanKeyword.end(), [](const unsigned char ch){ return !is_letter(ch); }), cleanKeyword.end()); for (size_t i = 0; i < ciphertext.size(); ++i) { ciphertext[i] = toupper(ciphertext[i]); cleanKeyword[i] = toupper(cleanKeyword[i]); // shift by corresponding character of keyword ciphertext[i] = positive_modulo((ciphertext[i] - 'A' + (cleanKeyword[i%keyword.size()] - 'A')), ('Z' - 'A' + 1)) + 'A'; } return ciphertext; } /** * Decrypts a string using Vigenere cipher * @input ciphertext ciphertext * @input keyword keyword * @return the decrypted ciphertext */ std::string decrypt_vigenere(const std::string &ciphertext, const std::string &keyword) { std::string plaintext(ciphertext); std::string cleanKeyword(keyword); plaintext.erase(std::remove_if(plaintext.begin(), plaintext.end(), [](const unsigned char ch){ return !is_letter(ch); }), plaintext.end()); cleanKeyword.erase(std::remove_if(cleanKeyword.begin(), cleanKeyword.end(), [](const unsigned char ch){ return !is_letter(ch); }), cleanKeyword.end()); for (size_t i = 0; i < plaintext.size(); ++i) { plaintext[i] = toupper(plaintext[i]); cleanKeyword[i] = toupper(cleanKeyword[i]); // shift by corresponding character of keyword plaintext[i] = positive_modulo((plaintext[i] - 'A' - (cleanKeyword[i%keyword.size()] - 'A')), ('Z' - 'A' + 1)) + 'A'; } return plaintext; } // Test section: #include using namespace std; int main() { string plaintext; string keyword; cout << "Enter plaintext:" << endl; getline(cin, plaintext); cout << endl << "Enter keyword:" << endl; getline(cin, keyword); string ciphertext = encrypt_vigenere(plaintext, keyword); cout << endl << "Ciphertext:" << endl << ciphertext << endl; string decryptedtext = decrypt_vigenere(ciphertext, keyword); cout << endl << "Decrypted text:" << endl << decryptedtext << endl; return 0; } ================================================ FILE: Algorithms/Cryptography/Vigenere_Cipher/Vigenere_Cipher.py ================================================ import sys def create_key(msg, key): key = list(key) if len(msg) == len(key): return key elif len(key) < len(msg): n = (len(msg) // len(key)) + 1 key = key * n return ''.join(key[:len(msg)]) def encrypt(msg, key): cipher_text = [] x = 0 key = create_key(msg, key) for i in range(0, len(msg)): x = (ord(msg[i]) + ord(key[i])) % 26 x += ord('A') cipher_text.append(chr(x)) return cipher_text def decrypt(msg, key): key = create_key(msg, key) plain_text = [] for i in range(0, len(msg)): x = (ord(msg[i]) - ord(key[i]) + 26) % 26 x += ord('A') plain_text.append(chr(x)) return plain_text if __name__ == '__main__': print("\t\tVigenere Cipher Application") print("\t"+"=" * 41) print("Please choose an option below:\n") print("1. Encrypt") print("2. Decrypt") print("3. Exit") while True: opt = input("Selection: ") try: opt = int(opt) if opt == 1: msg = input("Please provide your message to encrypt: ") msg = msg.upper().replace(" ", "") key = input("Please provide your key: ") key = key.upper().replace(" ", "") cipher_text = encrypt(msg, key) print("Encrypted message:", "".join(cipher_text)) elif opt == 2: msg = input("Please provide your message to decrypt: ") msg = msg.upper().replace(" ", "") key = input("Please provide your key: ") key = key.upper().replace(" ", "") plain_text = decrypt(msg, key) print("Encrypted message:", "".join(plain_text)) elif opt == 3: sys.exit() else: print("Incorrect option, try again") continue except ValueError: print("Incorrect option, try again") continue ================================================ FILE: Algorithms/Cryptography/Vigenere_Cipher/Vignere_Cipher.cs ================================================ using System; using System.Linq; using System.Collections.Generic; public class Program { static List characters = "abcdefghijklmnopqrstuvwxyz".ToList(); // wrap value if it is above n or below zero static int wrap(int k, int n) { int r = k % n; return (r < 0) ? r + n : r; } static string VignereCipher(string plaintext, string key) { string ciphertext = ""; for (int i = 0; i < plaintext.Length; i++) { // get the current key character. char keyCharacter = key[i % key.Length]; // shift value is the index of this character in 'characters'. int shift = characters.IndexOf(keyCharacter); // index of the plaintext character in the 'characters' array. int plaincharNumber = characters.IndexOf(plaintext[i]); // shift this index by the shift value, wrapping if it goes over 26. int ciphercharNumber = wrap((plaincharNumber + shift), 26); // and get the character from this index. char cipherchar = characters[ciphercharNumber]; ciphertext += cipherchar; } return ciphertext; } static string VignereDecipher(string ciphertext, string key) { string plaintext = ""; for (int i = 0; i < ciphertext.Length; i++) { // get the current key character. char keyCharacter = key[i % key.Length]; // shift value is the index of this character in 'characters'. int shift = characters.IndexOf(keyCharacter); // index of the ciphertext character in the 'characters' array. int ciphercharNumber = characters.IndexOf(ciphertext[i]); // shift this index by the shift value, but in the other direction, // wrapping through 26 if it goes under 0. int plaincharNumber = wrap((ciphercharNumber - shift), 26); // and get the character from this index. char plainchar = characters[plaincharNumber]; plaintext += plainchar; } return plaintext; } public static void Main(string[] args) { string ciphertext = VignereCipher("helloworld", "key"); Console.WriteLine($"Plaintext: helloworld -> Key: key -> Ciphertext: {ciphertext}."); string plaintext = VignereDecipher("uogtprtso", "pass"); Console.WriteLine($"Ciphertext: uogtprtso <- Key: pass <- Plaintext: {plaintext}."); } } ================================================ FILE: Algorithms/Cryptography/Vigenere_Cipher/vigenereCipher.py ================================================ def vignereCipher(plain_text, key): plain_text_length = len(plain_text) key_length = len(key) j = 0 cipher = '' for i in range(plain_text_length): if(j == key_length): j = 0 cipher_text = (ord(plain_text[i])+ ord(key[j])) % 26 j+=1 cipher += chr(cipher_text+65) return cipher def decryptVignereCipher(cipher_text, key): key_length = len(key) decrpted_text = '' j = 0 for i in range(len(cipher_text)): if(j == key_length): j = 0 decrpt = (ord(cipher_text[i]) - ord(key[j]) + 26) % 26 j+=1 decrpted_text += chr(decrpt+65) return decrpted_text if __name__ == "__main__": plain_text = "PLAINTEXT" key = "KEY" encrypted_text = vignereCipher(plain_text, key) print("Cipher text " + encrypted_text) decrpted_text = decryptVignereCipher(encrypted_text, key) print("Decrypt text " + decrpted_text) ================================================ FILE: Algorithms/DP/0-1_Knapsack_Problem/0-1 Knapsack Problem.java ================================================ /*0-1 Knapsack problem */ import java.util.*; public class Knapsack { //function to return max. of two integers static int max(int a, int b) { return (a > b) ? a : b; } //function to return proper max. value to fill knapsack of weight W static int knapSack(int W, int wt[], int val[], int n) { int i, w; int K[][] = new int[n + 1][W + 1]; // Build table K[][] in bottom up manner for (i = 0; i <= n; i++) { for (w = 0; w <= W; w++) { if (i == 0 || w == 0) K[i][w] = 0; else if (wt[i - 1] <= w) K[i][w] = max( val[i - 1] + K[i - 1][w - wt[i - 1]], K[i - 1][w]); else K[i][w] = K[i - 1][w]; } } return K[n][W]; } //Main function public static void main(String args[]) { Scanner input=new Scanner(System.in); System.out.println("Enter the number of items in a Knapsack:"); int n = input.nextInt(); int v[]=new int[n]; int w[]=new int[n]; for (int i=0; i using namespace std; // Structure for Item which store weight and corresponding // value of Item struct Item { float weight; int value; }; // Node structure to store information of decision // tree struct Node { // level --> Level of node in decision tree (or index // in arr[] // profit --> Profit of nodes on path from root to this // node (including this node) // bound ---> Upper bound of maximum profit in subtree // of this node/ int level, profit, bound; float weight; }; // Comparison function to sort Item according to // val/weight ratio bool cmp(Item a, Item b) { double r1 = (double)a.value / a.weight; double r2 = (double)b.value / b.weight; return r1 > r2; } // Returns bound of profit in subtree rooted with u. // This function mainly uses Greedy solution to find // an upper bound on maximum profit. int bound(Node u, int n, int W, Item arr[]) { // if weight overcomes the knapsack capacity, return // 0 as expected bound if (u.weight >= W) return 0; // initialize bound on profit by current profit int profit_bound = u.profit; // start including items from index 1 more to current // item index int j = u.level + 1; int totweight = u.weight; // checking index condition and knapsack capacity // condition while ((j < n) && (totweight + arr[j].weight <= W)) { totweight += arr[j].weight; profit_bound += arr[j].value; j++; } // If k is not n, include last item partially for // upper bound on profit if (j < n) profit_bound += (W - totweight) * arr[j].value / arr[j].weight; return profit_bound; } // Returns maximum profit we can get with capacity W int knapsack(int W, Item arr[], int n) { // sorting Item on basis of value per unit // weight. sort(arr, arr + n, cmp); // make a queue for traversing the node queue Q; Node u, v; // dummy node at starting u.level = -1; u.profit = u.weight = 0; Q.push(u); // One by one extract an item from decision tree // compute profit of all children of extracted item // and keep saving maxProfit int maxProfit = 0; while (!Q.empty()) { // Dequeue a node u = Q.front(); Q.pop(); // If it is starting node, assign level 0 if (u.level == -1) v.level = 0; // If there is nothing on next level if (u.level == n-1) continue; // Else if not last node, then increment level, // and compute profit of children nodes. v.level = u.level + 1; // Taking current level's item add current // level's weight and value to node u's // weight and value v.weight = u.weight + arr[v.level].weight; v.profit = u.profit + arr[v.level].value; // If cumulated weight is less than W and // profit is greater than previous profit, // update maxprofit if (v.weight <= W && v.profit > maxProfit) maxProfit = v.profit; // Get the upper bound on profit to decide // whether to add v to Q or not. v.bound = bound(v, n, W, arr); // If bound value is greater than profit, // then only push into queue for further // consideration if (v.bound > maxProfit) Q.push(v); // Do the same thing, but Without taking // the item in knapsack v.weight = u.weight; v.profit = u.profit; v.bound = bound(v, n, W, arr); if (v.bound > maxProfit) Q.push(v); } return maxProfit; } // driver program to test above function int main() { int W = 10; // Weight of knapsack Item arr[] = {{2, 40}, {3.14, 50}, {1.98, 100}, {5, 95}, {3, 30}}; int n = sizeof(arr) / sizeof(arr[0]); cout << "Maximum possible profit = " << knapsack(W, arr, n); return 0; } ================================================ FILE: Algorithms/DP/0-1_Knapsack_Problem/knapsackProblem.java ================================================ /*0-1 Knapsack problem */ import java.util.*; public class knapsackProblem { //function to return max. of two integers static int max(int a, int b) { return (a > b) ? a : b; } //function to return proper max. value to fill knapsack of weight W static int knapSack(int W, int wt[], int val[], int n) { int i, w; int K[][] = new int[n + 1][W + 1]; // Build table K[][] in bottom up manner for (i = 0; i <= n; i++) { for (w = 0; w <= W; w++) { if (i == 0 || w == 0) K[i][w] = 0; else if (wt[i - 1] <= w) K[i][w] = max( val[i - 1] + K[i - 1][w - wt[i - 1]], K[i - 1][w]); else K[i][w] = K[i - 1][w]; } } return K[n][W]; } //Main function public static void main(String args[]) { Scanner input=new Scanner(System.in); System.out.println("Enter the number of items in a Knapsack:"); int n = input.nextInt(); int v[]=new int[n]; int w[]=new int[n]; for (int i=0; i using namespace std; int max(int x, int y) { return (x > y) ? x : y; } int knapSack(int W, int w[], int v[], int n) { int i, wt; int K[n + 1][W + 1]; for (i = 0; i <= n; i++) { for (wt = 0; wt <= W; wt++) { if (i == 0 || wt == 0) K[i][wt] = 0; else if (w[i - 1] <= wt) K[i][wt] = max(v[i - 1] + K[i - 1][wt - w[i - 1]], K[i - 1][wt]); else K[i][wt] = K[i - 1][wt]; } } return K[n][W]; } int main() { cout << "Enter the number of items in a Knapsack:"; int n, W; cin >> n; int v[n], w[n]; for (int i = 0; i < n; i++) { cout << "Enter value and weight for item " << i << ":"; cin >> v[i]; cin >> w[i]; } cout << "Enter the capacity of knapsack"; cin >> W; cout << knapSack(W, w, v, n); return 0; } ================================================ FILE: Algorithms/DP/0-1_Knapsack_Problem/knapsack_problem_0_1.py ================================================ #0/1 Knapsack problem def knapsack(val, wt, N, C): table = [[ 0 for _ in range(0, C+1)] for _ in range(0, N+1)] table[0][0] = 0 for i in range(1, N+1): for c in range(1, C+1): if c - wt[i-1] < 0: table[i][c] = table[i-1][c] else: table[i][c] = max(table[i-1][c], table[i-1][c-wt[i-1]]+val[i-1]) return table[N][C] N = int(input().strip()) W = int(input().strip()) # capacity val = [ int(v) for v in input().strip().split(" ")] wt = [ int(w) for w in input().strip().split(" ")] print(knapsack(val, wt, N, W)) ================================================ FILE: Algorithms/DP/AdjacentBitCounts.cpp ================================================ /* Problem description: For a string of n bits x1,x2,x3,...,Xn the adjacent bit count of the string (AdjBC(x)) is given by X1*X2 + X2*X3 + X3*X4 + ... + Xn-1 * Xn which counts the number of times a 1 bit is adjacent to another 1 bit. For example: AdjBC(011101101) = 3 AdjBC(111101101) = 4 AdjBC(010101010) = 0 Write a program which takes as input integers n and k and returns the number of bit strings x of n bits (out of 2ⁿ) that satisfy AdjBC(x) = k. Link To Problem: https://www.spoj.com/problems/GNYR09F/ */ #include using namespace std; //find Number of bit string with Adjacent Bit count k. int findAns(int n, int k, int firstBit, int ***dp) { //Base cases if (k < 0) return 0; if (dp[n][k][firstBit] != -1) return dp[n][k][firstBit]; /*There are 2 cases 1. If First bit of binary string is assigned '1' 2. If first bit of binary string is assigned '0' */ int option1, option2; if (firstBit == 1) { option1 = findAns(n - 1, k - 1, 1, dp); option2 = findAns(n - 1, k, 0, dp); } else { option1 = findAns(n - 1, k, 1, dp); option2 = findAns(n - 1, k, 0, dp); } long long ans = (option1 + option2) % 1000000007; dp[n][k][firstBit] = (int)ans; return dp[n][k][firstBit]; } int main() { /* [Problem Link : https://www.spoj.com/problems/GNYR09F/] Input Format is taken from Problem Link */ int ts; //testcases cin >> ts; while (ts--) { int index, num, k; cin >> index >> num >> k; /*creating a dp array for storing previous state answers. Since dp array will depend on number of bits,k(Adjacent bit count) & firstbit(0 or 1) therefore dp will be 3d array.*/ int ***dp = new int **[num + 1]; for (int i = 0; i <= num; i++) dp[i] = new int *[k + 1]; for (int i = 0; i <= num; i++) { for (int j = 0; j <= k; j++) dp[i][j] = new int[2]; } //initialising dp for (int i = 0; i <= num; i++) { for (int j = 0; j <= k; j++) dp[i][j][0] = -1, dp[i][j][1] = -1; } dp[1][0][0] = dp[1][0][1] = 1; for (int i = 1; i <= k; i++) dp[1][i][0] = 0, dp[1][i][1] = 0; //calling function to find ans. int ans1 = findAns(num, k, 1, dp); int ans2 = findAns(num, k, 0, dp); long long int ans = (ans1 + ans2) % 1000000007; cout << index << " " << ans << endl; //deleting dp array delete dp; } return 0; } ================================================ FILE: Algorithms/DP/AdjacentBitCounts.js ================================================ const readline = require('readline') const reader = readline.createInterface(process.stdin, process.stdout) function countStrings(n, k) { let dp = Array(n+1) for(let i=0;i= 0) { dp[i][j][1] += dp[i-1][j-1][1] } } } return dp[n][k][0] + dp[n][k][1] } reader.question("Enter 'N' and 'K' seperated by space: ", data => { const arr = data.split(" ") console.log("Answer: " + countStrings(parseInt(arr[0]), parseInt(arr[1]))) reader.close() }) ================================================ FILE: Algorithms/DP/Bitmask DP/TravellingSalesman.cpp ================================================ #include #define int long long int using namespace std; int dis[21][21]; int dp[21][(1 << 21)]; int solve(int i, int mask, int n) { if (mask == 0) { return dp[i][mask] = dis[i][0]; } if (dp[i][mask] != -1) { return dp[i][mask]; } int ans = INT_MAX; for (int j = 0; j < n; j++) { if (mask & (1 << j)) { ans = min(ans, dis[i][j] + solve(j, (mask ^ (1 << j)), n)); } } return ans; } signed main() { int n; cin >> n; memset(dp, -1, sizeof(dp)); for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { cin >> dis[i][j]; } } cout << solve(0, (1 << n) - 1, n); } ================================================ FILE: Algorithms/DP/Branch_And_Bound/0_1_KnapSack.py ================================================ # a dynamic approach # Returns the maximum value that can be stored by the bag def knapSack(W, wt, val, n): K = [[0 for x in range(W + 1)] for x in range(n + 1)] #Table in bottom up manner for i in range(n + 1): for w in range(W + 1): if i == 0 or w == 0: K[i][w] = 0 elif wt[i-1] <= w: K[i][w] = max(val[i-1] + K[i-1][w-wt[i-1]], K[i-1][w]) else: K[i][w] = K[i-1][w] return K[n][W] #Main val = [50,100,150,200] wt = [8,16,32,40] W = 64 n = len(val) print(knapSack(W, wt, val, n)) ================================================ FILE: Algorithms/DP/Branch_And_Bound/Knapsack_Branch_and_Bound.java ================================================ import java.io.*; import java.util.*; public class Knapsack_Branch_and_Bound { static boolean sol_found = false; static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); static StringTokenizer st; //Node of Branch and Bound tree static class Node { int lvl, val; //lvl indicates depth of current node double cap, bound; Node next; Node(int lvl, int val, double cap, double bound) { this.lvl = lvl; this.val = val; this.cap = cap; this.bound = bound; this.next = null; } } //List to store node of Branch and Bound tree static class List { Node head; //add node in list in such a way that list always stay sorted in descending order by bound value of nodes void add(Node n) { if(this.head == null) head = n; else { Node temp = this.head; if(n.bound >= temp.bound) { n.next = temp; this.head = n; } else { while(temp.next != null && n.bound < temp.next.bound) temp = temp.next; if(temp.next != null) n.next = temp.next; temp.next = n; } } } //returns the node with maximum upper bound i.e. the first node //in the list since list is always sorted in descending order Node get() { Node n = head; head = n.next; n.next = null; return n; } } static class Item { double weight; int value; Item(double weight, int value) { this.weight = weight; this.value = value; } } //to sort the item array by value/weight in descending order static class Sort_Value_By_Weight implements Comparator { public int compare(Item a, Item b) { double x, y; x = a.value / a.weight; y = b.value / b.weight; if(x > y) return -1; else if(x == y) return 0; return 1; } } //get upperbound for a node of depth k static double upperBound(Item item[], double cap, int k, int n) { int i; double tot_val = 0; i = k; while(cap > 0 && i < n) { if(item[i].weight <= cap) tot_val += item[i].value; else tot_val += (1.0 * item[i].value / item[i].weight) * cap; cap -= item[i].weight; i++; } return tot_val; } //Solves 0-1 knapsack by branch and bound technique static void knapsackBnB(Item[] item, int n, Node curr, List list) { if(curr.lvl == n && curr.cap >= 0) { System.out.println("Max Value: " + curr.val); sol_found = true; } else if(curr.cap >= 0) { int k = curr.lvl; Node temp; //right child of current node temp = new Node(k+1, curr.val, curr.cap, curr.val + upperBound(item, curr.cap, k+1, n)); list.add(temp); //left child of current node curr = new Node(k+1, curr.val + item[k].value, curr.cap - item[k].weight, curr.bound); //function call itself for left child of current node //since it is the node with current max upperbound knapsackBnB(item, n, curr, list); if(!sol_found) knapsackBnB(item, n, list.get(), list);//call the function for max value of node in list } } public static void main(String[] args) throws IOException{ int i, n; double cap; System.out.print("Enter no. of Items: "); n = Integer.parseInt(br.readLine()); Item[] item = new Item[n]; System.out.println("Enter weight-value pair :-"); for(i=0; i using namespace std; int main() { //input n: rows and m: columns int n, m; cin >> n >> m; //create array of size n*m and take input from the user int ar[n][m]; for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) cin >> ar[i][j]; //initialize count with 0 which keeps count of all submatrices having 1. int count = 0; for (int i = 1; i < n; i++) { for (int j = 1; j < m; j++) { //if ar[i][j] = 0, continue; if (ar[i][j] == 0) continue; //calculate submtrices that end with index (i , j); //basically we look at the previous row, column and diagonal and then add 1 to it's minimum. else ar[i][j] = min({ar[i - 1][j], ar[i][j - 1], ar[i - 1][j - 1]}) + 1; } } //sum of the whole array to get final answer for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) count += ar[i][j]; //print number of square submatrices containing all zeroes. cout << count << "\n"; return 0; } ================================================ FILE: Algorithms/DP/Count_Square_Matrices.py ================================================ def countSquareMatrices(a, N, M): count = 0 for i in range(1, N): for j in range(1, M): if (a[i][j] == 0): continue # Calculating number of square submatrices ending at (i, j) a[i][j] = min([a[i - 1][j], a[i][j - 1], a[i - 1][j - 1]])+1 # Calculate the sum of the array for i in range(N): for j in range(M): count += a[i][j] return count n = int(input()) m = int(input()) matrix = [] print("Enter elements row-wise") for i in range(n): # a for loop for row entries a =[] for j in range(m): # a for loop for column entries a.append(int(input())) matrix.append(a) print("\nNumber of square submatrices with all ones is",countSquareMatrices(matrix, n, m)) ================================================ FILE: Algorithms/DP/Edit_Distance/Edit_Distance.js ================================================ var string1 = prompt("Enter String 1 -> "); var string2 = prompt("Enter String 2 -> "); var length1 = string1.length,length2=string2.length; var array1 = []; for(var i=0;i<=length1;i++){ array1[i] = []; } for(var i=0;i<=length1;i++){ array1[i][0] = i; } for(var i=0;i<=length2;i++){ array1[0][i]=i; } for(var i=1;i<=length1;i++){ for(var j=1;j<=length2;j++){ if(string1[i-1]==string2[j-1]){ array1[i][j]=array1[i-1][j-1]; [i][j]=array1[i-1][j-1]; } else{ array1[i][j]=Math.min(Math.min(array1[i-1][j],array1[i][j-1]),array1[i-1][j-1])+1; } } } alert("Edit Distance is -> " + array1[length1][length2]); ================================================ FILE: Algorithms/DP/Edit_Distance/Edit_distance.cpp ================================================ /* author-yogesh kansal problem :- The edit distance between two strings is the minimum number of operations (insertions, deletions, and substitutions of symbols) to transform one string into another. It is a measure of similarity of two strings. Edit distance has applications, for example, in computational biology, natural language processing, and spell checking. Your goal in this problem is to compute the edit distance between two strings Overall time complexity:- O(m*n) */ #include using namespace std; int main() { string s1,s2; cout<<"enter string1:- "; cin>>s1; cout<<"\nenter string2:- "; cin>>s2; int n=s1.length()+1,m=s2.length()+1,i,j; int dp[n][m]; for(i=0;i using namespace std; // Function for returning maximum of 2 numbers int max(int a, int b) { return (a > b) ? a : b; } // Function to obtain minimum number of trials required for finding the highest floor from which the egg can be dropped without breaking int EggDrop(int n, int k) { // DP table to keep track of minimum number of trials for i eggs and j floors int eggFloor[n + 1][k + 1]; int res; for (int i = 1; i <= n; i++) { // If there are no floors, then 0 trials are required. eggFloor[i][0] = 0; // If there is only 1 floor, then 1 trial is required. eggFloor[i][1] = 1; } // If there is only 1 egg, we have to drop it from each floor to check. // Hence for j floors, j trials are required for (int j = 1; j <= k; j++){ eggFloor[1][j] = j; } // For the rest of the floors from 2nd to nth for (int i = 2; i <= n; i++) { for (int j = 2; j <= k; j++) { // Consider the maximum possible trials initially eggFloor[i][j] = INT_MAX; // For jth floor, we consider all the trials from 1st floor to jth floor for (int x = 1; x <= j; x++) { // For each floor, we consider both cases: // a) when the egg breaks: Number of eggs reduce by 1, and we know the critical floor is below xth floor -> eggFloor[i-1][x-1] // b) when the egg doesn't break: Number of eggs remain same, and we know the critical is above xth floor -> eggFloor[i][j-x] // For considering the worst case scenario, the maximum of both cases is taken res = 1 + max(eggFloor[i - 1][x - 1], eggFloor[i][j - x]); // If the obtained result is better (smaller) than previous result for some other x, the previous result is replaced with the better result if (res < eggFloor[i][j]) eggFloor[i][j] = res; } } } // The result is available is eggFloor[n][k] after all the possible cases have been considered return eggFloor[n][k]; } int main() { // Initialise variables for number of eggs and number of floors // n = number of eggs, k = number of floors int n, k; cin >> n >> k; cout << "Minimum number of trials required: " << EggDrop(n,k) << endl; return 0; } ================================================ FILE: Algorithms/DP/Egg_Drop/Egg_Drop.cs ================================================ using System; namespace ConsoleApp1 { static class Program { private static void Main(string[] args) { int n = int.Parse(Console.ReadLine()); int k = int.Parse(Console.ReadLine()); Console.WriteLine("Minimum number of trials " + "in worst case with " + n + " eggs and " + k + " floors is " + eggDrop(n, k)); } static int max(int a, int b) { return (a > b) ? a : b; } /* Function to get minimum number of trials needed in worst case with n eggs and k floors */ static int eggDrop(int n, int k) { /* A 2D table where entery eggFloor[i][j] will represent minimum number of trials needed for i eggs and j floors. */ int[,] eggFloor = new int[n + 1, k + 1]; int res; int i, j, x; // We need one trial for one floor and0 // trials for 0 floors for (i = 1; i <= n; i++) { eggFloor[i, 1] = 1; eggFloor[i, 0] = 0; } // We always need j trials for one egg // and j floors. for (j = 1; j <= k; j++) eggFloor[1, j] = j; // Fill rest of the entries in table // using optimal substructure property for (i = 2; i <= n; i++) { for (j = 2; j <= k; j++) { eggFloor[i, j] = int.MaxValue; for (x = 1; x <= j; x++) { res = 1 + max(eggFloor[i - 1, x - 1], eggFloor[i, j - x]); if (res < eggFloor[i, j]) eggFloor[i, j] = res; } } } // eggFloor[n][k] holds the result return eggFloor[n, k]; } } } // This code is contributed by Sam007 - GFG. ================================================ FILE: Algorithms/DP/Egg_Drop/egg drop.java ================================================ public class EggDroppDP { public int getDrops(int eggs, int floors){ int [][] eggDrops = new int [eggs+1][floors+1]; //base case 1: //if floors = 0 then no drops are required // OR floors = 1 then 1 drop is required for (int i = 1; i <=eggs ; i++) { eggDrops[i][0] = 0; eggDrops[i][1] = 1; } //base case 2: //if only one egg is there then drops = floors for (int i = 1; i <=floors ; i++) { eggDrops[1][i] = i; } for (int i = 2; i <=eggs ; i++) { for (int j = 2; j <=floors ; j++) { eggDrops[i][j] = Integer.MAX_VALUE; int tempResult; for (int k = 1; k <=j ; k++) { tempResult = 1 + Math.max(eggDrops[i-1][k-1], eggDrops[i][j-k]); eggDrops[i][j] = Math.min(tempResult,eggDrops[i][j]); } } } // eggDrops[eggs][floors] will have the result : minimum number of drops required in worst case return eggDrops[eggs][floors]; } public static void main(String[] args) { EggDroppDP eggDP = new EggDroppDP(); int eggs = 2; int floors = 100; System.out.printf("(DP) Minimum number of drops required in worst case with eggs: %s and floors: %s is : %s",eggs,floors,eggDP.getDrops(eggs,floors)); } } ================================================ FILE: Algorithms/DP/Egg_Drop/egg_drop.py ================================================ INT_MAX=32767 def egg_drop(n,k): m=[[0 for x in range(k+1)]for x in range(n+1)] for i in range(1,n+1): m[i][0]=0 m[i][1]=1 for j in range(1,k+1): m[1][j]=j for i in range(2,n+1): for j in range(2,k+1): m[i][j]=INT_MAX for x in range(1,j+1): res = 1 + max(m[i-1][x-1], m[i][j-x]) if res < m[i][j]: m[i][j] = res print(m) return m[n][k] n=2 k=6 print(egg_drop(n,k)) ================================================ FILE: Algorithms/DP/Egg_Drop/egg_drop.ts ================================================ const eggDrop = (n: number, k: number) => { let eggFloor: number[][] = []; // A 2d array where entry eggFloor[i][j] will represent // the minimum number of trials needeed for i eggs and j floors for (let i = 0; i < n + 1; i++) { eggFloor.push(new Array(k + 1).fill(0)); } // One trial for one floor and 0 trial for zero floor for (let i = 1; i < n + 1; i++) { eggFloor[i][1] = 1; eggFloor[i][0] = 0; } // We always need j trials for one egg and j floors for (let j = 1; j < k + 1; j++) { eggFloor[1][j] = j; } // Fill the rest of the entries in table using optimal // subtructure property for (let i = 2; i < n + 1; i++) { for (let j = 2; j < k + 1; j++) { eggFloor[i][j] = Number.MAX_SAFE_INTEGER; for (let x = 0; x < j + 1; x++) { let res = 1 + Math.max(eggFloor[i - 1][x - 1], eggFloor[i][j - x]); if (res < eggFloor[i][j]) { eggFloor[i][j] = res; } } } } // eggFloor[n][k] holds the result return eggFloor[n][k]; }; const n = 2; const k = 36; console.log( "Minimum worst case of trials in worst case with " + n + " eggs " + k + " floors is " + eggDrop(n, k) ); ================================================ FILE: Algorithms/DP/Fibonacci_Series/Fibonacci.c ================================================ #include int main() { int first=0, second=1, i, n, sum=0; printf("Enter the number of terms: "); scanf("%d",&n); //accepting the terms printf("Fibonacci Series:"); for(i=0 ; i ================================================ FILE: Algorithms/DP/Fibonacci_Series/fibonacci.go ================================================ package main import "fmt" func Fibonacci(n uint) uint64 { if n <= 1 { return uint64(n) } var n2, n1 uint64 = 0, 1 for i := uint(2); i < n; i++ { n2, n1 = n1, n1+n2 } return n2 + n1 } func main() { for i := uint(0); i < 10; i++ { fmt.Println(Fibonacci(i)) } } ================================================ FILE: Algorithms/DP/Fibonacci_Series/fibonacci.js ================================================ /* This function returns the nth fibonacci number, given */ function fibonacci(n, memoizer) { memoizer = memoizer || {}; if (memoizer[n]) { return memoizer[n]; } if (n <= 1) { return 1; } return memoizer[n] = fibonacci(n - 1, memoizer) + fibonacci(n - 2, memoizer); } ================================================ FILE: Algorithms/DP/Fibonacci_Series/fibonacci.py ================================================ def fibonacci(n): FibArray = [0, 1] while len(FibArray) < n + 1: FibArray.append(0) if n <= 1: return n else: if FibArray[n - 1] == 0: FibArray[n - 1] = fibonacci(n - 1) if FibArray[n - 2] == 0: FibArray[n - 2] = fibonacci(n - 2) FibArray[n] = FibArray[n - 2] + FibArray[n - 1] return FibArray[n] print(fibonacci(5)) ================================================ FILE: Algorithms/DP/Gauss_Easter_Date/CalculateEasterDate.java ================================================ import java.util.HashMap; import java.util.Map; /** * @author Alessandro Arosio - 04/10/2020 08:39 */ public class CalculateEasterDate { private static final String LOCATION_OF_YEAR = "locationOfYear"; private static final String LEAP_DAYS = "leapDays"; private static final String NON_LEAP_YEAR = "nonLeapYear"; private static final String YEARS_DIVIDED_100 = "yearsDividedBy100"; private static final String CENTURY = "century"; private static final String DIFFERENCE_LEAP_DAYS = "differenceOfLeapDays"; private static final String DAYS_TO_ADD = "numberOfDaysToAdd"; private static final String DAYS_TO_NEXT_SUNDAY = "numberOfDaysToNextSunday"; private static final String DAYS = "days"; public static void main(String[] args) { int year = 2019; gaussEaster(year); } static void gaussEaster(int year) { Map gaussNumbers = getGaussNumbers(year); Integer days = gaussNumbers.get(DAYS).intValue(); if (is29Days(gaussNumbers.get(DAYS_TO_ADD), gaussNumbers.get(DAYS_TO_NEXT_SUNDAY))) { System.out.println(year + "-04" + "-19"); } else if (is28Days(gaussNumbers.get(DAYS_TO_ADD),gaussNumbers.get(DAYS_TO_NEXT_SUNDAY))) { System.out.println(year + "-04" + "-18"); } else { if (gaussNumbers.get(DAYS) > 31) { System.out.println(year + "-04-" + (days - 31)); } else { System.out.println(year + "-03-" + days); } } } private static boolean is29Days(Double days, Double daysToSunday) { return days.intValue() == 29 && daysToSunday.intValue() == 6; } private static boolean is28Days(Double days, Double daysToSunday) { return days.intValue() == 28 && daysToSunday.intValue() == 6; } private static Map getGaussNumbers(int year) { Map gauss = new HashMap<>(); gauss.put(LOCATION_OF_YEAR, Double.valueOf(year % 19)); gauss.put(LEAP_DAYS, Double.valueOf(year % 4)); gauss.put(NON_LEAP_YEAR, Double.valueOf(year % 7)); gauss.put(YEARS_DIVIDED_100, Math.floor(year / 100)); gauss.put(CENTURY, calculateCentury(gauss.get(YEARS_DIVIDED_100))); gauss.put(DIFFERENCE_LEAP_DAYS, (4 + gauss.get(YEARS_DIVIDED_100) - gauss.get(YEARS_DIVIDED_100) / 4) % 7); gauss.put(DAYS_TO_ADD, (19 * gauss.get(LOCATION_OF_YEAR) + gauss.get(CENTURY)) % 30); gauss.put(DAYS_TO_NEXT_SUNDAY, (2 * gauss.get(LEAP_DAYS) + 4 * gauss.get(NON_LEAP_YEAR) + 6 * gauss.get(DAYS_TO_ADD) + gauss.get(DIFFERENCE_LEAP_DAYS)) % 7); gauss.put(DAYS, 22 + gauss.get(DAYS_TO_ADD) + gauss.get(DAYS_TO_NEXT_SUNDAY)); return gauss; } private static Double calculateCentury(Double yearsDividedBy100) { double floor = Math.floor((13 + 8 * yearsDividedBy100) / 25); return (15 - floor + yearsDividedBy100 - yearsDividedBy100 / 4) % 30; } } ================================================ FILE: Algorithms/DP/Gauss_Easter_Date/Gauss_Easter_Date.cpp ================================================ #include using namespace std; void gaussAlgorithm(int year, int *month, int *day); int main() { int year, easterMonth=3, easterDay=22; cout << "Enter a year for which you wish to find out date of Easter for: "; cin >> year; //input year cout << endl; gaussAlgorithm(year, &easterMonth, &easterDay); //calculate month and day cout << "Date of easter for year " << year << " is: " << ((easterMonth == 3) ? "March " : "April ") << easterDay << endl; char ch; cin >> ch; //wait for user input return 0; } void gaussAlgorithm(int year, int *month, int *day) //https://math.stackexchange.com/questions/896954/decoding-gauss-easter-algorithm { int a, b, c, k, p, q, M, N, d, e; a = year%19; b = year%4; c = year%7; k = year/100; p = (13+8*k)/25; q = k/4; M = (15-p+k-q)%30; N = (4+k-q)%7; d = (19*a + M) %30; e = (2*b + 4*c + 6*d + N)%7; if((22+d+e) < 32) { *day=22+d+e; } else { *day=d+e-9; *month=4; } if(d==29 && e==6 && *month==4 && *day==26) *day=19; if(d==28 && e==6 && *month==4 && *day==25 && (11*M+11)%30 < 19) *day=18; } //"It is not possible to present here the entire analysis that led to the above formula" -Gauss ================================================ FILE: Algorithms/DP/Gauss_Easter_Date/Gauss_Easter_Date.php ================================================ 31){ echo $year."-April-".($days-31); } else{ echo $year."-March-".$days; } } } //Example Case echo Gauss_Easter(2020); ================================================ FILE: Algorithms/DP/Gauss_Easter_Date/Gauss_Easter_Date.py ================================================ import math def Easter(Year): # Gauss Easter Algorithm a = Year % 19 b = Year % 4 c = Year % 7 k = math.floor(Year / 100) p = math.floor((13 + 8 * k) / 25) q = k/4 m = (15 - p + k - q) % 30 n = (4 + k - q) % 7 d = (19 * a + m) % 30 e = (2 * b + 4 * c + 6 * d + n) % 7 days = (22 + d + e) # d is 29 if ((d == 29) and (e == 6)): print(Year, "- 04 -19") return # d is 28 elif ((d == 28) and (e == 6)): print(Year, "- 04 -18") return else: # If days > 31, April if (days > 31): print(Year, "- 04 -", int(days - 31)) return else: # Otherwise, March print(Year, "- 03 -", days) return Year = 2012 Easter(Year) ================================================ FILE: Algorithms/DP/Gauss_Easter_Date/Gauss_Easter_Date.rb ================================================ def gauss_easter(y) a = y % 19 b = y % 4 c = y % 7 p = (y / 100).floor q = ((13 + 8 * p) / 25).floor m = (15 - q + p - (p / 4)) % 30 n = (4 + p - (p / 4)) % 7 d = (19 * a + m) % 30 e = (2 * b + 4 * c + 6 * d + n) % 7 day = (22 + d + e) if (d == 29) && (e == 6) puts("The Easter date for your entered year is: #{y}-04-19") elsif (d == 28) && (e == 6) return puts("The Easter date for your entered year is: #{y}-04-18") else if day > 31 return puts("The Easter date for your entered year is: #{y}-04-#{day-31}") else return puts("The Easter date for your entered year is: #{y}-03-#{day}") end end end print("Enter the year you want to calculate the Easter date: ") y = Integer(gets.chomp()) gauss_easter(y) ================================================ FILE: Algorithms/DP/Gauss_Easter_Date/easterDate.cpp ================================================ #include #include using namespace std; int main() { unsigned short year, a, b; cout << "\nFor which year do you want to know Easter date?\n> "; cin >> year; a = (19 * (year % 19) + 15) % 30; b = (2 * (year % 4) + 4 * (year % 7) + 6 * a + 6) % 7; cout << "Easter date in " << year << " is " << ((a + b > 26) ? ("May " + to_string(a + b - 26)) : ("April " + to_string(4 + a + b))) << endl; return 0; } ================================================ FILE: Algorithms/DP/Gauss_Easter_Date/easterDate.go ================================================ package main import "fmt" func getEasterDate(_year int) { a := (19 * (_year % 19) + 15) % 30 b := (2 * (_year % 4) + 4 * (_year % 7) + 6 * a + 6) % 7 var _date string if a + b > 26 { _date = fmt.Sprintf("May %d", (a + b - 26)) } else { _date = fmt.Sprintf("April %d", (4 + a + b)) } fmt.Println(_date, _year) } func main() { getEasterDate(2020) } ================================================ FILE: Algorithms/DP/Gauss_Easter_Date/easterDate.java ================================================ import java.util.Date; import java.util.Scanner; // Function calculates and prints // easter date for given year Y class Main { static void gaussEaster(int Y) { float A, B, C, P, Q, M, N, D, E; // All calculations done // on the basis of // Gauss Easter Algorithm A = Y % 19; B = Y % 4; C = Y % 7; P = (float)Math.floor(Y / 100); Q = (float)Math.floor( (13 + 8 * P) / 25); M = (15 - Q + P - P / 4) % 30; N = (4 + P - P / 4) % 7; D = (19 * A + M) % 30; E = (2 * B + 4 * C + 6 * D + N) % 7; int days = (int)(22 + D + E); // A corner case, // when D is 29 if ((D == 29) && (E == 6)) { System.out.println(Y + "-04" + "-19"); return; } // Another corner case, // when D is 28 else if ((D == 28) && (E == 6)) { System.out.println(Y + "-04" + "-18"); return; } else { // If days > 31, move to April // April = 4th Month if (days > 31) { System.out.println(Y + "-04-" + (days - 31)); return; } // Otherwise, stay on March // March = 3rd Month else { System.out.println(Y + "-03-" + days); return; } } } // Driver code public static void main(String[] args) { int Y = new java.util.Scanner(System.in).nextInt(); gaussEaster(Y); } } ================================================ FILE: Algorithms/DP/Gauss_Easter_Date/easterDate.js ================================================ const readline = require('readline') const rl = readline.createInterface({ input: process.stdin, output: process.stdout }); rl.question('\nFor which year do you want to know Easter date?\n> ', year => { year = parseInt(year) const a = (19 * (year % 19) + 15) % 30 const b = (2 * (year % 4) + 4 * (year % 7) + 6 * a + 6) % 7 console.log(`Easter date in ${year} is \ ${a + b > 26 ? 'May ' + (a + b - 26) : 'April ' + (4 + a + b)}\n`) rl.close() }) ================================================ FILE: Algorithms/DP/Generate_ATM_Codes.py ================================================ print('Welcome to Northen Frock Bank ATM') restart=('Y') chances = 3 balance = 67.14 while chances >= 0: pin = int(input('Please Enter You 4 Digit Pin: ')) if pin == (1234): print('You entered you pin Correctly\n') while restart not in ('n','NO','no','N'): print('Please Press 1 For Your Balance\n') print('Please Press 2 To Make a Withdrawl\n') print('Please Press 3 To Pay in\n') print('Please Press 4 To Return Card\n') option = int(input('What Would you like to choose?')) if option == 1: print('Your Balance is £',balance,'\n') restart = input('Would You you like to go back? ') if restart in ('n','NO','no','N'): print('Thank You') break elif option == 2: option2 = ('y') withdrawl = float(input('How Much Would you like to withdraw? \n£10/£20/£40/£60/£80/£100 for other enter 1: ')) if withdrawl in [10, 20, 40, 60, 80, 100]: balance = balance - withdrawl print ('\nYour Balance is now £',balance) restart = input('Would You you like to go back? ') if restart in ('n','NO','no','N'): print('Thank You') break elif withdrawl != [10, 20, 40, 60, 80, 100]: print('Invalid Amount, Please Re-try\n') restart = ('y') elif withdrawl == 1: withdrawl = float(input('Please Enter Desired amount:')) elif option == 3: Pay_in = float(input('How Much Would You Like To Pay In? ')) balance = balance + Pay_in print ('\nYour Balance is now £',balance) restart = input('Would You you like to go back? ') if restart in ('n','NO','no','N'): print('Thank You') break elif option == 4: print('Please wait whilst your card is Returned...\n') print('Thank you for you service') break else: ================================================ FILE: Algorithms/DP/Gold_Mine_Problem/goldmine.java ================================================ // Java program to solve Gold Mine problem import java.util.Arrays; class goldmine { // Returns maximum amount of gold that // can be collected when journey started // from first column and moves allowed // are right, right-up and right-down static int getMaxGold(int gold[][], int m, int n) { // Create a table for storing // intermediate results and initialize // all cells to 0. The first row of // goldMineTable gives the maximum // gold that the miner can collect // when starts that row int goldTable[][] = new int[m][n]; for(int[] rows:goldTable) Arrays.fill(rows, 0); for (int col = n-1; col >= 0; col--) { for (int row = 0; row < m; row++) { // Gold collected on going to // the cell on the right(->) int right = (col == n-1) ? 0 : goldTable[row][col+1]; // Gold collected on going to // the cell to right up (/) int right_up = (row == 0 || col == n-1) ? 0 : goldTable[row-1][col+1]; // Gold collected on going to // the cell to right down (\) int right_down = (row == m-1 || col == n-1) ? 0 : goldTable[row+1][col+1]; // Max gold collected from taking // either of the above 3 paths goldTable[row][col] = gold[row][col] + Math.max(right, Math.max(right_up, right_down)); ; } } // The max amount of gold collected will be // the max value in first column of all rows int res = goldTable[0][0]; for (int i = 1; i < m; i++) res = Math.max(res, goldTable[i][0]); return res; } //driver code public static void main(String arg[]) { int gold[][]= { {1, 3, 1, 5}, {2, 2, 4, 1}, {5, 0, 2, 3}, {0, 6, 1, 2} }; int m = 4, n = 4; System.out.print(getMaxGold(gold, m, n)); } } ================================================ FILE: Algorithms/DP/Gold_Mine_Problem/goldmine.py ================================================ MAX = 100 def getMaxGold(gold, m, n): goldTable = [[0 for i in range(n)] for j in range(m)] for col in range(n-1, -1, -1): for row in range(m): if (col == n-1): right = 0 else: right = goldTable[row][col+1] if (row == 0 or col == n-1): right_up = 0 else: right_up = goldTable[row-1][col+1] if (row == m-1 or col == n-1): right_down = 0 else: right_down = goldTable[row+1][col+1] goldTable[row][col] = gold[row][col] + \ max(right, right_up, right_down) res = goldTable[0][0] for i in range(1, m): res = max(res, goldTable[i][0]) return res gold = [[1, 3, 1, 8], [2, 9, 8, 1], [7, 0, 1, 3], [0, 6, 1, 2]] m = 4 n = 4 print(getMaxGold(gold, m, n)) ================================================ FILE: Algorithms/DP/Golomb_Sequence/Golomb Sequence.cpp ================================================ #include using namespace std; void printGolomb(int n) { int dp[n + 1]; dp[1] = 1; cout << dp[1] << " "; for (int i = 2; i <= n; i++) { dp[i] = 1 + dp[i - dp[dp[i - 1]]]; cout << dp[i] << " "; } } int main() { int n; cin>>n; printGolomb(n); return 0; } I/P: n=9 O/P: 1 2 2 3 3 4 4 4 5 ================================================ FILE: Algorithms/DP/Golomb_Sequence/Golomb.cpp ================================================ // C++ Program to find first // n terms of Golomb sequence. #include using namespace std; // Print the first n term // of Golomb Sequence void printGolomb(int n) { int dp[100]; // base cases dp[1] = 1; cout << dp[1] << " "; // Finding and printing first // n terms of Golomb Sequence. for (int i = 2; i <= n; i++) { dp[i] = 1 + dp[i - dp[dp[i - 1]]]; cout << dp[i] << " "; } } // Driver Code int main() { int n = 9; printGolomb(n); return 0; } ================================================ FILE: Algorithms/DP/Golomb_Sequence/Golomb.java ================================================ import java.util.*; class Golomb { public static void printGolomb(int n) { int dp[] = new int[n + 1]; dp[1] = 1; System.out.print(dp[1] + " "); for (int i = 2; i <= n; i++) { dp[i] = 1 + dp[i - dp[dp[i - 1]]]; System.out.print(dp[i] + " "); } } public static void main (String[] args) { Scanner s = new Scanner(System.input()); int n = s.nextInt(); printGolomb(n); } } ================================================ FILE: Algorithms/DP/Golomb_Sequence/golomb.py ================================================ # Golomb sequence def findGolomb(n): if (n == 1): return 1 return 1 + findGolomb(n - findGolomb(findGolomb(n - 1))) def printGolomb(n): for i in range(1, n + 1): print(findGolomb(i), end=" ") n = 19 printGolomb(n) ================================================ FILE: Algorithms/DP/Knight_Probability/Knight_Probability_in_a_ChessBoard.cpp ================================================ #include using namespace std; double knightProbability(int N, int K, int sr, int sc) { vector > dp(N, vector(N)); int dr[8] = {2, 2, 1, 1, -1, -1, -2, -2}; int dc[8] = {1, -1, 2, -2, 2, -2, 1, -1}; dp[sr][sc] = 1; for (; K > 0; K--) { vector > dp2(N, vector(N)); for (int r = 0; r < N; r++) { for (int c = 0; c < N; c++) { for (int k = 0; k < 8; k++) { int cr = r + dr[k]; int cc = c + dc[k]; if (0 <= cr && cr < N && 0 <= cc && cc < N) { dp2[cr][cc] += dp[r][c] / 8.0; } } } } dp = dp2; } double ans = 0.0; for (auto row: dp) { for (double x: row) ans += x; } return ans; } int main() { int n, k, sr, sc; cout << "Please enter size of chessboard, number of moves, starting row and starting column" << endl; cin >> n >> k >> sr >> sc; cout << "The probability that the knight remains on the board after it has stopped moving is " << knightProbability(n, k, sr, sc) << endl; return 0; } ================================================ FILE: Algorithms/DP/Knight_Probability/Problem_Statement.md ================================================ On an NxN chessboard, a knight starts at the r-th row and c-th column and attempts to make exactly K moves. The rows and columns are 0 indexed, so the top-left square is (0, 0), and the bottom-right square is (N-1, N-1). A chess knight has 8 possible moves it can make, as illustrated below. Each move is two squares in a cardinal direction, then one square in an orthogonal direction. Each time the knight is to move, it chooses one of eight possible moves uniformly at random (even if the piece would go off the chessboard) and moves there. The knight continues moving until it has made exactly K moves or has moved off the chessboard. Return the probability that the knight remains on the board after it has stopped moving. ================================================ FILE: Algorithms/DP/LCS/LCS_of_three_strings.py ================================================ def three_LCS(A,B,C): m=len(A) n=len(B) o=len(C) L=[[[0 for i in range(o+1)]for j in range(n+1)]for k in range(m+1)] for i in range(m+1): for j in range(n+1): for k in range(o+1): if (i==0 or j==0 or k==0): L[i][j][k]=0 elif (A[i-1]==B[j-1] and A[i-1]==C[k-1]): L[i][j][k]= 1+L[i-1][j-1][k-1] else: L[i][j][k]=max(max(L[i-1][j][k],L[i][j-1][k]),L[i][j][k-1]) return L[m][n][o] X = 'ABCDAB' Y = 'BDCABA' Z = '12XBA' print('Length of LCS of three strings is', three_LCS(X, Y, Z)) ================================================ FILE: Algorithms/DP/LCS/LongestCommonSubsequence.cpp ================================================ #include using namespace std; int LCS(string s1, string s2){//function to get the longest common subsequence vector> dp(s1.length()+1, vector(s2.length()+1, 0));//table of dp for finding length of longest subsequence for(int i = 1; i<=s1.length(); i++){ for(int j = 1; j<= s2.length(); j++){ if(s1[i-1] == s2[j-1])//if letter match in both string the following line to be used dp[i][j] = 1+ dp[i-1][j-1]; else dp[i][j] = max(dp[i-1][j], dp[i][j-1]); } } return dp[s1.length()][s2.length()];//length of longest common subsequence here } int main() { string s1, s2; cin>>s1; cin>> s2; int res = LCS(s1,s2); cout<< res< #define M 1000000007LL #define mod 998244253LL #define ll long long int #define vi vector int max(int a,int b) { if(a>b) return a; else return b; } int main() { int n,m,i,j; printf("enter length of 1st subsequrnce:- "); scanf("%d",&n); int a[n]; printf("\nenter sequence:- "); for(i=0;i #define M 1000000007LL #define mod 998244253LL #define ll long long int #define vi vector int max(int a,int b) { if(a>b) return a; else return b; } int main() { int n,m,i,j; printf("enter length of 1st subsequrnce:- "); scanf("%d",&n); int a[n]; printf("\nenter sequence:- "); for(i=0;i using namespace std; #define ull unsigned long long #define int long long #define ld long double #define pb push_back #define pi pair< int,int > #define ff first #define ss second #define mod 1000000007 #define endl "\n" signed main() { ios_base::sync_with_stdio(false); cin.tie(NULL); // #ifndef ONLINE_JUDGE // freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); // #endif string s1,s2,s3; cin>>s1>>s2>>s3; // take input of three strings // Find the length of the three strings int n = s1.length(), m = s2.length(), l = s3.length(); // Finding the lcs length int dp[n+1][m+1][l+1]; for(int i=0; i<=n; i++) { for(int j=0; j<=m; j++) { for(int k=0; k<=l; k++) { if(i==0 || j==0 || k==0) dp[i][j][k] = 0; else if(s1[i-1] == s2[j-1] && s2[j-1] == s3[k-1]) dp[i][j][k] = dp[i-1][j-1][k-1] + 1; else dp[i][j][k] = max(dp[i-1][j][k], max(dp[i][j-1][k], dp[i][j][k-1])); } } } int length_of_lcs = dp[n][m][l]; // Length of LCS of the 3 strings int i=n, j=m, k=l; string ans=""; // Initializing lcs string while(i>0 && j>0 && k>0) { if(s1[i-1] == s2[j-1] && s2[j-1] == s3[k-1]) // If current character in s1, s2, and s3 are same, then current character is part of LCS { ans+=s1[i-1]; i--; j--; k--; } // If not same, then find the larger of the three and go in the direction of larger value else if(dp[i-1][j][k] > dp[i][j-1][k] || dp[i-1][j][k] > dp[i][j][k-1]) i--; else if(dp[i][j-1][k] > dp[i-1][j][k] || dp[i][j-1][k] > dp[i][j][k-1]) j--; else k--; } // We have to reverse the lcs string because we // put characters in the lcs string from the last reverse(ans.begin(), ans.end()); cout<<"The longest common subsequence is: "; cout< /* lis() returns the length of the longest increasing subsequence in arr[] of size n */ int lis( int arr[], int n ) { int lis[10000]; int i, j; lis[0] = 1; /* Compute optimized LIS values in bottom up manner */ for (i = 1; i < n; i++ ) { lis[i] = 1; for (j = 0; j < i; j++ ) if ( arr[i] > arr[j] && lis[i] < lis[j] + 1) lis[i] = lis[j] + 1; } // Return maximum value in lis[] int mmax=-99999; for(i=0;i using namespace std; /* Input Format: length of the array and contents of the array Output Format: length of LIS and contents of the LIS ALgorithm: Bottom Up Dynamic programming Time Complexity: O(N^2), where N is the length of the array Space Complexity: O(N^2) Sample Input and Output **Sample Input 1:** Enter the number of elements of the array: 8 Enter the elements of the array: 1 8 5 9 6 2 4 7 The length of LIS is: 4 The LIS is: 1 5 6 7 **Sample Input 2:** Enter the number of elements of the array: 10 Enter the elements of the array: 1 2 3 6 5 8 9 4 7 6 The length of LIS is: 6 The LIS is: 1 2 3 6 8 9 Graph contains cycle! */ int main() { int n; // number of elements of the array cout << "\nEnter the number of elements of the array: "; cin >> n; vector a(n); vector lis(n); // for storing the longest increasing subsequence size of each index vector> seq(n); // storing the longest increasing subsequence for each index from 0 to n-1 cout << "\nEnter the elements of the array: "; for (int i = 0; i < n; i++) { cin >> a[i]; } // initialising the LIS for each index to 1 for (int i = 0; i < n; i++) { lis[i] = 1; } // counting the LIS in bottom up manner dynamic programming for (int i = 1; i < n; i++) { vector tmp; for (int j = 0; j < i; j++) { // if the current LIS value is less that the value we just calculated we have got a new LIS for index i if (a[i] > a[j] and lis[i] < lis[j] + 1) { lis[i] = lis[j] + 1; tmp.push_back(a[j]); } } tmp.push_back(a[i]); seq[i] = tmp; } int answerIndex = 0; int maxLength = *max_element(lis.begin(), lis.end()); for (int i = 0; i < n; i++) { if ((int)seq[i].size() == maxLength) { answerIndex = i; break; } } // printing the LIS and contents of the LIS cout << "\nThe length of LIS is: " << maxLength << '\n'; cout << "\nThe LIS is: "; for (auto u : seq[answerIndex]) { cout << u << " "; } cout << '\n'; } ================================================ FILE: Algorithms/DP/LIS/LIS.go ================================================ package main import "fmt" func binarySearch(array []int, l int, r int, key int) int { for r-l > 1 { center := l + (r-l)/2 if array[center] >= key { r = center } else { l = center } } return r } // LongestIncreasingSubsequence will returned a maximum increasing subsequence inside the input given // with complexity O(N log N) func LongestIncreasingSubsequence(input []int) int { if len(input) == 0 { return 0 } length := 1 array := make([]int, len(input)) array[0] = input[0] for i := 1; i < len(array); i++ { if input[i] < array[0] { array[0] = input[i] } else if input[i] > array[length-1] { array[length] = input[i] length++ } else { array[binarySearch(array, -1, length-1, input[i])] = input[i] } } return length } func main() { input := []int{1, 4, 3, 8, 12, 1, 9, 10, 3, 11, 0, 3} output := LongestIncreasingSubsequence(input) fmt.Println(output) } ================================================ FILE: Algorithms/DP/LIS/LIS.java ================================================ /* Input Format: length of the array and contents of the array Output Format: length of LIS and contents of the LIS Sample Input and Output **Sample Input 1:** Enter the number of elements of the array: 8 Enter the elements of the array: 1 8 5 9 6 2 4 7 The length of LIS is: 4 The LIS is: 1 5 6 7 **Sample Input 2:** Enter the number of elements of the array: 10 Enter the elements of the array: 1 2 3 6 5 8 9 4 7 6 The length of LIS is: 6 The LIS is: 1 2 3 6 8 9 Graph contains cycle! */ import java.util.*; class Main { public static void findLIS(int[] arr) { // LIS.get(i) stores the longest increasing subsequence of subarray List> LIS = new ArrayList<>(); for (int i = 0; i < arr.length; i++) { LIS.add(new ArrayList<>()); } // LIS[0] denotes longest increasing subsequence ending with arr[0] LIS.get(0).add(arr[0]); for (int i = 1; i < arr.length; i++) { for (int j = 0; j < i; j++) { // find longest increasing subsequence that ends with arr[j] // where arr[j] is less than the current element arr[i] if (arr[j] < arr[i] && LIS.get(j).size() > LIS.get(i).size()) { LIS.set(i, new ArrayList<>(LIS.get(j))); } } // include arr[i] in LIS.get(i) LIS.get(i).add(arr[i]); } int j = 0; for (int i = 0; i < arr.length; i++) { if (LIS.get(j).size() < LIS.get(i).size()) { j = i; } } System.out.print("The length of LIS is:" + (LIS.get(j)).size()); System.out.print("\n"+"The LIS is:" + LIS.get(j)); } public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print("Enter the number of elements of the array:"+"\n"); int n = sc.nextInt(); System.out.print("Enter the elements of the array:"+"\n"); int array[] = new int[n]; for (int i = 0; i < n; ++i) { array[i] = sc.nextInt(); } findLIS(array); } } ================================================ FILE: Algorithms/DP/LIS/LongestIncreaseSubSequence.cpp ================================================ #include using namespace std; int lis(int* input, int n) { int* output = new int[n]; output[0] = 1; for (int i = 1; i < n; i++) { output[i] = 1; for (int j = i - 1; j >= 0; j--) { if (input[j] > input[i]) { continue; } int possibleAns = output[j] + 1; if (possibleAns > output[i]) { output[i] = possibleAns; } } } int best = 0; for (int i = 0; i < n; i++) { if (best < output[i]) { best = output[i]; } } delete [] output; return best; } int main() { int n; cin >> n; int * input = new int[n]; for (int i = 0; i < n; i++) { cin >> input[i]; } int ans = lis(input, n); cout << ans << endl; delete [] input; } ================================================ FILE: Algorithms/DP/LIS/README.md ================================================ ## LIS (Longest Increasing Subsequence) - [LIS C++](LIS.cpp) - [LIS Java](LIS.java) - [LIS Python3](lis.py) - [LIS Go](LIS.go) --- ### [⬆](#toc) Problem Statement Given an array of integers, find the length of the longest (strictly) increasing subsequence from the given array along with that print the contents of the LIS -

Input Format:

length of the array and contents of the array
-

Output Format:

length of LIS and contents of the LIS --- ### [⬆](#toc) Sample Input Output -

Input:

N = 16
A[] = 0 8 4 12 2 10 6 14 1 9 5 13 3 11 7 15 -

Output:

The length of LIS is: 6
The LIS is: 0 2 6 9 13 15 --- ================================================ FILE: Algorithms/DP/LIS/lis.py ================================================ def lis(arr): n = len(arr) lis = [1]*n for i in range (1, n): for j in range(0, i): if arr[i] > arr[j] and lis[i]< lis[j] + 1 : lis[i] = lis[j]+1 maximum = 0 for i in range(n): maximum = max(maximum, lis[i]) return maximum arr = [10, 22, 9, 33, 21, 50, 41, 60] print("Length of lis is"+" "+ str(lis(arr))) ================================================ FILE: Algorithms/DP/LSCS/LSCS.c ================================================ #include #include int largest_subarray_sum(int *arr, int size) { if (size <= 0) { printf("Size must be a positive integer\n"); return 1; } int start = 0, best_start = 0, best_end = 0; int sum = 0, best_sum = INT_MIN; for (int end = 0; end < size; ++end) { if (sum <= 0) { start = end; sum = arr[end]; } else { sum += arr[end]; } if (sum > best_sum) { best_sum = sum; best_start = start; best_end = end; } } printf("Best sum is %d\nFirst index: %d\nLast index: %d\n", best_sum, best_start, best_end); return 0; } ================================================ FILE: Algorithms/DP/LSCS/LSCS.cpp ================================================ using namespace std; #include #include int maxSubArraySum(int a[], int size) { int max_so_far = INT_MIN, max_ending_here = 0, start =0, end = 0, s=0; for (int i=0; i< size; i++ ) { max_ending_here += a[i]; if (max_so_far < max_ending_here) { max_so_far = max_ending_here; start = s; end = i; } if (max_ending_here < 0) { max_ending_here = 0; s = i + 1; } } cout << "Maximum contiguous sum is " << max_so_far << endl; cout << "Starting index "<< start << endl << "Ending index "<< end << endl; } ================================================ FILE: Algorithms/DP/LSCS/lscs.go ================================================ package main import "fmt" func max(x, y int) int { if x < y { return y } return x } func sol(s1 string, s2 string, n int, m int) int { dp := make([][]int, n+1) for i := 0; i <= n+1; i++ { dp[i] = make([]int, m+1) } for i := 1; i <= n; i++ { for j := 1; j <= m; j++ { if s1[i-1] == s2[j-1] { dp[i][j] = 1 + dp[i-1][j-1] } else { dp[i][j] = max(dp[i-1][j], dp[i][j-1]) } } } return dp[n][m] } func main() { var t int fmt.Scanf("%d", t) for _ = 0; t >= 0; t-- { var s1, s2 string fmt.Scanf("%s", s1) fmt.Scanf("%s", s2) n, m := len(s1), len(s2) raw_res := sol(s1, s2, n, n) res := n + m - raw_res fmt.Printf("%d\n", res) } } ================================================ FILE: Algorithms/DP/LSCS/lscs.py ================================================ def find_max_subarray(alist, start, end): max_ending_at_i = max_seen_so_far = alist[start] max_left_at_i = max_left_so_far = start max_right_so_far = start + 1 for i in range(start + 1, end): if max_ending_at_i > 0: max_ending_at_i += alist[i] else: max_ending_at_i = alist[i] max_left_at_i = i if max_ending_at_i > max_seen_so_far: max_seen_so_far = max_ending_at_i max_left_so_far = max_left_at_i max_right_so_far = i + 1 return max_left_so_far, max_right_so_far, max_seen_so_far alist = [-13, -3, -25, -20, -3, -16, -23, -12, -5, -22, -15, -4, -7] start, end, maximum = find_max_subarray(alist, 0, len(alist)) print('The maximum subarray starts at index {}, ends at index {}' ' and has sum {}.'.format(start, end - 1, maximum)) ================================================ FILE: Algorithms/DP/LSCS/shortest_common_supersequence.c ================================================ #include int max(int a,int b) { return a>b?a:b; } int sol(char* s1,char* s2,int n,int m) { int dp[n+1][m+1]; for(int i=0;i<=n;i++) { for(int j=0;j<=m;j++) dp[i][j]=0; } for(int i=1;i<=n;i++) { for(int j=1;j<=m;j++) { if(s1[i-1]==s2[j-1]) dp[i][j]=1+dp[i-1][j-1]; else dp[i][j]=max(dp[i-1][j],dp[i][j-1]); } } return dp[n][m]; } int main() { int t; scanf("%d",&t); while(t--){ char s1[101],s2[101]; scanf("%s",&s1); scanf("%s",&s2); // printf("%s %s\n",s1,s2); int n=strlen(s1),m=strlen(s2); int ans=sol(s1,s2,n,m); printf("%d\n",n+m-ans); } return 0; } ================================================ FILE: Algorithms/DP/Largest Divisible Subset.cpp ================================================ #include using namespace std; /* Given an array of distinct posotive integers,find the largest subset such that every pair(a1,a2) of elements in this subset satisfies a1 % a2 = 0 or a2 % a1 = 0 Note - In case of multiple sych solutions return any subset. Example 1: Input : [1 , 2 , 3] Output : [1 , 2] or [1 , 3] Example 2: Input : [1 , 2 , 4 , 8] Output : [1 , 2 , 4 , 8] */ vector largestDivisibleSubset(vector& nums) { int n = nums.size(); vectorans; int max = 1; sort(nums.begin(),nums.end()); vectordp(n+1,1); for(int i=1;idp[i]) { dp[i]=1+dp[j]; if(max=0;i--) { if(dp[i]==max&&(prev%nums[i]==0||prev==-1)){ ans.push_back(nums[i]); max-=1; prev=nums[i]; } } return ans; } } int main() { int n; cout << "array size : "; cin >> n; vector arr(n); cout << "array element :\n"; for(int i=0;i>arr[i]; } cout << largestDivisibleSubset(arr) << endl; return 0; } ================================================ FILE: Algorithms/DP/Largest divisible subset in array/file.py ================================================ # Python 3 program to find largest divisible subset in a given array # Prints largest divisible subset def findLargest(arr, n): # We first sort the array so that all divisors of a number are before it. arr.sort(reverse = False) # To store count of divisors of all elements divCount = [1 for i in range(n)] # To store previous divisor in result prev = [-1 for i in range(n)] # To store index of largest element in maximum size subset max_ind = 0 # In i'th iteration, we find length of chain ending with arr[i] for i in range(1,n): # Consider every smaller element as previous element. for j in range(i): if (arr[i] % arr[j] == 0): if (divCount[i] < divCount[j] + 1): divCount[i] = divCount[j]+1 prev[i] = j # Update last index of largest subset if size of current subset is more. if (divCount[max_ind] < divCount[i]): max_ind = i # Print result k = max_ind while (k >= 0): print(arr[k],end = " ") k = prev[k] # Driven code if __name__ == '__main__': arr = [1, 2, 17, 4] n = len(arr) findLargest(arr, n) ================================================ FILE: Algorithms/DP/Largest_Divisible_Subset.js ================================================ var largestDivisibleSubset = function(nums) { if(nums.length < 2) return nums; let n = nums.length; nums.sort((a,b) => a - b) let dp = Array(n).fill(1); let parent = Array(n); for(let i = 0; i < n; i++) parent[i] = i; for(let i = 0; i < n; i++) { for(let j = 0; j < i; j++) { if(nums[i] % nums[j] === 0) { if(dp[j] + 1 > dp[i]) { dp[i] = dp[j] + 1; parent[i] = j; } } } } let max = Math.max(...dp) let maxIndex = -1; for(let i = 0; i < n; i++ ) { if(dp[i] == max) { maxIndex = i; break; } } let ans = []; let member = maxIndex; while(true) { ans.push(member) if(parent[member] == member) { break; } member = parent[member]; } return ans.reverse().map(i => nums[i]) }; ================================================ FILE: Algorithms/DP/Largest_Divisible_Subsets.java ================================================ import java.util.*; public class DivSubset { public static int[][] dp; static void findLargest(int[] arr) { int divCount[] = new int[arr.length]; Arrays.fill(divCount, 1); int prev[] = new int[arr.length]; Arrays.fill(prev, -1); int max_ind = 0; for (int i = 1; i < arr.length; i++) { for (int j = 0; j < i; j++) { if (arr[i] % arr[j] == 0 && divCount[i] < divCount[j] + 1) { prev[i] = j; divCount[i] = divCount[j] + 1; } } if (divCount[i] > divCount[max_ind]) max_ind = i; } int k = max_ind; while (k >= 0) { System.out.print(arr[k] + " "); k = prev[k]; } } public static void main(String[] args) { int[] x = { 1, 2, 17, 4}; Scanner s = new Scanner(System.in); System.out.println("Enter number of elements"); int n = s.nextInt(); int arr[]=new int[n]; System.out.println("Enter elements"); for(int i=0;i #include"include/functions.h" int Kadane(int arr[], int size) { int max_so_far=0; int max_ending_here=0; for(int i=0; i #include "include/functions.h" using namespace std; int main() { int size; cout<<"Enter the size of the array: "; cin>>size; int arr[size]; cout<<"Enter array elements"<>arr[i]; } cout<<"The largest contiguous subsequence sum for the given array is:"< #include #include using namespace std; int main() { //code int T; cin>>T; while(T--) { int n; cin>>n; vector v(n,0); for(int i=0;i>v[i]; } int sum=INT_MIN; int maxSum=INT_MIN; for(int i=0;i0) { sum+=v[i]; } else { sum=v[i]; } maxSum=max(sum,maxSum); } cout< int Kadane(int arr[], int size) { int max_so_far=0; int max_ending_here=0; for(int i=0; i arr.every(n => n > 0) let allNegatives = arr => arr.every(n => n < 0) let sum = arr => arr.reduce((curr_max, max_so_far) => curr_max + max_so_far, 0) var maxSequence = function(arr){ if(arr.length === 0 || allNegatives(arr)) return 0; if(allPositives(arr)) return sum(arr); var curr_max = 0, max_so_far = 0; for(var i = 0; i < arr.length; i++){ curr_max = Math.max(0, curr_max + arr[i]); max_so_far = Math.max(curr_max, max_so_far); } return max_so_far; } ================================================ FILE: Algorithms/DP/Largest_Sum_Contiguous_Subarray/LSCS.swift ================================================ func maxSubArray(_ array: [Int]) -> Int { var currentSum = 0 var result = Int.min for i in 0 ..< array.count { currentSum = max(array[i], array[i] + currentSum) result = max(result, currentSum) } return result } var array:[Int] = [-2, -3, 4, -1, -2, 1, 5, -3] let max_sum = maxSubArray(array) print("Maximum continous sum is \(max_sum)") ================================================ FILE: Algorithms/DP/Largest_Sum_Contiguous_Subarray/lscs.c ================================================ #include int max(int a,int b) { if(a>b) { return a; } return b; } int maxSubArray(int* nums, int numsSize){ int i,ans; int maxSum[numsSize+1]; for(i=0;i using std::vector; using std::tuple; /* * Take out adding\removing logic into separate class. * It provides functions to add and remove numbers from * our structure, while maintaining cnt[] and current_answer. * */ struct Mo { static constexpr int MAX_VALUE = 1005000; vector cnt; long long current_answer; void process(int number, int delta) { current_answer -= cnt[number] * cnt[number] * number; cnt[number] += delta; current_answer += cnt[number] * cnt[number] * number; } public: Mo() { cnt = vector(MAX_VALUE, 0); current_answer = 0; } long long get_answer() const { return current_answer; } void add(int number) { process(number, 1); } void remove(int number) { process(number, -1); } }; int main() { int N, Q, BLOCK_SIZE; std::cin.sync_with_stdio(false); std::cin >> N >> Q; BLOCK_SIZE = static_cast(sqrt(N)); // No global variables, everything inside. vector arr(N); vector answers(Q); vector< tuple > queries; queries.reserve(Q); for(int i = 0; i < N; i++) std::cin >> arr[i]; for(int i = 0; i < Q; i++) { int le, rg; std::cin >> le >> rg; queries.emplace_back(le, rg, i); } // Comparator as a lambda-function, which catches BLOCK_SIZE // from the above definition. auto mo_cmp = [BLOCK_SIZE](const tuple &x, const tuple &y) -> bool { int block_x = std::get<0>(x) / BLOCK_SIZE; int block_y = std::get<0>(y) / BLOCK_SIZE; if(block_x != block_y) return block_x < block_y; return std::get<1>(x) < std::get<1>(y); }; std::sort(queries.begin(), queries.end(), mo_cmp); Mo solver; int mo_left = 0, mo_right = -1; // Usual Mo's algorithm stuff. for(const auto &q: queries) { int left, right, answer_idx; std::tie(left, right, answer_idx) = q; while(mo_right < right) { mo_right++; solver.add(arr[mo_right]); } while(mo_right > right) { solver.remove(arr[mo_right]); mo_right--; } while(mo_left < left) { solver.remove(arr[mo_left]); mo_left++; } while(mo_left > left) { mo_left--; solver.add(arr[mo_left]); } answers[answer_idx] = solver.get_answer(); } for(int i = 0; i < Q; i++) std::cout << answers[i] << "\n"; return 0; } ================================================ FILE: Algorithms/DP/Max_Product_Subarray/max_product_subarray.py ================================================ def max_product(nums): n = len(nums) ans = nums[0] maxy = mini = ans for i in range(1, n): if nums[i] < 0: maxy, mini = mini, maxy maxy = max(nums[i], maxy * nums[i]) mini = min(nums[i], mini * nums[i]) ans = max(ans, maxy) return ans if __name__ == '__main__': ans = max_product([2, 3, -2, 4]) assert ans == 6, "Wrong answer" print(ans) ================================================ FILE: Algorithms/DP/Maximum_Achievable_Coins/Maximum_Achievable_Coins.php ================================================ ================================================ FILE: Algorithms/DP/Maximum_Achievable_Coins/Maximum_Achievable_coins.c ================================================ #include void swap(int *xp, int *yp) { int temp = *xp; *xp = *yp; *yp = temp; } // A function to implement bubble sort void bubbleSort(int arr[], int n) { int i, j; for (i = 0; i < n-1; i++) // Last i elements are already in place for (j = 0; j < n-i-1; j++) if (arr[j] > arr[j+1]) swap(&arr[j], &arr[j+1]); } int main(void) { int numb; //I am assuming even input for numb scanf("%d",&numb); int coins[numb]; for(int i=0;i(numb/2)-1;i--)//looks complicated but i dont wanna use many variable to depict all the calculation sum += coins[i]; printf("%d",sum); return 0; } ================================================ FILE: Algorithms/DP/Maximum_Achievable_Coins/Maximum_Achievable_coins.java ================================================ class MaximumAchievablecoins { static int Maximum_Achievable_coins( int arr[], int n) { int table[][] = new int[n][n]; int gap, i, j, x, y, z; for (gap = 0; gap < n; ++gap) { for (i = 0, j = gap; j < n; ++i, ++j) { x = ((i + 2) <= j) ? table[i + 2][j] : 0; y = ((i + 1) <= (j - 1)) ? table[i + 1][j - 1] : 0; z = (i <= (j - 2)) ? table[i][j - 2] : 0; table[i][j] = Math.max( arr[i] + Math.min(x, y), arr[j] + Math.min(y, z)); } } return table[0][n - 1]; } public static void main(String[] args) { int arr1[] = { 8, 15, 3, 7 }; int n = arr1.length; System.out.println( "" + Maximum_Achievable_coins(arr1, n)); int arr2[] = { 2, 2, 2, 2 }; n = arr2.length; System.out.println( "" + Maximum_Achievable_coins(arr2, n)); int arr3[] = { 20, 30, 2, 2, 2, 10 }; n = arr3.length; System.out.println( "" + Maximum_Achievable_coins(arr3, n)); } } ================================================ FILE: Algorithms/DP/Maximum_Achievable_Coins/Maximum_Achievable_coins.py ================================================ def Maximum_Achievable_coins(arr, n): matrix = [[0 for x in range(n)] for y in range(n)] for diagonal in range(n): for j in range(diagonal,n): i = j - diagonal x = 0 if( (i+2) <= j): x = matrix[i+2][j] y = 0 if( (i+1) <= (j-1)): y = matrix[i+1][j-1] z = 0 if( i <= (j-2)): z = matrix[i][j-2] matrix[i][j] = max(arr[i]+min(x,y), arr[j]+min(y,z)) return print("The maximum possible amount of money that we can definitely win if we move first is: "+str(matrix[0][n-1])) if __name__ == '__main__': n = int(input('Coin numbers: ')) arr = [] [arr.append(int(input('Coin number '+str(x+1)+' : '))) for x in range(n)] Maximum_Achievable_coins(arr, n) ================================================ FILE: Algorithms/DP/Maximum_Achievable_Coins/maximum_achievable_coins.cpp ================================================ #include using namespace std; int optimalStrategyOfGame( int* arr, int n) { int table[n][n]; for (int gap = 0; gap < n; ++gap) { for (int i = 0, j = gap; j < n; ++i, ++j) { int x = ((i + 2) <= j) ? table[i + 2][j] : 0; int y = ((i + 1) <= (j - 1)) ? table[i + 1][j - 1] : 0; int z = (i <= (j - 2)) ? table[i][j - 2] : 0; table[i][j] = max( arr[i] + min(x, y), arr[j] + min(y, z)); } } return table[0][n - 1]; } int main() { int *arr; int n; cin>>n; arr = new int[n]; for(int i = 0; i < n; ++i) cin>>arr[i]; printf("%d\n", optimalStrategyOfGame(arr, n)); return 0; } ================================================ FILE: Algorithms/DP/Minimum_Sum_Descent/min-sum.c ================================================ /* * Contributor: Jean Choi * Minimum-Sum Descent * * Some positive integers are arranged in an equilateral triangle * with n numbers in its base like the one shown in the figure below * for n = 4. * * This program finds the the smallest sum in a descent * from the triangle apex to its base through a sequence * of adjacent numbers (shown in the figure by dashes). * * -2- * -5- 4 * -1- 4 7 * 8 -6- 9 6 * */ #include #include /* * Finds the minimum between two integers */ int minimum(int a, int b){ return (a < b) ? a : b; } /* * Tabular Solution for created pyramid */ int tabular(int ** arr, int n){ for(int r = n; r >= 0; r--){ for(int c = 0; c <= r; c++){ if(r == n) arr[r][c] = arr[r][c]; else arr[r][c] = arr[r][c] + minimum(arr[r+1][c], arr[r+1][c+1]); } } return arr[0][0]; } int main(){ //get number of levels in pyramid int levels; printf("Enter number of levels: "); scanf("%d", &levels); //allocate pyramid[][] int **pyramid; pyramid = malloc(levels * sizeof *pyramid); for (int i=0; i < levels; i++) { pyramid[i] = malloc(levels * sizeof *pyramid[i]); } //get values for pyramid[][] printf("Please only enter positive integers\n"); for(int r = 0; r <= levels-1; r++) { printf("Enter %d items for level %d: ", r+1, r); for(int c = 0; c <= r; c++) { scanf("%d", &pyramid[r][c]); } } //print pyramid[][] printf("Here's the pyramid: \n"); for (int r = 0; r < levels; r++){ for (int c = 0; c <= r; c++){ printf("%d ", pyramid[r][c]); } printf("\n"); } printf("Minimum-Sum Descent for created pyramid (Tabular): %d\n", tabular(pyramid, levels-1)); // deallocate the array for (int i=0; i> A = new List>(); A.Add(new List { 2 }); A.Add(new List { 3, 9 }); A.Add(new List { 1, 6, 7 }); Console.WriteLine(Triangle.minSumPath(ref A)); } } class Triangle { // Function to find minimum sum for a path public static int minSumPath(ref List> A) { // Storing the result in a array and simultaneously updating the result int[] memo = new int[A.Count]; int n = A.Count - 1; // For the bottom row for (int i = 0; i < A[n].Count; i++) memo[i] = A[n][i]; // Calculation of the remaining rows for (int i = A.Count - 2; i >= 0; i--) for (int j = 0; j < A[i + 1].Count - 1; j++) memo[j] = A[i][j] + (int)Math.Min(memo[j], memo[j + 1]); // Return the top element return memo[0]; } } } ================================================ FILE: Algorithms/DP/Minimum_Sum_Descent/minsum.go ================================================ package main import ( "fmt" ) func main() { //get number of levels in pyramid var levels int fmt.Println("Enter number of levels: ") fmt.Scan(&levels) //allocate pyramid[][] pyramid := make([][]int, levels) for i := range pyramid { pyramid[i] = make([]int, levels) } //get values for pyramid[][] fmt.Println("Please only enter positive integers") for r := 0; r <= levels-1; r++ { fmt.Printf("Enter %d items for level %d: ", r+1, r) for c := 0; c <= r; c++ { fmt.Scan(&pyramid[r][c]) } } //print pyramid[][] fmt.Println("Here's the pyramid: ") for r := 0; r < levels; r++ { for c := 0; c <= r; c++ { fmt.Printf("%d ", pyramid[r][c]) } fmt.Println("") } fmt.Printf("Minimum-Sum Descent for created pyramid (Tabular): %d", tabular(pyramid, levels-1)) fmt.Println("") } /* * Finds the minimum between two integers */ func minimum(a, b int) int { if a < b { return a } return b } /* * Tabular Solution for created pyramid */ func tabular(arr [][]int, n int) int { for r := n; r >= 0; r-- { for c := 0; c <= r; c++ { if r != n { arr[r][c] = arr[r][c] + minimum(arr[r+1][c], arr[r+1][c+1]) } } } return arr[0][0] } ================================================ FILE: Algorithms/DP/Minimum_Sum_Descent/minsum.ts ================================================ /* Implementation of Dynamic programming of Minimum sum descent in TypeScript */ const minSum = (triangle: number[][]) => { let memo: number[] = []; let n = triangle.length - 1; // memo for bottom row for (let i = 0; i < triangle[n].length; i++) { memo[i] = triangle[n][i]; } // Calculating the remaining rows in bottom-up manner for (let i = triangle.length - 2; i >= 0; i--) { for (let j = 0; j < triangle[i].length; j++) { memo[j] = triangle[i][j] + Math.min(memo[j], memo[j + 1]); } } return memo[0]; }; const triangle = [[2], [3, 9], [1, 6, 7]]; console.log(minSum(triangle)); ================================================ FILE: Algorithms/DP/Partition_Sum/DP_PartitionSum.java ================================================ //Code contributed by Aditya Prakash(@PrakashAditya17) import java.io.*; import java.util.*; public class DP_PartitionSum { public static boolean checking(int arr[],int SUM) { int len=arr.length; //arr2[i][j] ->true , when there's subset of arr[0..j-1] having sum=i. boolean arr2[][]=new boolean[SUM+1][len+1]; //Here sum->0, then its set true. for(int i=0;i<=len;i++) arr2[0][i]=true; //The 0th column is false because sum not equals 0(Except arr[0][0]) for (int i = 1; i<=SUM;i++) arr2[i][0]=false; //Rest of the 2d matrix DP is filled up in bottom up manner for (int i=1;i<= SUM;i++) { for (int j=1;j<=len;j++) { arr2[i][j]=arr2[i][j-1]; if (i>=arr[j - 1]) arr2[i][j]=arr2[i][j] || arr2[i-arr[j-1]][j-1]; } } //The corner most element is where the answer is stored. return(arr2[SUM][len]); } public static void main(String[] args) { Scanner sc=new Scanner(System.in); int n; System.out.println("Enter array size and the array"); n=sc.nextInt(); int sum=0; int a[]=new int[n]; for(int i=0;i // Returns true if arr[] can be partitioned in two subsets of equal sum, otherwise false int findPartiion (int arr[], int n) { int sum = 0; int i, j; // Calculate sum of all elements for (i = 0; i < n; i++) sum += arr[i]; if (sum%2 != 0) return 0; int part[sum/2+1][n+1]; // initialize top row as true for (i = 0; i <= n; i++) part[0][i] = 1; // initialize leftmost column, except part[0][0], as 0 for (i = 1; i <= sum/2; i++) part[i][0] = 0; // Fill the partition table in bottom up manner for (i = 1; i <= sum/2; i++) { for (j = 1; j <= n; j++) { part[i][j] = part[i][j-1]; if (i >= arr[j-1]) part[i][j] = part[i][j] || part[i - arr[j-1]][j-1]; } } return part[sum/2][n]; } // Driver program to test above function int main() { int n,i; int arr[10000]; scanf("%d", &n); for(i=0;i using namespace std; // Returns true if arr[] can be partitioned in two subsets of equal sum, otherwise false bool findPartiion (int arr[], int n) { int sum = 0; int i, j; // Calculate sum of all elements for (i = 0; i < n; i++) sum += arr[i]; if (sum % 2 != 0) return false; bool part[sum / 2 + 1][n + 1]; // initialize top row as true for (i = 0; i <= n; i++) part[0][i] = true; // initialize leftmost column, // except part[0][0], as 0 for (i = 1; i <= sum / 2; i++) part[i][0] = false; // Fill the partition table in bottom up manner for (i = 1; i <= sum / 2; i++) { for (j = 1; j <= n; j++) { part[i][j] = part[i][j - 1]; if (i >= arr[j - 1]) part[i][j] = part[i][j] || part[i - arr[j - 1]][j - 1]; } } return part[sum / 2][n]; } // Driver Code int main() { int n; cin>>n; int arr[n]; for(int i=0;i>arr[i]; if (findPartiion(arr, n) == true) cout << "Can be divided into two subsets of equal sum"; else cout << "Can not be divided into" << " two subsets of equal sum"; return 0; } ================================================ FILE: Algorithms/DP/Partition_Sum/partition_sum.cs ================================================ // A recursive C# solution for partition problem using System; class GFG { // A utility function that returns true if there is a // subset of arr[] with sun equal to given sum static bool isSubsetSum(int[] arr, int n, int sum) { // Base Cases if (sum == 0) return true; if (n == 0 && sum != 0) return false; // If last element is greater than sum, then ignore // it if (arr[n - 1] > sum) return isSubsetSum(arr, n - 1, sum); /* else, check if sum can be obtained by any of the following (a) including the last element (b) excluding the last element */ return isSubsetSum(arr, n - 1, sum) || isSubsetSum(arr, n - 1, sum - arr[n - 1]); } // Returns true if arr[] can be partitioned in two // subsets of equal sum, otherwise false static bool findPartition(int[] arr, int n) { // Calculate sum of the elements in array int sum = 0; for (int i = 0; i < n; i++) sum += arr[i]; // If sum is odd, there cannot be two subsets // with equal sum if (sum % 2 != 0) return false; // Find if there is subset with sum equal to half // of total sum return isSubsetSum(arr, n, sum / 2); } // Driver code public static void Main() { int[] arr = { 3, 1, 5, 9, 12 }; int n = arr.Length; // Function call if (findPartition(arr, n) == true) Console.Write("Can be divided into two " + "subsets of equal sum"); else Console.Write("Can not be divided into " + "two subsets of equal sum"); } } ================================================ FILE: Algorithms/DP/Partition_Sum/partition_sum.php ================================================ $target) { // The largest number is already larger than the target value, no point in trying to partition with equal sums. return []; } for ($i = $numElements - 2; $i >= 0; $i--) { for ($j = $i; $j >= 0; $j--) { $n = $temp[$j]; if ($sum + $n <= $target) { $usedElements[$j] = true; $sum += $n; } if ($sum === $target) { break 2; } } // Remove everything we tried so far for ($j = $i; $j >= 0; $j--) { if ($usedElements[$j]) { $usedElements[$j] = false; $sum -= $temp[$j]; } } } if ($sum !== $target) { return []; } $firstPartition = []; $secondPartition = []; for ($i = 0; $i < count($usedElements); $i++) { if ($usedElements[$i]) { $firstPartition[] = $temp[$i]; } else { $secondPartition[] = $temp[$i]; } } return [$firstPartition, $secondPartition]; } $array = [2, 4, 5, 6, 7, 8, 10]; $result = partitionSum($array); if (count($result) > 0) { printf("[%s]\n[%s]", implode(', ', $result[0]), implode(', ', $result[1])); } else { print 'Could not split array in two partitions with equals sums.'; } ================================================ FILE: Algorithms/DP/README.md ================================================ # This folder is empty. ================================================ FILE: Algorithms/DP/Recaman's Sequence.c ================================================ #include int main() { int i,j,a[101],gd,gm; float s=6.0; char text[80]; detectgraph(&gd,&gm); initgraph(&gd,&gm,NULL); setbkcolor(15); cleardevice(); setcolor(0); settextstyle(0,0,3); line(0,350,1400,350); delay(2000); a[0]=0; for(i=1;i<=100;i++) { j=i; if(a[i-1]-i>0) { for(j=i;j>0;j--) { if(a[j]==a[i-1]-i) break; } } if(j==0) a[i]=a[i-1]-i; else a[i]=a[i-1]+i; sprintf(text,"Recaman(%d) = %d ",i,a[i]); outtextxy(0,0,text); if(i%2==1) arc((a[i]+a[i-1])/2.0*s,350,0,180,abs(a[i]-a[i-1])/2.0*s); else arc((a[i]+a[i-1])/2.0*s,350,180,360,abs(a[i]-a[i-1])/2.0*s); Sleep(500); } getch(); closegraph(); return 0; } ================================================ FILE: Algorithms/DP/Scramble Strings/ScrambleString.cpp ================================================ #include using namespace std; unordered_mapmp; bool scramble(string s1,string s2) { if(s1==s2) return true; if(s1.length()<=1) return false; string key=s1+" "+s2; if(mp.find(key)!=mp.end()) return mp[key]; int n=s1.length(); bool flag=false; for(int i=1;i<=n-1;i++) { if((scramble(s1.substr(0,i),s2.substr(n-i,i)) && scramble(s1.substr(i,n-i),s2.substr(0,n-i)) )|| (scramble(s1.substr(0,i),s2.substr(0,i)) && scramble(s1.substr(i,n-i),s2.substr(i,n-i)) ) ) { flag=true; break; } } return mp[key]=flag; } bool isScramble(string s1, string s2) { if(s1.length()!=s2.length()) return false; if(s1.length()==0 && s2.length()==0) return true; mp.clear(); return scramble(s1,s2); } int main() { string s1,s2; cin>>s1>>s2; bool ans=isScramble(s1,s2); cout< 0 && j > 0){ if(str1.charAt(i-1) == str2.charAt(j-1)){ sb.append(str1.charAt(i-1)); i--; j--; } else{ if(dp[i-1][j]+1 == dp[i][j]){ sb.append(str1.charAt(i-1)); i--; } else{ sb.append(str2.charAt(j-1)); j--; } } } while(i > 0){ sb.append(str1.charAt(i-1)); i--; } while(j > 0){ sb.append(str2.charAt(j-1)); j--; } return sb.reverse().toString(); } } ================================================ FILE: Algorithms/DP/Shortest_Common_Supersequence/shortest_common_supersequence.cpp ================================================ #include using namespace std; int max(int a, int b) { return (a > b)? a : b; } int lcs(string X, string Y, int m, int n); int shortestSuperSequence(string X, string Y) { int m = X.length(); int n = Y.length(); int l = lcs(X, Y, m, n); return (m + n - l); } int lcs(string X,string Y,int m,int n) { int dp[m+1][n+1]; int i,j; for(i=0;i<=m;i++) { for(j=0;j<=n;j++) { if(i == 0 || j == 0) dp[i][j] = 0; else if(X[i-1] == Y[j-1]) dp[i][j] = dp[i-1][j-1] + 1; else dp[i][j] = max(dp[i-1][j],dp[i][j-1]); } } return dp[m][n]; } int main() { string s1,s2; cout<<"Enter the first string :"<<"\n"; cin>>s1; cout<<"\nEnter the second string :"<<"\n"; cin>>s2; cout<<"\nLength of the shortest common supersequence is "< 0 && j > 0) { if (X[i - 1] == Y[j - 1]) { str += (X[i - 1]); i--; j--; index--; } else if (dp[i - 1, j] > dp[i, j - 1]) { str += (Y[j - 1]); j--; index--; } else { str += (X[i - 1]); i--; index--; } } while (i > 0) { str += (X[i - 1]); i--; index--; } while (j > 0) { str += (Y[j - 1]); j--; index--; } str = reverse(str); return str; } static String reverse(String input) { char[] temparray = input.ToCharArray(); int left, right = 0; right = temparray.Length - 1; for (left = 0; left < right; left++, right--) { char temp = temparray[left]; temparray[left] = temparray[right]; temparray[right] = temp; } return String.Join("",temparray); } // code public static void Main(String[] args) { String X; String Y; X = Console.ReadLine(); Y = Console.ReadLine(); Console.WriteLine(printShortestSuperSeq(X, Y)); } } ================================================ FILE: Algorithms/DP/Shortest_Common_Supersequence/shortest_common_supersequence.js ================================================ const readline = require('readline') const reader = readline.createInterface(process.stdin, process.stdout); function shortestCommonSuperstring(str1, str2) { let m = str1.length, n = str2.length let dp = Array(m+1) for(let i=0;i<=m;++i) { dp[i] = Array(n+1) for(let j=0;j<=n;++j) { if(i === 0) dp[i][j] = j else if(j === 0) dp[i][j] = i else if(str1.charAt(i-1) === str2.charAt(j-1)) dp[i][j] = 1 + dp[i - 1][j - 1] else dp[i][j] = 1 + Math.min(dp[i - 1][j], dp[i][j - 1]) } } return dp[m][n] } reader.question('Enter two string seperated by space: ', string => { let string_arr = string.split(" ") console.log("Length of the shortest supersequence is " + shortestCommonSuperstring(string_arr[0], string_arr[1])) reader.close() }) ================================================ FILE: Algorithms/DP/Shortest_Common_Supersequence/shortest_common_supersequence.py ================================================ # This algorithm finds the shortest common supersequence of 2 strings - # the shortest string that has both str1 and str2 as subsequences. # If 'm' is the length of the first string and 'n' is the length of # the second string, then this algo takes O(m * n) time and O(m * n) space. # Returns length of the shortest supersequence of X and Y def superSeq(X, Y, m, n): dp = [[0] * (n + 2) for i in range(m + 2)] # Fill table in bottom up manner for i in range(m + 1): for j in range(n + 1): #Below steps follow above recurrence if (not i): dp[i][j] = j elif (not j): dp[i][j] = i elif (X[i - 1] == Y[j - 1]): dp[i][j] = 1 + dp[i - 1][j - 1] else: dp[i][j] = 1 + min(dp[i - 1][j], dp[i][j - 1]) return dp[m][n] # Driver Code X = "AGGTAB" Y = "GXTXAYB" print("Length of the shortest supersequence is %d" % superSeq(X, Y, len(X), len(Y))) # This code is contributed by Ansu Kumari ================================================ FILE: Algorithms/DP/Sudoku_Solver/README.md ================================================ ## This folder is empty. ================================================ FILE: Algorithms/DP/Sudoku_Solver/SudokuSolver.java ================================================ import java.util.*; import java.io.*; class SudokuSolver { static class FastReader{ BufferedReader br; StringTokenizer st; FastReader(){ br = new BufferedReader(new InputStreamReader(System.in)); } String next(){ while(st==null || !st.hasMoreElements()){ try{ st =new StringTokenizer(br.readLine()); } catch(IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt(){ return Integer.parseInt(next()); } } public static void main(String[] args) { FastReader fr = new FastReader(); int n = fr.nextInt(); int[][] board = new int[n][n]; for(int i=0;i using namespace std; #define UNASSIGNED 0 #define N 9 bool FindUnassignedLocation(int grid[N][N], int& row, int& col); bool isSafe(int grid[N][N], int row, int col, int num); bool SolveSudoku(int grid[N][N]) { int row, col; if (!FindUnassignedLocation(grid, row, col)) return true; for (int num = 1; num <= 9; num++) { if (isSafe(grid, row, col, num)) { grid[row][col] = num; if (SolveSudoku(grid)) return true; grid[row][col] = UNASSIGNED; } } return false; } bool FindUnassignedLocation(int grid[N][N], int& row, int& col) { for (row = 0; row < N; row++) for (col = 0; col < N; col++) if (grid[row][col] == UNASSIGNED) return true; return false; } bool UsedInRow(int grid[N][N], int row, int num) { for (int col = 0; col < N; col++) if (grid[row][col] == num) return true; return false; } bool UsedInCol(int grid[N][N], int col, int num) { for (int row = 0; row < N; row++) if (grid[row][col] == num) return true; return false; } bool UsedInBox(int grid[N][N], int boxStartRow, int boxStartCol, int num) { for (int row = 0; row < 3; row++) for (int col = 0; col < 3; col++) if (grid[row + boxStartRow] [col + boxStartCol] == num) return true; return false; } bool isSafe(int grid[N][N], int row, int col, int num) { return !UsedInRow(grid, row, num) && !UsedInCol(grid, col, num) && !UsedInBox(grid, row - row % 3, col - col % 3, num) && grid[row][col] == UNASSIGNED; } void printGrid(int grid[N][N]) { for (int row = 0; row < N; row++) { for (int col = 0; col < N; col++) cout << grid[row][col] << " "; cout << endl; } } int main() { int grid[N][N] = { { 3, 0, 6, 5, 0, 8, 4, 0, 0 }, { 5, 2, 0, 0, 0, 0, 0, 0, 0 }, { 0, 8, 7, 0, 0, 0, 0, 3, 1 }, { 0, 0, 3, 0, 1, 0, 0, 8, 0 }, { 9, 0, 0, 8, 6, 3, 0, 0, 5 }, { 0, 5, 0, 0, 9, 0, 6, 0, 0 }, { 1, 3, 0, 0, 0, 0, 2, 5, 0 }, { 0, 0, 0, 0, 0, 0, 0, 7, 4 }, { 0, 0, 5, 2, 0, 6, 3, 0, 0 } }; if (SolveSudoku(grid) == true) printGrid(grid); else cout << "No solution exists"; return 0; } ================================================ FILE: Algorithms/DP/Sudoku_Solver/Sudoku_Solver.cs ================================================ using System; class GFG { public static bool isSafe(int[, ] board, int row, int col, int num) { for (int d = 0; d < board.GetLength(0); d++) { if (board[row, d] == num) { return false; } } for (int r = 0; r < board.GetLength(0); r++) { if (board[r, col] == num) { return false; } } int sqrt = (int)Math.Sqrt(board.GetLength(0)); int boxRowStart = row - row % sqrt; int boxColStart = col - col % sqrt; for (int r = boxRowStart; r < boxRowStart + sqrt; r++) { for (int d = boxColStart; d < boxColStart + sqrt; d++) { if (board[r, d] == num) { return false; } } } return true; } public static bool solveSudoku(int[, ] board, int n) { int row = -1; int col = -1; bool isEmpty = true; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (board[i, j] == 0) { row = i; col = j; isEmpty = false; break; } } if (!isEmpty) { break; } } if (isEmpty) { return true; } for (int num = 1; num <= n; num++) { if (isSafe(board, row, col, num)) { board[row, col] = num; if (solveSudoku(board, n)) { // print(board, n); return true; } else { board[row, col] = 0; } } } return false; } public static void print(int[, ] board, int N) { for (int r = 0; r < N; r++) { for (int d = 0; d < N; d++) { Console.Write(board[r, d]); Console.Write(" "); } Console.Write("\n"); if ((r + 1) % (int)Math.Sqrt(N) == 0) { Console.Write(""); } } } public static void Main(String[] args) { int[, ] board = new int[, ] { { 3, 0, 6, 5, 0, 8, 4, 0, 0 }, { 5, 2, 0, 0, 0, 0, 0, 0, 0 }, { 0, 8, 7, 0, 0, 0, 0, 3, 1 }, { 0, 0, 3, 0, 1, 0, 0, 8, 0 }, { 9, 0, 0, 8, 6, 3, 0, 0, 5 }, { 0, 5, 0, 0, 9, 0, 6, 0, 0 }, { 1, 3, 0, 0, 0, 0, 2, 5, 0 }, { 0, 0, 0, 0, 0, 0, 0, 7, 4 }, { 0, 0, 5, 2, 0, 6, 3, 0, 0 } }; int N = board.GetLength(0); if (solveSudoku(board, N)) { print(board, N); // print solution } else { Console.Write("No solution"); } } } ================================================ FILE: Algorithms/DP/Sudoku_Solver/Sudoku_Solver.js ================================================ // I solved this question with backtracking algorithm: const _board = [ ['.', '9', '.', '.', '4', '2', '1', '3', '6'], ['.', '.', '.', '9', '6', '.', '4', '8', '5'], ['.', '.', '.', '5', '8', '1', '.', '.', '.'], ['.', '.', '4', '.', '.', '.', '.', '.', '.'], ['5', '1', '7', '2', '.', '.', '9', '.', '.'], ['6', '.', '2', '.', '.', '.', '3', '7', '.'], ['1', '.', '.', '8', '.', '4', '.', '2', '.'], ['7', '.', '6', '.', '.', '.', '8', '1', '.'], ['3', '.', '.', '.', '9', '.', '.', '.', '.'], ]; sodokuSolver(_board); console.log(_board); function isValid(board, row, col, k) { for (let i = 0; i < 9; i++) { const m = 3 * Math.floor(row / 3) + Math.floor(i / 3); const n = 3 * Math.floor(col / 3) + i % 3; if (board[row][i] == k || board[i][col] == k || board[m][n] == k) { return false; } } return true; } function sodokuSolver(data) { for (let i = 0; i < 9; i++) { for (let j = 0; j < 9; j++) { if (data[i][j] == '.') { for (let k = 1; k <= 9; k++) { if (isValid(data, i, j, k)) { data[i][j] = `${k}`; if (sodokuSolver(data)) { return true; } else { data[i][j] = '.'; } } } return false; } } } return true; } ================================================ FILE: Algorithms/DP/Target_Sum/Target_Sum.c ================================================ #include #include int CntSum(int arr[], int N, int required_sum) { int t[N+1][required_sum+1] , i ,j ; for(i = 0 ; i < N+1;i++) t[i][0] = 1; for(i = 1 ; i < required_sum+1;i++) t[0][i] = 0; for(i = 1; i < N+1;i++) { for(j = 1 ; j < required_sum+1;j++) { if(arr[i-1] <= j) t[i][j] = t[i-1][j-arr[i-1]]+t[i-1][j]; else t[i][j] = t[i-1][j]; } } return t[N][required_sum]; } int main() { int N , i; printf("Enter Size of Array :- \n"); scanf("%d",&N); int A[N]; printf("Enter Array Elements :- \n"); for(i = 0 ; i< N;i++) scanf("%d",&A[i]); printf("Enter Target Sum :- \n"); int X; scanf("%d",&X); long int ans = CntSum(A , N , X); printf("Count = %ld\n", ans); return 0; } ================================================ FILE: Algorithms/DP/Target_Sum/Target_Sum.cpp ================================================ #include using namespace std; int SubsetSum(int arr[],int n, int sum) { int t[n+1][sum+1]; for(int i=0;i>n; int arr[n]; cout<<"array element :\n"; for(int i=0;i>arr[i]; int sum; cout<<"sum :"; cin>>sum; cout<<"\ncount : "< "+dest); return; } // Move top n-1 disks from A to B using C as auxiliary. solveTowersOfHanoi(n-1, source, dest, aux); //Move remaining disks from A to C System.out.println(source+" --> "+dest); // Move n-1 disks from B to C using A as auxiliary solveTowersOfHanoi(n-1, aux, source, dest); } public static void main(String args[]) { TowersOfHanoi obj = new TowersOfHanoi(); System.out.println("Enter number of disks :- "); Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); scanner.close(); System.out.println("Move disks as below illustration."); obj.solveTowersOfHanoi(n, "A", "B", "C"); } } ================================================ FILE: Algorithms/DP/Tower_Of_Hanoi/Tower_Of_Hanoi.cs ================================================ using System; namespace Tower_Of_Hanoi { class Tower_Of_Hanoi { static void Main(string[] args) { int numOfDisks; char source = 'A', auxiliary = 'B', destination = 'C'; Console.WriteLine("The Tower of Hanoi consists of three rods and a number of disks of different sizes."); Console.Write("Enter the number of disks: "); numOfDisks = Convert.ToInt32(Console.ReadLine()); if(numOfDisks > 0) { TowerOfHanoi(numOfDisks, source, auxiliary, destination); } else { Console.WriteLine("The number should be greater than 0"); } } public static void TowerOfHanoi(int numDisk, char source, char auxiliary, char destination) { if (numDisk > 1) { TowerOfHanoi(numDisk - 1, source, auxiliary, destination); Console.WriteLine("Move disk " + numDisk + " from source " + source + " to destination " + destination); TowerOfHanoi(numDisk - 1, auxiliary, destination, source); } else { Console.WriteLine("Move disk 1 from cource " + source + " to destination " + destination); } } } } ================================================ FILE: Algorithms/DP/Tower_Of_Hanoi/Tower_Of_Hanoi.js ================================================ 'use strict'; function Tower_Of_Hanoi () { const game = { A : ['A'], B : ['B'], C : ['C'], print() { console.log(`${this.A} ${this.B} ${this.C}`) }, moveDiscs(n, source, dest, spare) { if (n === 1) { dest.push(1), source.pop() this.print(); } else { this.moveDiscs(n-1, source, spare, dest); dest.push(n); source.pop(); this.print(); this.moveDiscs(n-1, spare, dest, source); } }, play(n) { for (let i = n; i > 0; i--) this.A.push(i); this.print(); this.moveDiscs(n, this.A, this.B, this.C); } } return game; } const theGame = Tower_Of_Hanoi(); const readline = require("readline"); const rl = readline.createInterface({ input: process.stdin, output: process.stdout }); rl.question("Please enter the number of discs ? ", function(n) { theGame.play(n); rl.close() }); ================================================ FILE: Algorithms/DP/Tower_Of_Hanoi/Tower_of_hanoi.ts ================================================ function solveHanoi( counting: number, from: string, to: string, other: string, move: (from: string, to: string) => void ) { if (counting > 0) { solveHanoi(counting - 1, from, other, to, move) move(from, to) solveHanoi(counting - 1, other, to, from, move) } } // Example: six discs var moveCounting = 0 solveHanoi(6, "Left", "Right", "Middle", (from , to) => { ++moveCounting console.log(moveCounting + ": Move from " + from + " to " + to + ".") }) ================================================ FILE: Algorithms/DP/Tower_Of_Hanoi/tower_of_hanoi.c ================================================ #include void hanoi(char from, char helper, char to, int n) { //Base case - only one disk to move if (n == 1) { printf("Move disk 1 from tower %c to tower %c\n", from, to); return; } //When two or more disks must be moved we call the function again hanoi(from, to, helper, n - 1); printf("Move disk %d from tower %c to tower %c\n", n, from, to); hanoi(helper, from, to, n - 1); } int main() { int n; //Prompt for user interaction printf("Enter the number of disks to play: "); scanf_s("%d", &n); //Calculate the game moves hanoi('A', 'B', 'C', n); return 0; } ================================================ FILE: Algorithms/DP/Tower_Of_Hanoi/tower_of_hanoi.cpp ================================================ #include using namespace std; void towerOfHanoi(char from,char to,char aux,int n){ if(n == 1){ cout<<"Move disk 1 from rod "<>n; towerOfHanoi('A','C','B',n); return 0; } ================================================ FILE: Algorithms/DP/Tower_Of_Hanoi/tower_of_hanoi.go ================================================ package main import ( "fmt" ) //we will use a two-dimensional slice to hold our stacks //this representation of the stacks will use the first element of each //slice as the bottom (i.e. stacks[x][0]). the disc size will be //represented by the integer value, higher numbers meaning bigger discs var stacks = [][]int{ []int{}, []int{}, []int{}} func main() { //get tower height from user input var towerHeight int for towerHeight <= 1 { fmt.Println("Enter tower height") fmt.Scan(&towerHeight) } //initialize the first stack stacks[0] = make([]int, towerHeight) for i := range stacks[0] { stacks[0][i] = towerHeight - i } //display initial stack configuration fmt.Println("This is the starting position") printStacks() moveTower(towerHeight, 0, 2, 1) } func moveTower(height int, from int, to int, help int) { if height == 1 { //for one-disc-towers, there is nothing else to do but move the disc from start-stack to finish-stack moveDisc(height, from, to) } else { //for towers with more than one disk, we use recursion to moveTower(height-1, from, help, to) //move a smaller tower (all discs but the bottom) to the helper-stack moveDisc(height, from, to) //then move the bottom disc to the finish-stack moveTower(height-1, help, to, from) //and finally move the smaller tower from the helper stack on top of the bottom disk that now sits on the finish-stack } } func moveDisc(index int, from int, to int) { disc := stacks[from][len(stacks[from])-1] //get last element of the origin array stacks[from] = stacks[from][:len(stacks[from])-1] //new origin array will contain everything except the last element stacks[to] = append(stacks[to], disc) //append that element to the destination array fmt.Printf("Move disc %d from stack %d to stack %d\n", index, from+1, to+1) printStacks() } func printStacks() { //for the sake of simplicity, the display will just print out the slices for _, stack := range stacks { fmt.Println(stack) } fmt.Println() } ================================================ FILE: Algorithms/DP/Tower_Of_Hanoi/tower_of_hanoi.py ================================================ def TowerOfHanoi(n , source, destination, auxiliary): if n==1: print "Move disk 1 from source",source,"to destination",destination return TowerOfHanoi(n-1, source, auxiliary, destination) print "Move disk",n,"from source",source,"to destination",destination TowerOfHanoi(n-1, auxiliary, destination, source) n = int(input().strip()) TowerOfHanoi(n,'A','B','C') ================================================ FILE: Algorithms/DP/TrappingWater/TrappingWater.cpp ================================================ // Author - Nishit Bansal, Nishit278 @github // Solution using 2 pointer method // Time Complexity - O(n) #include using namespace std; int trap(vector& h) { int n = h.size(); int left = 0; int maxLeft = 0, maxRight = 0; int right = n-1; int ans = 0; while(left <= right){ if(h[left] <= h[right]){ if(maxLeft <= h[left]) maxLeft = h[left]; else ans+=maxLeft-h[left]; left++; } else { if(maxRight <= h[right]) maxRight = h[right]; else ans+=maxRight - h[right]; right--; } } return ans; } // Driver's code int main(){ int n; cin >> n; vector v(n); int x; for(int i=0;i>x; v[i] = x; } cout << trap(v) << endl; } ================================================ FILE: Algorithms/DP/Water_Area/QUESTION.md ================================================ ### Water Area You're given an array of non-negative integers where each non-zero integer represents the height of a pillar of width 1 . Imagine water being poured over all of the pillars; write a function that returns the surface area of the water trapped between the pillars viewed from the front. Note that spilled water should be ignored. ================================================ FILE: Algorithms/DP/Water_Area/Water-area.py ================================================ #O(N) T | O(1) S def waterArea(heights): water = 0 tallestRight = [0 for x in heights] maxHtRight = 0 tallestLeft = [0 for x in heights] maxHtLeft = 0 for i in reversed(range(len(tallestRight))): tallestRight[i] = maxHtRight maxHtRight = max(maxHtRight, heights[i]) for i in range(len(tallestLeft)): tallestLeft[i] = max(maxHtLeft, heights[i]) maxHtLeft = max(maxHtLeft,heights[i]) for i in range(len(heights)): leftMax = tallestLeft[i] rightMax = tallestRight[i] minHeight = min(leftMax, rightMax) height = heights[i] if height < minHeight: water += minHeight - height else: water += 0 return water heights = input('Enter a list of non-negative numbers separated by spaces without any enclosing braces\n') heights_str = list(heights.split(' ')) heights_int = [int(height) for height in heights_str] water = waterArea(heights_int) print(water) ================================================ FILE: Algorithms/DP/Water_Area/water_area.rb ================================================ #!/usr/bin/env ruby def calculateWaterArea(pillarHeights) waterArea = 0 maximumHeightRight = 0 maximumHeightLeft = 0 tallestFromRight = Array.new(pillarHeights.length()) tallestFromLeft = Array.new(pillarHeights.length()) (0...tallestFromLeft.length()).each do |i| tallestFromLeft[i] = [maximumHeightLeft, pillarHeights[i]].max maximumHeightLeft = [maximumHeightLeft, pillarHeights[i]].max end (0...tallestFromRight.length()).reverse_each do |i| tallestFromRight[i] = maximumHeightRight maximumHeightRight = [maximumHeightRight, pillarHeights[i]].max end (0...pillarHeights.length()).each do |i| leftMax = tallestFromLeft[i] rightMax = tallestFromRight[i] minHeight = [leftMax, rightMax].min height = pillarHeights[i] if height < minHeight then waterArea += minHeight - height else waterArea += 0 end end return waterArea end puts "Enter a list of positive numbers:" heights = gets.chomp(" ") .split(" ") .map(&:to_i) puts calculateWaterArea(heights) ================================================ FILE: Algorithms/DP/Z_Algorithm/README.md ================================================ ## This folder is empty. ================================================ FILE: Algorithms/DP/Z_Algorithm/Z-Algorithm.c++ ================================================ #include using namespace std; void getZarr(string str, int Z[]); void search(string text, string pattern) { string concat = pattern + "$" + text; int l = concat.length(); int Z[l]; getZarr(concat, Z); for (int i = 0; i < l; ++i) { if (Z[i] == pattern.length()) cout << "Pattern found at index " << i - pattern.length() -1 << endl; } } void getZarr(string str, int Z[]) { int n = str.length(); int L, R, k; L = R = 0; for (int i = 1; i < n; ++i) { if (i > R) { L = R = i; while (R pattern - (str) String having the pattern > text - (str) The text in which to search the data. @ Return: > Z - The Z array for the data ''' # L, R - variables which store the maximum window length L, R, k = 0, 0, 0 # tempString[L,..., R] is a substring which is a prefix # $ is a special character for separating pattern from string tempString = pattern + "$" + text totalLength = len(tempString) Z = [None] * totalLength # Z array for i in range(1, totalLength): # Fill each element of Z Array # If i is beyond R # use normal way to compute the Z[i] if i > R: # Start from current position L = R = i # while R is within bounds and tempString[0..R] == tempString[i..i+R] while R < totalLength and tempString[R - L] == tempString[R]: R += 1 # Z[i] is the largest prefix substring. R-L is the value Z[i] = R - L # [L, R] is the prefix substring, R exits loop with one more than length # Hence adjust the value R -= 1 # If within [L, R] # Try to do with fewer computations as we already know [L, R] # is a prefix substring else: # Get k value k = i - L # Check if i + Z[k] exceeds the string # if does not, fill normally with previous # computed values if Z[k] < R - i + 1: Z[i] = Z[k] else: # Recall that [L, R] is the largest substring # If Z[i] where L <= i <= R and i + Z[i] = t > R # Then [L, t] the largest substring. # Thus we further compute the values to get the proper R L = i while R < totalLength and tempString[R - L] == tempString[R]: R += 1 Z[i] = R - L # Decrease R by 1 to maintain condition R -= 1 # print(Z) return Z def ZSearch(text, pattern): ''' Searches for pattern using Z Algorithm''' lenPattern = len(pattern) Z = get_Z_arr(pattern, text) # Get the Z array patternPositions = [] # Positions where pattern is found for element in range(len(Z)): if Z[element] == lenPattern: patternPositions.append(element - lenPattern - 1) return patternPositions def main(): '''Driver Code''' pattern = input("Enter the pattern to be found > ") text = input("Enter the text where we need to find the pattern > ") positions = ZSearch(text, pattern) if positions: print(f"Pattern found at indices {positions}") else: print("! Pattern not found") if __name__ == '__main__': main() ================================================ FILE: Algorithms/DP/creating an string input function in C.c ================================================ #include int input(char str[],int n) { int ch; int i=0; while((ch=getchar())!='\n') { if(i= arr[j - 1]: part[i][j] = (part[i][j] or part[i - arr[j - 1]][j - 1]) return part[sum // 2][n] # Driver Code arr = [3, 1, 1, 2, 2, 1] n = len(arr) if findPartition(arr, n) == True: print("Can be divided into two", "subsets of equal sum") else: print("Can not be divided into ", "two subsets of equal sum") ================================================ FILE: Algorithms/DP/rod-cutting-problem.cpp ================================================ /* Code by Urjita Sharma Given a rod of length n inches and an array of prices that contains prices of all pieces of size smaller than n. Determine the maximum value obtainable by cutting up the rod and selling the pieces. */ #include #include #include using namespace std; int rodCut(vector price,int n){ vectorval(n+1,INT_MIN); //max value of rod for each length. val[0]=0; // value of rod of length zero is zero/\. for(int i=1;i<=n;i++){ for(int j=0;j>n; cout< prices(n,0); for(int i=0;i>x; cout< using namespace std; #define ROW 9 #define COL 10 typedef pair Pair; typedef pair> pPair; struct cell { int parent_i, parent_j; double f, g, h; }; bool isValid(int row, int col) { return (row >= 0) && (row < ROW) && (col >= 0) && (col < COL); } bool isUnBlocked(int grid[][COL], int row, int col) { if (grid[row][col] == 1) return (true); else return (false); } bool isDestination(int row, int col, Pair dest) { if (row == dest.first && col == dest.second) return (true); else return (false); } double calculateHValue(int row, int col, Pair dest) { return ((double)sqrt ((row-dest.first)*(row-dest.first) + (col-dest.second)*(col-dest.second))); } void tracePath(cell cellDetails[][COL], Pair dest) { printf ("\nThe Path is "); int row = dest.first; int col = dest.second; stack Path; while (!(cellDetails[row][col].parent_i == row && cellDetails[row][col].parent_j == col )) { Path.push (make_pair (row, col)); int temp_row = cellDetails[row][col].parent_i; int temp_col = cellDetails[row][col].parent_j; row = temp_row; col = temp_col; } Path.push (make_pair (row, col)); while (!Path.empty()) { pair p = Path.top(); Path.pop(); printf("-> (%d,%d) ",p.first,p.second); } return; } void aStarSearch(int grid[][COL], Pair src, Pair dest) { // If the source is out of range if (isValid (src.first, src.second) == false) { printf ("Source is invalid\n"); return; } // If the destination is out of range if (isValid (dest.first, dest.second) == false) { printf ("Destination is invalid\n"); return; } // Either the source or the destination is blocked if (isUnBlocked(grid, src.first, src.second) == false || isUnBlocked(grid, dest.first, dest.second) == false) { printf ("Source or the destination is blocked\n"); return; } if (isDestination(src.first, src.second, dest) == true) { printf ("We are already at the destination\n"); return; } bool closedList[ROW][COL]; memset(closedList, false, sizeof (closedList)); cell cellDetails[ROW][COL]; int i, j; for (i=0; i openList; openList.insert(make_pair (0.0, make_pair (i, j))); bool foundDest = false; while (!openList.empty()) { pPair p = *openList.begin(); openList.erase(openList.begin()); i = p.second.first; j = p.second.second; closedList[i][j] = true; double gNew, hNew, fNew; if (isValid(i-1, j) == true) { if (isDestination(i-1, j, dest) == true) { // Set the Parent of the destination cell cellDetails[i-1][j].parent_i = i; cellDetails[i-1][j].parent_j = j; printf ("The destination cell is found\n"); tracePath (cellDetails, dest); foundDest = true; return; } else if (closedList[i-1][j] == false && isUnBlocked(grid, i-1, j) == true) { gNew = cellDetails[i][j].g + 1.0; hNew = calculateHValue (i-1, j, dest); fNew = gNew + hNew; if (cellDetails[i-1][j].f == FLT_MAX || cellDetails[i-1][j].f > fNew) { openList.insert( make_pair(fNew, make_pair(i-1, j))); // Update the details of this cell cellDetails[i-1][j].f = fNew; cellDetails[i-1][j].g = gNew; cellDetails[i-1][j].h = hNew; cellDetails[i-1][j].parent_i = i; cellDetails[i-1][j].parent_j = j; } } } if (isValid(i+1, j) == true) { if (isDestination(i+1, j, dest) == true) { // Set the Parent of the destination cell cellDetails[i+1][j].parent_i = i; cellDetails[i+1][j].parent_j = j; printf("The destination cell is found\n"); tracePath(cellDetails, dest); foundDest = true; return; } else if (closedList[i+1][j] == false && isUnBlocked(grid, i+1, j) == true) { gNew = cellDetails[i][j].g + 1.0; hNew = calculateHValue(i+1, j, dest); fNew = gNew + hNew; if (cellDetails[i+1][j].f == FLT_MAX || cellDetails[i+1][j].f > fNew) { openList.insert( make_pair (fNew, make_pair (i+1, j))); // Update the details of this cell cellDetails[i+1][j].f = fNew; cellDetails[i+1][j].g = gNew; cellDetails[i+1][j].h = hNew; cellDetails[i+1][j].parent_i = i; cellDetails[i+1][j].parent_j = j; } } } if (isValid (i, j+1) == true) { if (isDestination(i, j+1, dest) == true) { // Set the Parent of the destination cell cellDetails[i][j+1].parent_i = i; cellDetails[i][j+1].parent_j = j; printf("The destination cell is found\n"); tracePath(cellDetails, dest); foundDest = true; return; } else if (closedList[i][j+1] == false && isUnBlocked (grid, i, j+1) == true) { gNew = cellDetails[i][j].g + 1.0; hNew = calculateHValue (i, j+1, dest); fNew = gNew + hNew; if (cellDetails[i][j+1].f == FLT_MAX || cellDetails[i][j+1].f > fNew) { openList.insert( make_pair(fNew, make_pair (i, j+1))); // Update the details of this cell cellDetails[i][j+1].f = fNew; cellDetails[i][j+1].g = gNew; cellDetails[i][j+1].h = hNew; cellDetails[i][j+1].parent_i = i; cellDetails[i][j+1].parent_j = j; } } } if (isValid(i, j-1) == true) { // If the destination cell is the same as the // current successor if (isDestination(i, j-1, dest) == true) { // Set the Parent of the destination cell cellDetails[i][j-1].parent_i = i; cellDetails[i][j-1].parent_j = j; printf("The destination cell is found\n"); tracePath(cellDetails, dest); foundDest = true; return; } else if (closedList[i][j-1] == false && isUnBlocked(grid, i, j-1) == true) { gNew = cellDetails[i][j].g + 1.0; hNew = calculateHValue(i, j-1, dest); fNew = gNew + hNew; if (cellDetails[i][j-1].f == FLT_MAX || cellDetails[i][j-1].f > fNew) { openList.insert( make_pair (fNew, make_pair (i, j-1))); // Update the details of this cell cellDetails[i][j-1].f = fNew; cellDetails[i][j-1].g = gNew; cellDetails[i][j-1].h = hNew; cellDetails[i][j-1].parent_i = i; cellDetails[i][j-1].parent_j = j; } } } //----------- 5th Successor (North-East) ------------ // Only process this cell if this is a valid one if (isValid(i-1, j+1) == true) { if (isDestination(i-1, j+1, dest) == true) { // Set the Parent of the destination cell cellDetails[i-1][j+1].parent_i = i; cellDetails[i-1][j+1].parent_j = j; printf ("The destination cell is found\n"); tracePath (cellDetails, dest); foundDest = true; return; } else if (closedList[i-1][j+1] == false && isUnBlocked(grid, i-1, j+1) == true) { gNew = cellDetails[i][j].g + 1.414; hNew = calculateHValue(i-1, j+1, dest); fNew = gNew + hNew; if (cellDetails[i-1][j+1].f == FLT_MAX || cellDetails[i-1][j+1].f > fNew) { openList.insert( make_pair (fNew, make_pair(i-1, j+1))); // Update the details of this cell cellDetails[i-1][j+1].f = fNew; cellDetails[i-1][j+1].g = gNew; cellDetails[i-1][j+1].h = hNew; cellDetails[i-1][j+1].parent_i = i; cellDetails[i-1][j+1].parent_j = j; } } } if (isValid (i-1, j-1) == true) { if (isDestination (i-1, j-1, dest) == true) { // Set the Parent of the destination cell cellDetails[i-1][j-1].parent_i = i; cellDetails[i-1][j-1].parent_j = j; printf ("The destination cell is found\n"); tracePath (cellDetails, dest); foundDest = true; return; } else if (closedList[i-1][j-1] == false && isUnBlocked(grid, i-1, j-1) == true) { gNew = cellDetails[i][j].g + 1.414; hNew = calculateHValue(i-1, j-1, dest); fNew = gNew + hNew; if (cellDetails[i-1][j-1].f == FLT_MAX || cellDetails[i-1][j-1].f > fNew) { openList.insert( make_pair (fNew, make_pair (i-1, j-1))); // Update the details of this cell cellDetails[i-1][j-1].f = fNew; cellDetails[i-1][j-1].g = gNew; cellDetails[i-1][j-1].h = hNew; cellDetails[i-1][j-1].parent_i = i; cellDetails[i-1][j-1].parent_j = j; } } } //----------- 7th Successor (South-East) ------------ // Only process this cell if this is a valid one if (isValid(i+1, j+1) == true) { // If the destination cell is the same as the // current successor if (isDestination(i+1, j+1, dest) == true) { // Set the Parent of the destination cell cellDetails[i+1][j+1].parent_i = i; cellDetails[i+1][j+1].parent_j = j; printf ("The destination cell is found\n"); tracePath (cellDetails, dest); foundDest = true; return; } else if (closedList[i+1][j+1] == false && isUnBlocked(grid, i+1, j+1) == true) { gNew = cellDetails[i][j].g + 1.414; hNew = calculateHValue(i+1, j+1, dest); fNew = gNew + hNew; if (cellDetails[i+1][j+1].f == FLT_MAX || cellDetails[i+1][j+1].f > fNew) { openList.insert(make_pair(fNew, make_pair (i+1, j+1))); // Update the details of this cell cellDetails[i+1][j+1].f = fNew; cellDetails[i+1][j+1].g = gNew; cellDetails[i+1][j+1].h = hNew; cellDetails[i+1][j+1].parent_i = i; cellDetails[i+1][j+1].parent_j = j; } } } //----------- 8th Successor (South-West) ------------ // Only process this cell if this is a valid one if (isValid (i+1, j-1) == true) { // If the destination cell is the same as the // current successor if (isDestination(i+1, j-1, dest) == true) { // Set the Parent of the destination cell cellDetails[i+1][j-1].parent_i = i; cellDetails[i+1][j-1].parent_j = j; printf("The destination cell is found\n"); tracePath(cellDetails, dest); foundDest = true; return; } // If the successor is already on the closed // list or if it is blocked, then ignore it. // Else do the following else if (closedList[i+1][j-1] == false && isUnBlocked(grid, i+1, j-1) == true) { gNew = cellDetails[i][j].g + 1.414; hNew = calculateHValue(i+1, j-1, dest); fNew = gNew + hNew; if (cellDetails[i+1][j-1].f == FLT_MAX || cellDetails[i+1][j-1].f > fNew) { openList.insert(make_pair(fNew, make_pair(i+1, j-1))); // Update the details of this cell cellDetails[i+1][j-1].f = fNew; cellDetails[i+1][j-1].g = gNew; cellDetails[i+1][j-1].h = hNew; cellDetails[i+1][j-1].parent_i = i; cellDetails[i+1][j-1].parent_j = j; } } } } if (foundDest == false) printf("Failed to find the Destination Cell\n"); return; } // Driver program to test above function int main() { /* Description of the Grid- 1--> The cell is not blocked 0--> The cell is blocked */ int grid[ROW][COL] = { { 1, 0, 1, 1, 1, 1, 0, 1, 1, 1 }, { 1, 1, 1, 0, 1, 1, 1, 0, 1, 1 }, { 1, 1, 1, 0, 1, 1, 0, 1, 0, 1 }, { 0, 0, 1, 0, 1, 0, 0, 0, 0, 1 }, { 1, 1, 1, 0, 1, 1, 1, 0, 1, 0 }, { 1, 0, 1, 1, 1, 1, 0, 1, 0, 0 }, { 1, 0, 0, 0, 0, 1, 0, 0, 0, 1 }, { 1, 0, 1, 1, 1, 1, 0, 1, 1, 1 }, { 1, 1, 1, 0, 0, 0, 1, 0, 0, 1 } }; // Source is the left-most bottom-most corner Pair src = make_pair(8, 0); // Destination is the left-most top-most corner Pair dest = make_pair(0, 0); aStarSearch(grid, src, dest); return(0); } ================================================ FILE: Algorithms/Graph/A_Star/A_star.cs ================================================ using System; using System.Collections.Generic; using System.Drawing; using System.Linq; //Please use Wikipedia to see, what A* is and how it works. I will try to point out as much as i can inside //my comments, but a complete explanation would blow up this file. //In this implementation, i do not support diagonal movement to reduce a little complexity and //eliminate the need for a rule about movement through diagonal walls public class AStar { private readonly IList _nodes; private readonly Point _start; private readonly Point _finish; public AStar(IList nodes, Point start, Point finish) { _nodes = nodes; _start = start; _finish = finish; } public IEnumerable GetPath() { //select the starting node var startNode = _nodes.Single(n => n.Position == _start); //calculate the path if (PathExists(startNode)) { //if a path between start and finish can be found, it can be read via the parentNode //properties that now link from finish to start //(for this example the order is irrelevant, but for other usecases, the result might //have to be reverted to point from start to finish) return ReadPath(); } return Enumerable.Empty(); } private bool PathExists(Node currentNode) { //uncomment following two lines to see A* in action //Tools.PrintMaze(_nodes.ToList(), Enumerable.Empty().ToList(), _start, _finish, currentNode.Position); //Console.ReadKey(); //set current node state to closed, so that we will not walk back here and create a loop currentNode.State = NodeState.Closed; //get possible next nodes var nextNodes = GetSurroundingWalkableNodes(currentNode) //get a list of all nodes that should be considered for our next move .Select(n => UpdateNodeParameters(n, currentNode)) //update each nodes properties .OrderBy(n => n.EstimatedTotalDistance); //check most promising decisions first foreach (var nextNode in nextNodes) //iterate through all possible next nodes { if (nextNode.Position == _finish) //if we reached the finishing point, we're done return true; if (PathExists(nextNode)) //otherwise we'll check our moves from this node on return true; //if the next node reached the finishing point, we're done. otherwise we continue withe the next foreach iteration } //if we checked every possible way and did not reach the finishing point, there is no way return false; } private IEnumerable GetSurroundingWalkableNodes(Node currentNode) { //first, get all four possibly surrounding points of current node //don't worry about nodes that are outside the grid, we'll filter them out next var surroundingPoints = GetSurroundingPoints(currentNode); return _nodes .Where(n => surroundingPoints .Contains(n.Position)) //now we have all nodes that exist for surrounding points .Where(n => n.IsWalkable) //filter out all that are not walkable .Where(n => n.State != NodeState.Closed) //filter out all nodes, that already exist in the current path .Where(n => { switch (n.State) { case NodeState.Untested: //previously untested nodes are always considered for next move return true; case NodeState.Open: //if a node has already been tested, we only consider it, if that new node cannot be reached on a shorter way if (currentNode.MovesFromStart + 1 < n.MovesFromStart) return true; return false; case NodeState.Closed: return false; default: throw new ArgumentOutOfRangeException(); } }); } private IEnumerable GetSurroundingPoints(Node currentNode) { yield return new Point(currentNode.Position.X + 1, currentNode.Position.Y); yield return new Point(currentNode.Position.X - 1, currentNode.Position.Y); yield return new Point(currentNode.Position.X, currentNode.Position.Y - 1); yield return new Point(currentNode.Position.X, currentNode.Position.Y + 1); } private Node UpdateNodeParameters(Node nextNode, Node currentNode) { //set new parent nextNode.Parent = currentNode; //on this path, this node is one hop further than the parent nextNode.MovesFromStart = currentNode.MovesFromStart + 1; //calculate the straight line distance to finish point. this will stay the same value on each iteration, //so it only needs to be done once if (nextNode.State == NodeState.Untested) { nextNode.StraightLineDistanceToFinish = StraightLineDistance(nextNode.Position, _finish); nextNode.State = NodeState.Open; } //return updatedNode return nextNode; } private double StraightLineDistance(Point a, Point b) { //simple pythagorean triangle. //no need to worry if b.X-a.X might become negative, because we square it anyway return Math.Sqrt(Math.Pow(b.X - a.X, 2) + Math.Pow(b.Y - a.Y, 2)); } private IEnumerable ReadPath() { yield return _finish; var node = _nodes.First(n => n.Position == _finish); while (node.Parent != null) { yield return node.Parent.Position; node = node.Parent; } yield return _start; } } public class Node { public Point Position { get; set; } public int MovesFromStart { get; set; } public double StraightLineDistanceToFinish { get; set; } public double EstimatedTotalDistance => MovesFromStart + StraightLineDistanceToFinish; public NodeState State { get; set; } public bool IsWalkable { get; set; } public Node Parent { get; set; } public Node(int x, int y, bool isWalkable) { Position = new Point(x, y); IsWalkable = isWalkable; } } public enum NodeState { Untested = 0, Open = 1, Closed = 2 } //use dotnet-script to run this file without solution private const char ObstacleChar = 'x'; private const char FreeFieldChar = '.'; private const char StartingPointChar = 's'; private const char FinishingPointChar = 'f'; private const char PathChar = '*'; Console.WriteLine("Enter maze via command line"); Console.WriteLine("S = Start"); Console.WriteLine("F = Finish"); Console.WriteLine("X = Obstacle"); Console.WriteLine(". = Free Field (actually any char but X, S or F will work)"); Console.WriteLine("Empty line will finish maze creation"); var maze = new List(); Point? start = null; Point? finish = null; var input = Console.ReadLine(); var yIndex = 0; while (!string.IsNullOrEmpty(input)) { var chars = input .ToLower() .ToCharArray(); var xIndex = 0; foreach (var c in chars) { var walkable = c != ObstacleChar; maze.Add(new Node(xIndex, yIndex, walkable)); if (c == StartingPointChar) start = new Point(xIndex, yIndex); if (c == FinishingPointChar) finish = new Point(xIndex, yIndex); xIndex++; } yIndex++; input = Console.ReadLine(); } if (start == null || finish == null) throw new ArgumentException("Start and Finish need to be set"); var solution = new AStar(maze, start.Value, finish.Value).GetPath().ToList(); Tools.PrintMaze(maze, solution, start, finish); Console.WriteLine(solution.Any() ? "A* found a path" : "Could not find a path"); public static class Tools { public static void PrintMaze(List maze, IList solution, Point? start, Point? finish, Point? current = null) { Console.Clear(); var lines = maze .OrderBy(n => n.Position.X) .GroupBy(n => n.Position.Y) .OrderBy(l => l.Key); foreach (var line in lines) { foreach (var node in line) { SetConsoleColor(solution, node, current); var character = GetCharacter(solution, start, finish, current, node); Console.Write(character); } Console.WriteLine(); } } private static char GetCharacter(IList solution, Point? start, Point? finish, Point? current, Node node) { var character = ObstacleChar; if (node.IsWalkable) character = FreeFieldChar; if (solution.Contains(node.Position)) character = PathChar; if (node.Position == start) character = StartingPointChar; if (node.Position == finish) character = FinishingPointChar; if (node.Position == current) character = PathChar; return character; } private static void SetConsoleColor(IList solution, Node node, Point? current) { Console.ForegroundColor = ConsoleColor.White; if (solution.Contains(node.Position)) Console.ForegroundColor = ConsoleColor.Green; if (node.Position == current) Console.ForegroundColor = ConsoleColor.Red; } } ================================================ FILE: Algorithms/Graph/A_Star/A_star.py ================================================ class Node: def __init__(self, position:(), parent:()): self.position = position self.parent = parent self.g = 0 self.h = 0 self.f = 0 def __eq__(self, other): return self.position == other.position def __lt__(self, other): return self.f < other.f def __repr__(self): return ('({0},{1})'.format(self.position, self.f)) def draw_grid(map, width, height, spacing=2, **kwargs): for y in range(height): for x in range(width): print('%%-%ds' % spacing % draw_tile(map, (x, y), kwargs), end='') print() def draw_tile(map, position, kwargs): value = map.get(position) if 'path' in kwargs and position in kwargs['path']: value = '+' if 'start' in kwargs and position == kwargs['start']: value = '@' if 'goal' in kwargs and position == kwargs['goal']: value = '$' return value def astar_search(map, start, end): open = [] closed = [] start_node = Node(start, None) goal_node = Node(end, None) open.append(start_node) while len(open) > 0: open.sort() current_node = open.pop(0) closed.append(current_node) if current_node == goal_node: path = [] while current_node != start_node: path.append(current_node.position) current_node = current_node.parent return path[::-1] (x, y) = current_node.position neighbors = [(x-1, y), (x+1, y), (x, y-1), (x, y+1)] for next in neighbors: map_value = map.get(next) if(map_value == '#'): continue neighbor = Node(next, current_node) if(neighbor in closed): continue neighbor.g = abs(neighbor.position[0] - start_node.position[0]) + abs(neighbor.position[1] - start_node.position[1]) neighbor.h = abs(neighbor.position[0] - goal_node.position[0]) + abs(neighbor.position[1] - goal_node.position[1]) neighbor.f = neighbor.g + neighbor.h if(add_to_open(open, neighbor) == True): open.append(neighbor) return None def add_to_open(open, neighbor): for node in open: if (neighbor == node and neighbor.f >= node.f): return False return True def main(): map = {} chars = ['c'] start = None end = None width = 0 height = 0 fp = open('data\\maze.in', 'r') while len(chars) > 0: chars = [str(i) for i in fp.readline().strip()] width = len(chars) if width == 0 else width for x in range(len(chars)): map[(x, height)] = chars[x] if(chars[x] == '@'): start = (x, height) elif(chars[x] == '$'): end = (x, height) if(len(chars) > 0): height += 1 fp.close() path = astar_search(map, start, end) print() print(path) print() draw_grid(map, width, height, spacing=1, path=path, start=start, goal=end) print() print('Steps to goal: {0}'.format(len(path))) print() if __name__ == "__main__": main() ================================================ FILE: Algorithms/Graph/A_Star/A_star.ts ================================================ /* GraphNode clas for A* Pathfinding parent is parent of the current Node position is current psition of the Node in the maze g is cost from start to current Node h is heuristic based estimated cost for current Node to end Node f is total cost of present node: i.e. : f = g + h */ class GraphNode { public g: number; public h: number; public f: number; public position: Position; public parent: GraphNode | undefined; constructor(position: Position); constructor(position: Position, parent: GraphNode); constructor(position: Position, parent?: GraphNode) { this.g = 0; this.h = 0; this.f = 0; this.position = position; this.parent = parent; } isEqual(other: Position): boolean { return this.position.x == other.x && this.position.y == other.y; } } // Check if node is within the graph const isValid = (grid: number[][], row: number, col: number): boolean => { return row >= 0 && row < grid.length && col >= 0 && col < grid[0].length; }; // Check if node is not blocked node const isUnBlocked = (grid: number[][], row: number, col: number) => { return grid[row][col] == 1; }; const reachedDestination = (src: Position, dst: Position) => { return src.x == dst.x && src.y == dst.y; }; const inList = (child: GraphNode, list: GraphNode[]): null | GraphNode => { for (let node of list) { if (node.isEqual(child.position)) { return node; } } return null; }; const aStarSearch = (grid: number[][], src: Position, dst: Position) => { // If source is invalid if (!isValid(grid, src.x, src.y)) { console.log("Source is invalid"); return; } // If destionation is invalid if (!isValid(grid, dst.x, dst.y)) { console.log("Destination is invalid"); } // Check if the source and destination node code is blocked if (!isUnBlocked(grid, src.x, src.y) || !isUnBlocked(grid, dst.x, dst.y)) { console.log("Source or the destination is blocked"); } //Check the destination node is the same as the source cell if (reachedDestination(src, dst)) { console.log("Destination is already reached "); } // Initialize startNode and endNode let startNode = new GraphNode(src); let endNode = new GraphNode(dst); console.log(startNode); console.log(endNode); // Initialize both open and closed list let openList: GraphNode[] = []; let closedList: GraphNode[] = []; // Add the start node to open list openList.push(startNode); while (openList.length > 0) { // Get the current node let currentNode = openList[0]; let currentIndex = 0; for (let i = 0; i < openList.length; i++) { if (openList[i].f < currentNode.f) { currentNode = openList[i]; currentIndex = i; } } // Pop current off open list, add to closed list openList.splice(currentIndex, 1); closedList.push(currentNode); // if the destination node is reached if (currentNode.isEqual(endNode.position)) { let path = []; let current: GraphNode | undefined = currentNode; while (current != undefined) { path.push(current.position); current = current.parent; } return path.reverse(); } // Generate children let children = []; let neighbours = [ new Position(0, -1), new Position(0, 1), new Position(-1, 0), new Position(1, 0), new Position(-1, -1), new Position(-1, 1), new Position(1, -1), new Position(1, 1), ]; for (let position of neighbours) { // Get node postion let nodePosition = new Position( currentNode.position.x + position.x, currentNode.position.y + position.y ); // Make sure within the range if (!isValid(grid, nodePosition.x, nodePosition.y)) { continue; } if (!isUnBlocked(grid, nodePosition.x, nodePosition.y)) { continue; } let newNode = new GraphNode(nodePosition, currentNode); children.push(newNode); // Loop through children for (let child of children) { if (inList(child, closedList)) { continue; } child.g = currentNode.g + 1; child.h = (child.position.x - endNode.position.x) ** 2 + (child.position.y - endNode.position.y) ** 2; child.f = child.g + child.h; let openNode = inList(child, openList); if (openNode && child.g > openNode.g) { continue; } // Add the child to the open list openList.push(child); } } } }; class Position { constructor(public x: number, public y: number) {} } // 1--> The cell is not blocked // 0--> The cell is blocked let grid: number[][] = [ [1, 0, 1, 1, 1, 1, 0, 1, 1, 1], [1, 1, 1, 0, 1, 1, 1, 0, 1, 1], [1, 1, 1, 0, 1, 1, 0, 1, 0, 1], [0, 0, 1, 0, 1, 0, 0, 0, 0, 1], [1, 1, 1, 0, 1, 1, 1, 0, 1, 0], [1, 0, 1, 1, 1, 1, 0, 1, 0, 0], [1, 0, 0, 0, 0, 1, 0, 0, 0, 1], [1, 0, 1, 1, 1, 1, 0, 1, 1, 1], [1, 1, 1, 0, 0, 0, 1, 0, 0, 1], ]; let src = new Position(8, 0); let dst = new Position(0, 0); let path = aStarSearch(grid, src, dst); console.log(path); ================================================ FILE: Algorithms/Graph/A_Star/astar.py ================================================ class Node(): def __init__(self, parent=None, position=None): self.parent = parent self.position = position self.g = 0 self.h = 0 self.f = 0 def __eq__(self, other): return self.position == other.position def astar(maze, start, end): start_node = Node(None, start) start_node.g = start_node.h = start_node.f = 0 end_node = Node(None, end) end_node.g = end_node.h = end_node.f = 0 open_list = [] closed_list = [] open_list.append(start_node) while len(open_list) > 0: current_node = open_list[0] current_index = 0 for index, item in enumerate(open_list): if item.f < current_node.f: current_node = item current_index = index open_list.pop(current_index) closed_list.append(current_node) if current_node == end_node: path = [] current = current_node while current is not None: path.append(current.position) current = current.parent return path[::-1] children = [] for new_position in [(0, -1), (0, 1), (-1, 0), (1, 0), (-1, -1), (-1, 1), (1, -1), (1, 1)]: node_position = (current_node.position[0] + new_position[0], current_node.position[1] + new_position[1]) if node_position[0] > (len(maze) - 1) or node_position[0] < 0 or node_position[1] > ( len(maze[len(maze) - 1]) - 1) or node_position[1] < 0: continue if maze[node_position[0]][node_position[1]] != 0: continue new_node = Node(current_node, node_position) children.append(new_node) for child in children: for closed_child in closed_list: if child == closed_child: continue child.g = current_node.g + 1 child.h = ((child.position[0] - end_node.position[0]) ** 2) + ( (child.position[1] - end_node.position[1]) ** 2) child.f = child.g + child.h for open_node in open_list: if child == open_node and child.g > open_node.g: continue open_list.append(child) def main(): graph = [[0, 1, 0, 0, 0, 0], [1, 0, 1, 0, 1, 0], [0, 1, 0, 0, 0, 1], [0, 0, 0, 0, 1, 0], [0, 1, 0, 1, 0, 0], [0, 0, 1, 0, 0, 0] ] start = (0, 0) end = (5, 5) path1 = astar(graph, start, end) print(path1) if __name__ == '__main__': main() ================================================ FILE: Algorithms/Graph/BFS/BFS.c ================================================ // BFS algorithm in C #include #include #define SIZE 40 struct queue { int items[SIZE]; int front; int rear; }; struct queue* createQueue(); void enqueue(struct queue* q, int); int dequeue(struct queue* q); void display(struct queue* q); int isEmpty(struct queue* q); void printQueue(struct queue* q); struct node { int vertex; struct node* next; }; struct node* createNode(int); struct Graph { int numVertices; struct node** adjLists; int* visited; }; // BFS algorithm void bfs(struct Graph* graph, int startVertex) { struct queue* q = createQueue(); graph->visited[startVertex] = 1; enqueue(q, startVertex); while (!isEmpty(q)) { printQueue(q); int currentVertex = dequeue(q); printf("Visited %d\n", currentVertex); struct node* temp = graph->adjLists[currentVertex]; while (temp) { int adjVertex = temp->vertex; if (graph->visited[adjVertex] == 0) { graph->visited[adjVertex] = 1; enqueue(q, adjVertex); } temp = temp->next; } } } // Creating a node struct node* createNode(int v) { struct node* newNode = malloc(sizeof(struct node)); newNode->vertex = v; newNode->next = NULL; return newNode; } // Creating a graph struct Graph* createGraph(int vertices) { struct Graph* graph = malloc(sizeof(struct Graph)); graph->numVertices = vertices; graph->adjLists = malloc(vertices * sizeof(struct node*)); graph->visited = malloc(vertices * sizeof(int)); int i; for (i = 0; i < vertices; i++) { graph->adjLists[i] = NULL; graph->visited[i] = 0; } return graph; } // Add edge void addEdge(struct Graph* graph, int src, int dest) { // Add edge from src to dest struct node* newNode = createNode(dest); newNode->next = graph->adjLists[src]; graph->adjLists[src] = newNode; // Add edge from dest to src newNode = createNode(src); newNode->next = graph->adjLists[dest]; graph->adjLists[dest] = newNode; } // Create a queue struct queue* createQueue() { struct queue* q = malloc(sizeof(struct queue)); q->front = -1; q->rear = -1; return q; } // Check if the queue is empty int isEmpty(struct queue* q) { if (q->rear == -1) return 1; else return 0; } // Adding elements into queue void enqueue(struct queue* q, int value) { if (q->rear == SIZE - 1) printf("\nQueue is Full!!"); else { if (q->front == -1) q->front = 0; q->rear++; q->items[q->rear] = value; } } // Removing elements from queue int dequeue(struct queue* q) { int item; if (isEmpty(q)) { printf("Queue is empty"); item = -1; } else { item = q->items[q->front]; q->front++; if (q->front > q->rear) { printf("Resetting queue "); q->front = q->rear = -1; } } return item; } // Print the queue void printQueue(struct queue* q) { int i = q->front; if (isEmpty(q)) { printf("Queue is empty"); } else { printf("\nQueue contains \n"); for (i = q->front; i < q->rear + 1; i++) { printf("%d ", q->items[i]); } } } int main() { struct Graph* graph = createGraph(6); addEdge(graph, 0, 1); addEdge(graph, 0, 2); addEdge(graph, 1, 2); addEdge(graph, 1, 4); addEdge(graph, 1, 3); addEdge(graph, 2, 4); addEdge(graph, 3, 4); bfs(graph, 0); return 0; } ================================================ FILE: Algorithms/Graph/BFS/BFS.cpp ================================================ #include #include using namespace std; // This class represents a directed graph using // adjacency list representation class Graph { int V; // No. of vertices // Pointer to an array containing adjacency // lists list *adj; public: Graph(int V); // Constructor // function to add an edge to graph void addEdge(int v, int w); // prints BFS traversal from a given source s void BFS(int s); }; Graph::Graph(int V) { this->V = V; adj = new list[V]; } void Graph::addEdge(int v, int w) { adj[v].push_back(w); // Add w to v’s list. } void Graph::BFS(int s) { // Mark all the vertices as not visited bool *visited = new bool[V]; for(int i = 0; i < V; i++) visited[i] = false; // Create a queue for BFS list queue; // Mark the current node as visited and enqueue it visited[s] = true; queue.push_back(s); // 'i' will be used to get all adjacent // vertices of a vertex list::iterator i; while(!queue.empty()) { // Dequeue a vertex from queue and print it s = queue.front(); cout << s << " "; queue.pop_front(); // Get all adjacent vertices of the dequeued // vertex s. If a adjacent has not been visited, // then mark it visited and enqueue it for (i = adj[s].begin(); i != adj[s].end(); ++i) { if (!visited[*i]) { visited[*i] = true; queue.push_back(*i); } } } } // Driver program to test methods of graph class int main() { // Create a graph given in the above diagram Graph g(4); g.addEdge(0, 1); g.addEdge(0, 2); g.addEdge(1, 2); g.addEdge(2, 0); g.addEdge(2, 3); g.addEdge(3, 3); cout << "Following is Breadth First Traversal " << "(starting from vertex 2) \n"; g.BFS(2); return 0; } ================================================ FILE: Algorithms/Graph/BFS/BFS.go ================================================ // Credits: Code inspiration from Milos Gajdos on Cybernetist package main import ( "container/list" "fmt" ) // node is a graph node type node struct { Id string friends map[string]*node } // Nodes returns a list of all graph nodes func Nodes(n *node) []*node { // track the visited nodes visited := make(map[string]*node) // queue of the nodes to visit queue := list.New() queue.PushBack(n) // add the root node to the map of the visited nodes visited[n.Id] = n for queue.Len() > 0 { qnode := queue.Front() // iterate through all of its friends // mark the visited nodes; enqueue the non-visited for id, node := range qnode.Value.(*node).friends { if _, ok := visited[id]; !ok { visited[id] = node queue.PushBack(node) } } queue.Remove(qnode) } nodes := make([]*node, 0) // collect all the nodes into slice for _, node := range visited { nodes = append(nodes, node) } return nodes } func main() { node1 := &node{Id: "node1", friends: make(map[string]*node)} node2 := &node{Id: "node2", friends: make(map[string]*node)} node3 := &node{Id: "node3", friends: make(map[string]*node)} // node2 is directly connected to node1 node2.friends[node1.Id] = node1 // node3 is directly connected to node2 node3.friends[node2.Id] = node2 // node1 is direcyly connected to node3 node1.friends[node3.Id] = node3 // root node; this graph is actually not atree so it does not have a root node root := &node{Id: "root", friends: make(map[string]*node)} n := make(map[string]*node) n[root.Id] = root n[root.Id] = friends[node1.Id] = node1 n[root.Id] = friends[node2.Id] = node2 n[root.Id] = friends[node3.Id] = node3 nodes := Nodes(root) for _, node := range nodes { fmt.Printf("%+V\n", node.Id) } } } ================================================ FILE: Algorithms/Graph/BFS/BFS.java ================================================ import java.io.*; import java.util.*; // This class represents a directed graph using adjacency list // representation class Graph { private int V; // No. of vertices private LinkedList adj[]; //Adjacency Lists // Constructor Graph(int v) { V = v; adj = new LinkedList[v]; for (int i=0; i queue = new LinkedList(); // Mark the current node as visited and enqueue it visited[s]=true; queue.add(s); while (queue.size() != 0) { // Dequeue a vertex from queue and print it s = queue.poll(); System.out.print(s+" "); // Get all adjacent vertices of the dequeued vertex s // If a adjacent has not been visited, then mark it // visited and enqueue it Iterator i = adj[s].listIterator(); while (i.hasNext()) { int n = i.next(); if (!visited[n]) { visited[n] = true; queue.add(n); } } } } // Driver method to public static void main(String args[]) { Graph g = new Graph(4); g.addEdge(0, 1); g.addEdge(0, 2); g.addEdge(1, 2); g.addEdge(2, 0); g.addEdge(2, 3); g.addEdge(3, 3); System.out.println("Following is Breadth First Traversal "+ "(starting from vertex 2)"); g.BFS(2); } } ================================================ FILE: Algorithms/Graph/BFS/BFS.py ================================================ #Created by Timothy Chua #Implementation of Breadth First Search in Python #References: # - https://csacademy.com/app/graph_editor/ # - https://www.tutorialspoint.com/data_structures_algorithms/graph_data_structure.htm def BFS(graph, point, explored, to_explore): if(len(graph) == len(explored)): #If we have explored every possible point return explored else: #We use two lists to track what we've explored and what is there left to explore explored.append(point) for vertice in graph[point]: if(vertice not in explored and vertice not in to_explore): #If the point we encounter isn't explored and not in our to_explore list, we add it. to_explore.append(vertice) while(len(to_explore) != 0): vertice = to_explore.pop(0) BFS(graph, vertice, explored, to_explore) return explored if __name__ == "__main__": #Let's construct the graph using a dictionary #The keys of the dictionary are called vertices of the graph #The values of the dictionary are called the edges of the the graph graph = { "a" : ["b", "c"], "b" : ["a", "d"], "c" : ["a", "d"], "d" : ["e"], "e" : ["d"] } #Let us start with point a on the graph print(BFS(graph, "b", [], [])) ================================================ FILE: Algorithms/Graph/BFS/BFS.rb ================================================ def bfs(node) return nil if node.nil? || root.nil? # nothing to do if there is no node or root to begin the search queue = Queue.new queue.enq(root) result = nil while !queue.empty? value = queue.deq if value.title == node.title && value.rating == node.rating result = value break end # keep moving the levels in tree by pushing left and right nodes of tree in queue queue.enq(value.left) if value.left queue.enq(value.right) if value.right end result # returns node found in BST else default value nil end ================================================ FILE: Algorithms/Graph/BFS/README.md ================================================ ## This folder is empty. ================================================ FILE: Algorithms/Graph/BFS/bfs.js ================================================ function bfs(at) { let queue = [at]; // mark the first node as visited visited[at] = true; // adding the first node to the result result.push(at) // find the node neighbours let nodes = adjList.get(at); while(queue.length > 0){ // take the next node to explore let node = queue.shift(); // find the node neighbours let nodes = adjList.get(node); for(let neigh of nodes){ if(!visited[neigh]){ queue.push(neigh); // mark the node as visited visited[neigh] = true; // adding the node to the explored nodes result.push(neigh); // or you can do something with the node } } } } function addNode(node) { // adding the node, at first point to nothing adjList.set(node, []); } function addEdge(origin, destination) { // finding the node origin and set the edge to destination adjList.get(origin).push(destination); // finding the node destination and set the edge to origin adjList.get(destination).push(origin); } // T E S T const nodes = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; const edges = [ [0, 4], [0, 3], [3, 2], [3, 7], [3, 8], [5, 4], [5, 1], [5, 10], [5, 6], [10, 1], ]; // define a structure to support the graph let adjList = new Map(); // biulding the nodes of the graph nodes.forEach(addNode); // building the edges edges.forEach(edge => addEdge(...edge)); // building an array for the flag of the visited nodes let visited = new Array(nodes.length).fill(false); // traverse starting from node 0 let start_node = 0; let result = []; bfs(start_node); console.log(`the result of traverse the graph from ${start_node} is`, result); ================================================ FILE: Algorithms/Graph/Bellman_Ford/BellMan_Ford.py ================================================ #Bellman-Ford Python Implementation #Complexity : O(|V|*|E|) where V = No. of vertices ; E = No. of edges class Graph: #Initialise the data structure def __init__(self, nodes): self.nodes = nodes self.weighted_edges = [] #Add edges in the form #(u -> 1st vertex, v -> 2nd vertex, weight -> weight of u--v) def createEdge(self, u, v, weight): if u>=self.nodes or v>=self.nodes: #Taking care of wrong Input print("Please enter vertices from 0 to |V|-1") exit(0) self.weighted_edges.append((u,v,weight)) class Solution: #Print the shortest distances from src to all vertices def printSoln(self, dist, src): print("Dist from source : ",src," are as follows") for vertex,weight in enumerate(dist): print("to vertex : ",vertex," shortest distance is : ",weight) def bellmanFord(self, graph, src): #Initialise all distances with infinity and src distance with 0 dist = [float("inf")]*graph.nodes dist[src] = 0 #Update each edge weight by any smaller weighted path possible #we do it for |V|-1 times to ensure all edge weights have least possible value for i in range(graph.nodes-1): #Relax all the edges for u,v,w in graph.weighted_edges: if dist[u] != float("inf") and dist[v] > dist[u] + w: dist[v] = dist[u] + w #After |V|-1 relaxations if again a shorter edge #found means a negative cycle encountered for u, v, w in graph.weighted_edges: if dist[u] != float("inf") and dist[u] + w < dist[v]: print("Negative weight cycle detected") #If negative cycle detected, no solution exists, so return return #To print the final solution self.printSoln(dist, src) if __name__=="__main__": #Inputs from stdin V = int(input("Enter total vertices in graph : ")) E = int(input("Enter no. of edges : ")) #Create a Graph object with |V| vertices g = Graph(V) #Input and Add edges to the graph object g for i in range(E): u,v,w = map(int,input("Enter u,v,w subjected to (0-|V|-1,0-|V|-1,Any Integer) values seperated by space : ").split()) g.createEdge(u, v, w) #Input Source from which distance is to be calculated src = int(input("Select the source : ")) ans = Solution() print("==================================") #Call the Bellman Ford algorithm ans.bellmanFord(g, src) ================================================ FILE: Algorithms/Graph/Bellman_Ford/README.md ================================================ Algorithm Following are the detailed steps. Input: Graph and a source vertex src Output: Shortest distance to all vertices from src. If there is a negative weight cycle, then shortest distances are not calculated, negative weight cycle is reported. 1) This step initializes distances from the source to all vertices as infinite and distance to the source itself as 0. Create an array dist[] of size |V| with all values as infinite except dist[src] where src is source vertex. 2) This step calculates shortest distances. Do following |V|-1 times where |V| is the number of vertices in given graph. …..a) Do following for each edge u-v ………………If dist[v] > dist[u] + weight of edge uv, then update dist[v] ………………….dist[v] = dist[u] + weight of edge uv 3) This step reports if there is a negative weight cycle in graph. Do following for each edge u-v ……If dist[v] > dist[u] + weight of edge uv, then “Graph contains negative weight cycle” The idea of step 3 is, step 2 guarantees the shortest distances if the graph doesn’t contain a negative weight cycle. If we iterate through all edges one more time and get a shorter path for any vertex, then there is a negative weight cycle How does this work? Like other Dynamic Programming Problems, the algorithm calculates shortest paths in a bottom-up manner. It first calculates the shortest distances which have at-most one edge in the path. Then, it calculates the shortest paths with at-most 2 edges, and so on. After the i-th iteration of the outer loop, the shortest paths with at most i edges are calculated. There can be maximum |V| – 1 edges in any simple path, that is why the outer loop runs |v| – 1 times. The idea is, assuming that there is no negative weight cycle, if we have calculated shortest paths with at most i edges, then an iteration over all edges guarantees to give shortest path with at-most (i+1) edges ================================================ FILE: Algorithms/Graph/Bellman_Ford/bellmanFord.cpp ================================================ // A C++ program for Bellman-Ford's single source // shortest path algorithm. #include // a structure to represent a weighted edge in graph struct Edge { int src, dest, weight; }; // a structure to represent a connected, directed and // weighted graph struct Graph { // V-> Number of vertices, E-> Number of edges int V, E; // graph is represented as an array of edges. struct Edge* edge; }; // Creates a graph with V vertices and E edges struct Graph* createGraph(int V, int E) { struct Graph* graph = new Graph; graph->V = V; graph->E = E; graph->edge = new Edge[E]; return graph; } // A utility function used to print the solution void printArr(int dist[], int n) { printf("Vertex Distance from Source\n"); for (int i = 0; i < n; ++i) printf("%d \t\t %d\n", i, dist[i]); } // The main function that finds shortest distances from src to // all other vertices using Bellman-Ford algorithm. The function // also detects negative weight cycle void BellmanFord(struct Graph* graph, int src) { int V = graph->V; int E = graph->E; int dist[V]; // Step 1: Initialize distances from src to all other vertices // as INFINITE for (int i = 0; i < V; i++) dist[i] = INT_MAX; dist[src] = 0; // Step 2: Relax all edges |V| - 1 times. A simple shortest // path from src to any other vertex can have at-most |V| - 1 // edges for (int i = 1; i <= V - 1; i++) { for (int j = 0; j < E; j++) { int u = graph->edge[j].src; int v = graph->edge[j].dest; int weight = graph->edge[j].weight; if (dist[u] != INT_MAX && dist[u] + weight < dist[v]) dist[v] = dist[u] + weight; } } // Step 3: check for negative-weight cycles. The above step // guarantees shortest distances if graph doesn't contain // negative weight cycle. If we get a shorter path, then there // is a cycle. for (int i = 0; i < E; i++) { int u = graph->edge[i].src; int v = graph->edge[i].dest; int weight = graph->edge[i].weight; if (dist[u] != INT_MAX && dist[u] + weight < dist[v]) { printf("Graph contains negative weight cycle"); return; // If negative cycle is detected, simply return } } printArr(dist, V); return; } // Driver program to test above functions int main() { /* Let us create the graph given in above example */ int V = 5; // Number of vertices in graph int E = 8; // Number of edges in graph struct Graph* graph = createGraph(V, E); // add edge 0-1 (or A-B in above figure) graph->edge[0].src = 0; graph->edge[0].dest = 1; graph->edge[0].weight = -1; // add edge 0-2 (or A-C in above figure) graph->edge[1].src = 0; graph->edge[1].dest = 2; graph->edge[1].weight = 4; // add edge 1-2 (or B-C in above figure) graph->edge[2].src = 1; graph->edge[2].dest = 2; graph->edge[2].weight = 3; // add edge 1-3 (or B-D in above figure) graph->edge[3].src = 1; graph->edge[3].dest = 3; graph->edge[3].weight = 2; // add edge 1-4 (or A-E in above figure) graph->edge[4].src = 1; graph->edge[4].dest = 4; graph->edge[4].weight = 2; // add edge 3-2 (or D-C in above figure) graph->edge[5].src = 3; graph->edge[5].dest = 2; graph->edge[5].weight = 5; // add edge 3-1 (or D-B in above figure) graph->edge[6].src = 3; graph->edge[6].dest = 1; graph->edge[6].weight = 1; // add edge 4-3 (or E-D in above figure) graph->edge[7].src = 4; graph->edge[7].dest = 3; graph->edge[7].weight = -3; BellmanFord(graph, 0); return 0; } ================================================ FILE: Algorithms/Graph/Bellman_Ford/bellman_ford.c ================================================ #include #include #include #include struct Edge { // This structure is equal to an edge. Edge contains two end points. These edges are directed edges so they //contain source and destination and some weight. These 3 are elements in this structure int source, destination, weight; }; // a structure to represent a connected, directed and weighted graph struct Graph { int V, E; // V is number of vertices and E is number of edges struct Edge* edge; // This structure contain another structure which we already created edge. }; struct Graph* createGraph(int V, int E) { struct Graph* graph = (struct Graph*) malloc( sizeof(struct Graph)); //Allocating space to structure graph graph->V = V; //assigning values to structure elements that taken form user. graph->E = E; graph->edge = (struct Edge*) malloc( graph->E * sizeof( struct Edge ) ); //Creating "Edge" type structures inside "Graph" structure, the number of edge type structures are equal to number of edges return graph; } void FinalSolution(int dist[], int n) { // This function prints the final solution printf("\nVertex\tDistance from Source Vertex\n"); int i; for (i = 0; i < n; ++i){ printf("%d \t\t %d\n", i, dist[i]); } } void BellmanFord(struct Graph* graph, int source) { int V = graph->V; int E = graph->E; int StoreDistance[V]; int i,j; // This is initial step that we know , we initialize all distance to infinity except source. // We assign source distance as 0(zero) for (i = 0; i < V; i++) StoreDistance[i] = INT_MAX; StoreDistance[source] = 0; //The shortest path of graph that contain V vertices, never contain "V-1" edges. So we do here "V-1" relaxations for (i = 1; i <= V-1; i++) { for (j = 0; j < E; j++) { int u = graph->edge[j].source; int v = graph->edge[j].destination; int weight = graph->edge[j].weight; if (StoreDistance[u] + weight < StoreDistance[v]) StoreDistance[v] = StoreDistance[u] + weight; } } // Actually upto now shortest path found. But BellmanFord checks for negative edge cycle. In this step we check for that // shortest distances if graph doesn't contain negative weight cycle. // If we get a shorter path, then there is a negative edge cycle. for (i = 0; i < E; i++) { int u = graph->edge[i].source; int v = graph->edge[i].destination; int weight = graph->edge[i].weight; if (StoreDistance[u] + weight < StoreDistance[v]) printf("This graph contains negative edge cycle\n"); } FinalSolution(StoreDistance, V); return; } int main() { int V,E,S; //V = no.of Vertices, E = no.of Edges, S is source vertex printf("Enter number of vertices in graph\n"); scanf("%d",&V); printf("Enter number of edges in graph\n"); scanf("%d",&E); printf("Enter your source vertex number\n"); scanf("%d",&S); struct Graph* graph = createGraph(V, E); //calling the function to allocate space to these many vertices and edges int i; for(i=0;iedge[i].source); scanf("%d",&graph->edge[i].destination); scanf("%d",&graph->edge[i].weight); } BellmanFord(graph, S); //passing created graph and source vertex to BellmanFord Algorithm function return 0; } ================================================ FILE: Algorithms/Graph/Bidirectional_search/Bidirectional_Search.py ================================================ # Python3 program for Bidirectional BFS # Search to check path between two vertices # Class definition for node to # be added to graph class AdjacentNode: def __init__(self, vertex): self.vertex = vertex self.next = None # BidirectionalSearch implementation class BidirectionalSearch: def __init__(self, vertices): # Initialize vertices and # graph with vertices self.vertices = vertices self.graph = [None] * self.vertices # Initializing queue for forward # and backward search self.src_queue = list() self.dest_queue = list() # Initializing source and # destination visited nodes as False self.src_visited = [False] * self.vertices self.dest_visited = [False] * self.vertices # Initializing source and destination # parent nodes self.src_parent = [None] * self.vertices self.dest_parent = [None] * self.vertices # Function for adding undirected edge def add_edge(self, src, dest): # Add edges to graph # Add source to destination node = AdjacentNode(dest) node.next = self.graph[src] self.graph[src] = node # Since graph is undirected add # destination to source node = AdjacentNode(src) node.next = self.graph[dest] self.graph[dest] = node # Function for Breadth First Search def bfs(self, direction = 'forward'): if direction == 'forward': # BFS in forward direction current = self.src_queue.pop(0) connected_node = self.graph[current] while connected_node: vertex = connected_node.vertex if not self.src_visited[vertex]: self.src_queue.append(vertex) self.src_visited[vertex] = True self.src_parent[vertex] = current connected_node = connected_node.next else: # BFS in backward direction current = self.dest_queue.pop(0) connected_node = self.graph[current] while connected_node: vertex = connected_node.vertex if not self.dest_visited[vertex]: self.dest_queue.append(vertex) self.dest_visited[vertex] = True self.dest_parent[vertex] = current connected_node = connected_node.next # Check for intersecting vertex def is_intersecting(self): # Returns intersecting node # if present else -1 for i in range(self.vertices): if (self.src_visited[i] and self.dest_visited[i]): return i return -1 # Print the path from source to target def print_path(self, intersecting_node, src, dest): # Print final path from # source to destination path = list() path.append(intersecting_node) i = intersecting_node while i != src: path.append(self.src_parent[i]) i = self.src_parent[i] path = path[::-1] i = intersecting_node while i != dest: path.append(self.dest_parent[i]) i = self.dest_parent[i] print("*****Path*****") path = list(map(str, path)) print(' '.join(path)) # Function for bidirectional searching def bidirectional_search(self, src, dest): # Add source to queue and mark # visited as True and add its # parent as -1 self.src_queue.append(src) self.src_visited[src] = True self.src_parent[src] = -1 # Add destination to queue and # mark visited as True and add # its parent as -1 self.dest_queue.append(dest) self.dest_visited[dest] = True self.dest_parent[dest] = -1 while self.src_queue and self.dest_queue: # BFS in forward direction from # Source Vertex self.bfs(direction = 'forward') # BFS in reverse direction # from Destination Vertex self.bfs(direction = 'backward') # Check for intersecting vertex intersecting_node = self.is_intersecting() # If intersecting vertex exists # then path from source to # destination exists if intersecting_node != -1: print(f"Path exists between {src} and {dest}") print(f"Intersection at : {intersecting_node}") self.print_path(intersecting_node, src, dest) exit(0) return -1 # Driver code if __name__ == '__main__': # Number of Vertices in graph n = 15 # Source Vertex src = 0 # Destination Vertex dest = 14 # Create a graph graph = BidirectionalSearch(n) graph.add_edge(0, 4) graph.add_edge(1, 4) graph.add_edge(2, 5) graph.add_edge(3, 5) graph.add_edge(4, 6) graph.add_edge(5, 6) graph.add_edge(6, 7) graph.add_edge(7, 8) graph.add_edge(8, 9) graph.add_edge(8, 10) graph.add_edge(9, 11) graph.add_edge(9, 12) graph.add_edge(10, 13) graph.add_edge(10, 14) out = graph.bidirectional_search(src, dest) if out == -1: print(f"Path does not exist between {src} and {dest}") ================================================ FILE: Algorithms/Graph/Bidirectional_search/Bidirectional_search.cpp ================================================ // C++ program for Bidirectional BFS search #include using namespace std; // class representing undirected graph // using adjacency list class Graph { //number of nodes in graph int V; // Adjacency list list *adj; public: Graph(int V); int isIntersecting(bool *s_visited, bool *t_visited); void addEdge(int u, int v); void printPath(int *s_parent, int *t_parent, int s, int t, int intersectNode); void BFS(list *queue, bool *visited, int *parent); int biDirSearch(int s, int t); }; Graph::Graph(int V) { this->V = V; adj = new list[V]; }; // Method for adding undirected edge void Graph::addEdge(int u, int v) { this->adj[u].push_back(v); this->adj[v].push_back(u); }; // Method for Breadth First Search void Graph::BFS(list *queue, bool *visited, int *parent) { int current = queue->front(); queue->pop_front(); list::iterator i; for (i=adj[current].begin();i != adj[current].end();i++) { // If adjacent vertex is not visited earlier // mark it visited by assigning true value if (!visited[*i]) { // set current as parent of this vertex parent[*i] = current; // Mark this vertex visited visited[*i] = true; // Push to the end of queue queue->push_back(*i); } } }; // check for intersecting vertex int Graph::isIntersecting(bool *s_visited, bool *t_visited) { int intersectNode = -1; for(int i=0;i path; path.push_back(intersectNode); int i = intersectNode; while (i != s) { path.push_back(s_parent[i]); i = s_parent[i]; } reverse(path.begin(), path.end()); i = intersectNode; while(i != t) { path.push_back(t_parent[i]); i = t_parent[i]; } vector::iterator it; cout<<"*****Path*****\n"; for(it = path.begin();it != path.end();it++) cout<<*it<<" "; cout<<"\n"; }; // Method for bidirectional searching int Graph::biDirSearch(int s, int t) { // boolean array for BFS started from // source and target(front and backward BFS) // for keeping track on visited nodes bool s_visited[V], t_visited[V]; // Keep track on parents of nodes // for front and backward search int s_parent[V], t_parent[V]; // queue for front and backward search list s_queue, t_queue; int intersectNode = -1; // necessary initialization for(int i=0; i using namespace std; // Graph class represents a directed graph // using adjacency list representation class Graph { int V; // No. of vertices // Pointer to an array containing // adjacency lists list *adj; // A recursive function used by DFS void DFSUtil(int v, bool visited[]); public: Graph(int V); // Constructor // function to add an edge to graph void addEdge(int v, int w); // DFS traversal of the vertices // reachable from v void DFS(int v); }; Graph::Graph(int V) { this->V = V; adj = new list[V]; } void Graph::addEdge(int v, int w) { adj[v].push_back(w); // Add w to v’s list. } void Graph::DFSUtil(int v, bool visited[]) { // Mark the current node as visited and // print it visited[v] = true; cout << v << " "; // Recur for all the vertices adjacent // to this vertex list::iterator i; for (i = adj[v].begin(); i != adj[v].end(); ++i) if (!visited[*i]) DFSUtil(*i, visited); } // DFS traversal of the vertices reachable from v. // It uses recursive DFSUtil() void Graph::DFS(int v) { // Mark all the vertices as not visited bool *visited = new bool[V]; for (int i = 0; i < V; i++) visited[i] = false; // Call the recursive helper function // to print DFS traversal DFSUtil(v, visited); } // Driver code int main() { // Create a graph given in the above diagram Graph g(4); g.addEdge(0, 1); g.addEdge(0, 2); g.addEdge(1, 2); g.addEdge(2, 0); g.addEdge(2, 3); g.addEdge(3, 3); cout << "Following is Depth First Traversal" " (starting from vertex 2) \n"; g.DFS(2); return 0; } ================================================ FILE: Algorithms/Graph/DFS/DFS.java ================================================ // Java program to print DFS traversal from a given given graph import java.io.*; import java.util.*; // This class represents a directed graph using adjacency list // representation class Graph { private int V; // No. of vertices // Array of lists for Adjacency List Representation private LinkedList adj[]; // Constructor @SuppressWarnings("unchecked") Graph(int v) { V = v; adj = new LinkedList[v]; for (int i=0; i i = adj[v].listIterator(); while (i.hasNext()) { int n = i.next(); if (!visited[n]) DFSUtil(n, visited); } } // The function to do DFS traversal. It uses recursive DFSUtil() void DFS(int v) { // Mark all the vertices as not visited(set as // false by default in java) boolean visited[] = new boolean[V]; // Call the recursive helper function to print DFS traversal DFSUtil(v, visited); } public static void main(String args[]) { Graph g = new Graph(4); g.addEdge(0, 1); g.addEdge(0, 2); g.addEdge(1, 2); g.addEdge(2, 0); g.addEdge(2, 3); g.addEdge(3, 3); System.out.println("Following is Depth First Traversal "+ "(starting from vertex 2)"); g.DFS(2); } } ================================================ FILE: Algorithms/Graph/DFS/Depth First Search[DFS].cpp ================================================ // DFS algorithm in C++ #include #include using namespace std; class Graph { int numVertices; list *adjLists; bool *visited; public: Graph(int V); void addEdge(int src, int dest); void DFS(int vertex); }; // Initialize graph Graph::Graph(int vertices) { numVertices = vertices; adjLists = new list[vertices]; visited = new bool[vertices]; } // Add edges void Graph::addEdge(int src, int dest) { adjLists[src].push_front(dest); } // DFS algorithm void Graph::DFS(int vertex) { visited[vertex] = true; list adjList = adjLists[vertex]; cout << vertex << " "; list::iterator i; for (i = adjList.begin(); i != adjList.end(); ++i) if (!visited[*i]) DFS(*i); } int main() { Graph g(4); g.addEdge(0, 1); g.addEdge(0, 2); g.addEdge(1, 2); g.addEdge(2, 0); g.addEdge(2, 3); g.addEdge(3, 3); g.DFS(2); return 0; } /* Output: 2 3 0 */ ================================================ FILE: Algorithms/Graph/DFS/README.md ================================================ ## This folder is empty. ================================================ FILE: Algorithms/Graph/DFS/dfs.js ================================================ function dfs(at) { // if we have been visited the node then return if(visited[at]) return; // mark the node as visited visited[at] = true; result.push(at); // or you can do something with the node // find the nodes in depth let nodes = adjList.get(at); for (let neigh of nodes) { dfs(neigh); } } function addNode(node) { // adding the node, at first point to nothing adjList.set(node, []); } function addEdge(origin, destination) { // finding the node origin and set the edge to destination adjList.get(origin).push(destination); // finding the node destination and set the edge to origin adjList.get(destination).push(origin); } // T E S T const nodes = [0,1,2,3,4,5,6,7,8,9,10]; const edges = [ [0, 4], [0, 3], [3, 2], [3, 7], [3, 8], [5, 4], [5, 1], [5, 10], [5, 6], [10, 1], ]; // define a structure to support the graph let adjList = new Map(); // biulding the nodes of the graph nodes.forEach(addNode); // building the edges edges.forEach(edge=>addEdge(...edge)); // building an array for the flag of the visited nodes let visited = new Array(nodes.length).fill(false); // traverse starting from node 0 let start_node = 0; let result = []; dfs(start_node); console.log(`the result of traverse the graph from ${start_node} is`, result); ================================================ FILE: Algorithms/Graph/DFS/dfs.py ================================================ """ Depth First Search - DFS A Graph Traversal Algorithm where the nodes in a graph are visited in a depth-first pattern. i.e The start or current node is processed and then its adjacent nodes are explored by going deeper into the graph or tree. Steps 1. Pick a starting node or vertex. 2. Process the node by printing or appending to an array. 3. Mark the node as 'seen' in a set so it doesn't get visited again. 3. For each current node get its adjacent nodes or edges and repeat processes 1, 2 and 3. Time complexity is O(N) since we visit every node at least once. N is the number of nodes in the graph. Space complexity is O(N) since we mark each visited node in a set data structure of size N. Sample Graph: 1 - 2 - 5 | | 4 - 3 , starting node = 1 DFS of this graph with starting node as 1 gives -> [1,2,5,3,4]. Another variant could be -> [1,2,3,4,5]. """ # Test Case class Graph(object): def __init__(self): self.nodes = {} # Stores all nodes # Method to add a node def addNode(self, node): self.nodes[node] = [] # Method to add an edge def addEdge(self, edge): self.nodes[edge[0]].append(edge[1]) # Method to view graph (all nodes) def peek(self): return self.nodes testGraph = Graph() nodes = [1, 2, 3, 4,5] edges = [[1,2], [1,4], [2,5], [2,3],[3,2], [3,4], [4,1], [4,3], [2,1]] for node in nodes: testGraph.addNode(node) for edge in edges: testGraph.addEdge(edge) # Our graph will now look like this # testGraph = { # 1: [2, 4], # 2: [5, 3, 1], # 3: [2, 4], # 4: [1, 3], # 5: [] # } # Code Implementation output = [] seen = set() currNode = 1 def dfs(currNode): if currNode in seen: # Check to see if the current node has been visited. return output.append(currNode) # Process the node seen.add(currNode) # Mark it as seen edges = testGraph.nodes[currNode] # Get current node's edges for edge in edges: # Explore and repeat the process dfs(edge) print(testGraph.nodes) print(output) # Prints [1,2,5,3,4] ================================================ FILE: Algorithms/Graph/DSU/dsu.cpp ================================================ /* Disjoint Set Union (Union Find) - DSU DSU is a data structure which is initialized of N sets with 1 element in each, and supports the following operations: union_sets(a, b) - unite two sets (the set where element a is located, and the set where element b is located) find_set(v)- return the head (leader) element of the set by one of it's elements DSU is usually implemented as a tree, where to find head element of a set we go up till the root. Usually two optimisations are implemented: 1. path shortening let's say you have a long chain of elements, you can cache the find_set calls and connect the deepest elements to higher elements in the tree to reduce traversion time 2. ranking system (either via size of a set, or it's depth) Example test: 10 10 2 1 DSU1: 1 DSU2: 1 2 2 DSU1: 2 DSU2: 2 1 1 2 2 1 DSU1: 1 DSU2: 1 2 2 DSU1: 1 DSU2: 1 2 8 DSU1: 8 DSU2: 8 1 8 2 2 8 DSU1: 1 DSU2: 1 2 2 DSU1: 1 DSU2: 1 2 5 DSU1: 5 DSU2: 5 You can see that, when uniting set with element 8 and element 2, the smaller set (with 8) is united with the bigger set (with 2) */ #include using namespace std; class AbstractDSU { /* Time complexity: worst case O(log n), often almost O(1) Space complexity: O(2n) Elements are numbered from 1 to n @param n number of elements (number of sets) */ protected: vector prev, rank; int DEFAULT_RANK = 1; /* Checks that element passed is within the required range @param x element to check @return Whether the element is within required range */ bool process_set_boundaries(int x) { if (x < 1 or x > prev.size()) return false; return true; } public: AbstractDSU(int n) : prev(n + 1), rank(n + 1) { for (int i = 1; i <= n; i++) { prev[i] = i; rank[i] = DEFAULT_RANK; } } /* Finds the head element of the set that contains the element passed @param v element of the set @return Head element of that set */ int find_set(int v) { if (!process_set_boundaries(v)) return -1; if (v == prev[v]) // if v is root, we found the head element return v; // re-connect the element higher up in the tree to not traverse the long path again return prev[v] = find_set(prev[v]); } /* Unite two sets that contain the elements passed @param a element of the first set @param b element of the second set */ void union_sets(int a, int b) { if (!process_set_boundaries(a) || !process_set_boundaries(b)) return; // Find head elements of each set, if they are equal-there is no need to unite the same set int x = find_set(a), y = find_set(b); if (x == y) return; if (rank[x] < rank[y]) swap(x, y); // union set y into bigger set x // the head element of set y gets connected to head element of set x prev[y] = x; update_rank(x, y); } /* Updates the rank of the set that contains the element passed Assumes that set x is the bigger set @param x element of the first set @param y element of the second set */ virtual void update_rank(int x, int y) = 0; }; class DSUBySize : public AbstractDSU { int DEFAULT_RANK = 1; public: DSUBySize(int n) : AbstractDSU(n) {} void update_rank(int x, int y) { rank[x] += rank[y]; } }; class DSUByRank : public AbstractDSU { int DEFAULT_RANK = 0; public: DSUByRank(int n) : AbstractDSU(n) {} void update_rank(int x, int y) { if (rank[x] == rank[y]) { rank[x] += 1; } } }; int main() { /* Sample program to test it Reads n - number of elements, q - number of queries Then q lines follow with first number being the query type (t) If t=1, then the query is to union sets by their elements x and y If t=2, then the query is to find the set of element x Output -1 if element doesn't belong to any set */ int n, q; cin >> n >> q; DSUBySize dsu1(n); DSUByRank dsu2(n); for (int i = 0; i < q; i++) { int t, a, b; cin >> t; if (t == 1) { cin >> a >> b; dsu1.union_sets(a, b); dsu2.union_sets(a, b); } else if (t == 2) { cin >> a; // The outputs should match, as the only difference is ranking strategy which only affects the asymptotic time complexity cout << "DSU1: " << dsu1.find_set(a) << endl; cout << "DSU2: " << dsu2.find_set(a) << endl; } } return 0; } ================================================ FILE: Algorithms/Graph/DSU/dsu.py ================================================ """ Disjoint Set Union (Union Find) - DSU DSU is a data structure which is initialized of N sets with 1 element in each, and supports the following operations: union_sets(a, b) - unite two sets (the set where element a is located, and the set where element b is located) find_set(v)- return the head (leader) element of the set by one of it's elements DSU is usually implemented as a tree, where to find head element of a set we go up till the root. Usually two optimisations are implemented: 1. path shortening let's say you have a long chain of elements, you can cache the find_set calls and connect the deepest elements to higher elements in the tree to reduce traversion time 2. ranking system (either via size of a set, or it's depth) Example test: 10 10 2 1 DSU1: 1 DSU2: 1 2 2 DSU1: 2 DSU2: 2 1 1 2 2 1 DSU1: 1 DSU2: 1 2 2 DSU1: 1 DSU2: 1 2 8 DSU1: 8 DSU2: 8 1 8 2 2 8 DSU1: 1 DSU2: 1 2 2 DSU1: 1 DSU2: 1 2 5 DSU1: 5 DSU2: 5 You can see that, when uniting set with element 8 and element 2, the smaller set (with 8) is united with the bigger set (with 2) """ from abc import abstractmethod class AbstractDSU: """DSU Time complexity: worst case O(log n), often almost O(1) Space complexity: O(2n) Elements are numbered from 1 to n Args: n (int): number of elements (number of sets) """ DEFAULT_RANK: int def __init__(self, n): self.prev = [i for i in range(n + 1)] self.rank = [self.DEFAULT_RANK for i in range(n + 1)] def _process_set_boundaries(self, x): """Checks that element passed is within the required range Args: x (int): element to check Returns: bool: Whether the element is within required range """ # len(X) is O(1) if x < 1 or x > len(self.prev): return False return True def find_set(self, v): """Finds the head element of the set that contains the element passed Args: v (int): element of the set Returns: int: Head element of that set """ if not self._process_set_boundaries(v): return -1 if v == self.prev[v]: # if v is root, we found the head element return v # re-connect the element higher up in the tree to not traverse the long path again self.prev[v] = self.find_set(self.prev[v]) return self.prev[v] def union_sets(self, a, b): """Unite two sets that contain the elements passed Args: a (int): element of the first set b (int): element of the second set """ if not self._process_set_boundaries(a) or not self._process_set_boundaries(b): return # Find head elements of each set, if they are equal-there is no need to unite the same set x = self.find_set(a) y = self.find_set(b) if x == y: return if self.rank[x] < self.rank[y]: x, y = y, x # union set y into bigger set x # the head element of set y gets connected to head element of set x self.prev[y] = x self.update_ranks(x, y) @abstractmethod def update_ranks(self, x, y): """Updates the rank of the set that contains the element passed Assumes that set x is the bigger set Args: x (int): element of the first set y (int): element of the second set """ raise NotImplementedError() class DSUBySize(AbstractDSU): DEFAULT_RANK = 1 def update_ranks(self, x, y): self.rank[x] += self.rank[y] class DSUByRank(AbstractDSU): DEFAULT_RANK = 0 def update_ranks(self, x, y): if self.rank[x] == self.rank[y]: self.rank[x] += 1 if __name__ == "__main__": # Sample program to test it # Reads n - number of elements, q - number of queries # Then q lines follow with first number being the query type (t) # If t=1, then the query is to union sets by their elements x and y # If t=2, then the query is to find the set of element x # Output -1 if element doesn't belong to any set n, q = map(int, input().split()) dsu1 = DSUBySize(n) dsu2 = DSUByRank(n) for _ in range(q): t, *args = map(int, input().split()) if t == 1: dsu1.union_sets(*args) dsu2.union_sets(*args) elif t == 2: # The outputs should match, as the only difference is ranking strategy which only affects the asymptotic time complexity print(f"DSU1: {dsu1.find_set(args[0])}") print(f"DSU2: {dsu2.find_set(args[0])}") ================================================ FILE: Algorithms/Graph/Depth First Transversal/DFT.py ================================================ class graph: def __init__(self,gdict=None): if gdict is None: gdict = {} self.gdict = gdict # Check for the visisted and unvisited nodes def dfs(graph, start, visited = None): if visited is None: visited = set() visited.add(start) print(start) for next in graph[start] - visited: dfs(graph, next, visited) return visited gdict = { "a" : set(["b","c"]), "b" : set(["a", "d"]), "c" : set(["a", "d"]), "d" : set(["e"]), "e" : set(["a"]) } dfs(gdict, 'a') ================================================ FILE: Algorithms/Graph/Dijkstra/Dijikstra.java ================================================ class Dijikstra { static final int V = 9; int minDistance(int dist[], Boolean sptSet[]) { int min = Integer.MAX_VALUE, min_index = -1; for (int v = 0; v < V; v++) if (sptSet[v] == false && dist[v] <= min) { min = dist[v]; min_index = v; } return min_index; } void printSolution(int dist[]) { System.out.println("Vertex \t\t Distance from Source"); for (int i = 0; i < V; i++) System.out.println(i + " \t\t " + dist[i]); } void dijkstra(int graph[][], int src) { int dist[] = new int[V]; Boolean sptSet[] = new Boolean[V]; for (int i = 0; i < V; i++) { dist[i] = Integer.MAX_VALUE; sptSet[i] = false; } dist[src] = 0; for (int count = 0; count < V - 1; count++) { int u = minDistance(dist, sptSet); sptSet[u] = true; for (int v = 0; v < V; v++) if (!sptSet[v] && graph[u][v] != 0 && dist[u] != Integer.MAX_VALUE && dist[u] + graph[u][v] < dist[v]) dist[v] = dist[u] + graph[u][v]; } printSolution(dist); } public static void main(String[] args) { int graph[][] = new int[][] { { 0, 4, 0, 0, 0, 0, 0, 8, 0 }, { 4, 0, 8, 0, 0, 0, 0, 11, 0 }, { 0, 8, 0, 7, 0, 4, 0, 0, 2 }, { 0, 0, 7, 0, 9, 14, 0, 0, 0 }, { 0, 0, 0, 9, 0, 10, 0, 0, 0 }, { 0, 0, 4, 14, 10, 0, 2, 0, 0 }, { 0, 0, 0, 0, 0, 2, 0, 1, 6 }, { 8, 11, 0, 0, 0, 0, 1, 0, 7 }, { 0, 0, 2, 0, 0, 0, 6, 7, 0 } }; Dijikstra t = new Dijikstra(); t.dijkstra(graph, 0); } } // This code is contributed by Aakash Hasija // Source : (Geeks for Geeks) // Cleaned by Harsh Kumar ================================================ FILE: Algorithms/Graph/Dijkstra/Dijkstra.c ================================================ #include #include #include int getMinVertex(bool* visited,int* distance,int n){ int minVertex = -1; for(int i=0;i (edges[minVertex][j]+distance[minVertex]) ){ distance[j] = edges[minVertex][j] + distance[minVertex]; } } } for(int i=0;i #include #include #include using namespace std; typedef pair ipair; class Graph{ int v; list *adj; public: Graph(int v); void Edge(int edge,int weight,int vertex); void dijkstra_pq(int src); }; Graph::Graph(int v){ this->v=v; adj=new list [v]; } void Graph::Edge(int u, int v, int w) { adj[u].push_back(make_pair(v, w)); adj[v].push_back(make_pair(u, w)); } void Graph::dijkstra_pq(int src){ priority_queue,greater> pq; //This is the syntax of creating a min heap using priority queue // Create a vector for distances and initialize all // distances as infinite (INF) vector dist(v,INT16_MAX); //Insert source itself in priority queue and initialize // its distance as 0. pq.push(make_pair(0,src)); dist[src]=0; while(!pq.empty()){ int u=pq.top().second; pq.pop(); for(auto i=adj[u].begin();i!=adj[u].end();i++){ int V=(*i).first; int w=(*i).second; if(dist[V]>dist[u]+w){ // Edge Relaxation dist[V]=dist[u]+w; pq.push(make_pair(dist[V],V)); } } } // Print shortest distances stored in dist[] cout<<"Vertex\t\tDistance"<= 0 { v = path[v] s = dg.names[v] + s } return s } func (dg DijkstraGraph) Vertices() []Vertex { vertices := make([]Vertex, 0, len(dg.ids)) for _, v := range dg.ids { vertices = append(vertices, v) } return vertices } func (dg DijkstraGraph) Neighbors(u Vertex) []Vertex { vertices := make([]Vertex, 0, len(dg.edges[u])) for v := range dg.edges[u] { vertices = append(vertices, v) } return vertices } func (dg DijkstraGraph) Weight(u, v Vertex) int { return dg.edges[u][v] } const ( Infinity = int(^uint(0) >> 1) Uninitialized = -1 ) // Dijkstra function will receive Graph interface and the source and output the distance and the path func Dijkstra(g Graph, source Vertex) (dist map[Vertex]int, path map[Vertex]Vertex) { vertices := g.Vertices() dist = make(map[Vertex]int, len(vertices)) path = make(map[Vertex]Vertex, len(vertices)) s := source dist[s] = 0 q := &PriorityQueue{ items: make([]Vertex, 0, len(vertices)), index: make(map[Vertex]int, len(vertices)), priority: make(map[Vertex]int, len(vertices)), } for _, v := range vertices { if v != s { dist[v] = Infinity } path[v] = Uninitialized q.addWithPriority(v, dist[v]) } for len(q.items) != 0 { u := heap.Pop(q).(Vertex) for _, v := range g.Neighbors(u) { alt := dist[u] + g.Weight(u, v) if alt < dist[v] { dist[v] = alt path[v] = u q.update(v, alt) } } } return dist, path } func main() { g := NewDijkstraGraph(map[string]Vertex{ "a": 1, "b": 2, "c": 3, "d": 4, "e": 5, "f": 6, }) g.edge("a", "b", 8) g.edge("a", "c", 9) g.edge("a", "f", 13) g.edge("b", "c", 9) g.edge("b", "d", 14) g.edge("c", "d", 11) g.edge("c", "f", 2) g.edge("d", "e", 7) g.edge("e", "f", 9) dist, path := Dijkstra(g, g.ids["a"]) fmt.Println("From a =") fmt.Printf("Distance to %s: %d, Path: %s\n", "e", dist[g.ids["e"]], g.path(g.ids["e"], path)) fmt.Printf("Distance to %s: %d, Path: %s\n", "f", dist[g.ids["f"]], g.path(g.ids["f"], path)) } ================================================ FILE: Algorithms/Graph/Dijkstra/Dijkstra.js ================================================ /*EXPLANATION OF THE CODE =>We are using adjacency matrix. Initialize the distance to the starting node as 0 and the distances to all other nodes as infinite Set all nodes to “unvisited” While we haven’t visited all nodes: 1.Find the node with currently shortest distance from the source (for the first pass, this will be the source node itself) 2.For all nodes next to it that we haven’t visited yet, check if the currently smallest distance to that neighbor is bigger than if we were to go via the current node If it is, update the smallest distance of that neighbor to be the distance from the source to the current node plus the distance from the current node to that neighbor In the end, the array we used to keep track of the currently shortest distance from the source to all other nodes will contain the (final) shortest distances. */ /*CODE*/ const dijkstra = function (graph, start) { //This contains the distances from the start node to all other nodes var distances = []; //Initializing with a distance of "Infinity" for (var i = 0; i < graph.length; i++) distances[i] = Number.MAX_VALUE; //The distance from the start node to itself is of course 0 distances[start] = 0; //This contains whether a node was already visited var visited = []; //While there are nodes left to visit... while (true) { // ... find the node with the currently shortest distance from the start node... var shortestDistance = Number.MAX_VALUE; var shortestIndex = -1; for (var i = 0; i < graph.length; i++) { //... by going through all nodes that haven't been visited yet if (distances[i] < shortestDistance && !visited[i]) { shortestDistance = distances[i]; shortestIndex = i; } } console.log("Visiting node " + shortestDistance + " with current distance " + shortestDistance); if (shortestIndex === -1) { // There was no node not yet visited --> We are done return distances; } //...then, for all neighboring nodes.... for (var i = 0; i < graph[shortestIndex].length; i++) { //...if the path over this edge is shorter... if (graph[shortestIndex][i] !== 0 && distances[i] > distances[shortestIndex] + graph[shortestIndex][i]) { //...Save this path as new shortest path. distances[i] = distances[shortestIndex] + graph[shortestIndex][i]; console.log("Updating distance of node " + i + " to " + distances[i]); } } // Lastly, note that we are finished with this node. visited[shortestIndex] = true; console.log("Visited nodes: " + visited); console.log("Currently lowest distances: " + distances); } }; module.exports = {dijkstra}; ================================================ FILE: Algorithms/Graph/Dijkstra/Dijkstra.php ================================================ edges = []; } public function addEdge($to, $d) { $this->edges[$to] = $d; } } class MinHeap extends SplPriorityQueue { public function compare($p1, $p2) { parent::compare($p2, $p1); } } class Graph { private $vList; public function __construct() { $this->vList = []; } public function insertVertex($label) { $this->vList[$label] = new Vertex(); } public function insertEdge($from, $to, $d) { $this->vList[$from]->addEdge($to, $d); } public function dijkstra($from, $destination) { $distance = []; $prev = []; $visited = [$from]; $pq = new MinHeap(); $pq->setExtractFlags(SplPriorityQueue::EXTR_BOTH); // First we populate the distance and previous matrixes // The we insert each node in the priority queue foreach ($this->vList as $vid => $vertex) { $distance[$vid] = INF; $prev[$vid] = null; } $distance[$from] = 0; $pq->insert($from, 0); // Then we do the "main loop" where we explore the node with least distance to source while(!$pq->isEmpty()) { $v_dist = $pq->extract(); $v = $v_dist['data']; $pathdist = $v_dist['priority']; $visited[$v] = True; foreach($this->vList[$v]->edges as $to=>$edgedist) { $tmpdist = $distance[$v] + $edgedist; if ($tmpdist < $distance[$to]) { $distance[$to] = $tmpdist; $prev[$to] = $v; $pq->insert($to, $tmpdist); } } } return $this->pathToString($prev, $destination); } public function pathToString($prev, $destination) { $from = $prev[$destination]; if (is_null($from)) { return $destination; } else { return $this->pathToString($prev, $from).' -'.$this->vList[$from]->edges[$destination].'-> '.$destination; } } } // Hola $g = new Graph(); $g->insertVertex("a"); $g->insertVertex("b"); $g->insertVertex("c"); $g->insertEdge("a", "b", 8); $g->insertEdge("b", "c", 4); $g->insertEdge("a", "c", 200); echo $g->dijkstra("a", "c").PHP_EOL; $g2 = new Graph(); $g2->insertVertex("a"); $g2->insertVertex("b"); $g2->insertVertex("c"); $g2->insertVertex("d"); $g2->insertEdge("a", "a", 0); $g2->insertEdge("a", "b", 5); $g2->insertEdge("a", "c", 10); $g2->insertEdge("a", "d", 34); $g2->insertEdge("b", "c", 3); $g2->insertEdge("c", "d", 7); $path = $g2->dijkstra("a", "d").PHP_EOL; echo $path; ================================================ FILE: Algorithms/Graph/Dijkstra/README.md ================================================ This folder contains Dijkstra Algorithms in various languages... ================================================ FILE: Algorithms/Graph/Dijkstra/dijkstra_leftist_heap/README.txt ================================================ Compilar: "g++ src/dijkstra.cpp src/leftistHeap.cpp src/WDGraph.cpp -o dijkstra" Ejecutar: "./dijkstra N_VERTICES MAX_WEIGHT CHANCE" El output indica el tiempo de ejecucion del algoritmo en milisegundos ================================================ FILE: Algorithms/Graph/Dijkstra/dijkstra_leftist_heap/WDGraph.cpp ================================================ #include "WDGraph.h" #define INF 10e6; // EdgeNode methods EdgeNode::EdgeNode(int src, int dst, float weight, EdgeNode *next) { _src = src; _dst = dst; _weight = weight; _next = next; } // VertexNode methods VertexNode::VertexNode(int elem, VertexNode *next, EdgeNode *edges) { _elem = elem; _dist = INF; _nodesPointed = 0; _visited = 0; _parentOnMinPath = NULL; _next = next; _edges = edges; } // WDGraph methods WDGraph::WDGraph() { _head = NULL; _nVertex = 0; _map = new std::unordered_map; } void WDGraph::addEdge(int src, int dst, float weight) { // Se encarga de anadir las aristas al grafo, si alguno de los vertices mencionados en la arista no forma parte del grafo, lo anade tambien if (_head == NULL) { EdgeNode *edge1 = new EdgeNode(src, dst, weight, NULL); // Creamos la arista src -> dst VertexNode *aux = new VertexNode(dst, NULL, NULL); // Creamos el vertice dst _head = new VertexNode(src, aux, edge1); // Creamos el vertice src y lo asignamos a _head _head->_nodesPointed++; _map->insert(std::make_pair(src, _head)); _map->insert(std::make_pair(dst, aux)); _nVertex += 2; // Aumentamos el # de vertices } else { EdgeNode *aux = NULL; VertexNode *vAux = NULL; std::unordered_map::iterator iter = _map->find(src); if (iter != _map->end()) { aux = iter->second->_edges; iter->second->_edges = new EdgeNode(src, dst, weight, aux); iter->second->_nodesPointed++; } else { EdgeNode *eAux = new EdgeNode(src, dst, weight, NULL); vAux = _head; _head = new VertexNode(src, vAux, eAux); _head->_nodesPointed++; _map->insert(std::make_pair(src, _head)); _nVertex++; } iter = _map->find(dst); if (iter == _map->end()) { vAux = _head; _head = new VertexNode(dst, vAux, NULL); _map->insert(std::make_pair(dst, _head)); _nVertex++; } } } void WDGraph::printGraph() { // DEBUG VertexNode *vertex = _head; for (int i = 0; i < _nVertex; i++) { std::cerr << "Adyacency list of: " << vertex->_elem << '\n'; EdgeNode *edge = vertex->_edges; while (edge) { std::cerr << " -> " << edge->_dst << " (" << edge->_weight << ')'; edge = edge->_next; } std::cerr << '\n'; vertex = vertex->_next; } } void WDGraph::printGraphvertices() { // DEBUG VertexNode *vertex = _head; for (int i = 0; i < _nVertex; i++) { std::cerr << "Vertex: " << vertex->_elem << '\n'; std::cerr << " # of pointed nodes: " << vertex->_nodesPointed << '\n'; std::cerr << " visited: " << (vertex->_visited ? "True\n" : "False\n"); std::cerr << " distance: " << vertex->_dist << '\n'; if (vertex->_parentOnMinPath != NULL) std::cerr << " parentOnShortestPath: " << vertex->_parentOnMinPath->_elem << '\n'; std::cerr << '\n'; vertex = vertex->_next; } } void WDGraph::getvertices(std::vector &ret) { VertexNode *vertex = _head; for (int i = 0; i < _nVertex; i++) { ret.push_back(vertex); vertex = vertex->_next; } } void WDGraph::changeVertexDistance(int e, float newDist) { std::unordered_map::iterator iter = _map->find(e); if (iter != _map->end()) { iter->second->_dist = newDist; } else { std::cerr << e << " is not currently in the graph.\n"; } } void WDGraph::changeParent(int e, VertexNode *parent) { std::unordered_map::iterator iter = _map->find(e); if (iter != _map->end()) { iter->second->_parentOnMinPath = parent; } else { std::cerr << e << " is not currently in the graph.\n"; } } void WDGraph::visitVertex(int e) { std::unordered_map::iterator iter = _map->find(e); if (iter != _map->end()) { iter->second->_visited = 1; } else { std::cerr << e << " is not currently in the graph.\n"; } } void WDGraph::getNeightbours(int e, std::vector &ret) { std::unordered_map::iterator iter = _map->find(e); EdgeNode *aux; if (iter != _map->end()) { aux = iter->second->_edges; for (int i = 0; i < iter->second->_nodesPointed; i++) { if (!getVertex(aux->_dst)->_visited) ret.push_back(aux); aux = aux->_next; } } else { std::cerr << e << " is not currently in the graph.\n"; } } int WDGraph::getNumberOfNeightbours(int e) { std::unordered_map::iterator iter = _map->find(e); if (iter != _map->end()) { return iter->second->_nodesPointed; } else { std::cerr << e << " is not currently in the graph.\n"; } return -1; } VertexNode* WDGraph::getVertex(int e) { std::unordered_map::iterator iter = _map->find(e); if (iter != _map->end()) { return iter->second; } else { std::cerr << e << " is not currently in the graph.\n"; } return NULL; } ================================================ FILE: Algorithms/Graph/Dijkstra/dijkstra_leftist_heap/WDGraph.h ================================================ #ifndef _WDGraph_ #define _WDGraph_ #include #include #include #include /* Implementation of a Weighted Directed Graph using Linked lists. Each vertex is represented by VertexNode: _elem contains the value of the given node _visited controls if the visited has been visited by any algorithm _nodesPointed controls the nomber of nodes in the list _visited stores the result of the dijkstra algorithm, true if visited after the algorithm _parentOnMinPath stores the parent of the note in the minimum path after dijkstra _next pointer to the next VertexNode in the graph _edges pointer to the first EdgeNode of the Vertex Each edge is represented by EdgeNode: _src contains the value from the vertex wich the edge comes out _dst contains the value from the vertex wich the edge goes to _weight contains the cost of traveling trought the given edge _next pointer to the next edge of the given VertexNode The complete graph is represented by WDGraph: _head pointer to the first VertexNode in the graph */ class EdgeNode { // Edges public: int _src; int _dst; float _weight; EdgeNode *_next; EdgeNode(int src, int dst, float weight, EdgeNode *next); // Constructor }; class VertexNode { // Adyacency list (linked list) public: int _elem; float _dist; int _nodesPointed; bool _visited; VertexNode *_parentOnMinPath; VertexNode *_next; EdgeNode *_edges; VertexNode(int elem, VertexNode *next, EdgeNode *edges); // Constructor }; class WDGraph { public: VertexNode *_head; int _nVertex; std::unordered_map *_map; // Stores the current vertex on the graph and a pointer to them in order to insert a new edge in O(1) void addEdge(int src, int dst, float weight); // Adds an EdgeNode from src to dst with the given weight void printGraph(); // Prints the adyacency list for the graph void printGraphvertices(); // Prints all the info of each vertex of the graph void getvertices(std::vector &ret);// Returns an array with all the vertices of the graph in it void changeVertexDistance(int e, float newDist);// Changes the distance attribute of the given node to the desired value void changeParent(int e, VertexNode* parent); // Changes the parent attribute of the given node to the desired value void visitVertex(int e); // Marks the node as visited void getNeightbours(int e, std::vector &ret); // Returns the neightbours oof the given vertex int getNumberOfNeightbours(int e); // Returns the number of neightbours of the given node VertexNode* getVertex(int e); // Returns the corresponding node to the given element WDGraph(); // Constructor }; #endif ================================================ FILE: Algorithms/Graph/Dijkstra/dijkstra_leftist_heap/dijkstra.cpp ================================================ #include #include #include #include #include "leftistHeap.h" #include "WDGraph.h" const float INF = 10e6; WDGraph g; std::vector vertices; std::vector EdgesToNeightbours; LeftistHeap h; void readGraph(WDGraph &g); void createGraph(int N_VERTICES, int MAX_WEIGHT, float EDGE_CHANCE, long unsigned int &edges); void dijkstra(WDGraph g, int src); int main(int argc, char **argv) { srand(time(NULL)); long unsigned int edges = 0; if (argc != 4){ std::cerr << "Wrong # of arguments\n"; std::cerr << "Correct arguments are: (int) N_VERTICES, (int) MAX_WEIGHT, (float) EDGE_CHANCE\n"; return 1; } std::cerr << "Generating a graph with: " << '\n'; std::cerr << " " << argv[1] << " N_VERTICES\n"; std::cerr << " " << argv[2] << " MAX_WEIGHT\n"; std::cerr << " " << std::stod(argv[3])*100 << "% EDGE_CHANCE\n"; std::cerr << "-------------------------\n"; std::cerr << std::pow(std::stoi(argv[1]), 2)*std::stod(argv[3]) << " expected edges (aprox)\n"; // readGraph(g); // Descomentar para leer el grafo (./dijkstra < inputFile) createGraph(std::stoi(argv[1]), std::stoi(argv[2]), std::stod(argv[3]), edges); // Comentar si se desea leer el grafo en lugar de generarlo // g.printGraph(); // Descomentar para imprimir las listas de adyacencia del grafo generado o leido std::cerr << "Executing dijkstra...\n"; auto start = std::chrono::steady_clock::now(); dijkstra(g, 0); auto end = std::chrono::steady_clock::now(); std::cout << std::chrono::duration(end - start).count() << "\n"; std::cerr << std::chrono::duration(end - start).count() << " ms - Total time\n"; std::cerr << edges/std::chrono::duration(end - start).count() << " edges/ms\n"; // g.printGraphvertices(); // Descomentar para imprimir los datos de todos los vertices tras la ejecucion del algoritmo return 0; } void dijkstra(WDGraph g, int src) { std::pair minElem; VertexNode *minElemVertex; vertices.clear(); g.getvertices(vertices); // Modificamos la distancia del nodo de inicio a 0 g.changeVertexDistance(src, 0); // Insertamos todos los vertices en el monticulo, tienen distancia INF, no estan visitados y no tienen nodo previo for (int i = 0; i < g._nVertex; i++) h.insert(std::make_pair(vertices[i]->_dist, vertices[i]->_elem)); // Mientras el monticulo no este vacio, operamos de la siguiente manera while (!h.isEmpty()) { // Extraemos el minimo elemento y conseguimos acceso a su nodo mediante el la funcion getVertex(), tambien eliminamos dicho elemento del monticulo ya que ya ha sido visitado h.deleteMin(minElem); minElemVertex = g.getVertex(minElem.second); // Si el nodo visitado tiene una distancia distinta a INF, implica que ha sido visitado por el algoritmo if (minElemVertex->_dist != INF) g.visitVertex(minElem.second); EdgesToNeightbours.clear(); // Extraemos la lista de adyacencia del vertice a tratar en esta iteraccion g.getNeightbours(minElemVertex->_elem, EdgesToNeightbours); for (long unsigned int i = 0; i < EdgesToNeightbours.size(); i++) { // Para cada vecino al vertice a tratar comprobamos que no haya sido visitado (y eliminado del monticulo) y si la distancia desde le nodo actual mejora la distancia obtenida por el camino anterior if (!(g.getVertex(EdgesToNeightbours[i]->_dst)->_visited) && (minElemVertex->_dist + EdgesToNeightbours[i]->_weight < g.getVertex(EdgesToNeightbours[i]->_dst)->_dist)) { // Modificamos la distancia de llegada al vecino a traves de su padre g.changeVertexDistance(EdgesToNeightbours[i]->_dst, minElemVertex->_dist + EdgesToNeightbours[i]->_weight); // Indicamos al vecino que el vertice actual es su padre en el camino minimo g.getVertex(EdgesToNeightbours[i]->_dst)->_parentOnMinPath = minElemVertex; // Decrecemos la clave de dicho vecino a su nuevo valor en el monticulo // Cabe destacar que esta funcion es un tanto extrana, ya que recibe el ELEMENTO del vertice para modificar su DISTANCIA, esta funcionalidad ha sido implementada // en la funcion decrecerClave() en el archivo leftistHeap.cpp. Dicho monticulo contiene un mapa que relaciona elemento - puntero al nodo correspondiente. h.decreaseKey(g.getVertex(EdgesToNeightbours[i]->_dst)->_elem, g.getVertex(EdgesToNeightbours[i]->_dst)->_dist); } } } } void readGraph(WDGraph &g) { int src; int dst; float weight; while ((std::cin >> src) && (std::cin >> dst) && (std::cin >> weight)) { g.addEdge(src, dst, weight); } } void createGraph(int N_VERTICES, int MAX_WEIGHT, float EDGE_CHANCE, long unsigned int &edges){ float r; float f; for (int row = 0; row < N_VERTICES; row++){ for (int col = 0; col < N_VERTICES; col++){ if (row != col){ r = static_cast (rand()) / static_cast (RAND_MAX); if (r <= EDGE_CHANCE){ f = static_cast (rand()) / static_cast (RAND_MAX); g.addEdge(row, col, f*MAX_WEIGHT); std::cerr.flush(); std::cerr << edges++ << " edges generated\r"; } } } } std::cerr << '\n'; } ================================================ FILE: Algorithms/Graph/Dijkstra/dijkstra_leftist_heap/leftistHeap.cpp ================================================ #include "leftistHeap.h" // Node Methods Node::Node(std::pair e) { this->_elem = e; this->_dist = 0; this->_parent = NULL; this->_left = NULL; this->_right = NULL; } Node::Node(std::pair e, int d, Node *parent, Node *l, Node *r) { this->_elem = e; this->_dist = d; this->_parent = parent; this->_left = l; this->_right = r; } // LeftistHeap Methods // Public methods LeftistHeap::LeftistHeap() { _root = NULL; _map = new std::unordered_map; } LeftistHeap::LeftistHeap(Node *newRoot, std::unordered_map *newMap) { _root = newRoot; _map = newMap; } int LeftistHeap::getMin() { return _root->_elem.second; } void LeftistHeap::deleteMin() { if (!isEmpty()) { _map->erase(_root->_elem.first); Node *aux = _root; if (_root->_left != NULL) _root->_left->_parent = NULL; if (_root->_right != NULL) _root->_right->_parent = NULL; _root = mergeHeaps(_root->_left, _root->_right); delete aux; } } void LeftistHeap::deleteMin(std::pair &minElem) { minElem = _root->_elem; deleteMin(); } void LeftistHeap::insert(std::pair elem) { if (_map->find(elem.second) != _map->end()) { std::cerr << elem.second << " already exists in the heap.\n"; return; } Node *newElem = new Node(elem); _map->insert(std::make_pair(elem.second, newElem)); _root = mergeHeaps(_root, newElem); } void LeftistHeap::decreaseKey(int elem, float newDist) { // Permite decrementar el valor de la distancia del nodo que contiene al elemento "elem" // Busca en el mapa el valor indicado por "elem" std::unordered_map::iterator iter = _map->find(elem); // Comprueba que exista en el monticulo if (iter != _map->end()) { // Si se trata de la raiz, decrece el valor correspondiente if (iter->second == _root) { _root->_elem.first = newDist; } // En caso de no ser la raiz, crea un nuevo nodo con los valores apropiados else { Node *aux = new Node( std::make_pair(newDist, iter->second->_elem.second), 0, iter->second->_parent, iter->second->_left, iter->second->_right ); // Comprueba si se trata del hijo izquierdo o derecho de su padre if ((aux->_parent->_left->_elem.second == elem)) { // Si se trata del izquierdo, el puntero _left del padre se apunta a NULL aux->_parent->_left = NULL; // Se intercambian los hijos del padre que el derecho no debe ser hijo unico swapChildren(aux->_parent); } else // Si se trata del derecho, el puntero _right del padre se apunta a NULL aux->_parent->_right = NULL; // Perdemos el puntero _parent, descolgando de forma efectiva nuestro nodo a decrementar del monticulo aux->_parent = NULL; // Se indica a nuestros hijos _left y _right que aux es el nuevo nodo padre, ya que es una direccion de memoria distinta if (aux->_left != NULL) aux->_left->_parent = aux; if (aux->_right != NULL) aux->_right->_parent = aux; // Llamamos a mergeHeaps() con la raiz original de nuestro monticulo y el nuevo nodo que hemos descolgado _root = mergeHeaps(_root, aux); // Eliminamos la antigua direccion del nodo del mapa e insertamos la nueva _map->erase(elem); _map->insert(std::make_pair(elem, aux)); } } } void LeftistHeap::merge(LeftistHeap &b) { if (this == &b) return; _root = mergeHeaps(_root, b._root); b._root = NULL; } bool LeftistHeap::isEmpty() { return _root == NULL; } void LeftistHeap::emptyHeap() { clearMem(_root); _root = NULL; _map->empty(); } void LeftistHeap::printHeap() { LeftistHeap aux; aux = *this; std::pair x; while (!aux.isEmpty()) { aux.deleteMin(x); std::cerr << '(' << x.second << ' ' << x.first << ')' << ' '; } std::cerr << '\n'; } LeftistHeap& LeftistHeap::operator =(LeftistHeap &h) { if (this != &h) { emptyHeap(); _root = cloneNode(h._root); } return *this; } std::unordered_map* LeftistHeap::map() { return _map; } // Private methods Node* LeftistHeap::mergeHeaps(Node *heap1, Node *heap2) { if (heap1 == NULL) return heap2; if (heap2 == NULL) return heap1; if (heap1->_elem.first <= heap2->_elem.first) { return MergeRecursive(heap1, heap2); } return MergeRecursive(heap2, heap1); } Node* LeftistHeap::MergeRecursive(Node *heap1, Node *heap2) { // Aparte de realizar el merge de forma correcta, se encarga de asignar el padre de cada nodo en cada asignacion if (heap1->_left == NULL) { heap1->_left = heap2; heap2->_parent = heap1; } else { heap1->_right = mergeHeaps(heap1->_right, heap2); heap1->_right->_parent = heap1; if (heap1->_left->_dist < heap1->_right->_dist) swapChildren(heap1); heap1->_dist = heap1->_right->_dist + 1; } return heap1; } void LeftistHeap::swapChildren(Node *parent) { Node *aux = parent->_right; parent->_right = parent->_left; parent->_left = aux; } void LeftistHeap::clearMem(Node *node) { if (node != NULL) { clearMem(node->_left); clearMem(node->_right); delete node; } } Node* LeftistHeap::cloneNode(Node *node) { if (node == NULL) return NULL; return new Node(node->_elem, node->_dist, node->_parent, cloneNode(node->_left), cloneNode(node->_right)); } ================================================ FILE: Algorithms/Graph/Dijkstra/dijkstra_leftist_heap/leftistHeap.h ================================================ /* FUNCTION: COMPLEXITY: - getMin() - O(1) - deleteMin() - O(log N) - insert() - O(log N) - merge() - O(log N) Node Info: - element - distance - parent - left child - right child Operations: - merge() is the main operation, called by deleteMin(), decreaseKey(), getMin() and insert() - deleteMin() removes the root of the tree and calls merge with both the left and right sons - getMin() returns the value of the pointer to the root - insert() creates a leftist heap with a single key and calls merge with the original and this new tree - decreaseKey() allows you to decrease the value of the first element of the pair given the second one */ #ifndef _LeftistHeap_ #define _LeftistHeap_ #include #include #include #include class Node { public: std::pair _elem; int _dist; Node *_parent; Node *_left; Node *_right; Node(std::pair e); // Constructor Node(std::pair e, int d, Node *p, Node *l, Node *r); // Constructor }; class LeftistHeap { public: LeftistHeap(); // Constructor int getMin(); // Returns the smallest element in the heap (root) void deleteMin(); // Removes the smallest element in the heap void deleteMin(std::pair &minElem); // Removes the smallest element in the heap and returns it to avoid using getMin() void insert(std::pair elem); // Inserts the given element into the heap void decreaseKey(int elem, float newKey); // Modifies the value of the first value of the pair of the given element into the the newKey void merge(LeftistHeap &b); // Merges the existing heap with the given one bool isEmpty(); // Tests if the heap is empty void emptyHeap(); // Empties the heap void printHeap(); // Prints all the elements of the heap in decreasing order (intended use: debbugin purposes -> O(N logN)) LeftistHeap& operator =(LeftistHeap &h); // Deep copy of a LeftistHeap std::unordered_map* map(); // Returns the map so it can be private private: Node *_root; // Root of the heap (also minimum element) std::unordered_map *_map; // Stores pointers to all the nodes of the heap given an element (second element of the pair) Node* mergeHeaps(Node *heap1, Node *heap2); // Merges both heaps, returning the root to the resulting heap Node* MergeRecursive(Node *heap1, Node *heap2); // Called by mergeHeaps() recursively void swapChildren(Node *parent); // Swaps the right and left childs of the given node void clearMem(Node *node); // Clears the dinamically allocated memory of the heap Node* cloneNode(Node *node); // Deep copy of a node LeftistHeap(Node *newRoot, std::unordered_map *newMap); // Constructor by copy }; #endif ================================================ FILE: Algorithms/Graph/Dijkstra/djikstra.py ================================================ import sys class Graph(): def __init__(self, vertices): self.V = vertices self.graph = [[0 for column in range(vertices)] for row in range(vertices)] def printSolution(self, dist): print ("Vertex tDistance from Source") for node in range(self.V): print (node, "t", dist[node]) def minDistance(self, dist, sptSet): min = sys.maxsize for v in range(self.V): if dist[v] < min and sptSet[v] == False: min = dist[v] min_index = v return min_index def dijkstra(self, src): dist = [sys.maxsize] * self.V dist[src] = 0 sptSet = [False] * self.V for cout in range(self.V): u = self.minDistance(dist, sptSet) sptSet[u] = True for v in range(self.V): if self.graph[u][v] > 0 and \ sptSet[v] == False and \ dist[v] > dist[u] + self.graph[u][v]: dist[v] = dist[u] + self.graph[u][v] self.printSolution(dist) g = Graph(9) g.graph = [[0, 4, 0, 0, 0, 0, 0, 8, 0], [4, 0, 8, 0, 0, 0, 0, 11, 0], [0, 8, 0, 7, 0, 4, 0, 0, 2], [0, 0, 7, 0, 9, 14, 0, 0, 0], [0, 0, 0, 9, 0, 10, 0, 0, 0], [0, 0, 4, 14, 10, 0, 2, 0, 0], [0, 0, 0, 0, 0, 2, 0, 1, 6], [8, 11, 0, 0, 0, 0, 1, 0, 7], [0, 0, 2, 0, 0, 0, 6, 7, 0] ]; g.dijkstra(0); ================================================ FILE: Algorithms/Graph/Flood_Fill/Flood_Fill.cpp ================================================ #include using namespace std; #define M 5 #define N 5 void floodFillUtil(int screen[][N], int x, int y, int prevC, int newC) { if (x < 0 || x >= M || y < 0 || y >= N) return; if (screen[x][y] != prevC) return; if (screen[x][y] == newC) return; screen[x][y] = newC; floodFillUtil(screen, x+1, y, prevC, newC); floodFillUtil(screen, x-1, y, prevC, newC); floodFillUtil(screen, x, y+1, prevC, newC); floodFillUtil(screen, x, y-1, prevC, newC); } void floodFill(int screen[][N], int x, int y, int newC) { int prevC = screen[x][y]; floodFillUtil(screen, x, y, prevC, newC); } int main() { int screen[M][N],x,y,newC; cout << "Enter the colors of the pixels\n"; for(int i=0;i> screen[i][j]; } } cout << "\nEnter the co-ordinates (x,y) of point in screen\n"; cin >> x; cin >> y; cout << "Enter the new color of the point (" << x << " , " << y << ")\n"; cin >> newC; floodFill(screen, x, y, newC); cout << "Updated screen after call to floodFill: \n"; for (int i=0; i= M || y < 0 || y >= N) return; if (screen[x][y] != prevC) return; // Replace the color at (x, y) screen[x][y] = newC; // Recur for north, east, south and west floodFillUtil(screen, x+1, y, prevC, newC); floodFillUtil(screen, x-1, y, prevC, newC); floodFillUtil(screen, x, y+1, prevC, newC); floodFillUtil(screen, x, y-1, prevC, newC); } // It mainly finds the previous color on (x, y) and // calls floodFillUtil() static void floodFill(int screen[][], int x, int y, int newC) { int prevC = screen[x][y]; floodFillUtil(screen, x, y, prevC, newC); } // Driver code public static void main(String[] args) { int screen[][] = {{1, 1, 1, 1, 1, 1, 1, 1}, {1, 1, 1, 1, 1, 1, 0, 0}, {1, 0, 0, 1, 1, 0, 1, 1}, {1, 2, 2, 2, 2, 0, 1, 0}, {1, 1, 1, 2, 2, 0, 1, 0}, {1, 1, 1, 2, 2, 2, 2, 0}, {1, 1, 1, 1, 1, 2, 1, 1}, {1, 1, 1, 1, 1, 2, 2, 1}, }; int x = 4, y = 4, newC = 3; floodFill(screen, x, y, newC); System.out.println("Updated screen after call to floodFill: "); for (int i = 0; i < M; i++) { for (int j = 0; j < N; j++) System.out.print(screen[i][j] + " "); System.out.println(); } } } ================================================ FILE: Algorithms/Graph/Flood_Fill/Flood_Fill.js ================================================ 'use strict' class Image { constructor (imageAsMatrix) { this.matrix = imageAsMatrix } static get COLORS () { return { BLACK: 'BLACK', AZURE: 'AZURE', WHITE: 'WHITE', GREEN: 'GREEN' } } get () { return this.matrix } randomColor () { var keys = Object.keys(Image.COLORS) return Image.COLORS[keys[keys.length * Math.random() << 0]] } buildWhithRandomColors (rows = 5, cols = 5) { this.matrix = Array.from( { length: rows }, () => Array.from({ length: cols }, () => this.randomColor()) ) } } class Floodfill { constructor (imageAsMatrix) { this.image = imageAsMatrix } get () { return this.image } bucket (row, column, newPixel) { const currentPixel = this.image[row][column] if (currentPixel === newPixel) { return this.image } this.fill(row, column, newPixel, currentPixel) return this.image } fill (row, column, newPixel, currentPixel) { if ( this.rowIsLessThenZero(row) || this.columnIsLessThenZero(column) || this.rowIsGreaterThenImageLength(row) || this.columnIsGreaterThenImageLength(row, column) || this.currentPixelNoNeedToFill(row, column, currentPixel) ) { return } this.fillCurrentPixel(row, column, newPixel) this.fillPreviousRow(row, column, newPixel, currentPixel) this.fillNextRow(row, column, newPixel, currentPixel) this.fillPreviousCol(row, column, newPixel, currentPixel) this.fillNextCol(row, column, newPixel, currentPixel) } fillCurrentPixel (row, column, newPixel) { this.image[row][column] = newPixel } fillPreviousRow (row, column, newPixel, currentPixel) { this.fill(row - 1, column, newPixel, currentPixel) } fillNextRow (row, column, newPixel, currentPixel) { this.fill(row + 1, column, newPixel, currentPixel) } fillPreviousCol (row, column, newPixel, currentPixel) { this.fill(row, column - 1, newPixel, currentPixel) } fillNextCol (row, column, newPixel, currentPixel) { this.fill(row, column + 1, newPixel, currentPixel) } rowIsLessThenZero (row) { return (row < 0) } columnIsLessThenZero (column) { return (column < 0) } rowIsGreaterThenImageLength (row) { return row > this.image.length - 1 } columnIsGreaterThenImageLength (row, column) { return column > this.image[row].length - 1 } currentPixelNoNeedToFill (row, column, currentPixel) { return (this.image[row][column] !== currentPixel) } } module.exports = { Image, Floodfill } /** * Execute for testing: * $ node ./Flood_Fill.js **/ const matrixAtBegin = [ [Image.COLORS.AZURE, Image.COLORS.AZURE, Image.COLORS.AZURE], [Image.COLORS.AZURE, Image.COLORS.AZURE, Image.COLORS.GREEN], [Image.COLORS.AZURE, Image.COLORS.GREEN, Image.COLORS.AZURE] ] /* EXPECTED: [ [Image.COLORS.BLACK, Image.COLORS.BLACK, Image.COLORS.BLACK], [Image.COLORS.BLACK, Image.COLORS.BLACK, Image.COLORS.GREEN], [Image.COLORS.BLACK, Image.COLORS.GREEN, Image.COLORS.AZURE] ] */ const imageAtBegin = new Image(matrixAtBegin).get() console.log(imageAtBegin) const floodFill = new Floodfill(imageAtBegin) const matrixAtEnd = floodFill.bucket(0, 1, Image.COLORS.BLACK) console.log(new Image(matrixAtEnd).get()) ================================================ FILE: Algorithms/Graph/Flood_Fill/flood_fill_algorithm.cs ================================================ public class Uebung1_2 implements PlugInFilter, MouseListener { private ImageProcessor ip; boolean[] state; int[] pixels; Queue nextPixels; int threshould; /** * adds one pixel to the next-pixel queue only if it's not * already added. */ void addNextPixel(int p) { if(!state[p]) { nextPixels.add(p); state[p] = true; } } boolean pixelsSimilar(int color1, int color2) { int dr = Math.abs(((color1 >> 16) & 0xff) - ((color2 >> 16) & 0xff)); int dg = Math.abs(((color1 >> 8) & 0xff) - ((color2 >> 8) & 0xff)); int db = Math.abs(((color1 >> 0) & 0xff) - ((color2 >> 0) & 0xff)); return ((double)(dr + dg + db) / 3.0) <= threshould; } /** * actually does the hard work :) * @param x the x position from which to start filling * @param y the y position from which to start filling */ private void doFill(int x, int y, boolean connect8) { // first, add the start pixel int width = ip.getWidth(), height = ip.getHeight(); /* for 8bit, we just gonna take the median of rgb */ Color colorC = ij.gui.Toolbar.getForegroundColor(); int color = colorC.getRGB(); int firstPixel = ip.get(x, y); // go on with the mainloop addNextPixel(y * width + x); while(!nextPixels.isEmpty()) { int nextPixel = nextPixels.remove(); int pixel = pixels[nextPixel]; if(pixelsSimilar(pixel, firstPixel)) { // yay it matches. put the neighbours. int xN = nextPixel % width, yN = nextPixel / width; /* the three pixels above */ if(yN - 1 >= 0) { if(connect8) { if(xN + 1 < width) { addNextPixel(nextPixel - width + 1); } if(xN - 1 >= 0) { addNextPixel(nextPixel - width - 1); } } addNextPixel(nextPixel - width); } /* pixels left and right from the current one */ if(xN > 0) { addNextPixel(nextPixel - 1); } if(xN + 1 < width) { addNextPixel(nextPixel + 1); } /* three pixels below */ if(yN + 1 < height) { if(connect8) { if(xN + 1 < width) { addNextPixel(nextPixel + width + 1); } if(xN - 1 >= 0) { addNextPixel(nextPixel + width - 1); } } addNextPixel(nextPixel + width); } /* color it finally */ pixels[nextPixel] = color; } } } @Override public void run(ImageProcessor ip) { ij.WindowManager.getCurrentImage().getCanvas().addMouseListener(this); this.ip = ip; this.pixels = (int[])ip.getPixels(); this.state = new boolean[ip.getPixelCount()]; this.nextPixels = new LinkedList(); } @Override public int setup(String arg0, ImagePlus arg1) { return DOES_RGB; } @Override public void mouseClicked(MouseEvent e) { ij.WindowManager.getCurrentWindow().getCanvas().removeMouseListener(this); ij.gui.GenericDialog g = new GenericDialog("Please enter parameters"); g.addChoice("connection", new String[]{"4-connect", "8-connect"}, "8-connect"); g.addNumericField("Threshould (0..255)", 0.0, 3); g.showDialog(); boolean connect8 = g.getNextChoice().equals("8-connect"); threshould = (int) g.getNextNumber(); doFill(e.getX(), e.getY(), connect8); ij.WindowManager.getCurrentImage().draw(); } } ================================================ FILE: Algorithms/Graph/Floyd_Warshall/Floyd_Warshall.c ================================================ // C Program for Floyd Warshall Algorithm #include // Number of vertices in the graph #define V 4 /* Define Infinite as a large enough value. This value will be used for vertices not connected to each other */ #define INF 99999 // A function to print the solution matrix void printSolution(int dist[][V]); // Solves the all-pairs shortest path problem using Floyd Warshall algorithm void floydWarshall (int graph[][V]) { /* dist[][] will be the output matrix that will finally have the shortest distances between every pair of vertices */ int dist[V][V], i, j, k; /* Initialize the solution matrix same as input graph matrix. Or we can say the initial values of shortest distances are based on shortest paths considering no intermediate vertex. */ for (i = 0; i < V; i++) for (j = 0; j < V; j++) dist[i][j] = graph[i][j]; /* Add all vertices one by one to the set of intermediate vertices. ---> Before start of an iteration, we have shortest distances between all pairs of vertices such that the shortest distances consider only the vertices in set {0, 1, 2, .. k-1} as intermediate vertices. ----> After the end of an iteration, vertex no. k is added to the set of intermediate vertices and the set becomes {0, 1, 2, .. k} */ for (k = 0; k < V; k++) { // Pick all vertices as source one by one for (i = 0; i < V; i++) { // Pick all vertices as destination for the // above picked source for (j = 0; j < V; j++) { // If vertex k is on the shortest path from // i to j, then update the value of dist[i][j] if (dist[i][k] + dist[k][j] < dist[i][j]) dist[i][j] = dist[i][k] + dist[k][j]; } } } // Print the shortest distance matrix printSolution(dist); } /* A utility function to print solution */ void printSolution(int dist[][V]) { printf ("The following matrix shows the shortest distances" " between every pair of vertices \n"); for (int i = 0; i < V; i++) { for (int j = 0; j < V; j++) { if (dist[i][j] == INF) printf("%7s", "INF"); else printf ("%7d", dist[i][j]); } printf("\n"); } } // driver program to test above function int main() { int graph[V][V] = { {0, 5, INF, 10}, {INF, 0, 3, INF}, {INF, INF, 0, 1}, {INF, INF, INF, 0} }; // Print the solution floydWarshall(graph); return 0; } ================================================ FILE: Algorithms/Graph/Floyd_Warshall/Floyd_Warshall.cpp ================================================ #include #include using namespace std; // defining the number of vertices #define nV 4 #define INF 999 void printMatrix(int matrix[][nV]); // Implementing floyd warshall algorithm void floydWarshall(int graph[][nV]) { int matrix[nV][nV], i, j, k; for (i = 0; i < nV; i++) for (j = 0; j < nV; j++) matrix[i][j] = graph[i][j]; // Adding vertices individually for (k = 0; k < nV; k++) { for (i = 0; i < nV; i++) { for (j = 0; j < nV; j++) { matrix[i][j] = min(matrix[i][j], matrix[i][k] + matrix[k][j]); } } } printMatrix(matrix); } void printMatrix(int matrix[][nV]) { for (int i = 0; i < nV; i++) { for (int j = 0; j < nV; j++) { if (matrix[i][j] == INF) printf("%4s", "INF"); else printf("%4d", matrix[i][j]); } printf("\n"); } } int main() { int graph[nV][nV] = { {0, 3, INF, 5}, {2, 0, INF, 4}, {INF, 1, 0, INF}, {INF, INF, 2, 0} }; floydWarshall(graph); return 0; } ================================================ FILE: Algorithms/Graph/Floyd_Warshall/Floyd_Warshall.java ================================================ package Algorithms.Graph_Algorithms.Floyd_Warshall; public class Floyd_Warshall { private int INF = Integer.MAX_VALUE; /** Number of nodes. Ex: 7 */ private int nodes = 7; /** Edge matrix (INF if not exist edge) */ private int[][] edges = { { INF, 2, INF, 1, INF, INF, INF }, { INF, INF, INF, 3, 10, INF, INF }, { 4, INF, INF, INF, INF, 5, INF }, { INF, INF, 2, INF, 2, 8, 4 }, { INF, INF, INF, INF, INF, INF, 6 }, { INF, INF, INF, INF, INF, INF, INF }, { INF, INF, INF, INF, INF, 1, INF } }; /** Warshall - Path */ private boolean[][] warshallP = new boolean[nodes][nodes]; public void warshall() { int i, j, k; // Adjacency matrix into warshallP for (i = 0; i < nodes; i++) for (j = 0; j < nodes; j++) warshallP[i][j] = (edges[i][j] != INF); // Iterate for (k = 0; k < nodes; k++) for (i = 0; i < nodes; i++) for (j = 0; j < nodes; j++) warshallP[i][j] = (warshallP[i][j] || (warshallP[i][k] && warshallP[k][j])); } } ================================================ FILE: Algorithms/Graph/Floyd_Warshall/Floyd_Warshall.py ================================================ # Python Program for Floyd Warshall Algorithm # Number of vertices in the graph V = 4 # Define infinity as the large enough value. This value will be # used for vertices not connected to each other INF = 99999 # Solves all pair shortest path via Floyd Warshall Algorithm def floydWarshall(graph): """ dist[][] will be the output matrix that will finally have the shortest distances between every pair of vertices """ """ initializing the solution matrix same as input graph matrix OR we can say that the initial values of shortest distances are based on shortest paths considering no intermediate vertices """ dist = map(lambda i : map(lambda j : j , i) , graph) """ Add all vertices one by one to the set of intermediate vertices. ---> Before start of an iteration, we have shortest distances between all pairs of vertices such that the shortest distances consider only the vertices in the set {0, 1, 2, .. k-1} as intermediate vertices. ----> After the end of a iteration, vertex no. k is added to the set of intermediate vertices and the set becomes {0, 1, 2, .. k} """ for k in range(V): # pick all vertices as source one by one for i in range(V): # Pick all vertices as destination for the # above picked source for j in range(V): # If vertex k is on the shortest path from # i to j, then update the value of dist[i][j] dist[i][j] = min(dist[i][j] , dist[i][k]+ dist[k][j] ) printSolution(dist) # A utility function to print the solution def printSolution(dist): print "Following matrix shows the shortest distances\ between every pair of vertices" for i in range(V): for j in range(V): if(dist[i][j] == INF): print "%7s" %("INF"), else: print "%7d\t" %(dist[i][j]), if j == V-1: print "" # Driver program to test the above program graph = [[0,5,INF,10], [INF,0,3,INF], [INF, INF, 0, 1], [INF, INF, INF, 0] ] # Print the solution floydWarshall(graph); ================================================ FILE: Algorithms/Graph/Floyd_Warshall/README.md ================================================ ## This folder is empty. ================================================ FILE: Algorithms/Graph/Hopcroft_Karp/Hopcroft_Karp_algorithm.cpp ================================================ // C++ implementation of Hopcroft Karp algorithm for // maximum matching /* Sample test case Enter the number of vertices on left side of Bipartite Graph: 4 Enter the number of vertces on Right side of Bipartite Graph: 4 Enter the number of edges: 6 Enter the left source vertex and right destination vertex with space 1 2 1 3 2 1 3 2 4 2 4 4 Size of maximum matching is 4 */ #include using namespace std; #define NIL 0 #define INF INT_MAX // A class to represent Bipartite graph class bipartiteGraph { // m and n are number of vertices on left // and right sides of Bipartite Graph int m, n; // pointers to arrays int *pairU, *pairV, *dist; // adj[u] stores adjacents of left side // vertex 'u'. The value of u ranges from 1 to m. // 0 is used for dummy vertex list *adj; public: bipartiteGraph(int m, int n); // Constructor void addEdge(int u, int v); // To add edge // Checking augmenting path bool bfs(); // Ading augmenting path bool dfs(int u); // Returns size of maximum matcing int hopcroftKarp(); }; int bipartiteGraph::hopcroftKarp() { // pairU[u] stores pair of u in matching where u // is a vertex on left side of Bipartite Graph. pairU = new int[m+1]; // pairV[v] stores pair of v in matching. If v pairV = new int[n+1]; // dist[u] stores distance of left side vertices // dist[u] is one more than dist[u'] if u is next // to u'in augmenting path dist = new int[m+1]; // Initialize NIL as pair of all vertices for (int u=0; u<=m; u++) pairU[u] = NIL; for (int v=0; v<=n; v++) pairV[v] = NIL; // Initialize result int result = 0; // Keep updating the result while there is an // augmenting path. while (bfs()) { // Find a free vertex for (int u=1; u<=m; u++) // If current vertex is free and there is // an augmenting path from current vertex if (pairU[u]==NIL && dfs(u)) result++; } return result; } bool bipartiteGraph::bfs() { queue Q; //an integer queue // First layer of vertices (set distance as 0) for (int u=1; u<=m; u++) { // If this is a free vertex, add it to queue if (pairU[u]==NIL) { // u is not matched dist[u] = 0; Q.push(u); } // Else set distance as infinite so that this vertex // is considered next time else dist[u] = INF; } // Initialize distance to NIL as infinite dist[NIL] = INF; // Q is going to contain vertices of left side only. while (!Q.empty()) { // Dequeue a vertex int u = Q.front(); Q.pop(); // If this node is not NIL and can provide a shorter path to NIL if (dist[u] < dist[NIL]) { // Get all adjacent vertices of the dequeued vertex u list::iterator i; for (i=adj[u].begin(); i!=adj[u].end(); ++i) { int v = *i; // If pair of v is not considered so far // (v, pairV[V]) is not yet explored edge. if (dist[pairV[v]] == INF) { // Consider the pair and add it to queue dist[pairV[v]] = dist[u] + 1; Q.push(pairV[v]); } } } } // If we could come back to NIL using alternating path of distinct // vertices then there is an augmenting path return (dist[NIL] != INF); } // Returns true if there is an augmenting path beginning with free vertex u bool bipartiteGraph::dfs(int u) { if (u != NIL) { list::iterator i; for (i=adj[u].begin(); i!=adj[u].end(); ++i) { // Adjacent to u int v = *i; // Follow the distances set by BFS if (dist[pairV[v]] == dist[u]+1) { // If dfs for pair of v also returns // true if (dfs(pairV[v]) == true) { pairV[v] = u; pairU[u] = v; return true; } } } // If there is no augmenting path beginning with u. dist[u] = INF; return false; } return true; } bipartiteGraph::bipartiteGraph(int m, int n) { this->m = m; this->n = n; adj = new list[m+1]; } void bipartiteGraph::addEdge(int u, int v) { adj[u].push_back(v); } // Driver Program int main() { int m,n,i; cout << "Enter the number of vertices on left side of Bipartite Graph: "; cin >> m; cout << "Enter the number of vertces on Right side of Bipartite Graph: "; cin >> n; bipartiteGraph g(m, n); cout << "Enter the number of edges: "; cin >> i; cout << "Enter the left source vertex and right destination vertex with space\n"; while (i) { int temp1, temp2; cin >> temp1>> temp2; g.addEdge(temp1,temp2); } cout << "Size of maximum matching is " << g.hopcroftKarp() << endl; return 0; } ================================================ FILE: Algorithms/Graph/Hungarian_algorithm/Hungarian_algorithm.cpp ================================================ ////////////////////////////////////////////////////////////////////////// // Hungarian.cpp: Implementation file for Class HungarianAlgorithm. // #include #include // for DBL_MAX #include // for fabs() #include "Hungarian.h" HungarianAlgorithm::HungarianAlgorithm(){} HungarianAlgorithm::~HungarianAlgorithm(){} //********************************************************// // A single function wrapper for solving assignment problem. //********************************************************// double HungarianAlgorithm::Solve(vector >& DistMatrix, vector& Assignment) { unsigned int nRows = DistMatrix.size(); unsigned int nCols = DistMatrix[0].size(); double *distMatrixIn = new double[nRows * nCols]; int *assignment = new int[nRows]; double cost = 0.0; // Fill in the distMatrixIn. Mind the index is "i + nRows * j". // Here the cost matrix of size MxN is defined as a double precision array of N*M elements. // In the solving functions matrices are seen to be saved MATLAB-internally in row-order. // (i.e. the matrix [1 2; 3 4] will be stored as a vector [1 3 2 4], NOT [1 2 3 4]). for (unsigned int i = 0; i < nRows; i++) for (unsigned int j = 0; j < nCols; j++) distMatrixIn[i + nRows * j] = DistMatrix[i][j]; // call solving function assignmentoptimal(assignment, &cost, distMatrixIn, nRows, nCols); Assignment.clear(); for (unsigned int r = 0; r < nRows; r++) Assignment.push_back(assignment[r]); delete[] distMatrixIn; delete[] assignment; return cost; } //********************************************************// // Solve optimal solution for assignment problem using Munkres algorithm, also known as Hungarian Algorithm. //********************************************************// void HungarianAlgorithm::assignmentoptimal(int *assignment, double *cost, double *distMatrixIn, int nOfRows, int nOfColumns) { double *distMatrix, *distMatrixTemp, *distMatrixEnd, *columnEnd, value, minValue; bool *coveredColumns, *coveredRows, *starMatrix, *newStarMatrix, *primeMatrix; int nOfElements, minDim, row, col; /* initialization */ *cost = 0; for (row = 0; row nOfColumns) */ { minDim = nOfColumns; for (col = 0; col= 0) *cost += distMatrix[row + nOfRows*col]; } } /********************************************************/ void HungarianAlgorithm::step2a(int *assignment, double *distMatrix, bool *starMatrix, bool *newStarMatrix, bool *primeMatrix, bool *coveredColumns, bool *coveredRows, int nOfRows, int nOfColumns, int minDim) { bool *starMatrixTemp, *columnEnd; int col; /* cover every column containing a starred zero */ for (col = 0; col(0)---->(1) | | ^ | | | \ 1 | -1 | 2 | \ | 3 | | \ | | v \ v ----(3)-----(2) 4 @ Sample output Enter the number of vertices : 4 Enter the number of edges : 7 Enter the edges with source, destination and weight : 0 1 -3 1 2 3 3 2 4 2 0 1 1 0 5 0 3 2 3 0 -1 Shortest distance with vertex 0 as the source : Vertex Distance from Source 0 0 1 -3 2 0 3 2 Shortest distance with vertex 1 as the source : Vertex Distance from Source 0 4 1 0 2 3 3 6 Shortest distance with vertex 2 as the source : Vertex Distance from Source 0 1 1 -2 2 0 3 3 Shortest distance with vertex 3 as the source : Vertex Distance from Source 0 -1 1 -4 2 -1 3 0 */ #include using namespace std; // a structure to represent a weighted edge in graph struct Edge { int src, dest, weight; }; // a structure to represent a connected, directed and // weighted graph struct Graph { // V-> Number of vertices, E-> Number of edges int V, E; // graph is represented as an array of edges. struct Edge* edge; }; // Creates a graph with V vertices and E edges struct Graph* createGraph(int V, int E) { struct Graph* graph = new Graph; graph->V = V; graph->E = E; graph->edge = new Edge[E]; return graph; } // The main function that finds shortest distances from src to // all other vertices using Bellman-Ford algorithm. The function // also detects negative weight cycle vector BellmanFord(struct Graph* graph) { int V = graph->V; int E = graph->E; vector dist; // Step 1: Add a source s and calculate its min distance from every other node for (int i = 0; i <= V; i++) dist.push_back(INT_MAX); dist[V] = 0; // An edge is added from s all other vertices... for (int i = 0; i < V; i++) { graph->edge[(E-V)+i].src = V; graph->edge[(E-V)+i].dest= i; graph->edge[(E-V)+i].weight = 0; } // Step 2: Relax all edges |V| - 1 times. A simple shortest // path from src to any other vertex can have at-most |V| - 1 // edges for (int i = 0; i < V; i++) { for (int j = 0; j < E; j++) { int u = graph->edge[j].src; int v = graph->edge[j].dest; int weight = graph->edge[j].weight; if (dist[u] != INT_MAX && dist[u] + weight < dist[v]) dist[v] = dist[u] + weight; } } // Step 3: check for negative-weight cycles. The above step // guarantees shortest distances if graph doesn't contain // negative weight cycle. If we get a shorter path, then there // is a cycle. for (int i = 0; i < E; i++) { int u = graph->edge[i].src; int v = graph->edge[i].dest; int weight = graph->edge[i].weight; if (dist[u] != INT_MAX && dist[u] + weight < dist[v]) { printf("Graph contains negative weight cycle"); return dist; // If negative cycle is detected, simply return } } dist.pop_back(); return dist; } void printSolution(int dist[]) { printf("Vertex \t\t Distance from Source\n"); for (int i = 0; i < 4; i++) printf("%d \t\t %d\n", i, dist[i]); } // Returns the vertex with minimum // distance from the source int minDistance(int dist[], bool sptSet[], int V) { // Initialize min value int min = INT_MAX, min_index; for (int v = 0; v < V; v++) if (sptSet[v] == false && dist[v] <= min) min = dist[v], min_index = v; return min_index; } // dijkstra algorithm for graph with // modified weights(removing negative weights) void dijkstra(struct Graph* graph, int src, vector h){ int V = graph->V; int E = graph->E; int dist[V]; bool sptSet[V]; for (int i = 0; i < V; i++) dist[i] = INT_MAX, sptSet[i] = false; dist[src] = 0; for (int i = 0; i < V-1; i++) { int u = minDistance(dist, sptSet, V); sptSet[u]= true; for (int j = 0; j < E-V; j++) { int tu = graph->edge[j].src; int v = graph->edge[j].dest; int w = graph->edge[j].weight; if (!sptSet[v] && dist[tu] != INT_MAX && dist[tu] + w < dist[v]) { dist[v] = dist[tu] + w; } } } // δ (u, v) + h (v) - h (u) for (int i = 0; i < V; i++) { dist[i] = dist[i] + h[i] - h[src]; } printSolution(dist); } // Johnson's algorithm for finding all pairs shortest paths // main algorithm void johnsonAlgorithm(struct Graph* graph){ int V = graph->V; int E = graph->E; vector modifiedWeights = BellmanFord(graph); cout << endl; for (int i = 0; i < E-V; i++) { int u = graph->edge[i].src; int v = graph->edge[i].dest; graph->edge[i].weight = graph->edge[i].weight + modifiedWeights[u] - modifiedWeights[v]; } for(int src = 0; src < V; src++){ cout << "\nShortest distance with vertex " << src << " as the source : \n"; dijkstra(graph,src,modifiedWeights); } } // Driver program to test above functions int main() { int V; // Number of vertices in graph int E; // Number of edges in graph cout << "Enter the number of vertices : "; cin >> V; cout << "Enter the number of edges : "; cin >> E; // Array of edges for graph struct Graph* graph = createGraph(V, E+V); //------- adding the edges of the graph /* edge(u, v) where u = start vertex of the edge (u,v) v = end vertex of the edge (u,v) w is the weight of the edge (u,v) */ cout << "Enter the edges with source, destination and weight : \n"; for (int i = 0; i < E; i++) { int t1, t2, t3; cin >> t1 >> t2 >> t3; graph->edge[i].src = t1; graph->edge[i].dest= t2; graph->edge[i].weight = t3; }; johnsonAlgorithm(graph); return 0; } ================================================ FILE: Algorithms/Graph/Karger_algorithm/Karger_algorithm.cpp ================================================ #include #include #include #include #include #include namespace std { }; using namespace std; class karger_graph { public: void set(size_t r, size_t c, size_t d) { _data[(r * _rc) + c] = d; return; }; size_t get(size_t r, size_t c) const { return _data[(r * _rc) + c]; }; void set_size(size_t rc) { _rc = rc; _data.resize(_rc * _rc); return; }; size_t get_size() const { return _rc; }; size_t count_vertices() const; size_t count_edges() const; karger_graph& remove_self_loops(); karger_graph& merge_vertices(size_t u, size_t v); private: size_t _rc; vector _data; }; size_t karger_graph::count_vertices() const { size_t n = 0; for (size_t i = 0; i < _rc; ++i) { size_t k = 0; for (size_t j = 0; j < _rc; ++j) { k = k + get(i, j); } if (k > 0) { ++n; } } return n; } size_t karger_graph::count_edges() const { size_t n = 0; for (size_t i = 0; i < _rc; ++i) { for (size_t j = 0; j < _rc; ++j) { n = n + get(i, j); } } return n; } karger_graph& karger_graph::remove_self_loops() { for (size_t i = 0; i < _rc; ++i) { set(i, i, 0); } return *this; } karger_graph& karger_graph::merge_vertices(size_t u, size_t v) { if (u < _rc && v < _rc) { for (size_t i = 0; i < _rc; ++i) { size_t e = get(v, i); set(v, i, 0); size_t n = e + get(u, i); set(u, i, n); e = get(i, v); set(i, v, 0); n = e + get(i, u); set(i, u, n); } } return *this; } void random_contraction_algorithm(karger_graph& km) { km.remove_self_loops(); while (km.count_vertices() > 2) { /* Pick an edge. */ size_t random_vertex_u = 0, random_vertex_v = 0; do { random_vertex_u = rand() % km.get_size(); random_vertex_v = rand() % km.get_size(); } while (km.get(random_vertex_u, random_vertex_v) == 0); assert(random_vertex_u != random_vertex_v); /* Merge both vertices. */ km.merge_vertices(random_vertex_u, random_vertex_v); /* Remove self-loops. */ km.remove_self_loops(); } return; } istream& operator>>(istream& is, karger_graph& km) { size_t dim = 0; is >> dim; km.set_size(dim); for (size_t i = 0; i < dim; ++i) { for (size_t j = 0; j < dim; ++j) { size_t k = 0; is >> k; if (is.good() != false) { km.set(i, j, k); } } } return is; } ostream& operator<<(ostream& os, const karger_graph& km) { size_t dim = km.get_size(); os << dim << " " << endl; for (size_t i = 0; i < dim; ++i) { for (size_t j = 0; j < dim; ++j) { os << km.get(i, j) << " "; } os << endl; } return os; } int main(int argc, char* argv[]) { karger_graph graph, minimum_graph; graph.set_size(0); minimum_graph.set_size(0); if (argc > 1) { ifstream ifs; ifs.open(argv[1]); ifs >> graph; ifs.close(); } if (graph.get_size() > 0) { cout << "Input vertex count: " << graph.count_vertices() << endl; cout << "Input edge count: " << (graph.count_edges() >> 1) << endl; srand((unsigned int) time(NULL)); size_t n = graph.count_vertices(); float ln = log((float) n); size_t runs = n * n * ln, minimum_cut = UINT_MAX; for (size_t i = 0; i < runs; ++i) { karger_graph copy = graph; random_contraction_algorithm(copy); size_t cut = copy.count_edges(); assert((cut % 2) == 0); if (cut < minimum_cut) { minimum_cut = cut; minimum_graph = copy; } } cout << "Runs: " << runs << endl; cout << "Output vertex count: " << minimum_graph.count_vertices() << endl; cout << "Output edge count: " << (minimum_graph.count_edges() >> 1) << endl; assert(minimum_cut == 6); if (argc > 2) { ofstream ofs; ofs.open(argv[2]); ofs << minimum_graph; ofs.close(); } } cin.get(); return 0; } ================================================ FILE: Algorithms/Graph/Karger_algorithm/sample.txt ================================================ 40 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 1 1 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 0 0 0 0 1 0 0 0 0 1 0 0 1 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 1 0 0 1 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 1 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 1 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 1 0 0 1 0 0 0 1 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 1 0 0 1 0 1 0 0 0 0 0 1 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 1 0 0 0 1 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 1 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 1 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 1 0 0 1 0 1 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 1 0 0 1 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 1 0 1 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 1 0 0 0 0 0 1 0 1 1 1 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 1 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 1 1 0 0 0 0 1 1 1 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 1 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 1 0 1 0 0 0 0 0 1 0 0 0 0 1 0 0 0 0 0 0 0 0 1 0 0 0 1 0 0 0 1 0 0 0 0 0 0 0 1 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 1 0 0 1 0 1 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 0 1 0 0 1 0 1 0 0 0 0 0 0 0 0 0 0 1 0 0 0 1 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 1 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 1 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 1 0 0 1 0 0 1 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 1 0 1 0 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 1 0 0 0 0 0 0 1 1 0 0 0 0 0 0 0 1 0 0 0 1 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 1 0 0 0 0 0 0 0 0 0 1 0 1 0 0 0 1 0 0 ================================================ FILE: Algorithms/Graph/Kosarajus_Algorithm/kosajaru.rs ================================================ use std::vec; type Node = usize; type Graph = Vec>; // A directed graph, in adjacency list type Stack = Vec; // The rust std does not provides a default stack, but we can use a vector instead // Example fn main() { let graph = vec![ vec![2,3], vec![0], vec![1], vec![4], vec![], ]; let n_nodes = 5; println!("Provided graph: "); println!(" Number of nodes: {}", n_nodes); println!(" Edges:"); for (i, v) in graph.iter().enumerate() { for j in v { println!(" {} {}", i, j); } } let components = kosajaru(graph, n_nodes); println!("Obtained result: "); for (node, component) in components.iter().enumerate() { println!(" node {} belongs to component {}", node, component); } } /* Given a graph represented by an adjacency list and the number of nodes, return an array A such that A[i] == m iff the node i belongs to strongly connected component m. The Kosajaru algorithm works by traversing the graph with DFS traversal and storing in a stack the finalization order, from the node that ended first in the bottom of the stack, to the node that ended last, at the top of the stack. Next, we have to traverse the inverse graph in the order stored in the stack, meaning that we traverse the nodes in the inverse finalization order. Each DFS tree generated by this second traversal represents a strongly connected component */ fn kosajaru(graph : Graph, n_nodes : usize) -> Vec { // Order at which each node ends its DFS traversal let mut call_stack = vec![]; // remember what nodes were visited so far with the memo array let mut memo = vec::from_elem(0, n_nodes); for node in 0..n_nodes { // visit all non-visited nodes if memo[node] == 0 { dfs_traversal(&graph, node, &mut memo, &mut call_stack) } } // Now that we have the call stack, we compute the strong components by traversing the // inverse graph in the orden given by the call stack let graph_inverse = reverse_graph(&graph); // Reset our memo array for i in &mut memo{ *i = 0; } // just a counter let mut numerator = 1..; for node in call_stack.iter().rev() { // traverse every non-visited node in the stack order (left to right in our stack vector) if memo[*node] == 0 { dfs_color(&graph_inverse, *node, &mut memo, numerator.next().unwrap()); } } memo } // Utility function to reverse the given graph fn reverse_graph(graph : &Graph) -> Graph{ // init an empty graph let mut graph_inverse : Graph = vec::from_elem(vec![], graph.len()); // iterate over our current graph, i is the current node, // v is a list of nodes, such that there's an edge i -> j por every j in v. for (i, v) in graph.iter().enumerate() { for j in v { // we add an edge j -> i to our inverse graph // for every edge i -> j in our graph graph_inverse[*j].push(i); } } graph_inverse } // Given a graph, a source node v, the the list of not visited nodes 'memo' such that the node i // has not been visited iff memo[i] == 0, the stack of traversed nodes, // perform a dfs traversal over a graph storing the order at which each sub traversal has ended // in the given stack fn dfs_traversal(graph : &Graph, v : Node, memo : &mut Vec, stack : &mut Stack) { memo[v] = 1; for node in &graph[v] { if memo[*node] == 0 { dfs_traversal(graph, *node, memo, stack); } } stack.push(v); } // Traverse a graph starting in the node v and setting the color of the resulting // dfs tree to the given color fn dfs_color(graph : &Graph, v : Node, memo : &mut Vec, color : usize) { memo[v] = color; for node in &graph[v] { if memo[*node] == 0 { dfs_color(graph, *node, memo, color); } } } ================================================ FILE: Algorithms/Graph/Kosarajus_Algorithm/kosaraju.ts ================================================ // TypeScript Implementation of Kosarajus's Algorithm class Graph { public vertices: number; public adjancency: number[][]; constructor(vertices: number) { this.vertices = vertices; this.adjancency = []; for (let i = 0; i < vertices; i++) { this.adjancency.push([]); } } addEdge(v: number, w: number): void { this.adjancency[v].push(w); } printSCCs(): void { var stack: number[] = []; let visited: boolean[] = new Array(this.vertices); for (let i = 0; i < this.vertices; i++) { visited[i] = false; } for (let i = 0; i < this.vertices; i++) { if (visited[i] == false) { this.fillOrder(i, visited, stack); } } const gr = this.getTranspose(); for (let i = 0; i < this.vertices; i++) { visited[i] = false; } while (stack.length != 0) { let v = stack.pop() as number; if (visited[v] == false) { console.log(gr.DFSUtil(v, visited)); } } } fillOrder(v: number, visited: boolean[], stack: number[]): void { // Mark the current node as visited and print it visited[v] = true; // Recur for all the vertices adjacent to this vertex for (let i = 0; i < this.adjancency[v].length; i++) { let n = this.adjancency[v][i]; if (!visited[n]) this.fillOrder(n, visited, stack); } // All vertices reachable from v are processed by now, // push v to Stack stack.push(v); } getTranspose(): Graph { let g = new Graph(this.vertices); for (let v = 0; v < this.vertices; v++) { // Recur for all the vertices adjacent to this vertex for (let i = 0; i < this.adjancency[v].length; i++) { let n = this.adjancency[v][i]; g.adjancency[n].push(v); } } return g; } DFSUtil(v: number, visited: boolean[]): string { // Mark the current node as visited and print it visited[v] = true; let result = ""; result += v + " "; // Recur for all the vertices adjacent to this vertex for (let i = 0; i < this.adjancency[v].length; i++) { let n = this.adjancency[v][i]; if (!visited[n]) result += this.DFSUtil(n, visited); } return result; } } // Create a graph given in the above diagram let g = new Graph(5); g.addEdge(1, 0); g.addEdge(0, 2); g.addEdge(2, 1); g.addEdge(0, 3); g.addEdge(3, 4); console.log("Following are strongly connected components " + "in given graph "); g.printSCCs(); ================================================ FILE: Algorithms/Graph/Kosarajus_Algorithm/kosaraju_algorithm_strongly_connected_components.cpp ================================================ #include using namespace std; void init() { #ifndef ONLINE_JUDGE freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout); #endif } void dfs(vector graph[], int node, bool *visited, vector &ordering) { visited[node] = true; for (int neigh : graph[node]) { if (!visited[neigh]) { dfs(graph, neigh, visited, ordering); } } // Ordering based on finish time. Finish Time: When you are going back after visiting all its neighbours ordering.push_back(node); } // Normal dfs call after reversing the graph void dfs2(vector rev_graph[], int node, bool *visited) { visited[node] = true; cout << node << ","; for (int neigh : rev_graph[node]) { if (!visited[neigh]) { dfs2(rev_graph, neigh, visited); } } } void solve(vector graph[], vector rev_graph[], int V) { bool visited[V] = {0}; vector ordering; for (int i = 0; i < V; i++) { if (!visited[i]) { dfs(graph, i, visited, ordering); } } char component_name = 'A'; memset(visited, 0, V); for (int x = ordering.size() - 1; x >= 0; x--) { int node = ordering[x]; if (!visited[node]) { cout << "Component " << component_name << "--> "; // There is a component starting from this node dfs2(rev_graph, node, visited); } cout << endl; component_name++; } } int main() { init(); int V, E; cin >> V >> E; vector graph[V], rev_graph[V]; for (int i = 0; i < E; i++) { int x, y; cin >> x >> y; graph[x].push_back(y); // graph where all the directed edges are reversed in the original graph rev_graph[y].push_back(x); } // Strongly Connected Components solve(graph, rev_graph, V); return 0; } ================================================ FILE: Algorithms/Graph/Kruskal's_MST/KruskalMST.c ================================================ // Kruskal's Minimum Spanning Tree // C Programming #include #define MAX 30 // GraphEdgeWeights -> Array storing the weights of edges in the graph. int GraphEdgeWeights[MAX][MAX]; // nVertices -> No: of vertices in the graph. int nVertices; // Edge -> Structure for an edge with its source vertex, destination vertex and its weight. typedef struct Edge{ int src, dest, weight; } Edge; // EdgeList -> Structure for storing an array of Edge along with its size. typedef struct EdgeList{ Edge data[MAX]; int size; } EdgeList; EdgeList edgeList; EdgeList spanList; // Function name : SortEdges // Input : void // Output : void // Logic : For sorting the edges based on their weights. void SortEdges(){ int i, j; Edge tempEdge; for(i=1; i edgeList.data[j+1].weight){ tempEdge = edgeList.data[j]; edgeList.data[j] = edgeList.data[j+1]; edgeList.data[j+1] = tempEdge; } } // Function name : FindVertexSet // Input : vertexSet array, vertexNo // Output : vertexSet // Logic : For finding the vertexSet of a node in the spanning tree. int FindVertexSet(int vertexSet[], int vertexNo){ return(vertexSet[vertexNo]); } // Function name : Union // Input : vertexSet array, source node, destination node // Output : void // Logic : For adding the both nodes to the same vertexSet. void Union(int vertexSet[], int srcNode, int destNode){ int i; for(i=0; i%d:%d", spanList.data[i].src, spanList.data[i].dest, spanList.data[i].weight); cost = cost + spanList.data[i].weight; } printf("\n=====================================\n"); printf("Cost = %d", cost); } // Function name : main // Input : void // Output : void // Logic : The driver function of the program. void main(){ int i, j, total_cost, weight; printf("\nNumber of vertices : "); scanf("%d",&nVertices); for(i=0; i #include #include using namespace std; #define edge pair class Graph { private: vector > G; // graph vector > T; // mst int *parent; int V; // number of vertices/nodes in graph public: Graph(int V); void AddWeightedEdge(int u, int v, int w); int find_set(int i); void union_set(int u, int v); void kruskal(); void print(); }; Graph::Graph(int V) { parent = new int[V]; //i 0 1 2 3 4 5 //parent[i] 0 1 2 3 4 5 for (int i = 0; i < V; i++) parent[i] = i; G.clear(); T.clear(); } void Graph::AddWeightedEdge(int u, int v, int w) { G.push_back(make_pair(w, edge(u, v))); } int Graph::find_set(int i) { // If i is the parent of itself if (i == parent[i]) return i; else // Else if i is not the parent of itself // Then i is not the representative of his set, // so we recursively call Find on its parent return find_set(parent[i]); } void Graph::union_set(int u, int v) { parent[u] = parent[v]; } void Graph::kruskal() { int i, uRep, vRep; sort(G.begin(), G.end()); // increasing weight for (i = 0; i < G.size(); i++) { uRep = find_set(G[i].second.first); vRep = find_set(G[i].second.second); if (uRep != vRep) { T.push_back(G[i]); // add to tree union_set(uRep, vRep); } } } void Graph::print() { cout << "Edge :" << " Weight" << endl; for (int i = 0; i < T.size(); i++) { cout << T[i].second.first << " - " << T[i].second.second << " : " << T[i].first; cout << endl; } } int main() { Graph g(6); g.AddWeightedEdge(0, 1, 4); g.AddWeightedEdge(0, 2, 4); g.AddWeightedEdge(1, 2, 2); g.AddWeightedEdge(1, 0, 4); g.AddWeightedEdge(2, 0, 4); g.AddWeightedEdge(2, 1, 2); g.AddWeightedEdge(2, 3, 3); g.AddWeightedEdge(2, 5, 2); g.AddWeightedEdge(2, 4, 4); g.AddWeightedEdge(3, 2, 3); g.AddWeightedEdge(3, 4, 3); g.AddWeightedEdge(4, 2, 4); g.AddWeightedEdge(4, 3, 3); g.AddWeightedEdge(5, 2, 2); g.AddWeightedEdge(5, 4, 3); g.kruskal(); g.print(); return 0; } /* Output: Edge : Weight 1 - 2 : 2 2 - 5 : 2 2 - 3 : 3 3 - 4 : 3 0 - 1 : 4 */ ================================================ FILE: Algorithms/Graph/Kruskal's_MST/README.md ================================================ ## This folder is empty. ================================================ FILE: Algorithms/Graph/Kruskal's_MST/cpp/kruskal.cpp ================================================ #include #include #include #include using namespace std; // Typedef to represent a weighted edge: (weight, (node u,node v)) typedef pair> edge; // Typedef to represent a disjoint set from a node (int) vector: typedef vector disjoint_set; /* Given an undirected, edge-weighted connected graph, computes the edges of the minimum spanning tree. We use disjoint sets to provide an efficient computation. The kruskal algorithm works by selecting the lightest edge at each iteration. The problem with this approach is that it's possible to find an edge with minimum weight such that this edge creates a cycle with our currently added edges. Thus, we have to find a way to check for cycles when we are about to add an edge. We can achieve this using disjoints sets, which is the solution provided below. Given the set of edges of the connected graph and the number of nodes returns the list of edges of the MST */ vector kruskal(vector graph, int n_nodes); /* The disjoint set data structure works by representing each subset as a root parent for every sub element. We choose such parent for the subset, and when we add a new element to the subset, we make this element a child of the root or a child of some other child of the root. This way, to check whether an element belongs to an specific subset, we have tu check if its root is the same as the subsets root. Here, we start with a disjoint set such that every element represents its own singleton subset. */ disjoint_set create_set(int n); /* To merge two sets together, we have to make the root of one of the sets be a child of an element of the second subset */ void set_union(disjoint_set &s, int u, int v); /* The get parent function returns the root of the subset containing i. Also, this function flattens the parents tree by updating the parents of i such that every parent points directly to the root. This way, the next time we need to ask for the parent of some of these elements, we have to traverse a shorter distance to the root. */ int get_parent(disjoint_set &s, int i); /* */ int main() { // Example. vector graph = { {14, {3, 5}}, {11, {1, 7}}, {10, {5, 4}}, {1, {7, 6}}, {2, {8, 2}}, {2, {6, 5}}, {4, {0, 1}}, {9, {3, 4}}, {8, {1, 2}}, {8, {0, 7}}, {7, {7, 8}}, {7, {2, 3}}, {6, {8, 6}}, {4, {2, 5}} }; printf("Input graph: \n"); for(auto e : graph) printf("(%d, %d) w: %d\n", e.second.first, e.second.second, e.first); vector MST = kruskal(graph, 9); printf("obtained graph: \n"); for (auto e : MST ) printf("(%d, %d) w: %d\n", e.second.first, e.second.second, e.first); return 0; } /* Create a new partition of n sets, enumerated in the range 0 <= i < n */ disjoint_set create_set(int n) { disjoint_set set(n); for (int i = 0; i < n; i++) set[i] = i; return set; } /* Get the parent of element i in the disjoint set s and flattens the disjoint set as much as it can */ int get_parent(disjoint_set &s, int i) { // If this node is its own parent, return it. // This is the parent of the subset. if (i == s[i]) return i; // Get the parent of this node's parent int parent = get_parent(s, s[i]); // update the parent and return it return s[i] = parent; } /* Merge two sets in one, making the set v a child of set u */ void set_union(disjoint_set &s, int u, int v) { int parent_u = get_parent(s, u); int parent_v = get_parent(s, v); // Set the parent of root of v as the parent of root of u s[parent_v] = parent_u; } /* Check if node u contains the node v for the set s */ bool contains(disjoint_set &s, int u, int v) { int u_parent = get_parent(s, u); int v_parent = get_parent(s, v); // The subset where u belongs contains the subset v // if they have the same parent. return u_parent == v_parent; } vector kruskal(vector graph, const int n_nodes) { priority_queue edge_queue; // Use this priority queue to sort the edges by weight within a queue int edge_counter = 0; // how many edges have been added so far vector tree(n_nodes - 1); // the resulting spanning tree disjoint_set set = create_set(n_nodes); // Our disjoint set to test for cycles for (auto e : graph) { // Note that the priority queue sorts in non-increasing order, // so we have to negate the weight in order to invert the order. edge inverted_weight_edge = {-e.first, e.second }; edge_queue.push(inverted_weight_edge); } // note that every spanning tree follows: // number of edges = number of nodes - 1 while (edge_counter < n_nodes - 1) { edge current = edge_queue.top(); edge_queue.pop(); // each side of the edge int u = current.second.first; int v = current.second.second; if ( !contains(set, u, v) ) { // Add this edge to our tree, since it does not creates a cycle tree[edge_counter++] = { -current.first, {u,v} }; // (Remember to negate the weight ^, so we have the original edge) // Merge the spanning tree containing u with the spanning tree containing v set_union(set, u, v); } } return tree; } ================================================ FILE: Algorithms/Graph/Kruskal's_MST/python/KruskalMST.py ================================================ # Python program for Kruskal's algorithm to find # Minimum Spanning Tree of a given connected, # undirected and weighted graph def takeInput(): """ Takes input from stdin :return: Graph """ v = int(input("Enter the number of vertices \t")) e = int(input("Enter the number of edges \t ")) edges = [] for i in range(e): print("Enter edge {} in form u v w".format(str(i+1))) inputEdge = list(map(int, input().split(" "))) edges.append(inputEdge) graph = Graph(v,edges) return graph class Graph: def __init__(self, vertices,graph ): """ constructor for the graph object :param vertices: No of vertices :param graph: dictionary used to store the graph # Graph is stored as a list of tuples [(u,v,w)] """ self.V = vertices self.graph = graph def find(self, parent, i): """ Finds the parent or representative element :param parent: Array storing current belongingness of the vertices :param i: vertex whose parent is to be found :return: parent vertex """ if parent[i] == i: return i return self.find(parent, parent[i]) def union(self, parent, rank, x, y): """ union by rank of two sets of x and y :param parent: array storing current belongingness of the vertices :param rank: array storing current rank of the vertices (used to find the rank of parent) :param x: set x :param y: set y :return: """ xroot = self.find(parent, x) yroot = self.find(parent, y) # Attach smaller rank tree under root of high rank tree (Union by Rank) if rank[xroot] < rank[yroot]: parent[xroot] = yroot elif rank[xroot] > rank[yroot]: parent[yroot] = xroot else: # If ranks are same, then make one as root # and increment its rank by one parent[yroot] = xroot rank[xroot] += 1 def KruskalMST(self): """ main function construct MST using Kruskal's Algo :return: List of edges in the MST """ result = [] # This will store the resultant MST i = 0 # An index variable, used for sorted edges e = 0 # An index variable, used for result[] # Sorting all the edges in non-decereasing order of the weights self.graph = sorted(self.graph, key=lambda item: item[2]) parent = [] rank = [] # Create V subsets with single elements for node in range(self.V): parent.append(node) rank.append(0) # Number of edges to be taken is equal to V-1 while e < self.V - 1: # Pick the smallest edge and increment # the index for next iteration u, v, w = self.graph[i] i = i + 1 x = self.find(parent, u) y = self.find(parent, v) # If including this edge does't cause cycle, # include it in result and increment the index # of result for next edge if x != y: e = e + 1 result.append([u, v, w]) self.union(parent, rank, x, y) # Else discard the edge else: continue # print the contents of result[] to display the built MST print("Edges in the MST are as follows ") print("Source \t-> Destination \t| Weight") for u, v, weight in result: print("%d \t-> %d \t\t| %d" % (u, v, weight)) graph = takeInput() graph.KruskalMST() ================================================ FILE: Algorithms/Graph/Kruskal's_MST/rust/kruskal.rs ================================================ use std::vec; /* The disjoint set data structure we are using to improve performance */ struct DisjointSet { partition : vec::Vec } /* Struct representing a simple weighted edge */ struct Edge { weight : i32, u : usize, v : usize } /* Since we are interested in connected graphs, the list of edges is enough to specify the entire graph for our algorithm */ type Graph = vec::Vec; fn main() { // Example: let graph = vec![ Edge::new(13, 3, 5), Edge::new(11,1, 7), Edge::new(10,5, 4), Edge::new(1, 7, 6), Edge::new(2, 8, 2), Edge::new(2, 6, 5), Edge::new(4, 0, 1), Edge::new(9, 3, 4), Edge::new(8, 1, 2), Edge::new(8, 0, 7), Edge::new(7, 7, 8), Edge::new(7, 2, 3), Edge::new(6, 8, 6), Edge::new(4, 2, 5) ]; println!("Input graph: "); for e in graph.iter() { println!("({}, {}) W: {}", e.u, e.v, e.weight); } let tree = kruskal(graph, 9); println!("Obtained graph: "); for e in tree.iter() { println!("({}, {}) W: {}", e.u, e.v, e.weight); } } impl Edge { fn new(weight : i32, u : usize, v : usize) -> Edge { Edge{ weight, u, v } } } impl DisjointSet { /* The disjoint set data structure works by representing each subset as a root parent for every sub element. We choose such parent for the subset, and when we add a new element to the subset, we make this element a child of the root or a child of some other child of the root. This way, to check whether an element belongs to an specific subset, we have tu check if its root is the same as the subset's root. Here, we start with a convenient disjoint set such that every element represents its own singleton subset. */ fn new(n_nodes : usize) -> DisjointSet { DisjointSet { partition : (0..n_nodes).collect() } } /* Get the parent of element i in the disjoint set s and flattens the disjoint set as much as it can. The get parent function returns the root of the subset containing i. Also, this function flattens the parents tree by updating the parents of i such that every parent points directly to the root. This way, the next time we need to ask for the parent of some of these elements, we have to traverse a shorter distance to the root. */ fn get_parent(&mut self, i : usize) -> usize { // If this node is its own parent, return it. // This is the parent of the subset. if self.partition[i] == i { return i; } // Otherwise, get the parent of this node's parent let parent = self.get_parent(self.partition[i]); self.partition[i] = parent; // flattens the tree parent } /* Merge two sets in one, making the set v a child of set u */ fn union(&mut self, u : usize, v : usize) { let parent_u = self.get_parent(u); let parent_v = self.get_parent(v); if parent_u != parent_v { // Set the parent of root of v as the parent of root of u self.partition[parent_v] = parent_u; } } /* Check if u's subset contains v for the set s */ fn contains(&mut self, u : usize, v : usize) -> bool { // The subset where u belongs contains the subset v // if they have the same parent. self.get_parent(u) == self.get_parent(v) } } /* Given an undirected, edge-weighted connected graph, computes the edges of the minimum spanning tree. We use disjoint sets to provide an efficient computation. The kruskal algorithm works by selecting the lightest edge at each iteration. The problem with this approach is that it's possible to find an edge with minimum weight such that this edge creates a cycle with our currently added edges. Thus, we have to find a way to check for cycles when we are about to add an edge. We can achieve this using disjoints sets, which is the solution provided below. Given the set of edges of the connected graph and the number of nodes returns the list of edges of the MST */ fn kruskal(mut graph : Graph, n_nodes : usize) -> Graph { let mut n_edges = 0; // how many edges have been added so far let mut tree : Graph = vec::Vec::with_capacity(n_nodes); // The resulting spanning tree let mut set = DisjointSet::new(n_nodes); // Our disjoint set to test for cycles // note that we use unstable since it does not requires additional space // and we're conssuming the graph anyways graph.sort_unstable_by_key(|e| e.weight); // Sort edges by their weight for edge in graph { // if u's subset contains v, then this edge creates a cycle. if !set.contains(edge.u, edge.v) { // Merge the spanning tree containing u with the spanning tree containing v set.union(edge.u, edge.v); // Add this edge to our tree, since it does not creates a cycle: tree.push(edge); n_edges += 1; } // every spanning tree follows: // number of edges = number of nodes - 1 if n_edges >= n_nodes - 1 { break; } } tree } ================================================ FILE: Algorithms/Graph/LIS/README.md ================================================ ## This folder is empty. ================================================ FILE: Algorithms/Graph/Level order traversal.cpp ================================================ #include using namespace std; #define ll long long struct node{ ll int data; node* left; node* right; }; node* newnode(ll int data) { node* newnode=new node(); newnode->data=data; newnode->left=NULL; newnode->right=NULL; //cout<q; q.push(root); while(!q.empty()) { node* current= q.front(); cout<data<<" "; if(current->left!=NULL)q.push(current->left); if(current->right!=NULL)q.push(current->right); q.pop(); } } } node* inser(node* root,int data) { if(root==NULL) { root=newnode(data); } else if(data<=root->data) { root->left=inser(root->left,data); } else { root->right=inser(root->right,data); } return root; } int main() { node* root; root=NULL; root=inser(root,10); root=inser(root,25); root=inser(root,15); root=inser(root,7); root=inser(root,8); root=inser(root,5); root=inser(root,30); levelorder(root); } ================================================ FILE: Algorithms/Graph/Lowest_Common_Manager/Lowest_Common_Manager.py ================================================ # O(N) T | O(d) S #numIP = numberOfImportantReports #lcm = lowestCommonManager def getLowestCommonManager(topManager, reportOne, reportTwo): return getOrgInfo(topManager, reportOne, reportTwo).lcm def getOrgInfo(manager, reportOne, reportTwo): numIP = 0 for dirRep in manager.directReports: orgInfo = getOrgInfo(dirRep, reportOne, reportTwo) if orgInfo.lcm is not None: return orgInfo numIP += orgInfo.numIP if manager == reportOne or manager == reportTwo: numIP += 1 lcm = manager if numIP == 2 else None return OrgInfo(lcm, numIP) class OrgInfo: def __init__(self, lcm, numIP): self.lcm = lcm self.numIP = numIP # This is an input class. Do not edit. class OrgChart: def __init__(self, name): self.name = name self.directReports = [] ================================================ FILE: Algorithms/Graph/Lowest_Common_Manager/QUESTION.md ================================================ ### Lowest Common Manager You're given three inputs, all of which are instances of an OrgChart class that have a directReports property pointing to their direct reports. The first input is the top manager in an organizational chart (i.e., the only instance that isn't anybody else's direct report), and the other two inputs are reports in the organizational chart. The two reports are guaranteed to be distinct. Write a function that returns the lowest common manager to the two reports. Example of an input : topManager : node A reportOne : node E reportTwo : node I A / \ B C / \ / \ D E F G / \ H I ================================================ FILE: Algorithms/Graph/Prim's_MST/Prim's_MST.py ================================================ # Prim's Algorithm in Python #Created by Sneha Sai KNVS(snehaa1989) #Implementation of Prim's Minimum spanning tree in Python #References: # - https://www.geeksforgeeks.org/prims-minimum-spanning-tree-mst-greedy-algo-5/ INF = 9999999 # number of vertices N = int(input("Enter the number of vertices:")) # adjacency matrix to represent graph # Initialize list G G = [] print("Enter the entries rowwise:") # For user input for i in range(N): a =[] for j in range(N): a.append(int(input())) G.append(a) # array to track node that was selected. selected_node = [0, 0, 0, 0, 0] no_edge = 0 selected_node[0] = True # Let's print for edge and weight print("Edge : Weight\n") while (no_edge < N - 1): # For every vertex in the set S, Let's find the all adjacent vertices # we calculate the distance from the vertex selected and # if the vertex is already in the set S, leave it otherwise # choose another vertex nearest to selected vertex. minimum = INF a = 0 b = 0 for m in range(N): if selected_node[m]: for n in range(N): if ((not selected_node[n]) and G[m][n]): # not in selected and there is an edge if minimum > G[m][n]: minimum = G[m][n] a = m b = n print(str(a) + "-" + str(b) + ":" + str(G[a][b])) selected_node[b] = True no_edge += 1 ================================================ FILE: Algorithms/Graph/Prim's_MST/Prims_MST.java ================================================ import java.util.ArrayList; import java.util.List; import java.util.PriorityQueue; import java.util.Scanner; class Node { int node; // Adjacent node int cost; // weight/cost/distance to adjacent node Node (int node, int cost) { this.node = node; this.cost = cost; } } public class Prims_MST { public static int Find_MST(int source_node, List> graph) { // Priority queue stores the object node-cost into the queue with // the smallest cost node at the top. PriorityQueue pq = new PriorityQueue<>((a,b)-> a.cost-b.cost); // The cost of the source node to itself is 0 pq.add(new Node(source_node, 0)); boolean vis[] = new boolean[graph.size()]; int mst_cost = 0; while (!pq.isEmpty()) { // remove the smallest element Node item = pq.poll(); int node = item.node; int cost = item.cost; // If the node is node not yet added to the minimum spanning tree, add it and increment the cost. if ( !vis[node] ) { mst_cost += cost; vis[node] = true; // Iterate through all the nodes adjacent to the node taken out of priority queue. // Push only those nodes (node, cost) that are not yet present in the minumum spanning tree. for (Node pair_node_cost : graph.get(node)) { int adj_node = pair_node_cost.node; if (vis[adj_node] == false) { pq.add(pair_node_cost); } } } } return mst_cost; } public static void main(String args[]) { Scanner sc =new Scanner(System.in); int num_nodes = 6; // Nodes (0, 1, 2, 3, 4, 5) List> adjGraph = new ArrayList<>(num_nodes); for (int i=0; i < num_nodes; i++) { adjGraph.add(new ArrayList<>()); } for (int i=0; i < num_nodes; i++) { int v1 = sc.nextInt(); int v2 = sc.nextInt(); int cost = sc.nextInt(); adjGraph.get(v1).add(new Node(v2,cost)); } // Start adding nodes to minimum spanning tree with 0 as the souce node System.out.println("Cost of the minimum spanning tree in graph 1 : " + Find_MST(0, adjGraph)); sc.close(); } } ================================================ FILE: Algorithms/Graph/Prim's_MST/README.md ================================================ ## This folder is empty. ================================================ FILE: Algorithms/Graph/README.md ================================================ # This folder is empty. ================================================ FILE: Algorithms/Graph/Tarjan's Algorithm/StronglyConnectedComponents.cpp ================================================ #include using namespace std; int t; vector disc, low, instack; vector> ans; void DFS(int u, vector adj[], stack &st) { t += 1; disc[u] = t; low[u] = t; instack[u] = 1; st.push(u); for (int k : adj[u]) { if (disc[k] == -1) { DFS(k, adj, st); low[u] = min(low[u], low[k]); } else { if (instack[k]) { low[u] = min(low[u], disc[k]); } } } if (disc[u] == low[u]) { vector a; while (!st.empty() and st.top() != u) { a.push_back(st.top()); instack[st.top()] = 0; st.pop(); } a.push_back(st.top()); instack[st.top()] = 0; st.pop(); sort(a.begin(), a.end()); ans.push_back(a); } } vector> tarjans(int V, vector adj[]) { t = 0; disc = vector(V, -1); low = vector(V, -1); instack = vector(V, 0); ans.clear(); stack st; for (int i = 0; i < V; i++) { if (disc[i] == -1) { DFS(i, adj, st); } } sort(ans.begin(), ans.end()); return ans; } int main() { int V, E; cin >> V >> E; vector adj[V]; for (int i = 0; i < E; i++) { int u, v; cin >> u >> v; adj[u].push_back(v); } vector> ptr = tarjans(V, adj); for (int i = 0; i < ptr.size(); i++) { for (int j = 0; j < ptr[i].size(); j++) { if (j == ptr[i].size() - 1) cout << ptr[i][j]; else cout << ptr[i][j] << " "; } cout << ','; } cout << endl; return 0; } ================================================ FILE: Algorithms/Graph/Topological Sort/QUESTION.md ================================================ ### Topological Sort You're given a list of arbitrary jobs that need to be completed; these jobs are represented by distinct integers. You're also given a list of dependencies. A dependency is represented as a pair of jobs where the first job is a prerequisite of the second one. In other words, the second job depends on the first one; it can only be completed once the first job is completed. Write a function that takes in a list of jobs and a list of dependencies and returns a list containing a valid order in which the given jobs can be completed. If no such order exists, the function should return an empty array. ================================================ FILE: Algorithms/Graph/Topological Sort/topo_sort.py ================================================ # METHOD - 1 : TRAVERSING FROM DEPENDENCIES TO MATCHING PREREQUISITE JOBS # O(j+d) T | O(j+d) S def topologicalSort(jobs, deps): jobGraph = createJobGraph(jobs, deps) return getOrderedJobs(jobGraph) def createJobGraph(jobs, deps): graph = JobGraph(jobs) for prereq, job in deps: graph.addPrereq(job, prereq) return graph def getOrderedJobs(graph): orderedJobs = [] nodes = graph.nodes while len(nodes): node = nodes.pop() containsCycle = dft(node, orderedJobs) if containsCycle: return [] return orderedJobs def dft(node, orderedJobs): if node.visited: return False if node.visiting: return True node.visiting = True for prereqNode in node.prereqs: containsCycle = dft(prereqNode, orderedJobs) if containsCycle: return True node.visited = True node.visiting = False orderedJobs.append(node.job) return False class JobGraph: def __init__(self, jobs): self.nodes = [] self.graph = {} for job in jobs: self.addNode(job) def addNode(self, job): self.graph[job] = JobNode(job) self.nodes.append(self.graph[job]) def getNode(self, job): if job not in self.graph: self.addNode(job) return self.graph[job] def addPrereq(self, job, prereq): jobNode = self.getNode(job) prereqNode = self.getNode(prereq) jobNode.prereqs.append(prereqNode) class JobNode: def __init__(self, job): self.job = job self.prereqs = [] self.visited = False self.visiting = False # METHOD 2 : TRAVERSING FROM PREREQUISITE JOB TO MATCHING DEPENDENCIES # O(j+d) T | 0(j+d) S def topologicalSort(jobs, deps): jobGraph = createJobGraph(jobs, deps) return getOrderedJobs(jobGraph) def createJobGraph(jobs, deps): graph = JobGraph(jobs) for job, dep in deps: graph.addDep(job, dep) return graph def getOrderedJobs(graph): orderedJobs = [] nwnp = list(filter(lambda node: node.numOfPrereqs == 0, graph.nodes)) while len(nwnp): node = nwnp.pop() orderedJobs.append(node.job) removeDeps(node, nwnp) graphHasEdges = any(node.numOfPrereqs for node in graph.nodes) return [] if graphHasEdges else orderedJobs def removeDeps(node, nwnp): while len(node.deps): dep = node.deps.pop() dep.numOfPrereqs -= 1 if dep.numOfPrereqs == 0: nwnp.append(dep) class JobGraph: def __init__(self, jobs): self.nodes = [] self.graph = {} for job in jobs: self.addNode(job) def addNode(self, job): self.graph[job] = JobNode(job) self.nodes.append(self.graph[job]) def addDep(self, job, dep): jobNode = self.getNode(job) depNode = self.getNode(dep) jobNode.deps.append(depNode) depNode.numOfPrereqs += 1 def getNode(self, job): if job not in self.graph: self.addNode(job) return self.graph[job] class JobNode: def __init__(self, job): self.job = job self.deps = [] self.numOfPrereqs = 0 ================================================ FILE: Algorithms/Graph/Topological sort/README.md ================================================ Topological sorting for Directed Acyclic Graph (DAG) is a linear ordering of vertices such that for every directed edge u v, vertex u comes before v in the ordering. Topological Sorting for a graph is not possible if the graph is not a DAG. For example, a topological sorting of the following graph is “5 4 2 3 1 0”. There can be more than one topological sorting for a graph. For example, another topological sorting of the following graph is “4 5 2 3 1 0”. The first vertex in topological sorting is always a vertex with in-degree as 0 (a vertex with no incoming edges). We can modify DFS to find Topological Sorting of a graph. In DFS, we start from a vertex, we first print it and then recursively call DFS for its adjacent vertices. In topological sorting, we use a temporary stack. We don’t print the vertex immediately, we first recursively call topological sorting for all its adjacent vertices, then push it to a stack. Finally, print contents of the stack. Note that a vertex is pushed to stack only when all of its adjacent vertices (and their adjacent vertices and so on) are already in the stack. Complexity Analysis: Time Complexity: O(V+E). The above algorithm is simply DFS with an extra stack. So time complexity is the same as DFS which is. Auxiliary space: O(V). The extra space is needed for the stack. Note: Here, we can also use vector instead of the stack. If the vector is used then print the elements in reverse order to get the topological sorting. ================================================ FILE: Algorithms/Graph/Topological sort/Topological_sort.cpp ================================================ using namespace std; vector topoSort(int N, vector adj[]); /* Function to check if elements returned by user * contains the elements in topological sorted form * V: number of vertices * *res: array containing elements in topological sorted form * adj[]: graph input */ bool check(int V, vector &res, vector adj[]) { vector map(V, -1); for (int i = 0; i < V; i++) { map[res[i]] = i; } for (int i = 0; i < V; i++) { for (int v : adj[i]) { if (map[i] > map[v]) return false; } } return true; } // Driver Code int main() { int T; cin >> T; while (T--) { int N, E; cin >> E >> N; int u, v; vector adj[N]; for (int i = 0; i < E; i++) { cin >> u >> v; adj[u].push_back(v); } vector res = topoSort(N, adj); cout << check(N, res, adj) << endl; } }// } Driver Code Ends // The Graph structure is as folows /* Function which sorts the graph vertices in topological form * N: number of vertices * adj[]: input graph */ stack st; unordered_map mp; void dfs(int s,vector adj[]) { mp[s]=true; for(int i=0;i topoSort(int V, vector adj[]) { for(int i=0;i v; while(!st.empty()) { v.push_back(st.top());st.pop(); } mp.clear(); return v; } ================================================ FILE: Algorithms/Graph/Youngest_Common_Ancestor/QUESTION.md ================================================ ### Youngest Common Ancestor You're given three inputs, all of which are instances of an AncestralTree class that have an ancestor property pointing to their youngest ancestor. The first input is the top ancestor in an ancestral tree (i.e., the only instance that has no ancestor--its ancestor property points to None / null ), and the other two inputs are descendants in the ancestral tree. Write a function that returns the youngest common ancestor to the two descendants. Note that a descendant is considered its own ancestor. So in the simple ancestral tree below, the youngest common ancestor to nodes A and B is node A. ================================================ FILE: Algorithms/Graph/Youngest_Common_Ancestor/YoungerCommonAncestor.cpp ================================================ // C++ Program for Lowest Common Ancestor in a Binary Tree // A O(n) solution to find LCA of two given values n1 and n2 #include #include using namespace std; // A Binary Tree node struct Node { int key; struct Node *left, *right; }; // Utility function creates a new binary tree node with given key Node * newNode(int k) { Node *temp = new Node; temp->key = k; temp->left = temp->right = NULL; return temp; } // Finds the path from root node to given root of the tree, Stores the // path in a vector path[], returns true if path exists otherwise false bool findPath(Node *root, vector &path, int k) { // base case if (root == NULL) return false; // Store this node in path vector. The node will be removed if // not in path from root to k path.push_back(root->key); // See if the k is same as root's key if (root->key == k) return true; // Check if k is found in left or right sub-tree if ( (root->left && findPath(root->left, path, k)) || (root->right && findPath(root->right, path, k)) ) return true; // If not present in subtree rooted with root, remove root from // path[] and return false path.pop_back(); return false; } // Returns LCA if node n1, n2 are present in the given binary tree, // otherwise return -1 int findLCA(Node *root, int n1, int n2) { // to store paths to n1 and n2 from the root vector path1, path2; // Find paths from root to n1 and root to n1. If either n1 or n2 // is not present, return -1 if ( !findPath(root, path1, n1) || !findPath(root, path2, n2)) return -1; /* Compare the paths to get the first different value */ int i; for (i = 0; i < path1.size() && i < path2.size() ; i++) if (path1[i] != path2[i]) break; return path1[i-1]; } // Driver program to test above functions int main() { // Let us create the Binary Tree shown in above diagram. Node * root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); root->right->left = newNode(6); root->right->right = newNode(7); cout << "LCA(4, 5) = " << findLCA(root, 4, 5); cout << "nLCA(4, 6) = " << findLCA(root, 4, 6); cout << "nLCA(3, 4) = " << findLCA(root, 3, 4); cout << "nLCA(2, 4) = " << findLCA(root, 2, 4); return 0; } ================================================ FILE: Algorithms/Graph/Youngest_Common_Ancestor/YoungestCommonAncestor.java ================================================ public class YoungestCommonAncestor { static Integer[] treeNodes = new Integer[]{1, 4, 5, 6, 7, null, null, 8, 9, 10, 11, null, null, null, null, null, null, 13}; static int sizeOfTree = treeNodes.length; static NodeWrap youngestCommonAncestorNode = null; public static void main(String[] args) { /** * 1 * 4 5 * 6 7 * 8 9 10 11 * 13 */ TreeNode root = insert(0); findYoungestCommon(root, 8, 13); if (youngestCommonAncestorNode != null) { System.out.println(youngestCommonAncestorNode.treeNode.val); } } static boolean findYoungestCommon(TreeNode node, int val1, int val2) { if (node == null) { return false; } if (node.val == val1 || node.val == val2) { youngestCommonAncestorNode = new NodeWrap(node); return true; } boolean left = findYoungestCommon(node.left, val1, val2); boolean right = findYoungestCommon(node.right, val1, val2); if (left && right) { youngestCommonAncestorNode = new NodeWrap(node); } return left || right; } static TreeNode insert(int index) { if (index < sizeOfTree) { if (treeNodes[index] == null) { return null; } TreeNode node = new TreeNode(treeNodes[index]); node.left = insert(2 * index + 1); node.right = insert(2 * index + 2); return node; } return null; } static void inOrder(TreeNode root) { if (root == null) { return; } inOrder(root.left); System.out.print(root.val + " "); inOrder(root.right); } static class TreeNode { int val; TreeNode left; TreeNode right; public TreeNode(int val) { this.val = val; } } static class NodeWrap { TreeNode treeNode; public NodeWrap(TreeNode treeNode) { this.treeNode = treeNode; } } } ================================================ FILE: Algorithms/Graph/Youngest_Common_Ancestor/youngest-comm-anc.py ================================================ # O(d) T | O(1)S class AncestralTree: def __init__(self, name): self.name = name self.ancestor = None def getYoungestCommonAncestor(topAncestor, descendantOne, descendantTwo): depOne = getDescDep(descendantOne, topAncestor) depTwo = getDescDep(descendantTwo, topAncestor) if depOne > depTwo: return youngCommon(descendantOne, descendantTwo, depOne-depTwo) else: return youngCommon(descendantTwo, descendantOne, depTwo-depOne) def getDescDep(desc, top): depth = 1 while desc != top: depth += 1 desc = desc.ancestor return depth def youngCommon(lowerDesc, higherDesc, diff): while diff > 0: lowDesc = lowerDesc.ancestor diff -= 1 while higherDesc != lowerDesc: higherDesc = higherDesc.ancestor lowerDesc = lowerDesc.ancestor return lowerDesc ================================================ FILE: Algorithms/Graph/articulation_points.py ================================================ from collections import defaultdict class Graph: def __init__(self,vertices): self.V= vertices #No. of vertices self.graph = defaultdict(list) # default dictionary to store graph self.Time = 0 # function to add an edge to graph def addEdge(self,u,v): self.graph[u].append(v) self.graph[v].append(u) def APUtil(self,u, visited, ap, parent, low, disc): #Count of children in current node children =0 # Mark the current node as visited and print it visited[u]= True # Initialize discovery time and low value disc[u] = self.Time low[u] = self.Time self.Time += 1 #Recur for all the vertices adjacent to this vertex for v in self.graph[u]: if visited[v] == False : parent[v] = u children += 1 self.APUtil(v, visited, ap, parent, low, disc) # Check if the subtree rooted with v has a connection to # one of the ancestors of u low[u] = min(low[u], low[v]) # u is an articulation point in following cases # (1) u is root of DFS tree and has two or more chilren. if parent[u] == -1 and children > 1: ap[u] = True #(2) If u is not root and low value of one of its child is more # than discovery value of u. if parent[u] != -1 and low[v] >= disc[u]: ap[u] = True # Update low value of u for parent function calls elif v != parent[u]: low[u] = min(low[u], disc[v]) #The function to do DFS traversal. It uses recursive APUtil() def AP(self): # Mark all the vertices as not visited # and Initialize parent and visited, # and ap(articulation point) arrays visited = [False] * (self.V) disc = [float("Inf")] * (self.V) low = [float("Inf")] * (self.V) parent = [-1] * (self.V) ap = [False] * (self.V) #To store articulation points # Call the recursive helper function # to find articulation points # in DFS tree rooted with vertex 'i' for i in range(self.V): if visited[i] == False: self.APUtil(i, visited, ap, parent, low, disc) for index, value in enumerate (ap): if value == True: print(index, end=",") # Create a graph given in the above diagram g1 = Graph(5) g1.addEdge(1, 0) g1.addEdge(0, 2) g1.addEdge(2, 1) g1.addEdge(0, 3) g1.addEdge(3, 4) print("\nArticulation points in first graph ") g1.AP() ================================================ FILE: Algorithms/Graph/flood_fill.py ================================================ M = 8 N = 8 def floodFillUtil(screen, x, y, prevC, newC): # Base cases if (x < 0 or x >= M or y < 0 or y >= N or screen[x][y] != prevC or screen[x][y] == newC): return screen[x][y] = newC # Recur for north, east, south and west floodFillUtil(screen, x + 1, y, prevC, newC) floodFillUtil(screen, x - 1, y, prevC, newC) floodFillUtil(screen, x, y + 1, prevC, newC) floodFillUtil(screen, x, y - 1, prevC, newC) def floodFill(screen, x, y, newC): prevC = screen[x][y] floodFillUtil(screen, x, y, prevC, newC) screen = [[1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 0, 0], [1, 0, 0, 1, 1, 0, 1, 1], [1, 2, 2, 2, 2, 0, 1, 0], [1, 1, 1, 2, 2, 0, 1, 0], [1, 1, 1, 2, 2, 2, 2, 0], [1, 1, 1, 1, 1, 2, 1, 1], [1, 1, 1, 1, 1, 2, 2, 1]] x = 4 y = 4 newC = 3 floodFill(screen, x, y, newC) print ("Updated screen after call to floodFill:") for i in range(M): for j in range(N): print(screen[i][j], end = ' ') print() ================================================ FILE: Algorithms/Graph/lagrange_interpolation.cpp ================================================ #include using namespace std; int main() { float x[100], y[100], xp, yp=0, p; int i,j,n; cout<<"Enter number of data: "; cin>>n; cout<<"Enter data:"<< endl; for(i=1;i<=n;i++) { cout<<"x["<< i<<"] = "; cin>>x[i]; cout<<"y["<< i<<"] = "; cin>>y[i]; } cout<<"Enter interpolation point: "; cin>>xp; /* Implementing Lagrange Interpolation */ for(i=1;i<=n;i++) { p=1; for(j=1;j<=n;j++) { if(i!=j) { p = p* (xp - x[j])/(x[i] - x[j]); } } yp = yp + p * y[i]; } cout<< endl<<"Interpolated value at "<< xp<< " is "<< yp; return 0; } ================================================ FILE: Algorithms/Graph/lowest_common_manager/lowest_common_manager.java ================================================ public class Employee { private String name; private List reportee; private Employee manager; Employee(String name) { this.name = name; reportee = new ArrayList<>(); } public void setManager(Employee m) { manager = m; } public void addReprotee(Employee e) { reportee.add(e); e.manager = this; } //O(log(n)) time complexity, O(1) memory static Employee closestCommonManager2(Employee a, Employee b) { Employee e1 = a; Employee e2 = b; int h1 = 0; int h2 = 0; while (e1 != null || e2 != null) { if (e1 != null) { e1 = e1.manager ; h1++; } if (e2 != null) { e2 = e2.manager ; h2++; } } int diff = Math.abs(h1 - h2); if(h1 > h2) { e1 = a; e2 = b; } else { e1 = b; e2 = a; } while (diff > 0) { e1 = e1.manager; diff--; } while (e1 != e2) { e1 = e1.manager ; e2 = e2.manager ; } return e1; } //O(log(n)) time complexity, O(log(n)) memory static Employee closestCommonManager(Employee a, Employee b) { Stack ls1 = new Stack(); Stack ls2 = new Stack(); while (a != null || b != null) { if (a != null) { ls1.push(a); a = a.manager ; } if (b != null) { ls2.push(b); b = b.manager; } } while(!ls1.isEmpty() && !ls2.isEmpty()) { if (ls1.peek() != ls2.peek()) { break; } a = ls1.pop(); ls2.pop(); } return a; } public String toString() { return name; } } ================================================ FILE: Algorithms/Graph/newton_raphson_method.c ================================================ #include #include #include #include #define f(x) 3*x - cos(x) -1 #define g(x) 3 + sin(x) void main() { float x0, x1, f0, f1, g0, e; int step = 1, N; printf("\nEnter initial guess:\n"); scanf("%f", &x0); printf("Enter tolerable error:\n"); scanf("%f", &e); printf("Enter maximum iteration:\n"); scanf("%d", &N); printf("\nStep\t\tx0\t\tf(x0)\t\tx1\t\tf(x1)\n"); do { g0 = g(x0); f0 = f(x0); if(g0 == 0.0) { printf("Mathematical Error."); exit(0); } x1 = x0 - f0/g0; printf("%d\t\t%f\t%f\t%f\t%f\n",step,x0,f0,x1,f1); x0 = x1; step = step+1; if(step > N) { printf("Not Convergent."); exit(0); } f1 = f(x1); }while(fabs(f1)>e); printf("\nRoot is: %f", x1); getch(); } ================================================ FILE: Algorithms/Hashing/Amicable/Amicable_Number.rb ================================================ class AmicableNumber class << self def are_amicables?(number_1, number_2) # Prevents for not valid arguments errors raise ArgumentError, "Both arguments must be Integer positive number. Argumens: (#{number_1}, #{number_2})" unless is_valid?(number_1) && is_valid?(number_2) sum_divisors_of(number_1) === sum_divisors_of(number_2) end private # Validates if params are positive integer numbers def is_valid?(number) number.is_a?(Integer) && number > 0 end # Returns the sum of the divisors def sum_divisors_of(number) divisors = divisors_of(number) divisors.sum end # Finds all divisor of each number def divisors_of(number) (1..number).select { |divisor| number % divisor === 0 } end end end puts AmicableNumber.are_amicables?(220, 284) # true puts AmicableNumber.are_amicables?(1184, 1210) # true puts AmicableNumber.are_amicables?(1184, 121) # false puts AmicableNumber.are_amicables?("A", 98) # Raise error ================================================ FILE: Algorithms/Hashing/Amicable/Amicable_Numbers..c ================================================ #include int main(){ int i,a,b,c=0; printf("To check whether the given two numbers are Amicable numbers or not.\n\n"); printf("Enter two numbers : "); scanf("%d%d",&a,&b); for(i=0;i<=a/2;i++){ if(a%i==0) c+=i; } if(c==b) printf("%d and %d are Amicable numbers .\n",a,b); else printf("%d and %d are not Amicable numbers .\n",a,b); printf("\n\nSome Amicable Numbers under 100,000 are :- \n"); int x,y,m,n,j; for(i=220;i<100000;i++){ x=0,y=0; for(j=1;j<=i/2;j++){ if(i%j==0) x+=j;} m=1,n=0; while(m<=x/2){ if(x%m==0) y+=m; m++;} if(i==y){ if(x!=y){ printf("%d and %d \n",x,y); i+=500;} }} return 0; } ================================================ FILE: Algorithms/Hashing/Amicable/Amicable_Numbers.cpp ================================================ #include using namespace std; int main(){ int i,a,b,c=0; cout<<"To check for the entered pair of numbers are Amicable Numbers or not.\n"<>a>>b; for(i=1;i<=a/2;i++) { if(a%i==0) c+=i; } if(c==b) cout< divisors = new List(); for (int i = 1; i <= Math.Sqrt(n); i++) { if (n % i == 0) { divisors.Add(i); if (i != n / i) { divisors.Add(n / i); } } } divisors.Remove(n); divisors.Sort(); return divisors.ToArray(); } } ================================================ FILE: Algorithms/Hashing/Amicable/amicable.js ================================================ /* projecteuler.net Amicable numbers Problem 21 Let d(n) be defined as the sum of proper divisors of n (numbers less than n which divide evenly into n). If d(a) = b and d(b) = a, where a ≠ b, then a and b are an amicable pair and each of a and b are called amicable numbers. For example, the proper divisors of 220 are 1, 2, 4, 5, 10, 11, 20, 22, 44, 55 and 110; therefore d(220) = 284. The proper divisors of 284 are 1, 2, 4, 71 and 142; so d(284) = 220. Evaluate the sum of all the amicable numbers under 10000. */ var total = 10000; var halfTotal = total / 2; var amicableNumbers = []; var sum = 0; for (var i = 0; i < halfTotal; i++){ if (total % i === 0){ amicableNumbers.push(i); sum += i; } } console.log("Sum of all amicable numbers under " + total + " is " + sum); console.log(amicableNumbers); ================================================ FILE: Algorithms/Hashing/Amicable/amicable.swift ================================================ // returns true if two numbers are amicable func isAmicable(_ a : Int, _ b : Int) -> Bool { return getSum(num: a) == b && getSum(num: b) == a } // returns a sum of all of the factors of a Int func getSum(num a: Int) -> Int { var sum : Int = 0; // check for factors for i in 1 ..< a { // add to sum if remainder is 0 if a % i == 0 { sum += i; } } return sum; } // driver code print(isAmicable(284, 220)) // true print(isAmicable(6, 12)) // false ================================================ FILE: Algorithms/Hashing/Amicable/amicable_numbers.php ================================================ ================================================ FILE: Algorithms/Hashing/Amicable/amicable_numbers.py ================================================ import math # Calculating the sum # of proper divisors def sumOfDiv(x): # 1 is a proper divisor sum = 1; for i in range(2,int(math.sqrt(x))): if x % i==0: sum += i # To handle perfect squares if i != x/i: sum += x/i return int(sum); def isAmbicle(a, b): return (sumOfDiv(a) == b and sumOfDiv(b) == a) def countPairs(arr,n): s = set() count = 0 for i in range(n): s.add(arr[i]) for i in range(n): if sumOfDiv(arr[i]) in s: # It's sum of proper divisors sum = sumOfDiv(arr[i]) if isAmbicle(arr[i], sum): count += 1 return int(count/2); # Driver Code arr1 = [220, 284, 1184, 1210, 2, 5] n1 = len(arr1) print(countPairs(arr1, n1)) ================================================ FILE: Algorithms/Hashing/Brick_Wall/Brick_wall.cpp ================================================ class Solution { public: int leastBricks(vector> &wall) { unordered_map m; //Maintain a sort of prefix array with counts for each sum int max_surpass = 0; int res = wall.size(); int sum; for (int i = 0; i < wall.size(); i++) { sum = 0; for (int j = 0; j < wall[i].size() - 1; j++) { sum += wall[i][j]; m[sum] += 1; max_surpass = max(max_surpass, m[sum]); } } return wall.size() - max_surpass; } }; ================================================ FILE: Algorithms/Hashing/Brick_Wall/QUESTION.md ================================================ ### Brick Wall There is a brick wall in front of you. The wall is rectangular and has several rows of bricks. The bricks have the same height but different width. You want to draw a vertical line from the top to the bottom and cross the least bricks. The brick wall is represented by a list of rows. Each row is a list of integers representing the width of each brick in this row from left to right. If your line go through the edge of a brick, then the brick is not considered as crossed. You need to find out how to draw the line to cross the least bricks and return the number of crossed bricks. You cannot draw a line just along one of the two vertical edges of the wall, in which case the line will obviously cross no bricks. ================================================ FILE: Algorithms/Hashing/Chaining/chainingHashing.cpp ================================================ #include #include using namespace std; struct Node { int data; struct Node *next; } * head[100], *curr /*points to the current node*/; /*initialize hash table i.e., head[] with null*/ void init() { for (int i = 0; i < 100; i++) head[i] = NULL; } /* * given the data and hash * add a new Node with given data in the hash table */ void add(int x, int h) { struct Node *temp = new Node; temp->data = x; temp->next = NULL; if (!head[h]) { head[h] = temp; curr = head[h]; } else { curr = head[h]; while (curr->next) curr = curr->next; curr->next = temp; } } /* * given the mod * prints the hash table in console */ void display(int mod) { struct Node *temp; int i; for (i = 0; i < mod; i++) { if (!head[i]) { cout << "Key " << i << " is empty" << endl; } else { cout << "Key " << i << " has values = "; temp = head[i]; while (temp->next) { cout << temp->data << " "; temp = temp->next; } cout << temp->data; cout << endl; } } } /*return hash*/ int get_hash(int x, int mod) { return x % mod; } /* * given the data and hash * finds the Node in the hash table */ void find(int x, int h) { struct Node *temp = head[h]; if (!head[h]) { cout << "Element not found"; return; } while (temp->data != x && temp->next) temp = temp->next; if (temp->next) cout << "Element found"; else { if (temp->data == x) cout << "Element found"; else cout << "Element not found"; } } int main(void) { init(); int choice, x /*buffer to store user input in each switch case*/; int mod /*size of the hash table*/, h; cout << "Enter the size of Hash Table. = "; cin >> mod; bool loop = true; while (loop) { cout << endl; cout << "PLEASE CHOOSE -" << endl; cout << "1. Add element." << endl; cout << "2. Find element." << endl; cout << "3. Generate Hash." << endl; cout << "4. Display Hash table." << endl; cout << "5. Exit." << endl; cin >> choice; switch (choice) { case 1: cout << "Enter element to add = "; cin >> x; h = get_hash(x, mod); h = fabs(h); add(x, h); break; case 2: cout << "Enter element to search = "; cin >> x; h = get_hash(x, mod); find(x, h); break; case 3: cout << "Enter element to generate hash = "; cin >> x; cout << "Hash of " << x << " is = " << get_hash(x, mod); break; case 4: display(mod); break; default: loop = false; break; } cout << endl; } /*add(1,&head1); add(2,&head1); add(3,&head2); add(5,&head1); display(&head1); display(&head2);*/ return 0; } ================================================ FILE: Algorithms/Hashing/Cuckoo_Hashing/Cuckoo_Hashing.cpp ================================================ //C++ program to perform Cuckoo Hashing #include using namespace std; #define hashTableNum 2 //Number of table hash consist //Number of element to be hashed static int tableSize=0; //Initialized to zero //Array to store hash value int cuckooTable[hashTableNum][100]; //Array to store hashed position of element int Position[hashTableNum]; //Initialize cuckooTable with minimum value of Integer type void fillTable(){ for (int j=0; j "; //Print hash position of various element for(int j=0; j>n; tableSize=n; int keyTable[n]; //Array to store keys or elements cout<<"Enter desired numbers:\n"; //Initialize each key or elment in array for(int i=0; i>keyTable[i]; } cuckooFunction(keyTable, n); return 0; } ================================================ FILE: Algorithms/Hashing/Cuckoo_Hashing/Cuckoo_Hashing.java ================================================ import java.util.*; class Cuckoo_Hashing { static int MAXN = 11; static int ver = 2; static int [][]hashtable = new int[ver][MAXN]; static int []pos = new int[ver]; static void initTable() { for (int j = 0; j < MAXN; j++) for (int i = 0; i < ver; i++) hashtable[i][j] = Integer.MIN_VALUE; } static int hash(int function, int key) { switch (function) { case 1: return key % MAXN; case 2: return (key / MAXN) % MAXN; } return Integer.MIN_VALUE; } static void place(int key, int tableID, int cnt, int n) { if (cnt == n) { System.out.printf("%d unpositioned\n", key); System.out.printf("Cycle present. REHASH.\n"); return; } for (int i = 0; i < ver; i++) { pos[i] = hash(i + 1, key); if (hashtable[i][pos[i]] == key) return; } if (hashtable[tableID][pos[tableID]] != Integer.MIN_VALUE) { int dis = hashtable[tableID][pos[tableID]]; hashtable[tableID][pos[tableID]] = key; place(dis, (tableID + 1) % ver, cnt + 1, n); } else hashtable[tableID][pos[tableID]] = key; } static void printTable() { System.out.printf("Final hash tables:\n"); for (int i = 0; i < ver; i++, System.out.printf("\n")) for (int j = 0; j < MAXN; j++) if(hashtable[i][j] == Integer.MIN_VALUE) System.out.printf("- "); else System.out.printf("%d ", hashtable[i][j]); System.out.printf("\n"); } static void cuckoo(int keys[], int n) { initTable(); for (int i = 0, cnt = 0; i < n; i++, cnt = 0) place(keys[i], 0, cnt, n); printTable(); } public static void main(String[] args) { int keys_1[] = {20, 50, 53, 75, 100, 67, 105, 3, 36, 39}; int n = keys_1.length; cuckoo(keys_1, n); int keys_2[] = {20, 50, 53, 75, 100, 67, 105, 3, 36, 39, 6}; int m = keys_2.length; cuckoo(keys_2, m); } } ================================================ FILE: Algorithms/Hashing/Divisible_Pair_Count/DivisiblePairCount.c ================================================ #include "stdio.h" #include int DivisiblePairsCount(int arr[], int n) { int res = 0; for (int i = 0; i < n; ++i) { // Iterating through each pair. for (int j = i+1; j < n; ++j) { if (arr[i] % arr[j] == 0 || arr[j] % arr[i] == 0) // Checking for problem condition. res++; } } return res; } int main() { int n; int *arr; printf("Enter Size of the Array: "); scanf("%d", &n); arr = malloc(sizeof(int) * n); printf("Enter the Array Elements: "); for(int i = 0; i ", i+1) fmt.Scan(&arr[i]) } for j := 0; j < n; j++ { for k := j + 1; k < n; k++ { if arr[j]%arr[k] == 0 || arr[k]%arr[j] == 0 { count++ } } } fmt.Printf("The number of divisible pair in the array %d is %d\n", arr, count) } ================================================ FILE: Algorithms/Hashing/Divisible_Pair_Count/DivisiblePairCount.java ================================================ import java.io.*; import java.lang.*; import java.util.*; class DivisiblePairCount{ public static int countDivisibles(int arr[],int n) { int res = 0; for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { if (arr[i] % arr[j] == 0 || arr[j] % arr[i] == 0) { res++; } } } return res; } public static void main(String[] args) { Scanner sc = new Scanner(System.in); int num = sc.nextInt(); int a[] = new int[num]; for(int i=0;i { let count = 0; // set count = 0 for (let i = 0; i < n; i++) // iterate through the array from i = 0 { for (let j = i + 1; j < n; j++) // iterate through the array start from the element next to arr[i] { if ( (arr[i] % arr[j] == 0) || (arr[j] % arr[i] == 0) ) { count++; // increase count by 1, if it is under the condition } } } return count; } let arr = [2,3,5,8,9]; console.log(DivisiblePairCount(arr, arr.length)); ================================================ FILE: Algorithms/Hashing/Divisible_Pair_Count/DivisiblePairCount.py ================================================ def DivisiblePairCount(arr, n) : res = 0 for i in range(0, n): for j in range(i+1, n): if (arr[i] % arr[j] == 0 or arr[j] % arr[i] == 0): res+=1 return res if __name__=='__main__': arr = [int(item) for item in input("Enter the array items : ").split()] n = len(arr); print("Number of divisible pairs are:", DivisiblePairCount(arr, n) ) ================================================ FILE: Algorithms/Hashing/Divisible_Pair_Count/DivsiblePairCount.cpp ================================================ #include // C++ program to count divisible pairs. using namespace std; int DivisiblePairsCount(vector v, int n) { int res = 0; for (int i = 0; i < n; ++i) { // Iterating through each pair. for (int j = i+1; j < n; ++j) { if (v[i] % v[j] == 0 || v[j] % v[i] == 0) // Checking for problem condition. res++; } } return res; } int main() { int n; cout << "Enter Size of the Array: "; cin >> n; vector v(n); cout << "Enter Array Elements: "; for (auto &i : v) { // Vector Input cin >> i; } cout << "Number of Divisible Pairs: "; cout << DivisiblePairsCount(v, n); return 0; } ================================================ FILE: Algorithms/Hashing/Group_Anagrams/Group_Anagrams.cpp ================================================ #include #include #include #include using namespace std; vector> groupAnagrams(vector &strs) { //basically what we need to do is that we need to create a map that will store the characters of a particular string // Now compare it with every other string //O(n3) solution vector> res; unordered_map> m; for (int i = 0; i < strs.size(); i++) { string eq = strs[i]; sort(eq.begin(), eq.end()); m[eq].push_back(strs[i]); } for (auto it = m.begin(); it != m.end(); it++) { res.push_back(it->second); } return res; } int main() { int n; cout << "Input number of words in string: "; cin >> n; vector strs(n); for (int i = 0; i < n; i++) { cout << "Enter word: "; cin >> strs[i]; } vector> res = groupAnagrams(strs); cout << "["; for (int i = 0; i < res.size(); i++) { cout << "["; for (int j = 0; j < res[i].size(); j++) { cout << res[i][j]; if (j != res[i].size() - 1) { cout << ","; } } cout << "]"; if (i != res.size() - 1) cout << ","; } cout << "]"; return 0; } ================================================ FILE: Algorithms/Hashing/Group_Anagrams/QUESTIONS.md ================================================ ### Group Anagrams Given an array of strings strs, group the anagrams together. You can return the answer in any order. An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once. ================================================ FILE: Algorithms/Hashing/Group_Anagrams/group_anagrams.js ================================================ function groupAnagrams(stringValue) { //create dictionary object to keep track of which strings are made up of which letters let anagrams = {}; for (let str of stringValue) { // loop through strings and sort them alphabetically let letters = str.split("").sort().join(""); //if the sorted string already exists as a key on the dictionary, push string if (anagrams[letters]) anagrams[letters].push(str) //else it as a key to the dictionary else anagrams[letters] = [str] } // use objects.values on the dictionary to return all values as an array return Object.values(anagrams); }; //Test let array = [] let array_len = parseInt(prompt("Input number of words in string array:")) for(var i =0; i< array_len; i++){ let word = prompt("Enter a word"); array.push(word) } console.log(groupAnagrams(array)) ================================================ FILE: Algorithms/Hashing/Group_Anagrams/group_anagrams.py ================================================ from itertools import groupby print("Please input the required data seperated with space") test_list=input("Enter data:").split() temp = lambda test_list: sorted(test_list) res = [list(val) for key, val in groupby(sorted(test_list, key = temp), temp)] # print result print("The grouped Anagrams : " + str(res)) ================================================ FILE: Algorithms/Hashing/Open Addressing/doubleHashHashingTable.cpp ================================================ #include #include #include #include #include using std::endl; using std::cout; using std::cin; using std::string; // fwd declarations struct Entry; bool putProber(Entry entry, int key); bool searchingProber(Entry entry, int key); void add(int key); // globals int notPresent; struct Entry* table; int totalSize; int tomb = -1; int size; bool rehashing; // Node that holds key struct Entry { explicit Entry(int key = notPresent) : key(key) {} int key; }; // Hash a key int hashFxn(int key) { std::hash hash; return hash(key); } // Used for second hash function int otherHashFxn(int key) { std::hash hash; return 1 + (7 - (hash(key) % 7)); } // Performs double hashing to resolve collisions int doubleHash(int key, bool searching) { int hash = static_cast(fabs(hashFxn(key))); int i = 0; Entry entry; do { int index = static_cast(fabs((hash + (i * otherHashFxn(key))))) % totalSize; entry = table[index]; if (searching) { if (entry.key == notPresent) { return notPresent; } if (searchingProber(entry, key)) { cout << "Found key!" << endl; return index; } cout << "Found tombstone or equal hash, checking next" << endl; i++; } else { if (putProber(entry, key)) { if (!rehashing) cout << "Spot found!" << endl; return index; } if (!rehashing) cout << "Spot taken, looking at next (next index:" << " " << static_cast(fabs((hash + (i * otherHashFxn(key))))) % totalSize << ")" << endl; i++; } if (i == totalSize * 100) { cout << "DoubleHash probe failed" << endl; return notPresent; } } while (entry.key != notPresent); return notPresent; } // Finds empty spot bool putProber(Entry entry, int key) { if (entry.key == notPresent || entry.key == tomb) { return true; } return false; } // Looks for a matching key bool searchingProber(Entry entry, int key) { if (entry.key == key) return true; return false; } // Displays the table void display() { for (int i = 0; i < totalSize; i++) { if (table[i].key == notPresent) { cout << " Empty "; } else if (table[i].key == tomb) { cout << " Tomb "; } else { cout << " "; cout << table[i].key; cout << " "; } } cout << endl; } // Rehashes the table into a bigger table void rehash() { // Necessary so wall of add info isn't printed all at once rehashing = true; int oldSize = totalSize; Entry* oldTable = table; // Really this should use the next prime number greater than totalSize * 2 table = new Entry[totalSize * 2]; totalSize *= 2; for (int i = 0; i < oldSize; i++) { if (oldTable[i].key != -1 && oldTable[i].key != notPresent) { size--; // Size stays the same (add increments size) add(oldTable[i].key); } } delete[] oldTable; rehashing = false; cout << "Table was rehashed, new size is: " << totalSize << endl; } // Checks for load factor here void add(int key) { Entry * entry = new Entry(); entry->key = key; int index = doubleHash(key, false); table[index] = *entry; // Load factor greater than 0.5 causes resizing if (++size/ static_cast(totalSize) >= 0.5) { rehash(); } } // Removes key. Leaves tombstone upon removal. void remove(int key) { int index = doubleHash(key, true); if (index == notPresent) { cout << "key not found" << endl; } table[index].key = tomb; cout << "Removal successful, leaving tombstone" << endl; size--; } // Information about the adding process void addInfo(int key) { cout << "Initial table: "; display(); cout << endl; cout << "hash of " << key << " is " << hashFxn(key) << " % " << totalSize << " == " << fabs(hashFxn(key) % totalSize); cout << endl; add(key); cout << "New table: "; display(); } // Information about removal process void removalInfo(int key) { cout << "Initial table: "; display(); cout << endl; cout << "hash of " << key << " is " << hashFxn(key) << " % " << totalSize << " == " << hashFxn(key) % totalSize; cout << endl; remove(key); cout << "New table: "; display(); } // I/O int main(void) { int cmd, hash, key; cout << "Enter the initial size of Hash Table. = "; cin >> totalSize; table = new Entry[totalSize]; bool loop = true; while (loop) { system("pause"); cout << endl; cout << "PLEASE CHOOSE -" << endl; cout << "1. Add key. (Numeric only)" << endl; cout << "2. Remove key." << endl; cout << "3. Find key." << endl; cout << "4. Generate Hash. (Numeric only)" << endl; cout << "5. Display Hash table." << endl; cout << "6. Exit." << endl; cin >> cmd; switch (cmd) { case 1: cout << "Enter key to add = "; cin >> key; addInfo(key); break; case 2: cout << "Enter key to remove = "; cin >> key; removalInfo(key); break; case 3: { cout << "Enter key to search = "; cin >> key; Entry entry = table[doubleHash(key, true)]; if (entry.key == notPresent) { cout << "Key not present"; } break; } case 4: cout << "Enter element to generate hash = "; cin >> key; cout << "Hash of " << key << " is = " << fabs(hashFxn(key)); break; case 5: display(); break; default: loop = false; break; delete[] table; } cout << endl; } return 0; } ================================================ FILE: Algorithms/Hashing/Open Addressing/linearProbingHashTable.cpp ================================================ #include #include #include #include #include using std::endl; using std::cout; using std::cin; using std::string; // fwd declarations struct Entry; bool putProber(Entry entry, int key); bool searchingProber(Entry entry, int key); void add(int key); // globals int notPresent; struct Entry* table; int totalSize; int tomb = -1; int size; bool rehashing; // Node that holds key struct Entry { explicit Entry(int key = notPresent) : key(key) {} int key; }; // Hash a key int hashFxn(int key) { std::hash hash; return hash(key); } // Performs linear probing to resolve collisions int linearProbe(int key, bool searching) { int hash = static_cast(fabs(hashFxn(key))); int i = 0; Entry entry; do { int index = static_cast(fabs((hash + i) % totalSize)); entry = table[index]; if (searching) { if (entry.key == notPresent) { return notPresent; } if (searchingProber(entry, key)) { cout << "Found key!" << endl; return index; } cout << "Found tombstone or equal hash, checking next" << endl; i++; } else { if (putProber(entry, key)) { if (!rehashing) cout << "Spot found!" << endl; return index; } if (!rehashing) cout << "Spot taken, looking at next" << endl; i++; } if (i == totalSize) { cout << "Linear probe failed" << endl; return notPresent; } } while (entry.key != notPresent); return notPresent; } // Finds empty spot bool putProber(Entry entry, int key) { if (entry.key == notPresent || entry.key == tomb) { return true; } return false; } // Looks for a matching key bool searchingProber(Entry entry, int key) { if (entry.key == key) return true; return false; } // Displays the table void display() { for (int i = 0; i < totalSize; i++) { if (table[i].key == notPresent) { cout << " Empty "; } else if (table[i].key == tomb) { cout << " Tomb "; } else { cout << " "; cout << table[i].key; cout << " "; } } cout << endl; } // Rehashes the table into a bigger table void rehash() { // Necessary so wall of add info isn't printed all at once rehashing = true; int oldSize = totalSize; Entry* oldTable = table; // Really this should use the next prime number greater than totalSize * 2 table = new Entry[totalSize * 2]; totalSize *= 2; for (int i = 0; i < oldSize; i++) { if (oldTable[i].key != -1 && oldTable[i].key != notPresent) { size--; // Size stays the same (add increments size) add(oldTable[i].key); } } delete[] oldTable; rehashing = false; cout << "Table was rehashed, new size is: " << totalSize << endl; } // Adds entry using linear probing. Checks for load factor here void add(int key) { Entry * entry = new Entry(); entry->key = key; int index = linearProbe(key, false); table[index] = *entry; // Load factor greater than 0.5 causes resizing if (++size/ static_cast(totalSize) >= 0.5) { rehash(); } } // Removes key. Leaves tombstone upon removal. void remove(int key) { int index = linearProbe(key, true); if (index == notPresent) { cout << "key not found" << endl; } cout << "Removal Successful, leaving tomb" << endl; table[index].key = tomb; size--; } // Information about the adding process void addInfo(int key) { cout << "Initial table: "; display(); cout << endl; cout << "hash of " << key << " is " << hashFxn(key) << " % " << totalSize << " == " << fabs(hashFxn(key) % totalSize); cout << endl; add(key); cout << "New table: "; display(); } // Information about removal process void removalInfo(int key) { cout << "Initial table: "; display(); cout << endl; cout << "hash of " << key << " is " << hashFxn(key) << " % " << totalSize << " == " << hashFxn(key) % totalSize; cout << endl; remove(key); cout << "New table: "; display(); } // I/O int main(void) { int cmd, hash, key; cout << "Enter the initial size of Hash Table. = "; cin >> totalSize; table = new Entry[totalSize]; bool loop = true; while (loop) { system("pause"); cout << endl; cout << "PLEASE CHOOSE -" << endl; cout << "1. Add key. (Numeric only)" << endl; cout << "2. Remove key." << endl; cout << "3. Find key." << endl; cout << "4. Generate Hash. (Numeric only)" << endl; cout << "5. Display Hash table." << endl; cout << "6. Exit." << endl; cin >> cmd; switch (cmd) { case 1: cout << "Enter key to add = "; cin >> key; addInfo(key); break; case 2: cout << "Enter key to remove = "; cin >> key; removalInfo(key); break; case 3: { cout << "Enter key to search = "; cin >> key; Entry entry = table[linearProbe(key, true)]; if (entry.key == notPresent) { cout << "Key not present"; } break; } case 4: cout << "Enter element to generate hash = "; cin >> key; cout << "Hash of " << key << " is = " << fabs(hashFxn(key)); break; case 5: display(); break; default: loop = false; break; delete[] table; } cout << endl; } return 0; } ================================================ FILE: Algorithms/Hashing/Open Addressing/quadraticProbingHashTable.cpp ================================================ #include #include #include #include #include using std::endl; using std::cout; using std::cin; using std::string; // fwd declarations struct Entry; bool putProber(Entry entry, int key); bool searchingProber(Entry entry, int key); void add(int key); // globals int notPresent; struct Entry* table; int totalSize; int tomb = -1; int size; bool rehashing; // Node that holds key struct Entry { explicit Entry(int key = notPresent) : key(key) {} int key; }; // Hash a key int hashFxn(int key) { std::hash hash; return hash(key); } // Performs quadratic probing to resolve collisions int quadraticProbe(int key, bool searching) { int hash = static_cast(fabs(hashFxn(key))); int i = 0; Entry entry; do { int index = std::round(fabs((hash + static_cast(std::round(std::pow(i, 2)))) % totalSize)); entry = table[index]; if (searching) { if (entry.key == notPresent) { return notPresent; } if (searchingProber(entry, key)) { cout << "Found key!" << endl; return index; } cout << "Found tombstone or equal hash, checking next" << endl; i++; } else { if (putProber(entry, key)) { if (!rehashing) cout << "Spot found!" << endl; return index; } if (!rehashing) { cout << "Spot taken, looking at next (next index = " << std::round(fabs((hash + static_cast(std::round( std::pow(i + 1, 2)))) % totalSize)) << endl; } i++; } if (i == totalSize * 100) { cout << "Quadratic probe failed (infinite loop)" << endl; return notPresent; } } while (entry.key != notPresent); return notPresent; } // Finds empty spot bool putProber(Entry entry, int key) { if (entry.key == notPresent || entry.key == tomb) { return true; } return false; } // Looks for a matching key bool searchingProber(Entry entry, int key) { if (entry.key == key) return true; return false; } // Helper Entry find(int key) { int index = quadraticProbe(key, true); if (index == notPresent) return Entry(); return table[index]; } // Displays the table void display() { for (int i = 0; i < totalSize; i++) { if (table[i].key == notPresent) { cout << " Empty "; } else if (table[i].key == tomb) { cout << " Tomb "; } else { cout << " "; cout << table[i].key; cout << " "; } } cout << endl; } // Rehashes the table into a bigger table void rehash() { // Necessary so wall of add info isn't printed all at once rehashing = true; int oldSize = totalSize; Entry* oldTable = table; // Really this should use the next prime number greater than totalSize * 2 table = new Entry[totalSize * 2]; totalSize *= 2; for (int i = 0; i < oldSize; i++) { if (oldTable[i].key != -1 && oldTable[i].key != notPresent) { size--; // Size stays the same (add increments size) add(oldTable[i].key); } } delete[] oldTable; rehashing = false; cout << "Table was rehashed, new size is: " << totalSize << endl; } // Checks for load factor here void add(int key) { Entry * entry = new Entry(); entry->key = key; int index = quadraticProbe(key, false); table[index] = *entry; // Load factor greater than 0.5 causes resizing if (++size/ static_cast(totalSize) >= 0.5) { rehash(); } } // Removes key. Leaves tombstone upon removal. void remove(int key) { int index = quadraticProbe(key, true); if (index == notPresent) { cout << "key not found" << endl; } table[index].key = tomb; cout << "Removal successful, leaving tombstone" << endl; size--; } // Information about the adding process void addInfo(int key) { cout << "Initial table: "; display(); cout << endl; cout << "hash of " << key << " is " << hashFxn(key) << " % " << totalSize << " == " << fabs(hashFxn(key) % totalSize); cout << endl; add(key); cout << "New table: "; display(); } // Information about removal process void removalInfo(int key) { cout << "Initial table: "; display(); cout << endl; cout << "hash of " << key << " is " << hashFxn(key) << " % " << totalSize << " == " << hashFxn(key) % totalSize; cout << endl; remove(key); cout << "New table: "; display(); } // I/O int main(void) { int cmd, hash, key; cout << "Enter the initial size of Hash Table. = "; cin >> totalSize; table = new Entry[totalSize]; bool loop = true; while (loop) { system("pause"); cout << endl; cout << "PLEASE CHOOSE -" << endl; cout << "1. Add key. (Numeric only)" << endl; cout << "2. Remove key." << endl; cout << "3. Find key." << endl; cout << "4. Generate Hash. (Numeric only)" << endl; cout << "5. Display Hash table." << endl; cout << "6. Exit." << endl; cin >> cmd; switch (cmd) { case 1: cout << "Enter key to add = "; cin >> key; addInfo(key); break; case 2: cout << "Enter key to remove = "; cin >> key; removalInfo(key); break; case 3: { cout << "Enter key to search = "; cin >> key; Entry entry = table[quadraticProbe(key, true)]; if (entry.key == notPresent) { cout << "Key not present"; } break; } case 4: cout << "Enter element to generate hash = "; cin >> key; cout << "Hash of " << key << " is = " << fabs(hashFxn(key)); break; case 5: display(); break; default: loop = false; break; delete[] table; } cout << endl; } return 0; } ================================================ FILE: Algorithms/Hashing/Recaman_Sequence/Recamans_Sequence.java ================================================ //Java program to generate Recaman's Sequence upto nth term import java.util.*; class Sequence{ //Prints Sequence upto first n term void recamansSeq(int n){ //Array to store sequence int seqenceArray[] = new int [n]; //First term of Sequence is always 0 seqenceArray[0] = 0; System.out.print("Recanman's Sequence is: "+seqenceArray[0] + ", "); //Generate remaining terms using recursive formula for(int i=1; i 0 && !list.includes(list[n-1] - n)) { list[n] = list[n-1] - n; } else { list[n] = list[n-1] + n; } console.log(list[n]); } rl.close(); }); ================================================ FILE: Algorithms/Hashing/Recaman_Sequence/recaman.py ================================================ def recaman(n): arr = [0] * n arr[0] = 0 print(arr[0], end=", ") for i in range(1, n): curr = arr[i-1] - i for j in range(0, i): if ((arr[j] == curr) or curr < 0): curr = arr[i-1] + i break arr[i] = curr print(arr[i], end=", ") # Driver code n = 10 recaman(n) ================================================ FILE: Algorithms/Hashing/Recaman_Sequence/recaman_sequence.cpp ================================================ #include using namespace std; int get_recaman_sequence(int n) { int *arr = new int[n]; arr[0] = 0; cout << arr[0]; for (int i = 1; i < n; i++) { int curr_element = arr[i - 1] - i; for (int j = 0; j < i; j++) { if ((arr[j] == curr_element) || curr_element < 0) { curr_element = arr[i - 1] + i; break; } } arr[i] = curr_element; cout << arr[i]; } delete[] arr; } int main() { int n; cout << "enter the number"; cin >> n; cout << get_recaman_sequence(n); return 0; } ================================================ FILE: Algorithms/Hashing/Recaman_Sequence/recamans_sequence.cs ================================================ sing System; using System.Collections.Generic; class Program { static void Main(string[] args) { Console.WriteLine("How many numbers do you want to write out?"); int count = int.Parse(Console.ReadLine()); List numbers = new List(); numbers.Add(0); long last = numbers[0]; Console.WriteLine(numbers[0]); for (int i = 1; i < count; i++) { if (last - i > 0 && !numbers.Contains(last - i)) { numbers.Add(last - i); Console.WriteLine(numbers[i]); last = numbers[i]; } else { numbers.Add(last + i); Console.WriteLine(numbers[i]); last = numbers[i]; } } Console.ReadLine(); // otherwise the console closes } } ================================================ FILE: Algorithms/Heap/README.md ================================================ ================================================ FILE: Algorithms/LinkedList/Floyd_Cylce_detection/floyd_cycle_detection.cpp ================================================ #include using namespace std; //Definition for singly-linked list- struct ListNode { int val; ListNode *next; }; //Utility function- void push(ListNode** head, int new_val) { ListNode* new_node = new ListNode(); new_node->val = new_val; //link the old list off the new node- new_node->next = (*head); //move the head to point to the new node- (*head) = new_node; } //Floyd cycle-finding algorithm uses two pointers: fast_ptr (moving two nodes at a time) and slow_ptr (moving one node at a time). //The concept used is that if these two pointers meet at any time, then a cycle exists, otherwise it does not. int isCyclePresent(ListNode* head) { //both pointers start at the head node of the list- ListNode* slow=head; ListNode* fast=head; bool cycle=false; //cycle is not yet detected //Floyd Algorithm- while(fast!=NULL){ slow=slow->next; //move forward one node if(fast->next!=NULL) fast=fast->next->next; //move forward two nodes else fast=NULL; //reached end of list if(slow==fast){ //the pointers meet cycle=true; break; } } if(cycle) return 1; //cycle exists else return 0; //cycle doesn't exist } int main() { //Start with the empty list ListNode* head = NULL; push(&head, 20); push(&head, 4); push(&head, 15); push(&head, 10); //making cycle- head->next->next->next->next = head; if (isCyclePresent(head)) cout << "Loop found"; else cout << "No Loop"; return 0; } ================================================ FILE: Algorithms/LinkedList/Floyd_Cylce_detection/floyd_cycle_detection.java ================================================ // Java program to detect loop in a linked list using Floyd’s Cycle-Finding Algorithm class LinkedList { Node head; // head of list /* Linked list Node*/ class Node { int data; Node next; Node(int d) { data = d; next = null; } } /* Inserts a new Node at front of the list. */ public void push(int new_data) { /* 1 & 2: Allocate the Node & Put in the data*/ Node new_node = new Node(new_data); /* 3. Make next of new Node as head */ new_node.next = head; /* 4. Move the head to point to new Node */ head = new_node; } boolean detectLoop() { Node slow_p = head, fast_p = head; int flag = 0; while (slow_p != null && fast_p != null && fast_p.next != null) { slow_p = slow_p.next; fast_p = fast_p.next.next; if (slow_p == fast_p) { flag = 1; break; } } if (flag == 1) return true; else return false; } /* Driver program to test above functions */ public static void main(String args[]) { LinkedList llist = new LinkedList(); llist.push(20); llist.push(4); llist.push(15); llist.push(10); llist.push(77); /*Create loop for testing */ llist.head.next.next.next.next.next = llist.head; boolean v = llist.detectLoop(); if (v) System.out.println("Cycle found"); else System.out.println("Cycle not found"); } } ================================================ FILE: Algorithms/LinkedList/Floyd_Cylce_detection/floyd_cycle_detection.kt ================================================ class LinkedList { class Node(val value: T, var next: Node? = null) var head: Node? = null private lateinit var tail: Node fun insert(item: T) { if (head == null) { tail = Node(item) head = tail } else { tail.next = Node(item) tail = tail.next!! } } fun detectLoop(): Boolean { var slowPointer = head?.next var fastPointer = head?.next?.next while (slowPointer != null && fastPointer != null) { if (slowPointer == fastPointer) return true slowPointer = slowPointer.next fastPointer = fastPointer.next?.next } return false } fun forceLoop() { tail.next = head } } fun main() { val linkedList = LinkedList() linkedList.apply { insert(1) } println("linkedList has loop: " + linkedList.detectLoop()) linkedList.forceLoop() println("linkedList has loop: " + linkedList.detectLoop()) } ================================================ FILE: Algorithms/LinkedList/Floyd_Cylce_detection/floyd_cycle_detection.py ================================================ class Node: def __init__(self, data): self.data = data self.next = None class LinkedList: def __init__(self): self.head = None def push(self, new_data): new_node = Node(new_data) new_node.next = self.head self.head = new_node def printList(self): temp = self.head while(temp): print (temp.data, end =" ") temp = temp.next def detectLoop(self): s = set() temp = self.head while (temp): if (temp in s): return True s.add(temp) temp = temp.next return False # Driver program for testing llist = LinkedList() llist.push(10) llist.push(4) llist.push(15) llist.push(40) # Create a loop for testing llist.head.next.next.next.next = llist.head; if( llist.detectLoop()): print ("Loop found") else : print ("No Loop ") ================================================ FILE: Algorithms/LinkedList/Floyd_Cylce_detection/floyd_cycle_detection.swift ================================================ // floyd_cycle_detection.swift // // Swift implementation of a linked list with cycle detection functionality // // How to run: type on terminal `swift floyd_cycle_detection.swift` and type enter. // The test program will populate two lists, one with loop and one without // and will print test both for if theres a loop or not. // A class representing one node of the list class Node { // Public properties public var value: T public var next: Node? // Create a new node with a given value public init (value: T) { self.value = value } } // A class representing the list class LinkedList { // Current head of list var head: Node // Create a new list with a given node public init(node: Node) { head = node } // Insert a node at the start of the list public func insert(_ node: Node) { node.next = head head = node } // Detects if there is a loop on the list using the Floyd`s Cycle-Finding Algorithm public func detectLoop() -> Bool { var slowPointer = head.next var fastPointer = head.next?.next // Transverse the list with two pointers going on different speeds. // If there is a loop on the list, eventually the fastest pointer will catch up the slower, and they will be equal. // If not, eventually they will reach the end of the list. while slowPointer != nil && fastPointer != nil { if fastPointer! === slowPointer! { return true } slowPointer = slowPointer!.next fastPointer = fastPointer!.next?.next } return false } } /*********** Testing the detect loop method ***********/ // Adding a print funcionality just so we can see the list elements extension LinkedList { public func description(maxElements: Int) -> String { var count = 0 var currentNode = Optional(head) var listDescription = "" while currentNode != nil { listDescription += (String(describing: currentNode!.value) + " -> ") count += 1 if count >= maxElements { return listDescription + " (list continues...) " } currentNode = currentNode?.next } return listDescription + "(End of list)" } } // Populating a list without loop let linkedListWithoutLoop = LinkedList(node: Node(value: "1")) linkedListWithoutLoop.insert(Node(value:"2")) linkedListWithoutLoop.insert(Node(value:"3")) linkedListWithoutLoop.insert(Node(value:"4")) linkedListWithoutLoop.insert(Node(value:"5")) linkedListWithoutLoop.insert(Node(value:"6")) linkedListWithoutLoop.insert(Node(value:"7")) print("List: \(linkedListWithoutLoop.description(maxElements: 20))") print("Loop detected: \(linkedListWithoutLoop.detectLoop())") // Populating a list with loop let listTail = Node(value: "A") let linkedListWithLoop = LinkedList(node: listTail) linkedListWithLoop.insert(Node(value:"B")) linkedListWithLoop.insert(Node(value:"C")) linkedListWithLoop.insert(Node(value:"D")) linkedListWithLoop.insert(Node(value:"E")) linkedListWithLoop.insert(Node(value:"F")) linkedListWithLoop.insert(listTail) print("List: \(linkedListWithLoop.description(maxElements: 20))") print("Loop detected: \(linkedListWithLoop.detectLoop())") ================================================ FILE: Algorithms/Matrix/README.md ================================================ # This folder is empty. ================================================ FILE: Algorithms/Matrix/Spiral-Matrix/Spiral-Matrix.cpp ================================================ // Code contributed by Vatsalya Gupta #include #include using namespace std; #define R 4 #define C 4 bool isInBounds(int i, int j) { if (i < 0 || i >= R || j < 0 || j >= C) return false; return true; } bool isBlocked(int matrix[R][C], int i, int j) { if (!isInBounds(i, j)) return true; if (matrix[i][j] == -1) return true; return false; } void spirallyDFSTravserse(int matrix[R][C], int i, int j, int dir, vector& res) { if (isBlocked(matrix, i, j)) return; bool allBlocked = true; for (int k = -1; k <= 1; k += 2) { allBlocked = allBlocked && isBlocked(matrix, k + i, j) && isBlocked(matrix, i, j + k); } res.push_back(matrix[i][j]); matrix[i][j] = -1; if (allBlocked) { return; } // dir: 0 - right, 1 - down, 2 - left, 3 - up int nxt_i = i; int nxt_j = j; int nxt_dir = dir; if (dir == 0) { if (!isBlocked(matrix, i, j + 1)) { nxt_j++; } else { nxt_dir = 1; nxt_i++; } } else if (dir == 1) { if (!isBlocked(matrix, i + 1, j)) { nxt_i++; } else { nxt_dir = 2; nxt_j--; } } else if (dir == 2) { if (!isBlocked(matrix, i, j - 1)) { nxt_j--; } else { nxt_dir = 3; nxt_i--; } } else if (dir == 3) { if (!isBlocked(matrix, i - 1, j)) { nxt_i--; } else { nxt_dir = 0; nxt_j++; } } spirallyDFSTravserse(matrix, nxt_i, nxt_j, nxt_dir, res); } vector spirallyTraverse(int matrix[R][C]) { vector res; spirallyDFSTravserse(matrix, 0, 0, 0, res); return res; } int main() { int a[R][C] = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 } }; vector res = spirallyTraverse(a); int size = res.size(); for (int i = 0; i < size; ++i) cout << res[i] << " "; cout << endl; return 0; } ================================================ FILE: Algorithms/Merging-Interval/#999 merging_intervals.py ================================================ def mergeIntervals(arr): arr.sort(key = lambda x: x[0]) m = [] s = -10000 max = -100000 for i in range(len(arr)): a = arr[i] if a[0] > max: if i != 0: m.append([s,max]) max = a[1] s = a[0] else: if a[1] >= max: max = a[1] if max != -100000 and [s, max] not in m: m.append([s, max]) print("The Merged Intervals are :", end = " ") for i in range(len(m)): print(m[i], end = " ") arr = [[6, 8], [1, 9], [2, 4], [4, 7]] mergeIntervals(arr) ================================================ FILE: Algorithms/Merging-Interval/Merging_Intervals.java ================================================ import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class Merging_Intervals { public static void main(String args[]) { //Given 2D array containing intervals int[][] ans = {{1,3},{2,6},{8,10},{15,18}}; //This function returns 2D array having our merged intervals ans = merge(ans); //Each merged interval will be displayed on each line for (int i = 0; i < ans.length; i++) { for (int j = 0; j < ans[0].length; j++) { System.out.print(ans[i][j] + " "); } System.out.println(); } } public static int[][] merge(int[][] intervals) { if (intervals.length <= 1) { return intervals; } //Perform sorting in increasing order of first element of each interval Arrays.sort(intervals, (a1, a2) -> a1[0] - a2[0]); List output_arr = new ArrayList(); int[] curr_interval = intervals[0]; output_arr.add(curr_interval); for (int[] interval : intervals) { int curr_beg = curr_interval[0]; int curr_end = curr_interval[1]; int next_beg = interval[0]; int next_end = interval[1]; if (curr_end >= next_beg) { curr_interval[1] = Math.max(curr_end, next_end); } else { curr_interval = interval; output_arr.add(curr_interval); } } return output_arr.toArray(new int[output_arr.size()][]); } } ================================================ FILE: Algorithms/Merging-Interval/README.md ================================================ # This folder is empty. ================================================ FILE: Algorithms/Merging-Interval/merge_intervals.cpp ================================================ #include using namespace std; // An interval has start time and end time struct Interval { int start, end; }; // To compare two intervals accoridng to their start time bool myComp(Interval interval1, Interval interval2) { return (interval1.start < interval2.start); } // This function takes a set of intervals, merges // overlapping intervals and prints the result void mergeIntervals(Interval arr[], int n) { // Test if the given set has at least one interval if (n <= 0) return; // Create an empty stack of intervals stack s; // sorting the intervals in increasing order of start time sort(arr, arr+n, myComp); // push the first interval to stack s.push(arr[0]); // Start from the next interval and merge if necessary for (int i = 1 ; i < n; i++) { // get interval from stack top Interval top = s.top(); // if current interval is not overlapping with stack top, // push it to the stack if (top.end < arr[i].start) s.push(arr[i]); // Otherwise update the ending time of top if ending of current // interval is more else if (top.end < arr[i].end) { top.end = arr[i].end; s.pop(); s.push(top); } } // Print contents of stack cout << "\n After merging Intervals are: "; while (!s.empty()) { Interval t = s.top(); cout << "[" << t.start << "," << t.end << "] "; s.pop(); } return; } int main() { Interval arr[]= {{1,6},{3,9},{11,13},{2,5}}; //creating an array int n = sizeof(arr)/sizeof(arr[0]); //size of the array mergeIntervals(arr,n); return 0; } ================================================ FILE: Algorithms/Merging-Interval/merge_intervals.js ================================================ // list of intervals as an array of objects const arr = [ { start: 1, end: 3 }, { start: 2, end: 4 }, { start: 5, end: 8 }, { start: 6, end: 7 } ]; function mergeIntervals(arr) { // sort the array of intervals in ascending order based on the start value of each interval arr.sort(function(a, b) { if (a.start < b.start) return -1; if (a.start > b.start) return 1; return 0; }); // result array which will work as stack let res = []; // push first interval into result array res.push(arr[0]); for (let i = 1; i < arr.length; i++) { // get the top of the result array // we will call it top interval const top = res[res.length - 1] // top interval's end is less than the current interval's start that means disjoint intervals // we can push the current interval to our result if (top.end < arr[i].start) { res.push(arr[i]); } // top interval's end is between the current interval's start and end // we can merge intervals with the ending at current interval's end else if (top.end < arr[i].end) { top.end = arr[i].end; // delete the top interval res.pop(); // insert new modified interval res.push(top); } // Otherwise top interval's end is after the current interval's end // i.e after merge we will get top interval, hence no change required } // print the array of merged intervals console.log(res); } mergeIntervals(arr); ================================================ FILE: Algorithms/Pattern-Searching/Aho-Corasick/Readme.md ================================================ # This folder is created. ================================================ FILE: Algorithms/Pattern-Searching/Binary_Search/search_in_2D_matrix.java ================================================ public class search_in_2D_matrix { public static boolean searchMatrix(int[][] matrix, int target) { int colLength = matrix[0].length-1; // each row length for(int i = 0; i < matrix.length; i++) { // iterate over every row if(target > matrix[i][colLength]) continue; // if target is greater than the highest number in that row then skip that row int start = 0, end = colLength; while(start <= end) { // using binary search algorithm to search through the row for the target int mid = start + (end-start)/2; if(matrix[i][mid] == target) return true; if(matrix[i][mid] > target) end = mid-1; else if(matrix[i][mid] < target) start = mid+1; } } return false; } public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("Enter number of rows"); int row = sc.nextInt(); System.out.println("Enter number of coloumns"); int col = sc.nextInt(); int mat[][] = new int[row][col]; System.out.println("Enter matrix elements in sorted manner"); for(int i=0;i ================================================ FILE: Algorithms/Queue/first_negative_integer_in_window.cpp ================================================ /* Given an array and a positive integer k, find the first negative integer for each and every window(contiguous subarray) of size k. Input: The first line of input contains an integer T denoting the number of test cases. Then T test cases follow. Each test case contains an integer n denoting the size of the array. The next line contains n space separated integers forming the array. The last line contains the window size k. Output: Print the space separated negative integer starting from the first till the end for every window size k. If a window does not contain a negative integer , then print 0 for that window. Constraints: 1<=T<=10^5 1<=n<=10^5 1<=a[i]<=10^5 1<=k<=n Example: Input: 2 5 -8 2 3 -6 10 2 8 12 -1 -7 8 -15 30 16 28 3 Output: -8 0 -6 -6 -1 -1 -7 -15 -15 0 */ #include using namespace std; int findd(int low,int high,int a[]){ for(int i=low;i>t; while(t--){ int n,k; cin>>n; int a[n]; for(int i=0;i>a[i]; cin>>k; for(int i=0;i<=n-k;i++) cout< using namespace std; int main(){ int t; cin>>t; while(t--){ int n; cin>>n; vector ch(n); for(int i=0;i>ch[i]; int freq[26]; for(int i=0;i q; for(int i=0;i1) q.pop(); else{ cout< using namespace std; // Utility function to print the queue void Print(queue& Queue) { while (!Queue.empty()) { cout << Queue.front() << " "; Queue.pop(); } } // Function to reverse the queue void reverseQueue(queue& Queue) { stack Stack; while (!Queue.empty()) { Stack.push(Queue.front()); Queue.pop(); } while (!Stack.empty()) { Queue.push(Stack.top()); Stack.pop(); } } // Driver code int main() { queue Queue; Queue.push(10); Queue.push(20); Queue.push(30); Queue.push(40); Queue.push(50); Queue.push(60); Queue.push(70); Queue.push(80); Queue.push(90); Queue.push(100); reverseQueue(Queue); Print(Queue); } ================================================ FILE: Algorithms/README.md ================================================ # Index * [DP](DP/) * [Heap](Heap/) * [Tree](Tree/) * [Array](Array/) * [Graph](Graph/) * [Queue](Queue/) * [Graph](Graph/) * [String](String/) * [Matrix](Matrix/) * [Sorting](Sorting/) * [Hashing](Hashing/) * [Recursion](Recursion/) * [Searching](Searching/) * [LinkedList](LinkedList/) * [Backtracking](Backtracking/) * [Cryptography](Cryptography/) * [Merging-Interval](Merging-Interval/) * [Pattern-Searching](Pattern-Searching/) ================================================ FILE: Algorithms/Recursion/All_Subsets.c ================================================ /** * Generate all subsets of a set comprised of 0 <= N ({0 1 2 3 ... N}). * * @author Ytalo Ramon */ #include "stdio.h" #include "stdlib.h" typedef struct _Stack{ int posi, length; int *items; } Stack; int is_empty(Stack *stack); void push(Stack *stack, int value); int pop(Stack *stack); void show_stack(Stack *stack); void set_value_seq(Stack *stack, int start, int end); void generate(Stack *stack, int max); int main(int argc, char const *argv[]){ int max = 6; Stack stack = {posi: -1, length: max, items: malloc(sizeof(int) * max + 1)} ; printf("----- All Subsets {0 ... %d} -----\n", max); set_value_seq(&stack, 0, max); if(max > 0) generate(&stack, max); printf("{ }\n"); return 0; } int is_empty(Stack *stack){ return stack->posi == -1; } void push(Stack *stack, int value){ stack->items[++stack->posi] = value; } int pop(Stack *stack){ return stack->items[stack->posi--]; } void show_stack(Stack *stack){ printf("{"); for (int i = 0; i <= stack->posi; i++) printf(" %d", stack->items[i]); printf(" }\n"); } void set_value_seq(Stack *stack, int start, int end){ for (int i = start; i <= end; i++) push(stack, i); } void generate(Stack *stack, int max){ show_stack(stack); int v = pop(stack), q; set_value_seq(stack, v + 1, max); if(!is_empty(stack)) generate(stack, max); } ================================================ FILE: Algorithms/Recursion/Combination_Sum/Combination_Sum.php ================================================ 0) { $combinations[] = $combination; } } printCombinations($combinations); } /** * Find the combination for a specific target * * @param array $elements * @param int $target * @param array $combination possible combinations from previous iteration */ function findCombination(array $elements, int $target, array $combination): array { for($i = 0; $i < count($elements); $i++) { $newTarget = $target - $elements[$i]; if($newTarget == 0) { $combination[] = $elements[$i]; return $combination; } if($newTarget < 0) { continue; } $combination[] = $elements[$i]; return findCombination(array_slice($elements, $i + 1), $newTarget, $combination); } return []; } /** * Print the combinations * * @param array $combinations */ function printCombinations(array $combinations) { for($i = 0; $i < count($combinations); $i++) { for($j = 0; $j < count($combinations[$i]); $j++) { echo $combinations[$i][$j] . " "; } echo "\n"; } } //Test $elements = [1, 5, 2, 8, 6, 4, 3, 10]; $target = 10; combinationalSum($elements, $target); //Result: 5 2 3 // 2 8 // 6 4 // 10 ================================================ FILE: Algorithms/Recursion/Combination_Sum/combination_sum.cpp ================================================ #include using namespace std; void generatePermutation(vector &arr, int target, int currSum, int currIndex, vector> &ans, vector &currCandidates) { if (currSum == target) { ans.push_back(currCandidates); return; } if (currSum > target) return; for (int i = currIndex; i < arr.size(); i++) { currCandidates.push_back(arr[i]); currSum += arr[i]; generatePermutation(arr, target, currSum, i, ans, currCandidates); currCandidates.pop_back(); currSum -= arr[i]; } } vector> combinationSum(vector &candidates, int target) { vector> ans; vector temp; generatePermutation(candidates, target, 0, 0, ans, temp); return ans; } int main() { ios_base::sync_with_stdio(false); int n, target; cin >> n >> target; vector candidates(n, 0); for (int i = 0; i < n; i++) { cin >> candidates[i]; } vector> solution = combinationSum(candidates, target); for (auto &i : solution) { for (int j : i) { cout << j << " "; } cout << "\n"; } return 0; } //Input 4 7 2 3 6 7 //Output 2 2 3 7 ================================================ FILE: Algorithms/Recursion/Factorial/Factorial.c ================================================ /** * Factorial * * @author Ytalo Ramon */ #include "stdio.h" #include "stdlib.h" int run(int value){ if(value <= 1) return 1; return value * run(value - 1); } int main(int argc, char const *argv[]){ int number = 6; printf("Factorial of %d: %d\n", number, run(number)); return 0; } ================================================ FILE: Algorithms/Recursion/Factorial/Factorial.cs ================================================ using System; namespace Demo { class Factorial { public int checkFact(int n) { if (n == 1) return 1; else return n * checkFact(n - 1); } static void Main(string[] args) { int value = 9; int ret; Factorial fact = new Factorial(); ret = fact.checkFact(value); Console.WriteLine("Value is : {0}", ret ); Console.ReadLine(); } } } ================================================ FILE: Algorithms/Recursion/Factorial/Factorial.go ================================================ package main import "fmt" func fact(n int) int { if n == 0 { return 1 } return n * fact(n-1) } func main() { for i := 1; i <= 10; i++ { fmt.Printf("%2d: %d \n", i, fact(i)) } } ================================================ FILE: Algorithms/Recursion/Factorial/Factorial_Algorithm.cpp ================================================ #include using namespace std; int main() // main function: the execution of the program starts from here { int factorial(int); // function prototype int f,value; cout<<"Enter any number: "; cin>>value; f=factorial(value); cout<<"Factorial of "< // Factorial Recursive Algorithm C++ Implementation int n{ 0 }; // Initialize int answer{ 0 }; int recursiveFactorial(int n) { // takes int n, to calculate n! if (n > 1) { // Since 1! = 1 and 0! = 1, and n must be positive; answer = (n-1) * answer; // n! = (n * n-1) repeating until n < 1 n -= 1; recursiveFactorial(n); // We keep calling back until } else if (n == 0) { // Special case if n = 0; 0! = 1; answer = 1; return answer; } else { // We finished our recursive calculation now we return our result. return answer; // Side note: we don't need a special if-case for n = 1 since the returned answer already equals 1. } } int main() { std::cout << "Enter n for n!" << "\n" << "n = "; // Prompt user for n std::cin >> n; // Get User Response answer = n; std::cout << "n! = " << recursiveFactorial(n); // print result of our calculation; } ================================================ FILE: Algorithms/Recursion/Factorial/Factorial_Algorithm.py ================================================ ''' The factorial of a positive integer n, detoned by n! is the product of all positive integers less than or equal to n. Examples: 1) The factorial of 3 is 6, because: 3*2*1 = 6 2) The factorial of 5 is 120, because: 5*4*3*2 = 120 The value of 0! is 1 The following method shows how recursion can be used to calculate the factorial of any given number ''' def factorial(n): if(n == 1 or n == 0): return 1 else: return n * factorial(n-1) #The following code is used to test the code with an input from the user while True: try: user_input = int(input("Please enter the number to be computed: ")) if(user_input < 0): print("The number cannot be negative!") continue else: print(factorial(user_input)) except ValueError: print("The number should be a integer!") continue else: break ================================================ FILE: Algorithms/Recursion/Factorial/factorial.js ================================================ function factorial(n) { if (n<0) { return("Negatives don't have factorial") } else if (n==0 || n==1) { return (1) } else { while(n>1) { return (n*factorial(n-1)) } } } number = prompt("Enter number") console.log(factorial(number)) ================================================ FILE: Algorithms/Recursion/Factorial/factorial.py ================================================ def factorial(n): if (n<0): return ("ERROR - Negatives can't have factorials !!") if (n==0 or n==1): return 1 while (n>1): return n*factorial(n-1) number = int(input("Enter number")) print (factorial(number)) ================================================ FILE: Algorithms/Recursion/Josephus/Josephus.c ================================================ #include #include typedef struct person { int position; struct person *next; } person; int findWinner(int n, int k) { int i, count; person *p, *q, *r; p = (person *)malloc(sizeof(person)); p->position = 1; p->next = p; q = p; for (i = 2; i <= n; i++) { r = (person *)malloc(sizeof(person)); r->position = i; r->next = p; q->next = r; q = r; } while (p->next != p) { q = p; r = q; for (count = 1; count < k; count++) { r = q; q = q->next; } r->next = q->next; p = r->next; q->next = NULL; free(q); q = NULL; } return p->position; } int main() { int n, k; scanf("%d", &n); scanf("%d", &k); int w = findWinner(n, k); printf("%d", w); return 0; } ================================================ FILE: Algorithms/Recursion/Josephus/Josephus.cs ================================================ using System; class TEMP { static int josephus(int n, int k) { if (n == 1) return 1; else return (josephus(n - 1, k) + k - 1) % n + 1; } public static void Main() { int n ; int k ; n= Convert.ToInt32(Console.ReadLine()); k= Convert.ToInt32(Console.ReadLine()); Console.WriteLine("The chosen " + "place is " + josephus(n, k)); } } ================================================ FILE: Algorithms/Recursion/Josephus/Josephus.java ================================================ import java.util.*; public class Josephus { public static int execute(int n, int k) { int killIndex = 0;//stores index of person to be executed ArrayList prisoners = new ArrayList(n); for(int i = 0;i < n;i++){ prisoners.add(i); } System.out.println("Prisoners executed in order:"); while(prisoners.size() > 1) {//until only one person remains alive killIndex = (killIndex + k - 1) % prisoners.size(); System.out.print(prisoners.get(killIndex) + " "); prisoners.remove(killIndex); } System.out.println(); return prisoners.get(0); } public static void main(String[] args){ Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int k = sc.nextInt(); System.out.println("Survivor : " + execute(n,k)); } } ================================================ FILE: Algorithms/Recursion/Josephus/josephus.cpp ================================================ #include using namespace std; int Josephus(int, int); int main() { int n, k; cin >> n >> k; cout << Josephus(n, k); return 0; } int Josephus(int n, int k) { k--; int arr[n]; for (int i = 0; i < n; i++) { arr[i] = 1; // Makes all the 'n' people alive by // assigning them value = 1 } int cnt = 0, cut = 0, num = 1; // Cut = 0 gives the sword to 1st person. while ( cnt < (n - 1)) // Loop continues till n-1 person dies. { while (num <= k) // Checks next (kth) alive persons. { cut++; cut = cut % n; // Checks and resolves overflow // of Index. if (arr[cut] == 1) { num++; // Updates the number of persons // alive. } } num = 1; // refreshes value to 1 for next use. arr[cut] = 0; // Kills the person at position of 'cut' cnt++; // Updates the no. of killed persons. cut++; cut = cut % n; // Checks and resolves overflow of Index. while (arr[cut] == 0) // Checks the next alive person the // sword is to be given. { cut++; cut = cut % n; // Checks and resolves overflow // of Index. } } return cut + 1; // Output is the position of the last // man alive(Index + 1); } /********************THIS CODE IS PRESENTED BY VIKASH PATEL ***************************/ ================================================ FILE: Algorithms/Recursion/Josephus/josephus.kt ================================================ fun main(args: Array){ //Taking n, k as input values val (n, k) = readLine()!!.split(' ').map{it.toInt()} //array to store status dead/alive of a person //initially all persons are alive so we set the staus to false, meaning all are //not dead val is_dead = BooleanArray(n) var index = 0 //index of a person in the circle var died_count = 0 //count of died people so far while(true){ //if only one person is alive, indeed that's our answer so break if(died_count == n-1) break //next we move until we reach the kth alive person from the current index var count = k-1//to keep track of alive people while(count > 0){ index = (index + 1)%n // to move around the circle so that after the last index we move to the first index if(!is_dead[index])count-- } //kth person would die is_dead[index] = true //count of person died so far would be incremented died_count++ //now start from the next alive person while(is_dead[index])index = (index + 1)%n } //after the loop the only person alive is at the position of the 'index'. println(index + 1)//index + 1 to make it 1 based indexing } ================================================ FILE: Algorithms/Recursion/Keypadcodes.cpp ================================================ #include using namespace std; int sub(string s,string output[],string s1[]) { if(s.length()==1) { string s2=s1[s[0]-48]; for(int i=0;i>s; string* output= new string[10000000]; string s1[10]; s1[0]=".;"; s1[1]="abc"; s1[2]="def"; s1[3]="ghi"; s1[4]="jkl"; s1[5]="mno"; s1[6]="pqrs"; s1[7]="tu"; s1[8]="vwx"; s1[9]="yz"; int n=sub(s,output,s1); cout<<"["; for(int i=0;i SinglePermutations(string s) { // Example: s = "abc" // Set is used to avoid duplicates var hash = new SortedSet(); var stack = ""; int len = s.Length; GetPermutations(s, hash, stack, len); return new List(hash); // returned value is ["abc", "acb", "bac", "bca", "cab", "cba"] } private static void GetPermutations(string item, SortedSet hash, string stack, int len) { // Checks length of stack if equal to that of item if (stack.Length == len) { hash.Add(stack); } else { // lops through the for (var i = 0; i < item.Length; i++) { // Adds an item to the stack stack += item[i]; // Populates available combinations and permutation // with the elements in stack GetPermutations(item.Remove(i, 1), hash, stack, len); // Removes the last item in stack stack = stack.Remove(stack.Length - 1, 1); } } } } } ================================================ FILE: Algorithms/Recursion/Permutation/Permutation.js ================================================ function getPermutations(input) { // Input should be a string. if (!input || typeof input !== "string") { return "Input must be a string." } // No permutation. if (input.length < 2) { return [input]; } var output = []; var counter = 0; for (counter = 0; counter < input.length; counter++) { var computeChar = input[counter]; // No character repetitions allowed. if (input.indexOf(computeChar) != counter) continue; var characterYetToBeComputed = input.slice(0, counter) + input.slice(counter + 1, input.length); // For...of is supported in ECMAScript 5 and higher. for (var permutation of getPermutations(characterYetToBeComputed)) { output.push(computeChar + permutation); } } return output; } ================================================ FILE: Algorithms/Recursion/Permutation/Permutation.ts ================================================ class Permutation { getPermutations(input: string): string | string[] { // No permutation. if (input.length < 2) { return input; } const output: string[] = []; let counter: number = 0; for (counter = 0; counter < input.length; counter++) { const computeChar = input[counter]; // No character repetitions allowed. if (input.indexOf(computeChar) != counter) continue; const characterYetToBeComputed = input.slice(0, counter) + input.slice(counter + 1, input.length); // For...of is supported in ECMAScript 5 and higher. for (const permutation of this.getPermutations(characterYetToBeComputed)) { output.push(computeChar + permutation); } } return output; } } ================================================ FILE: Algorithms/Recursion/Permutation/Permutations_Recursion.cpp ================================================ // C++ program to print all // permutations with duplicates allowed #include using namespace std; void permute(string a, int l, int r) { if (l == r) cout< 0:\n", " \n", " # Every time any node is referred from yet_to_visit list, counter of limit operation incremented\n", " outer_iterations += 1 \n", "\n", " \n", " # Get the current node\n", " current_node = yet_to_visit_list[0]\n", " current_index = 0\n", " for index, item in enumerate(yet_to_visit_list):\n", " if item.f < current_node.f:\n", " current_node = item\n", " current_index = index\n", " \n", " # if we hit this point return the path such as it may be no solution or \n", " # computation cost is too high\n", " if outer_iterations > max_iterations:\n", " print (\"giving up on pathfinding too many iterations\")\n", " return return_path(current_node,maze)\n", "\n", " # Pop current node out off yet_to_visit list, add to visited list\n", " yet_to_visit_list.pop(current_index)\n", " visited_list.append(current_node)\n", "\n", " # test if goal is reached or not, if yes then return the path\n", " if current_node == end_node:\n", " return return_path(current_node,maze)\n", "\n", " # Generate children from all adjacent squares\n", " children = []\n", "\n", " for new_position in move: \n", "\n", " # Get node position\n", " node_position = (current_node.position[0] + new_position[0], current_node.position[1] + new_position[1])\n", "\n", " # Make sure within range (check if within maze boundary)\n", " if (node_position[0] > (no_rows - 1) or \n", " node_position[0] < 0 or \n", " node_position[1] > (no_columns -1) or \n", " node_position[1] < 0):\n", " continue\n", "\n", " # Make sure walkable terrain\n", " if maze[node_position[0]][node_position[1]] != 0:\n", " continue\n", "\n", " # Create new node\n", " new_node = Node(current_node, node_position)\n", "\n", " # Append\n", " children.append(new_node)\n", "\n", " # Loop through children\n", " for child in children:\n", " \n", " # Child is on the visited list (search entire visited list)\n", " if len([visited_child for visited_child in visited_list if visited_child == child]) > 0:\n", " continue\n", "\n", " # Create the f, g, and h values\n", " child.g = current_node.g + cost\n", " ## Heuristic costs calculated here, this is using eucledian distance\n", " child.h = (((child.position[0] - end_node.position[0]) ** 2) + \n", " ((child.position[1] - end_node.position[1]) ** 2)) \n", "\n", " child.f = child.g + child.h\n", "\n", " # Child is already in the yet_to_visit list and g cost is already lower\n", " if len([i for i in yet_to_visit_list if child == i and child.g > i.g]) > 0:\n", " continue\n", "\n", " # Add the child to the yet_to_visit list\n", " yet_to_visit_list.append(child)\n", "\n", "\n", "if __name__ == '__main__':\n", "\n", " maze = [[0, 1, 0, 0, 0, 0],\n", " [0, 0, 0, 0, 0, 0],\n", " [0, 1, 0, 1, 0, 0],\n", " [0, 1, 0, 0, 1, 0],\n", " [0, 0, 0, 0, 1, 0]]\n", " \n", " start = [0, 0] # starting position\n", " end = [4,5] # ending position\n", " cost = 1 # cost per movement\n", "\n", " path = search(maze,cost, start, end)\n", " print(path)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Final result path " ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ " 0 -1 -1 -1 -1 -1\n", " 1 2 3 4 5 -1\n", " -1 -1 -1 -1 6 7\n", " -1 -1 -1 -1 -1 8\n", " -1 -1 -1 -1 -1 9\n" ] } ], "source": [ "print('\\n'.join([''.join([\"{:\" \">3d}\".format(item) for item in row]) \n", " for row in path]))" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.6.8" } }, "nbformat": 4, "nbformat_minor": 1 } ================================================ FILE: Algorithms/Searching/A-Star Search/README.md ================================================ # A* Search Algorithm The most widely known form of best-first search is called A* Search. Few terminologies: - Node (also called State) — All potential position or stops with a unique identification - Transition — The act of moving between states or nodes. - Starting Node — Whereto start searching - Goal Node — The target to stop searching. - Search Space — A collection of nodes, like all board positions of a board game - Cost — Numerical value (say distance, time, or financial expense) for the path from a node to another node. - g(n) — this represents the exact cost of the path from the starting node to any node n - h(n) — this represents the heuristic estimated cost from node n to the goal node. - f(n) — lowest cost in the neighboring node n It evaluates nodes by combining g(n), the cost to reach the node, and h(n), the cost to get from the node to the goal: F(n) = g(n) + h(n) Since g(n) gives the path cost from the start node to node n, and h(n) is the estimated cost of the cheapest path from n to the goal, we have: F(n)= estimated cost of the cheapest solution through n. Thus, if we are trying to find the cheapest solution, a reasonable thing to try first is the node with the lowest of f(n). It turns out that this strategy is more reasonable: provided that the heuristic function h(n) satisfies certain conditions, A* search is both complete and optimal. The algorithm is identical to Uniform-cost-search exceptthat A* uses g(h) and h(n) instead of g(h). The way of how the A* Search works is illustrated in the figure below. Each time, the node having the lowest f(n) value is the node expanded. The targets nodes will be expanded until reaching the goal destination, which is Bucharest. ## How it works ![A Star Search](algo.png) ## Demo ![A Star Search](screenshot.png) ================================================ FILE: Algorithms/Searching/Binary-Search/Binary_Search_CubicRoot.cpp ================================================ #include #include #define EPS 1e-8 using namespace std; double a, b, c, d; double f(double x){ return a*x*x*x + b*x*x + c*x + d; } double binsearch(double l, double r) { double x = (l + r)/2; if(fabs(f(x)) < EPS) return x; if(f(x) > EPS) return binsearch(l, x); else return binsearch(x, r); } int main(){ cin >> a >> b >> c >> d; if(a < 0){ a *= -1; b *= -1; c *= -1; d *= -1; } int r = 1; while(f(r) * f(-r) >= 0){ r *= 2; } printf("%.8f\n", binsearch(-r, r)); return 0; } ================================================ FILE: Algorithms/Searching/Binary-Search/Binary_search_javascript.js ================================================ ================================================ FILE: Algorithms/Searching/Binary-Search/Koko_Eating_Bananas/KEB.java ================================================ //Code contributed by Aditya Prakash(@PrakashAditya) import java.io.*; import java.util.*; public class KEB { public static boolean check(int p[],int h,int K) //check if bananas can be eaten in 'h' hrs with speed K { int t=0; for(int i=0;i #include #include using namespace std; int computeMinHours(vector &piles, int speed) { int n = piles.size(); int res = 0; int i = 0; for (i = 0; i < n; i++) res += ceil((float)piles[i] / speed); return res; } int computeMax(vector &piles) { int n = piles.size(); int maxval = INT_MIN; for (int i = 0; i < n; i++) maxval = max(maxval, piles[i]); return maxval; } int minEatingSpeed(vector &piles, int H) { int n = piles.size(); if (n == 1) { double b = (double)piles[0]; int temp = ceil(b / H); return temp; } int lo = 1; int hi = computeMax(piles); int mid; int intval; while (lo < hi) { mid = lo + (hi - lo) / 2; intval = computeMinHours(piles, mid); if (intval <= H) { hi = mid; } else { lo = mid + 1; } } return lo; } int main() { vector piles; int H; cout << "Enter contents of each pile (enter any negative number to stop)\n"; while (true) { int x; cout << "Enter content of pile: "; cin >> x; if (x < 0) break; piles.push_back(x); } cout << "Enter number of hours for guards to return \n"; cin >> H; int res = minEatingSpeed(piles, H); cout << "The minimum eating speed should be " << res << " bananas per hour"; return 0; } ================================================ FILE: Algorithms/Searching/Binary-Search/Koko_Eating_Bananas/Koko_Eating_Bananas.py ================================================ # -*- coding: utf-8 -*- """ Created on Wed Oct 14 23:34:35 2020 @author: Abhinav Tiwari Solution to question as per QUESTION.md's Koko eating bananas finds eating rate K bananas/hr So, that she can finish the pile before the guards arrive. """ import math def min_rate(pile,hrs): res = 0 for i in range(len(pile)): res += math.ceil(pile[i]/hrs) return res def banana_per_hour(pile,hrs): if len(pile)==1: return math.ceil(pile[0]/hrs) lo = 1 hi = max(pile) value = -986765 while(lo0): bananas.append(n) n = int(input()) H = int(input("Enter hours till the guards arrive: ")) K = banana_per_hour(bananas, H) print("For her to eat all the bananas till the guards arrive, she must eat @ ",K,"bananas per hour") main() ================================================ FILE: Algorithms/Searching/Binary-Search/Koko_Eating_Bananas/QUESTION.md ================================================ ### Koko Eating Bananas Koko loves to eat bananas. There are N piles of bananas, the i-th pile has piles[i] bananas. The guards have gone and will come back in H hours. Koko can decide her bananas-per-hour eating speed of K. Each hour, she chooses some pile of bananas, and eats K bananas from that pile. If the pile has less than K bananas, she eats all of them instead, and won't eat any more bananas during this hour. Koko likes to eat slowly, but still wants to finish eating all the bananas before the guards come back. Return the minimum integer K such that she can eat all the bananas within H hours. ================================================ FILE: Algorithms/Searching/Binary-Search/README.md ================================================ ## This folder is empty. ================================================ FILE: Algorithms/Searching/Binary-Search/Rotated-Sorted-Array-Search.cs ================================================ // C# program to find a pair with a given // sum in a sorted and rotated array // Written By - Ayush Sharma (belphegor-s) using System; class PairInSortedRotated { // This function returns true if arr[0..n-1] // has a pair with sum equals to x. static bool pairInSortedRotated(int []arr, int n, int x) { // Find the pivot element int i; for (i = 0; i < n - 1; i++) if (arr[i] > arr[i + 1]) break; // l is now index of smallest element int l = (i + 1) % n; // r is now index of largest element int r = i; // Keep moving either l or r till they meet while (l != r) { // If we find a pair with sum x, we // return true if (arr[l] + arr[r] == x) return true; // If current pair sum is less, // move to the higher sum if (arr[l] + arr[r] < x) l = (l + 1) % n; // Move to the lower sum side else r = (n + r - 1) % n; } return false; } // Driver Code public static void Main () { int []arr = {11, 15, 6, 8, 9, 10}; int sum = 16; int n = arr.Length; if (pairInSortedRotated(arr, n, sum)) Console.WriteLine("Array has two elements" + " with sum 16"); else Console.WriteLine("Array doesn't have two" + " elements with sum 16 "); } } ================================================ FILE: Algorithms/Searching/Binary-Search/Rotated-Sorted-Array-Search.js ================================================ function rotatedSearch(arr, target) { let left = 0 ,right = arr.length-1; // First part : Find the pivot that is point from array is rotated // For example pivot(index) in 5 6 7 1 2 is 2 while(left < right){ let mid = left + Math.floor((right-left)/2) ; if(arr[right] < arr[mid]){ left = mid+1; }else{ right = mid; } } let pivot = left; // reassign left and right for next binary search left = 0 ; right = arr.length-1; // select the part of array where the target lie. // we have two sorted part of array divided by pivot if(target <= arr[right] && arr[pivot]<=target ){ left = pivot; }else{ right = pivot; } // binary search on the part containing target while(left<=right){ let mid = left + Math.floor((right-left)/2); if(arr[mid] == target){ return mid; } if(arr[mid] arr[mid + 1]: return mid if mid > low and arr[mid] < arr[mid - 1]: return (mid-1) if arr[low] >= arr[mid]: return findPivot(arr, low, mid-1) return findPivot(arr, mid + 1, high) def binarySearch(arr, low, high, key): if high < low: return -1 # low + (high - low)/2; mid = int((low + high)/2) if key == arr[mid]: return mid if key > arr[mid]: return binarySearch(arr, (mid + 1), high, key); return binarySearch(arr, low, (mid -1), key); arr1 = [] print("Please Enter number of elements in array") n = int(input()) for i in range(n): demo = int(input()) arr1.append(demo) print("Please enter the element in array") key = int(input()) if key not in arr1: print("Element not in array") print("Index of the element is : ", pivotedBinarySearch(arr1, n, key)) ================================================ FILE: Algorithms/Searching/Binary-Search/binarySearch.c ================================================ #include int binarySearch(int arr[], int l, int r, int x) { if (r >= l) { int mid = l + (r - l) / 2; // If the element is present at the middle // itself if (arr[mid] == x) return mid; // If element is smaller than mid, then // it can only be present in left subarray if (arr[mid] > x) return binarySearch(arr, l, mid - 1, x); // Else the element can only be present // in right subarray return binarySearch(arr, mid + 1, r, x); } // We reach here when element is not // present in array return -1; } int main(void) { int arr[] = { 2, 3, 4, 10, 40 }; int n = sizeof(arr) / sizeof(arr[0]); int x = 10; int result = binarySearch(arr, 0, n - 1, x); (result == -1) ? printf("Element is not present in array") : printf("Element is present at index %d", result); return 0; } ================================================ FILE: Algorithms/Searching/Binary-Search/binarySearch.cpp ================================================ #include using namespace std; int main() { int count, i, arr[30], num, first, last, middle; cout<<"Enter Number of Elements:"; //Count for number of elements cin>>count; for (i=0; i>arr[i]; } cout<<"Enter the number you want to search:"; //Query Input cin>>num; first = 0; last = count-1; middle = (first+last)/2; while (first <= last) { if(arr[middle] < num) { first = middle + 1; } else if(arr[middle] == num) { cout< last) { cout< let recursiveFunction = function(arr, x, start, end) { // Base Condition if (start > end) return false; // Find the middle index let mid = Math.floor((start + end) / 2); // Compare mid with given key x if (arr[mid] === x) return true; // If element at mid is greater than x, // search in the left half of mid if (arr[mid] > x) return recursiveFunction(arr, x, start, mid - 1); else // If element at mid is smaller than x, // search in the right half of mid return recursiveFunction(arr, x, mid + 1, end); } // Driver code let arr = [1, 3, 5, 7, 8, 9]; let x = 5; if (recursiveFunction(arr, x, 0, arr.length - 1)) document.write("Element found!
"); else document.write("Element not found!
"); x = 6; if (recursiveFunction(arr, x, 0, arr.length - 1)) document.write("Element found!
"); else document.write("Element not found!
"); < /script> ================================================ FILE: Algorithms/Searching/Binary-Search/binarySearch.kt ================================================ fun binarySearch(arr: List, lo: Int, hi: Int, target: Int): Int{ //base case: if the left index crosses right index //it means target is not present if(lo > hi)return -1 //calculate the middle index of the current range [lo, hi] val mid = lo + (hi - lo)/2 //return the index if the target is present at that index if(arr[mid] == target) return mid //do a recursive binary search on the basis of the whether the found element is //lesser or greater than the target return if(arr[mid] < target) binarySearch(arr, mid+1, hi, target) else binarySearch(arr, lo, mid - 1, target) } fun main(){ //read the input array val arr = readLine()!!.split(' ').map{it.toInt()} //read the target to be found val target = readLine()!!.toInt() //do a binary search in the range of index [0, arr.size - 1] val index = binarySearch(arr, 0, arr.size - 1, target) //if the target if not in the array if(index == -1) println("$target not found") //if target is present in the array prints its index //note: if there are multiple occurences of the target, the index could be any of //those else println("$target found at index $index") } ================================================ FILE: Algorithms/Searching/Binary-Search/binarySearch.scala ================================================ object GFG{ // Creating Binary Search function def RecursiveBinarySearch(arr: Array[Int], Element_to_Search: Int) (low: Int = 0, high: Int = arr.length - 1): Int = { if (low > high) return -1 var middle = low + (high - low) / 2 // If element found if (arr(middle) == Element_to_Search) return middle else if (arr(middle) > Element_to_Search) return RecursiveBinarySearch(arr, Element_to_Search)(low, middle - 1) // Searching in the right half else return RecursiveBinarySearch(arr, Element_to_Search)(middle + 1, high) } // Creating main function def main(args: Array[String]){ var index = RecursiveBinarySearch(Array(1, 2, 3, 4, 55, 65, 75), 4)(0, 6); // If value not found if(index == -1) print("Cannot be Found") // Else print the index where the value is found else print("Found element at Index = " + index) } } ================================================ FILE: Algorithms/Searching/Binary-Search/binary_search.cpp ================================================ // binary search #include using namespace std ; int binarySearch(int arr[], int l,int r,int x) { if (r >= l) { int mid = l + (r - l) / 2; // If the element is present at the middle // itself if (arr[mid] == x) return mid; // If element is smaller than mid, then // it can only be present in left subarray if (arr[mid] > x) return binarySearch(arr, l, mid - 1, x); // Else the element can only be present // in right subarray return binarySearch(arr, mid + 1, r, x); } // We reach here when element is not // present in array return -1; } int main() { int n ,i ,l , h , key ; cin >> n ; int arr[n] ; for(i=0;i> arr[i] ; } l=0 ; h=n-1 ; cout << "enter the key you want to search : "; cin >> key ; // while(h>=l) // { // mid=(l+h)/2 ; // if(arr[mid]==key) // { // cout << "found\n" ; // return 0 ; // } // else if (key>mid) // { // l=mid+1 ; // } // else if (key= l) { int midvalue = l + (l - r) / 2; if (array[midvalue] == y) // mid value to start in both directions return midvalue; if (array[midvalue] > x) return binarySearch(arr, r, midvalue - 1, y); return binarySearch(array, midvalue + 1, l, y); } return -1; } public static void main(String args[]) { BinarySearch ob = new BinarySearch(); int array[] = { 17, 34, 54, 65, 87, 99, 129, 135 }; int n = array.length; int y = 37; int index = ob.binarySearch(array, 0, n - 1, y); //check if selection is present if (index == -1) System.out.println("Selection not found"); else System.out.println("Selection found at index " + index); } } ================================================ FILE: Algorithms/Searching/Binary-Search/binarysearch.java ================================================ class Solution { public int BinarySearch(int[] nums, int target) { int left = 0; int right = nums.length - 1; while (left <= right) { int pivot = left + (right - left) / 2; if (nums[pivot] == target) return pivot; if (target < nums[pivot]) right = pivot - 1; else left = pivot + 1; } return -1; } } ================================================ FILE: Algorithms/Searching/Binary-Search/binarysearch.js ================================================ < script > let recursiveFunction = function(arr, x, start, end) { // Base Condition if (start > end) return false; // Find the middle index let mid = Math.floor((start + end) / 2); // Compare mid with given key x if (arr[mid] === x) return true; // If element at mid is greater than x, // search in the left half of mid if (arr[mid] > x) return recursiveFunction(arr, x, start, mid - 1); else // If element at mid is smaller than x, // search in the right half of mid return recursiveFunction(arr, x, mid + 1, end); } // Driver code let arr = [1, 3, 5, 7, 8, 9]; let x = 5; if (recursiveFunction(arr, x, 0, arr.length - 1)) document.write("Element found!
"); else document.write("Element not found!
"); x = 6; if (recursiveFunction(arr, x, 0, arr.length - 1)) document.write("Element found!
"); else document.write("Element not found!
"); < /script> ================================================ FILE: Algorithms/Searching/Binary-Search/binarysearch.php ================================================ = l: mid = l + (r - l) // 2 # If element is present at the middle itself if arr[mid] == x: return mid # If element is smaller than mid, then it # can only be present in left subarray elif arr[mid] > x: return binarySearch(arr, l, mid-1, x) # Else the element can only be present # in right subarray else: return binarySearch(arr, mid + 1, r, x) else: # Element is not present in the array return -1 ================================================ FILE: Algorithms/Searching/Binary-Search/binarysearch.sh ================================================ #!/bin/bash echo “Enter the limit:” read n echo “Enter the numbers” for(( i=0 ;ibool: # Dimensions of the matrix row=len(matrix) col=len(matrix[0]) if len(matrix)>0 else 0 # In case of empty matrix if col==0: return False # Row limits to iterate the row row_low,row_high=0,row # the row and column position of the target, if found. target_row,target_col=-1,-1 while row_low=matrix[mid][0] and target<=matrix[mid][col-1]: target_row=mid break # if the target might be after the mid row elif target>matrix[mid][col-1]: row_low=mid+1 else: row_high=mid-1 # if no row contains the target element if target_row==-1: return False col_low,col_high=0,col while col_lowmatrix[target_row][mid]: col_low=mid+1 else: col_high=mid-1 # If the element was not found in the selected row. return False r,c=map(int,input().split()) matrix=[[]]*r for i in range(r): for j in range(c): matrix[i].append(int(input())) target=int(input()) print("Target Found" if searchMatrix(matrix,target) else "Target Not Found") ================================================ FILE: Algorithms/Searching/Binary-Search/search_in_2d_matrix.cpp ================================================ #include using namespace std; bool searchMatrix(vector>& mat, int target) { int n=mat.size(); int m=mat[0].size(); int l=0,h=n; int mid; while(l=mat[mid][0] && target <=mat[mid][m-1]) break; else if(target>=mat[mid][m-1]) l=mid+1; else h=mid; } l=0,h=m; while(l>n>>m>>target; vector>mat(n,vector(m)); for(int i=0;i>mat[i][j]; if(searchMatrix(mat,target)) cout<<"ELEMENT FOUND"; else cout<<"ELEMENT NOT FOUND"; return 0; } ================================================ FILE: Algorithms/Searching/Exponential-Search/exponential_search.cpp ================================================ #include using namespace std; //Templates start here #define pb push_back #define mp make_pair #define F first #define S second #define ll long long #define fo(i, j, k, in) for (int i = j; i < k; i += in) #define refo(i, j, k, in) for (int i = j; i >= k; i -= in) #define rep(i, j) fo(i, 0, j, 1) #define rerep(i, j) fo(i, j, 0, 1) #define all(cont) cont.begin(), cont.end() #define reall(cont) cont.end(), cont.begin() #define foreach(it, l) for (auto it = l.begin() l it != l.end(); it++) #define in(A, B, C) assert(B <= A && A <= C) #define MOD (int)1e9 #define MOD7 1000000007 #define PI 3.1415926535897932384626433832795 typedef pair PII; typedef pair PLL; typedef vector VI; typedef vector VL; typedef vector VS; typedef vector VII; typedef vector VLL; typedef vector VVI; typedef vector VVL; typedef map MPII; typedef map MPLL; typedef set SETI; typedef multiset MSETI; //Templates end here //I'm not using my templates for better understanding, else above templates can be easily used, you can alse benefit yourself just copy above templates and use them int binSearch(int arr[], int, int, int); int expoSearch(int arr[], int n, int x) { if (arr[0] == x) return 0; int i = 1; while (i < n && arr[i] <= x) i = i*2; return binSearch(arr, i/2, min(i, n), x); } int binSearch(int arr[], int l, int r, int x) { if (r >= l) { int mid = l + (r - l)/2; if (arr[mid] == x) return mid; if (arr[mid] > x) return binSearch(arr, l, mid-1, x); return binSearch(arr, mid+1, r, x); } return -1; } int main(void) { int n,x; cout<<"\nEnter the size of input array : "; cin>>n; int arr[n]; cout<<"\nEnter the array elements : "; for(int i=0 ; i>arr[i]; cout<<"\nEnter the number to be searched : "; cin>>x; int result = expoSearch(arr, n, x); (result == -1)? printf("\nElement is not present in array") : printf("\nElement is present at index %d", result); return 0; } ================================================ FILE: Algorithms/Searching/Exponential-Search/exponential_search.php ================================================ = $l) { $mid = $l + ($r - $l)/2; if ($arr[$mid] == $x) return $mid; if ($arr[$mid] > $x) return binSearch($arr, $l, $mid - 1, $x); return binSearch($arr, $mid + 1, $r, $x); } return -1; } $arr = array(2, 3, 4, 10, 40); $n = count($arr); $x = 10; $result = expoSearch($arr, $n, $x); if($result == -1) echo "Element is not present in array"; else echo "Element is present at index ", $result; ?> ================================================ FILE: Algorithms/Searching/Exponential-Search/exponential_search.py ================================================ def bin_search(arr, x, low=0, high=None): if high is None: high = len(arr) - 1 if high < low: return -1 mid = (high + low) // 2 if arr[mid] == x: return mid elif arr[mid] < x: return bin_search(arr, x, mid+1, high) elif arr[mid] > x: return bin_search(arr, x, low, mid) return -1 def exp_search(arr, x): i = 1 while True: if 2**i >= len(arr): return bin_search(arr, x, 2**(i-1)-1) elif arr[2**i] == x: return 2**i elif arr[2**i] > x: return bin_search(arr, x, 2**(i-1), 2**i - 1) i += 1 user_input = input("Enter numbers separated by comma:\n").strip() sequence = [int(item.strip()) for item in user_input.split(",")] target = int(input("Enter a single number to be found in the list:\n").strip()) result = exp_search(sequence, target) if result == -1: print(f"{target} was not found in list.") else: print(f"{target} was found in position {result} of list.") ================================================ FILE: Algorithms/Searching/Fibonacci-Search/Fibonacci_Search.cpp ================================================ // Cpp program for Fibonacci Search #include using namespace std ; // Utility function to find minimum of two elements int min(int x, int y) { return (x<=y)? x : y; } /* Returns index of x if present, else returns -1 */ int fibMonaccianSearch(int arr[], int x, int n) { /* Initialize fibonacci numbers */ int fibMMm2 = 0; // (m-2)'th Fibonacci No. int fibMMm1 = 1; // (m-1)'th Fibonacci No. int fibM = fibMMm2 + fibMMm1; // m'th Fibonacci /* fibM is going to store the smallest Fibonacci Number greater than or equal to n */ while (fibM < n) { fibMMm2 = fibMMm1; fibMMm1 = fibM; fibM = fibMMm2 + fibMMm1; } // Marks the eliminated range from front int offset = -1; /* while there are elements to be inspected. Note that we compare arr[fibMm2] with x. When fibM becomes 1, fibMm2 becomes 0 */ while (fibM > 1) { // Check if fibMm2 is a valid location int i = min(offset+fibMMm2, n-1); /* If x is greater than the value at index fibMm2, cut the subarray array from offset to i */ if (arr[i] < x) { fibM = fibMMm1; fibMMm1 = fibMMm2; fibMMm2 = fibM - fibMMm1; offset = i; } /* If x is greater than the value at index fibMm2, cut the subarray after i+1 */ else if (arr[i] > x) { fibM = fibMMm2; fibMMm1 = fibMMm1 - fibMMm2; fibMMm2 = fibM - fibMMm1; } /* element found. return index */ else return i; } /* comparing the last element with x */ if(fibMMm1 && arr[offset+1]==x) return offset+1; /*element not found. return -1 */ return -1; } /* driver function */ int main(void) { int arr[] = {10, 22, 35, 40, 45, 50, 80, 82, 85, 90, 100}; int n = sizeof(arr)/sizeof(arr[0]); int x = 85; cout<<"Found at index: "< 1) { // Check if fibMm2 is a valid location int i = min(offset+fibMMm2, n-1); /* If x is greater than the value at index fibMm2, cut the subarray array from offset to i */ if (arr[i] < x) { fibM = fibMMm1; fibMMm1 = fibMMm2; fibMMm2 = fibM - fibMMm1; offset = i; } /* If x is less than the value at index fibMm2, cut the subarray after i+1 */ else if (arr[i] > x) { fibM = fibMMm2; fibMMm1 = fibMMm1 - fibMMm2; fibMMm2 = fibM - fibMMm1; } /* element found. return index */ else return i; } /* comparing the last element with x */ if(fibMMm1 == 1 && arr[offset+1] == x) return offset+1; /*element not found. return -1 */ return -1; } // driver code public static void main(String[] args) { int arr[] = {10, 22, 35, 40, 45, 50, 80, 82, 85, 90, 100}; int n = 11; int x = 85; System.out.print ("Found at index: "+ fibMonaccianSearch(arr, x, n)); } } ================================================ FILE: Algorithms/Searching/Fibonacci-Search/Fibonacci_search.php ================================================ 1) { // Check if fibMm2 is a valid location $i = min($offset+$fibMMm2, $n-1); /* If x is greater than the value at index fibMm2, cut the subarray array from offset to i */ if ($arr[$i] < $x) { $fibM = $fibMMm1; $fibMMm1 = $fibMMm2; $fibMMm2 = $fibM - $fibMMm1; $offset = $i; } /* If x is less than the value at index fibMm2, cut the subarray after i+1 */ else if ($arr[$i] > $x) { $fibM = $fibMMm2; $fibMMm1 = $fibMMm1 - $fibMMm2; $fibMMm2 = $fibM - $fibMMm1; } /* element found. return index */ else return $i; } /* comparing the last element with x */ if($fibMMm1 && $arr[$offset + 1] == $x)return $offset+1; /*element not found. return -1 */ return -1; } $arr = array(10, 22, 35, 40, 45, 50, 80, 82,85, 90, 100); $n = count($arr); $x = 85; printf("Found at index: ".fibMonaccianSearch($arr, $x, $n)); ?> ================================================ FILE: Algorithms/Searching/Fibonacci-Search/Fibonacci_search_in_C.c ================================================ // C program for Fibonacci Search #include // Utility function to find minimum of two elements int min(int x, int y) { return (x<=y)? x : y; } /* Returns index of x if present, else returns -1 */ int fibMonaccianSearch(int arr[], int x, int n) { /* Initialize fibonacci numbers */ int fibMMm2 = 0; // (m-2)'th Fibonacci No. int fibMMm1 = 1; // (m-1)'th Fibonacci No. int fibM = fibMMm2 + fibMMm1; // m'th Fibonacci /* fibM is going to store the smallest Fibonacci Number greater than or equal to n */ while (fibM < n) { fibMMm2 = fibMMm1; fibMMm1 = fibM; fibM = fibMMm2 + fibMMm1; } // Marks the eliminated range from front int offset = -1; /* while there are elements to be inspected. Note that we compare arr[fibMm2] with x. When fibM becomes 1, fibMm2 becomes 0 */ while (fibM > 1) { // Check if fibMm2 is a valid location int i = min(offset+fibMMm2, n-1); /* If x is greater than the value at index fibMm2, cut the subarray array from offset to i */ if (arr[i] < x) { fibM = fibMMm1; fibMMm1 = fibMMm2; fibMMm2 = fibM - fibMMm1; offset = i; } /* If x is greater than the value at index fibMm2, cut the subarray after i+1 */ else if (arr[i] > x) { fibM = fibMMm2; fibMMm1 = fibMMm1 - fibMMm2; fibMMm2 = fibM - fibMMm1; } /* element found. return index */ else return i; } /* comparing the last element with x */ if(fibMMm1 && arr[offset+1]==x)return offset+1; /*element not found. return -1 */ return -1; } /* driver function */ int main(void) { int arr[] = {10, 22, 35, 40, 45, 50, 80, 82, 85, 90, 100}; int n = sizeof(arr)/sizeof(arr[0]); int x = 85; printf("Found at index: %d", fibMonaccianSearch(arr, x, n)); return 0; } ================================================ FILE: Algorithms/Searching/Fibonacci-Search/fibonacciSearch.py ================================================ arr = [10, 22, 30, 44, 56, 58, 60, 72, 105, 110, 160] x = 60 def FibonacciGenerator(n): if n < 1: return 0 elif n == 1: return 1 else: return FibonacciGenerator(n - 1) + FibonacciGenerator(n - 2) def FibonacciSearch(arr, x): m = 0 while FibonacciGenerator(m) < len(arr): m = m + 1 offset = -1 while (FibonacciGenerator(m) > 1): i = min(offset + FibonacciGenerator(m - 2), len(arr) - 1) print('Current Element : ', arr[i]) if (x > arr[i]): m = m - 1 offset = i elif (x < arr[i]): m = m - 2 else: return i if(FibonacciGenerator(m - 1) and arr[offset + 1] == x): return offset + 1 return -1 print('Number found at index : ', FibonacciSearch(arr, x)) ================================================ FILE: Algorithms/Searching/Fibonacci-Search/fibonacci_search.c ================================================ // C program for Fibonacci Search #include // Utility function to find minimum of two elements int min(int x, int y) { return (x<=y)? x : y; } /* Returns index of x if present, else returns -1 */ int fibMonaccianSearch(int arr[], int x, int n) { /* Initialize fibonacci numbers */ int fibMMm2 = 0; // (m-2)'th Fibonacci No. int fibMMm1 = 1; // (m-1)'th Fibonacci No. int fibM = fibMMm2 + fibMMm1; // m'th Fibonacci /* fibM is going to store the smallest Fibonacci Number greater than or equal to n */ while (fibM < n) { fibMMm2 = fibMMm1; fibMMm1 = fibM; fibM = fibMMm2 + fibMMm1; } // Marks the eliminated range from front int offset = -1; /* while there are elements to be inspected. Note that we compare arr[fibMm2] with x. When fibM becomes 1, fibMm2 becomes 0 */ while (fibM > 1) { // Check if fibMm2 is a valid location int i = min(offset+fibMMm2, n-1); /* If x is greater than the value at index fibMm2, cut the subarray array from offset to i */ if (arr[i] < x) { fibM = fibMMm1; fibMMm1 = fibMMm2; fibMMm2 = fibM - fibMMm1; offset = i; } /* If x is greater than the value at index fibMm2, cut the subarray after i+1 */ else if (arr[i] > x) { fibM = fibMMm2; fibMMm1 = fibMMm1 - fibMMm2; fibMMm2 = fibM - fibMMm1; } /* element found. return index */ else return i; } /* comparing the last element with x */ if(fibMMm1 && arr[offset+1]==x)return offset+1; /*element not found. return -1 */ return -1; } /* driver function */ int main(void) { int arr[] = {10, 22, 35, 40, 45, 50, 80, 82, 85, 90, 100}; int n = sizeof(arr)/sizeof(arr[0]); int x = 85; printf("Found at index: %d", fibMonaccianSearch(arr, x, n)); return 0; } ================================================ FILE: Algorithms/Searching/Fibonacci-Search/fibonacci_search.js ================================================ //JavaScript program for Fibonacci Search /* * Find an element in the given sorted array with the help of Fibonacci series in O(log N) time complexity. * Let the length of given array be n [0...n-1] and the element to be searched be x. * Find the smallest Fibonacci number greater than or equal to n. * source: https://iq.opengenus.org/fibonacci-search/ */ //length/size: n , element to search: x function fibonacciSearch(n, arr, x){ //Let this number be fb(M) [m’th Fibonacci number]. //Let the two Fibonacci numbers preceding it be fb(M-1) [(m-1)’th Fibonacci number] let fbMm2 = 0; let fbMm1 = 1; let fbM = fbMm1 + fbMm2; let offset = -1; //Find the smallest Fibonacci number greater than or equal to n while(fbM < n){ fbMm2 = fbMm1; fbMm1 = fbM; fbM = fbMm1 + fbMm2; } //While the array has elements to be checked: //-> Compare x with the last element of the range covered by fb(M-2) //-> If x matches, return index value //-> Else if x is less than the element, move the third Fibonacci variable two Fibonacci down, let i = 0; while(fbM > 1){ i = Math.min(offset + fbMm2, n - 1); if(arr[i] < x){ fbM = fbMm1; fbMm1 = fbMm2; fbMm2 = fbM - fbMm1; offset = i; } else if(arr[i] > x){ fbM = fbMm2; fbMm1 = fbMm1 - fbMm2; fbMm2 = fbM - fbMm1; } else return i; } //comparing the last element if(fbMm1 && arr[offset + 1] == x) return offset + 1; return -1; } let arr = [10, 15, 30, 60, 90, 100, 120]; let n = 7; let x = 92; console.log(fibonacciSearch(n, arr, x)); ================================================ FILE: Algorithms/Searching/Interpolation-Search/IS.cpp ================================================ #include using namespace std; int interpolationSearch(int array[], int start, int end, int key) { int dist, valRange, indexRange, estimate; float fraction; while(start <= end && key >= array[start] && key <= array[end]) { dist = key - array[start]; valRange = array[end] - array[start]; //range of value fraction = dist / valRange; indexRange = end - start; estimate = start + (fraction * indexRange); //estimated position of the key if(array[estimate] == key) return estimate; if(array[estimate] < key) start = estimate +1; else end = estimate - 1; } return -1; } int main() { int n, searchKey, loc; cout << "Enter number of items: "; cin >> n; int arr[n]; //create an array of size n cout << "Enter items: " << endl; for(int i = 0; i< n; i++) { cin >> arr[i]; } cout << "Enter search key to search in the list: "; cin >> searchKey; if((loc = interpolationSearch(arr, 0, n-1, searchKey)) >= 0) cout << "Item found at location: " << loc << endl; else cout << "Item is not found in the list." << endl; } ================================================ FILE: Algorithms/Searching/Interpolation-Search/IS.py ================================================ def intpolsearch(values,x ): idx0 = 0 idxn = (len(values) - 1) while idx0 <= idxn and x >= values[idx0] and x <= values[idxn]: # Find the mid point mid = idx0 +\ int(((float(idxn - idx0)/( values[idxn] - values[idx0])) * ( x - values[idx0]))) # Compare the value at mid point with search value if values[mid] == x: return "Found "+str(x)+" at index "+str(mid) if values[mid] < x: idx0 = mid + 1 return "Searched element not in the list" l = [2, 6, 11, 19, 27, 31, 45, 121] print(intpolsearch(l, 2)) ================================================ FILE: Algorithms/Searching/Jump-Search/JumpSearch.java ================================================ // Java program to implement Jump Search. public class JumpSearch { public static int jumpSearch(int[] arr, int x) { int n = arr.length; // Finding block size to be jumped int step = (int)Math.floor(Math.sqrt(n)); // Finding the block where element is // present (if it is present) int prev = 0; while (arr[Math.min(step, n)-1] < x) { prev = step; step += (int)Math.floor(Math.sqrt(n)); if (prev >= n) return -1; } // Doing a linear search for x in block // beginning with prev. while (arr[prev] < x) { prev++; // If we reached next block or end of // array, element is not present. if (prev == Math.min(step, n)) return -1; } // If element is found if (arr[prev] == x) return prev; return -1; } // Driver program public static void main(String [ ] args) { int arr[] = { 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610}; int x = 55; // Find the index of 'x' using Jump Search int index = jumpSearch(arr, x); // Print the index where 'x' is located System.out.println("\nNumber " + x + " is at index " + index); } } ================================================ FILE: Algorithms/Searching/Jump-Search/Jump_Search.cpp ================================================ // C++ program to implement Jump Search #include using namespace std; int jumpSearch(int arr[], int x, int n) { // Finding block size to be jumped int step = sqrt(n); // Finding the block where element is // present (if it is present) int prev = 0; while (arr[min(step, n)-1] < x) { prev = step; step += sqrt(n); if (prev >= n) return -1; } // Doing a linear search for x in block // beginning with prev. while (arr[prev] < x) { prev++; // If we reached next block or end of // array, element is not present. if (prev == min(step, n)) return -1; } // If element is found if (arr[prev] == x) return prev; return -1; } // Driver program to test function int main() { int arr[] = { 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610 }; int x = 55; int n = sizeof(arr) / sizeof(arr[0]); // Find the index of 'x' using Jump Search int index = jumpSearch(arr, x, n); // Print the index where 'x' is located cout << "\nNumber " << x << " is at index " << index; return 0; } // Contributed by nuclode ================================================ FILE: Algorithms/Searching/Jump-Search/jumpSearch.cs ================================================ //Jump Search implementation in C#. using System; class MainClass { public static void Main (string[] args) { double[] arr = {0, 1, 2, 4, 9, 16, 25, 36, 64, 81, 100, 121, 144, 189, 400, 625}; double n = arr.Length; double x = 144; double step = Math.Sqrt(n); step = Math.Truncate(step); double j = n-step-1; for (double i=0; ix) { j = i - step; break; } } double ub = j + step + 1; for ( ; j x){ break; } } i = i - step ub:= i + step for ; i < ub; i++{ if(arr[int(i)]==x){ return i; } } return -1; } ================================================ FILE: Algorithms/Searching/Jump-Search/jumpSearch.js ================================================ //Jump Search implementation in JavaScript. var arr = [0, 1, 2, 4, 9, 16, 25, 36, 64, 81, 100, 121, 144, 189, 400, 625]; var n = arr.length; var x = 144; var step = Math.floor((Math.sqrt(n))); var j = n-step-1; for (var i = 0; ix) { j = i - step; break; } } var ub = j + step; for ( ; jx) { j = i - step; break; } } let ub = j + step; for ( ; j= n: return -1 while arr[int(prev)] < x: prev += 1 if prev == min(step, n): return -1 if arr[int(prev)] == x: return prev return -1 arr = [ 0,0, 1, 1, 2, 4, 5, 8, 17, 21,29, 34, 70, 89, 200, 377] x = 200 n = len(arr) index = jumpSearch(arr, x, n) if(index == -1): print("Number" , x , "is not present in array") else: print("Number" , x, "is at index" ,"%.0f"%index) ================================================ FILE: Algorithms/Searching/Linear-Search/LINEAR_SEARH.cpp ================================================ #include using namespace std; int main() { cout<<"Enter The Size Of Array: "; int size; cin>>size; int array[size], key,i; // Taking Input In Array for(int j=0;j>array[j]; } //Your Entered Array Is for(int a=0;a>key; for(i=0;i using namespace std; int main(){ int n; cin>>n; //size of the array int element; cin>>element; //element that have to searched int arr[n]; for(int i=0;i>arr[i]; //taking array input } for(int i=0;i void main() { int num; int i, keynum, found = 0; printf("Enter the number of elements "); scanf("%d", &num); int array[num]; printf("Enter the elements one by one \n"); for (i = 0; i < num; i++) { scanf("%d", &array[i]); } printf("Enter the element to be searched "); scanf("%d", &keynum); /* Linear search begins */ for (i = 0; i < num ; i++) { if (keynum == array[i] ) { found = 1; break; } } if (found == 1) printf("Element is present in the array at position %d",i+1); else printf("Element is not present in the array\n"); } ================================================ FILE: Algorithms/Searching/Linear-Search/README.md ================================================ ## This folder is empty. ================================================ FILE: Algorithms/Searching/Linear-Search/linear_search.java ================================================ class Search { public static int Linear (int array[], int num) { int length = array.length; //to calculate array length for(int i = 0; i < length; i++) { if(array[i] == num) return i; } return -1; } public static void main(String args[]) { int array[] = { 5, 13, 29, 38, 44, 59, 63, 69, 84, 90, 208 }; int num = 69; int index = search(array, num); //looking for the selection in array if(result == -1) System.out.print("Could not find the selection in the array."); else System.out.print("Selection found at index: " + index); } } ================================================ FILE: Algorithms/Searching/Linear-Search/linear_search.sh ================================================ #!/bin/bash echo 'Enter the array elements:' read -a arr echo 'Enter the element to search for: ' read s for i in ${arr[@]}; do if [ $i -eq $s ]; then echo 'Element found!' exit 0 fi done echo 'Element not found' ================================================ FILE: Algorithms/Searching/README.md ================================================ # This folder is empty. ================================================ FILE: Algorithms/Searching/Sublist-Search/Sublist_Search.php ================================================ key = $key; $node->next = null; return $node; } /** * Search sublist * * @param Node $first First node * @param Node $second Second node * @return bool */ function subListSearch(Node $first, Node $second): bool { $fNode = $first; $sNode = $second; if ($first == null && $second == null) { return true; } if ($first == null || ($first != null && $second == null)) { return false; } while ($second != null) { $sNode = $second; while ($fNode != null) { if ($sNode == null) { return false; } elseif ($fNode->key == $sNode->key) { $fNode = $fNode->next; $sNode = $sNode->next; } else { break; } } if ($fNode == null) { return true; } $fNode = $first; $second = $second->next; } return false; } /** * Print a specific node * * @param Node $node */ function printList(Node $node) { while($node != null) { echo $node->key . ' '; $node = $node->next; } echo "\n"; } /** * Test sublist search */ function testSubListSearch() { $first = createNewNode(1); $first->next = createNewNode(2); $first->next->next = createNewNode(3); $first->next->next->next = createNewNode(4); $second = createNewNode(1); $second->next = createNewNode(2); $second->next->next = createNewNode(1); $second->next->next->next = createNewNode(2); $second->next->next->next->next = createNewNode(3); $second->next->next->next->next->next = createNewNode(4); echo "First list:\n"; printList($first); echo "Second list: \n"; printList($second); echo "\n"; if(subListSearch($first, $second)) { echo 'List Found'; } else { echo 'List Not Found'; } echo "\n"; } // Test: testSubListSearch(); // Result: // First list: // 1 2 3 4 // Second list: // 1 2 1 2 3 4 // List Found ================================================ FILE: Algorithms/Searching/Sublist-Search/sublist_search.cpp ================================================ #include using namespace std; //Templates start here #define pb push_back #define mp make_pair #define F first #define S second #define ll long long #define fo(i, j, k, in) for (int i = j; i < k; i += in) #define refo(i, j, k, in) for (int i = j; i >= k; i -= in) #define rep(i, j) fo(i, 0, j, 1) #define rerep(i, j) fo(i, j, 0, 1) #define all(cont) cont.begin(), cont.end() #define reall(cont) cont.end(), cont.begin() #define foreach(it, l) for (auto it = l.begin() l it != l.end(); it++) #define in(A, B, C) assert(B <= A && A <= C) #define MOD (int)1e9 #define MOD7 1000000007 #define PI 3.1415926535897932384626433832795 typedef pair PII; typedef pair PLL; typedef vector VI; typedef vector VL; typedef vector VS; typedef vector VII; typedef vector VLL; typedef vector VVI; typedef vector VVL; typedef map MPII; typedef map MPLL; typedef set SETI; typedef multiset MSETI; //Templates end here //I'm not using my templates for better understanding, else above templates can be easily used, you can alse benefit yourself just copy above templates and use them struct Node { int data; Node* next; }; bool findList(Node* first, Node* second) { Node* ptr1 = first, *ptr2 = second; if (first == NULL && second == NULL) return true; if ( first == NULL || (first != NULL && second == NULL)) return false; while (second != NULL) { ptr2 = second; while (ptr1 != NULL) { if (ptr2 == NULL) return false; else if (ptr1->data == ptr2->data) { ptr1 = ptr1->next; ptr2 = ptr2->next; } else break; } if (ptr1 == NULL) return true; ptr1 = first; second = second->next; } return false; } void printList(Node* node) { while (node != NULL) { printf("%d ", node->data); node = node->next; } } Node *newNode(int key) { Node *temp = new Node; temp-> data= key; temp->next = NULL; return temp; } int main() { Node *a = newNode(1); a->next = newNode(2); a->next->next = newNode(3); a->next->next->next = newNode(4); Node *b = newNode(1); b->next = newNode(2); b->next->next = newNode(1); b->next->next->next = newNode(2); b->next->next->next->next = newNode(3); b->next->next->next->next->next = newNode(4); findList(a,b) ? cout << "LIST FOUND" : cout << "LIST NOT FOUND"; return 0; } ================================================ FILE: Algorithms/Searching/Sublist-Search/sublist_search.cs ================================================ /******************************************** * C# program to find a list in second list * * Author - Ayush Sharma (belphegor-s) * * ********************************************/ using System; class GFG { // A Linked List node class Node { public int data; public Node next; }; // Returns true if first list is // present in second list static Boolean findList(Node first, Node second) { Node ptr1 = first, ptr2 = second; // If both linked lists are empty, // return true if (first == null && second == null) return true; // Else If one is empty and // other is not, return false if (first == null || (first != null && second == null)) return false; // Traverse the second list by // picking nodes one by one while (second != null) { // Initialize ptr2 with // current node of second ptr2 = second; // Start matching first list // with second list while (ptr1 != null) { // If second list becomes empty and // first not then return false if (ptr2 == null) return false; // If data part is same, go to next // of both lists else if (ptr1.data == ptr2.data) { ptr1 = ptr1.next; ptr2 = ptr2.next; } // If not equal then break the loop else break; } // Return true if first list gets traversed // completely that means it is matched. if (ptr1 == null) return true; // Initialize ptr1 with first again ptr1 = first; // And go to next node of second list second = second.next; } return false; } /* Function to print nodes in a given linked list */ static void printList(Node node) { while (node != null) { Console.Write("{0} ", node.data); node = node.next; } } // Function to add new node to linked lists static Node newNode(int key) { Node temp = new Node(); temp.data= key; temp.next = null; return temp; } // Driver Code public static void Main(String[] args) { /* Let us create two linked lists to test the above functions. Created lists shall be a: 1->2->3->4 b: 1->2->1->2->3->4*/ Node a = newNode(1); a.next = newNode(2); a.next.next = newNode(3); a.next.next.next = newNode(4); Node b = newNode(1); b.next = newNode(2); b.next.next = newNode(1); b.next.next.next = newNode(2); b.next.next.next.next = newNode(3); b.next.next.next.next.next = newNode(4); if(findList(a, b) == true) Console.Write("LIST FOUND"); else Console.Write("LIST NOT FOUND"); } } ================================================ FILE: Algorithms/Searching/Sublist-Search/sublist_search.java ================================================ import java.util.*; class GFG { static class Node { int data; Node next; }; static boolean findList(Node first, Node second) { Node ptr1 = first, ptr2 = second; if (first == null && second == null) return true; if (first == null || (first != null && second == null)) return false; while (second != null) { ptr2 = second; while (ptr1 != null) { if (ptr2 == null) return false; else if (ptr1.data == ptr2.data) { ptr1 = ptr1.next; ptr2 = ptr2.next; } else break; } if (ptr1 == null) return true; ptr1 = first; second = second.next; } return false; } static void printList(Node node) { while (node != null) { System.out.printf("%d ", node.data); node = node.next; } } static Node newNode(int key) { Node temp = new Node(); temp.data= key; temp.next = null; return temp; } public static void main(String[] args) { Node a = newNode(1); a.next = newNode(2); a.next.next = newNode(3); a.next.next.next = newNode(4); Node b = newNode(1); b.next = newNode(2); b.next.next = newNode(1); b.next.next.next = newNode(2); b.next.next.next.next = newNode(3); b.next.next.next.next.next = newNode(4); if(findList(a, b) == true) System.out.println("LIST FOUND"); else System.out.println("LIST NOT FOUND"); } } ================================================ FILE: Algorithms/Searching/Sublist-Search/sublist_search.js ================================================ class node { constructor(value) { this.value = value; this.next = null; } } var findList = function(first, second) { if(!first && !second) { return true; } if(!first || !second) { return false; } ptr1 = first; ptr2 = second; while(ptr2) { ptr2 = second; while(ptr1) { if(!ptr2) { return false; } else if(ptr1.value === ptr2.value) { ptr1 = ptr1.next; ptr2 = ptr2.next; } else { break; } } if(!ptr1) { return true; } ptr1 = first; second = second.next; } return false; } node_a = new node(1); node_a.next = new node(2); node_a.next.next = new node(3); node_a.next.next.next = new node(4); node_b = new node(1); node_b.next = new node(2); node_b.next.next = new node(1); node_b.next.next.next = new node(2); node_b.next.next.next.next = new node(3); node_b.next.next.next.next.next = new node(4); if(findList(node_a, node_b)) { console.log("List Found"); } else { console.log("List Not Found"); } ================================================ FILE: Algorithms/Searching/Sublist-Search/sublist_search.py ================================================ class Node: def __init__(self, value = 0): self.value = value self.next = None def findList(first, second): if not first and not second: return True if not first or not second: return False ptr1 = first ptr2 = second while ptr2: ptr2 = second while ptr1: if not ptr2: return False elif ptr1.value == ptr2.value: ptr1 = ptr1.next ptr2 = ptr2.next else: break if not ptr1: return True ptr1 = first second = second.next return False node_a = Node(1) node_a.next = Node(2) node_a.next.next = Node(3) node_a.next.next.next = Node(4) node_b = Node(1) node_b.next = Node(2) node_b.next.next = Node(1) node_b.next.next.next = Node(2) node_b.next.next.next.next = Node(3) node_b.next.next.next.next.next = Node(4) if findList(node_a, node_b): print("LIST FOUND") else: print("LIST NOT FOUND") ================================================ FILE: Algorithms/Searching/Ternary-Search/README.md ================================================ ## This folder is empty. ================================================ FILE: Algorithms/Searching/Ternary-Search/Ternary-String.c ================================================ /* You are given a string s such that each its character is either 1, 2, or 3. You have to choose the shortest contiguous substring of s such that it contains each of these three characters at least once. A contiguous substring of string s is a string that can be obtained from s by removing some (possibly zero) characters from the beginning of s and some (possibly zero) characters from the end of s. */ #include #include #include #include #include #include #include #include #include #include using namespace std; #define ll long long #define len length() #define vi vector #define vl vector #define fr(i,n) for(ll i=0;ij?i:j; } int main(){ ll t; cin>>t; while(t--){ string s; cin>>s; ll l=0; ll x1 =-1,x2=-1,x3=-1; ll ans=INT_MAX; fr(i,s.len){ { if(s[i]=='1') x1=i; if(s[i]=='2') x2=i; if(s[i]=='3') x3=i; if(x1!=-1&&x2!=-1&&x3!=-1){ l=(max(x1,max(x2,x3))-min(x1,min(x2,x3))); ans=min(ans,l+1); } } } if(ans==INT_MAX) ans=0; cout< using namespace std; int ternarySearch(int l, int r, int key, int ar[]) { while (r >= l) { int mid1 = l + (r - l) / 3; int mid2 = r - (r - l) / 3; if (ar[mid1] == key) { return mid1; } if (ar[mid2] == key) { return mid2; } if (key < ar[mid1]) { r = mid1 - 1; } else if (key > ar[mid2]) { l = mid2 + 1; } else { l = mid1 + 1; r = mid2 - 1; } } return -1; } // Driver code int main() { int l, r, p, key, n; cin >> n; int arr[n]; for (int i = 0; i < n; i++) { cin >> arr[i]; } l = 0; r = n - 1; cin >> key; // Search the key using ternarySearch p = ternarySearch(l, r, key, arr); // Print the result cout << "Index of " << key << " is " << p << endl; return 0; } ================================================ FILE: Algorithms/Searching/Ternary-Search/unimodal_func.cpp ================================================ #include using namespace std; // This is the amount of error we are ready to tolerate in our answer. #define PRECISION 0.0000001 // The main aim of this problem is to find the // minimum and maximum value of a unimodal function // using the ternary search algorithm. // the unimodal function whose maxima has to be found // Let the range be [-10^9,10^9] double func1(double x){ return -x*x-2*x+3; } // the unimodal function whose minima has to be found // let the range be [-10^9,10^9] double func2(double x){ return x*x-2*x+3; } /*To find the maxima of a function we go in the following way: 1. We choose any two points m1 and m2 such that l<=m1<=m2<=r. 2. if func(m1)func(m2){ we go for the range [l,m2] } else{ we reduce our space to [m1,m2] } 3. Step 2 is repeated with same conditions until we reach our desired precision value in our result. */ double find_maxima(double l, double r){ if(abs(l-r)<=PRECISION) return func1(l); else{ double m1 = l+(r-l)/3; double m2 = l+2*(r-l)/3; if(func1(m1)func1(m2)) return find_maxima(l,m2); return find_maxima(m1,m2); } } /* To find the minima of a unimodal function we have to do the following task: 1. We choose any two points m1 and m2 such that l<=m1<=m2<=r. 2. if func(m1)func(m2){ we go for the range [m1,r] } else{ we reduce our space to [m1,m2] } 3. Step 2 is repeated with same conditions until we reach our desired precision value in our result. */ double find_minima(double l, double r){ if(abs(l-r)<=PRECISION) return func2(l); else{ double m1 = l+(r-l)/3; double m2 = l+2*(r-l)/3; if(func2(m1)func2(m2)) return find_minima(m1,r); return find_minima(m1,m2); } } int main(){ cout<<"maxima for func1: "; cout<func(m2){ we go for the range [l,m2] } else{ we reduce our space to [m1,m2] } 3. Step 2 is repeated with same conditions until we reach our desired precision value in our result. */ public static double find_maxima(double l, double r){ if(Math.abs(l-r)<=0.0000001) return func1(l); else{ double m1 = l+(r-l)/3; double m2 = l+2*(r-l)/3; if(func1(m1)func1(m2)) return find_maxima(l,m2); return find_maxima(m1,m2); } } /* To find the minima of a unimodal function we have to do the following task: 1. We choose any two points m1 and m2 such that l<=m1<=m2<=r. 2. if func(m1)func(m2){ we go for the range [m1,r] } else{ we reduce our space to [m1,m2] } 3. Step 2 is repeated with same conditions until we reach our desired precision value in our result. */ public static double find_minima(double l, double r){ if(Math.abs(l-r)<=0.0000001) return func2(l); else{ double m1 = l+(r-l)/3; double m2 = l+2*(r-l)/3; if(func2(m1)func2(m2)) return find_minima(m1,r); return find_minima(m1,m2); } } // Main method public static void main(String args[]){ System.out.println("The maximum value of func1 is: "+find_maxima(-10000000000.0, 10000000000.0)); System.out.println("The maximum value of func1 is: "+find_minima(-10000000000.0, 10000000000.0)); } } ================================================ FILE: Algorithms/Searching/Ternary-Search/unimodal_func.js ================================================ // This is the amount of error we are ready to tolerate in our answer. const PRECISION = 0.0000001 // The main aim of this problem is to find the // minimum and maximum value of a unimodal function // using the ternary search algorithm. // the unimodal function whose maxima has to be found // Let the range be [-10^9,10^9] function func1(x) { return -x * x - 2 * x + 3; } // the unimodal function whose minima has to be found // let the range be [-10^9,10^9] function func2(x) { return x * x - 2 * x + 3; } /*To find the maxima of a function we go in the following way: 1. We choose any two points m1 and m2 such that l<=m1<=m2<=r. 2. if func(m1)func(m2){ we go for the range [l,m2] } else{ we reduce our space to [m1,m2] } 3. Step 2 is repeated with same conditions until we reach our desired precision value in our result. */ function find_maxima(l, r) { if (Math.abs(l - r) <= PRECISION) return func1(l); else { var m1 = l + (r - l) / 3; var m2 = l + 2 * (r - l) / 3; if (func1(m1) < func1(m2)) return find_maxima(m1, r); else if (func1(m1) > func1(m2)) return find_maxima(l, m2); return find_maxima(m1, m2); } } /* To find the minima of a unimodal function we have to do the following task: 1. We choose any two points m1 and m2 such that l<=m1<=m2<=r. 2. if func(m1)func(m2){ we go for the range [m1,r] } else{ we reduce our space to [m1,m2] } 3. Step 2 is repeated with same conditions until we reach our desired precision value in our result. */ function find_minima(l, r) { if (Math.abs(l - r) <= PRECISION) return func2(l); else { var m1 = l + (r - l) / 3; var m2 = l + 2 * (r - l) / 3; if (func2(m1) < func2(m2)) return find_minima(l, m2); else if (func2(m1) > func2(m2)) return find_minima(m1, r); return find_minima(m1, m2); } } var s1 = "The maxima for func1 is " + find_maxima(-1000000.0, 1000000.0); var s2 = "The minima for func2 is " + find_minima(-1000000.0, 10000000.0); console.log(s1); console.log(s2); ================================================ FILE: Algorithms/Searching/Ternary-Search/unimodal_func.py ================================================ """ The main aim of this problem is to find the minimum and maximum value of a unimodal function using the ternary search algorithm.""" """This is the amount of error we are ready to tolerate in our answer.""" PRECISION = 0.0000001 """ the unimodal function whose maxima has to be found. Let the range be [-10^9,10^9]""" def func1(x): return -x*x-2*x+3; """the unimodal function whose minima has to be found. Let the range be [-10^9,10^9]""" def func2(x): return x*x-2*x+3; """To find the maxima of a function we go in the following way: 1. We choose any two points m1 and m2 such that l<=m1<=m2<=r. 2. if func(m1)func(m2){ we go for the range [l,m2] } else{ we reduce our space to [m1,m2] } 3. Step 2 is repeated with same conditions until we reach our desired precision value in our result. """ def find_maxima(l,r): if(abs(l-r)<=PRECISION): return func1(l) else: m1 = l+(r-l)/3; m2 = l+2*(r-l)/3; if(func1(m1)func1(m2)): return find_maxima(l,m2) return find_maxima(m1,m2); """ To find the minima of a unimodal function we have to do the following task: 1. We choose any two points m1 and m2 such that l<=m1<=m2<=r. 2. if func(m1)func(m2){ we go for the range [m1,r] } else{ we reduce our space to [m1,m2] } 3. Step 2 is repeated with same conditions until we reach our desired precision value in our result. """ def find_minima(l,r): if(abs(l-r)<=PRECISION): return func2(l); else: m1 = l+(r-l)/3; m2 = l+2*(r-l)/3; if(func2(m1)func2(m2)): return find_minima(m1,r) return find_minima(m1,m2) def main_func(): print("maxima for func1: ", end="") print(find_maxima(-1000000000,1000000000)) print("minima for func2: ", end ="") print(find_minima(-1000000000,1000000000)) main_func(); ================================================ FILE: Algorithms/Searching/Trie-Search/Trie Data Structure.cpp ================================================ #include #include using namespace std; class Node{ public: char data; unordered_map children; bool terminal; Node(char d){ data = d; terminal = false; } }; class Trie{ Node *root; int cnt; public: Trie(){ root = new Node('\0'); cnt = 0; } void insert(char *w){ Node *temp = root; for(int i=0;ichildren.count(ch)){ temp = temp->children[ch]; } else{ Node *n = new Node(ch); temp->children[ch] = n; temp = n; } } temp->terminal = true; } bool find(char *w){ Node *temp = root; for(int i=0;ichildren.count(ch)){ temp = temp->children[ch]; } else{ return false; } } return temp->terminal; } }; int main(){ Trie T; char words[][10] = {"a","hello","not","news","apple","no"}; for(int i=0;i<6;i++){ T.insert(words[i]); } char *w; w = "no"; if(T.find(w)){ cout<<"Present"; } else{ cout<<"Absent"; } } ================================================ FILE: Algorithms/Searching/Trie-Search/Trie1_HashMap.java ================================================ import java.util.HashMap; import java.util.Map; public class Trie1_HashMap{ public static void main(String[] args) { Trie t=new Trie(); t.insert("CAT"); t.insert("CAP"); t.insert("DOG"); t.insert("DAD"); t.insert("DADDY"); t.insert("COPY"); System.out.println(t.search("CAP")); // t.display(); } } class TrieNode{ char data; Map next; boolean terminate; public TrieNode(char data,boolean terminate) { this.data=data; next=new HashMap<>(); this.terminate=terminate; } } class Trie{ TrieNode root; public Trie() { this.root=new TrieNode('\0',false); } public boolean search(String s) { TrieNode x=this.root; for(int i=0;i e:root.next.entrySet()) { System.out.print(e.getValue().data+" "+e.getValue().terminate+" "); display(e.getValue()); System.out.println(); } } public void insert(String data) { insert(root,data); } private void insert(TrieNode root, String s) { TrieNode x=root; for(int i=0;i #include // define character size #define CHAR_SIZE 26 // A Trie node struct Trie { int isLeaf; // 1 when node is a leaf node struct Trie* character[CHAR_SIZE]; }; // Function that returns a new Trie node struct Trie* getNewTrieNode() { struct Trie* node = (struct Trie*)malloc(sizeof(struct Trie)); node->isLeaf = 0; for (int i = 0; i < CHAR_SIZE; i++) node->character[i] = NULL; return node; } // Iterative function to insert a string in Trie void insert(struct Trie *head, char* str) { // start from root node struct Trie* curr = head; while (*str) { // create a new node if path doesn't exists if (curr->character[*str - 'a'] == NULL) curr->character[*str - 'a'] = getNewTrieNode(); // go to next node curr = curr->character[*str - 'a']; // move to next character str++; } // mark current node as leaf curr->isLeaf = 1; } // Iterative function to search a string in Trie. It returns 1 // if the string is found in the Trie, else it returns 0 int search(struct Trie* head, char* str) { // return 0 if Trie is empty if (head == NULL) return 0; struct Trie* curr = head; while (*str) { // go to next node curr = curr->character[*str - 'a']; // if string is invalid (reached end of path in Trie) if (curr == NULL) return 0; // move to next character str++; } // if current node is a leaf and we have reached the // end of the string, return 1 return curr->isLeaf; } // returns 1 if given node has any children int haveChildren(struct Trie* curr) { for (int i = 0; i < CHAR_SIZE; i++) if (curr->character[i]) return 1; // child found return 0; } // Recursive function to delete a string in Trie int deletion(struct Trie **curr, char* str) { // return if Trie is empty if (*curr == NULL) return 0; // if we have not reached the end of the string if (*str) { // recur for the node corresponding to next character in // the string and if it returns 1, delete current node // (if it is non-leaf) if (*curr != NULL && (*curr)->character[*str - 'a'] != NULL && deletion(&((*curr)->character[*str - 'a']), str + 1) && (*curr)->isLeaf == 0) { if (!haveChildren(*curr)) { free(*curr); (*curr) = NULL; return 1; } else { return 0; } } } // if we have reached the end of the string if (*str == '\0' && (*curr)->isLeaf) { // if current node is a leaf node and don't have any children if (!haveChildren(*curr)) { free(*curr); // delete current node (*curr) = NULL; return 1; // delete non-leaf parent nodes } // if current node is a leaf node and have children else { // mark current node as non-leaf node (DON'T DELETE IT) (*curr)->isLeaf = 0; return 0; // don't delete its parent nodes } } return 0; } // Trie Implementation in C - Insertion, Searching and Deletion int main() { struct Trie* head = getNewTrieNode(); insert(head, "hello"); printf("%d ", search(head, "hello")); // print 1 insert(head, "helloworld"); printf("%d ", search(head, "helloworld")); // print 1 printf("%d ", search(head, "helll")); // print 0 (Not present) insert(head, "hell"); printf("%d ", search(head, "hell")); // print 1 insert(head, "h"); printf("%d \n", search(head, "h")); // print 1 + newline deletion(&head, "hello"); printf("%d ", search(head, "hello")); // print 0 (hello deleted) printf("%d ", search(head, "helloworld")); // print 1 printf("%d \n", search(head, "hell")); // print 1 + newline deletion(&head, "h"); printf("%d ", search(head, "h")); // print 0 (h deleted) printf("%d ", search(head, "hell")); // print 1 printf("%d\n", search(head, "helloworld")); // print 1 + newline deletion(&head, "helloworld"); printf("%d ", search(head, "helloworld")); // print 0 printf("%d ", search(head, "hell")); // print 1 deletion(&head, "hell"); printf("%d\n", search(head, "hell")); // print 0 + newline if (head == NULL) printf("Trie empty!!\n"); // Trie is empty now printf("%d ", search(head, "hell")); // print 0 return 0; } ================================================ FILE: Algorithms/Searching/Trie-Search/Trie_Search.go ================================================ package main import ( "fmt" "strings" ) // Trie structure type Trie struct { root *trieNode } type trieNode struct { children [26]*trieNode wordEnd bool } // Constructor initialize the Trie data structure func Constructor() Trie { return Trie{ root: &trieNode{}, } } // Insert a word into the trie func (this *Trie) Insert(word string) { word = strings.ToLower(word) current := this.root for i := 0; i < len(word); i++ { index := word[i] - 'a' if current.children[index] == nil { current.children[index] = &trieNode{} } current = current.children[index] } current.wordEnd = true } // Search returns if the word is in the trie func (this *Trie) Search(word string) bool { word = strings.ToLower(word) current := this.root for i := 0; i < len(word); i++ { index := word[i] - 'a' if current.children[index] == nil { return false } current = current.children[index] } if current.wordEnd { return true } return false } func main() { insertWords := []string{"hello", "world", "golang", "trie", "tree"} searchWords := []string{ "world", /* true */ "Golang", /* true */ "word", /* false */ } trie := Constructor() for _, node := range insertWords { trie.Insert(node) } for _, node := range searchWords { found := trie.Search(node) if found { fmt.Println(node, ": Found in the trie") } else { fmt.Println(node, ": Not found in the trie") } } } ================================================ FILE: Algorithms/Searching/Trie-Search/Trie_Search.py ================================================ # Program for Trie Insert and Search # Trie node class TrieNode: def __init__(self): self.children = [None]*26 self.isEndOfWord = False # Trie Class class Trie: def __init__(self): self.root = self.getNode() def getNode(self): return TrieNode() def toIndex(self, ch): return ord(ch)-ord('a') # Function to Insert into Trie def insert(self, key): node = self.root length = len(key) for i in range(length): idx = self.toIndex(key[i]) if not node.children[idx]: node.children[idx] = self.getNode() node = node.children[idx] node.isEndOfWord = True # Function for Trie Search def search(self, key): node = self.root length = len(key) for i in range(length): idx = self.toIndex(key[i]) if not node.children[idx]: return False node = node.children[idx] return node!=None and node.isEndOfWord # Main function # To test code, please edit keys list and print statements for search def main(): keys = ["the","apple","there","hello","world", "by","python"] output = ["Not present in trie", "Present in trie"] # Construct Trie trie = Trie() for key in keys: trie.insert(key) # Search in trie print("{} => {}".format("the", output[trie.search("the")])) print("{} => {}".format("hi", output[trie.search("hi")])) print("{} => {}".format("apple", output[trie.search("apple")])) print("{} => {}".format("man", output[trie.search("man")])) if __name__ == '__main__': main() ## Sample Output ## # the => Present in trie # hi => Not present in trie # apple => Present in trie # man => Not present in trie ================================================ FILE: Algorithms/Sorting/3-Way_Quick_Sort/3-Way_Quick_Sort.cpp ================================================ /* Author: immortal-j Implementation Details Quick sort 3 works on Dutch National Flag Algorithm The major diffrence between simple quicksort and quick sort 3 comes in the function quick_sort_partition3 In quick_sort_partition3 we divide the vector/array into 3 parts i.e a[0...q_l]-->less than pivot a[q_l+1...q_e-1]-->Equal to pivot a[q_e...r]-->Greater than pivot quick sort 3 works faster in some cases as compared to simple quicksort. */ #include #include #include /*This function takes first element as pivot, places the pivot element at its correct position in sorted array*/ std::vector quick_sort_partition3(std::vector &arr, int low, int high) { int x = arr[low];//taking first element as pivot int q_l = low;//We initiate q_l to be the part that is less than the pivot int count = low; int q_e = high;// The part that is greater than the pivot std::vector m(2);//this vector is used to return positions of higher and lower while (count <= q_e) { if (arr[count] < x) { std::swap(arr[q_l], arr[count]); q_l++; count++;//increment index } else if (arr[count] == x) { count++;//increment index } else { std::swap(arr[count], arr[q_e]); q_e -= 1; } m[0] = q_l; m[1] = q_e; } return m; } /* arr-->vector to be sorted low-->Starting index high-->Ending Index */ void randomized_quick_sort(std::vector &arr, int low, int high) { if (low >= high) { return; } int random = low + rand() % (high - low + 1);//provides a random index; std::swap(arr[low], arr[random]); std::vector m = quick_sort_partition3(arr, low, high); randomized_quick_sort(arr, low, m[0] - 1); randomized_quick_sort(arr, m[1] + 1, high); } //Driver program to test above functions int main() { int sizeofvector; std::cin >> sizeofvector; std::vector arr(sizeofvector); for (size_t i = 0; i < arr.size(); ++i) { std::cin >> arr[i]; } randomized_quick_sort(arr, 0, arr.size() - 1); //prints vector/array after sorting for (size_t i = 0; i < arr.size(); ++i) { std::cout << arr[i] << ' '; } return 0; } ================================================ FILE: Algorithms/Sorting/3-Way_Quick_Sort/3-Way_Quick_Sort.cs ================================================ using System; class Sort { static void swap(ref T lhs, ref T rhs) { T temp; temp = lhs; lhs = rhs; rhs = temp; } public static void partition(int[] a, int l, int r, ref int i, ref int j) { i = l - 1; j = r; int p = l - 1, q = r; int v = a[r]; while (true) { while (a[++i] < v) ; while (v < a[--j]) if (j == l) break; if (i >= j) break; swap(ref a[i], ref a[j]); if (a[i] == v) { p++; swap(ref a[p], ref a[i]); } if (a[j] == v) { q--; swap(ref a[j], ref a[q]); } } swap(ref a[i], ref a[r]); j = i - 1; for (int k = l; k < p; k++, j--) swap(ref a[k], ref a[j]); i = i + 1; for (int k = r - 1; k > q; k--, i++) swap(ref a[i], ref a[k]); } public static void quicksort(int[] a, int l, int r) { if (r <= l) return; int i = 0, j = 0; partition(a, l, r, ref i, ref j); quicksort(a, l, j); quicksort(a, i, r); } public static void printarr(int[] a, int n) { for (int i = 0; i < n; ++i) Console.Write(a[i] + " "); Console.Write("\n"); } static void Main() { int[] a = { 4, 9, 4, 4, 1, 9, 4, 4, 9, 4, 4, 1, 4 }; int size = a.Length; printarr(a, size); quicksort(a, 0, size - 1); printarr(a, size); } } ================================================ FILE: Algorithms/Sorting/3-Way_Quick_Sort/3-Way_Quick_Sort.java ================================================ import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class QuickSort { private static void swap(Comparable[] arr, int first, int second) { // Swaps the two array elements with indices passed as arguments. Comparable temp = arr[first]; arr[first] = arr[second]; arr[second] = temp; } private static void quickSort3Way(Comparable[] arr, int low, int high) { /* arr: Array to be sorted using the Three Way QuickSort Algorithm low: The starting index of a subarray high: The ending index of a subarray */ // No partitioning for subarrays of size 1 or below. if(high <= low) return; // Partitioning item value Comparable v = arr[low]; // Three variables lesser, i and greater are used for the corresponding partitions to be made. // lesser partition i.e. arr[low .. lesser - 1] denotes the partition with items of value less than the partitioning item v. // greater partition i.e arr[greater + 1 .. high] denotes the partition with items of value greater than the partitioning item v. // equals partition i.e. arr[lesser .. greater] denotes the partition with items of value equal to the partitioning item v. // variable i represents the current element that is to be put into one of the above three partitions. int lesser = low, i = low + 1, greater = high; while(i <= greater) { int cmp = arr[i].compareTo(v); if(cmp < 0) swap(arr, lesser++, i++); else if(cmp > 0) swap(arr, i, greater--); else i++; } quickSort3Way(arr, low, lesser-1); quickSort3Way(arr, greater+1, high); } private static void printSortedArray(Comparable[] arr) { // Prints the sorted array as output. for(int index=0; index #include void swap(int &x, int &y) { int temp = x; x = y; y = temp; } void partition(int a[], int l, int r, int& i, int& j) { i = l - 1, j = r; int p = l - 1, q = r; int v = a[r]; while (true) { while (a[++i] < v); while (v < a[--j]) if (j == l) break; if (i >= j) break; swap(a[i], a[j]); if (a[i] == v) { p++; swap(a[p], a[i]); } if (a[j] == v) { q--; swap(a[j], a[q]); } } swap(a[i], a[r]); j = i - 1; for (int k = l; k < p; k++, j--) swap(a[k], a[j]); i = i + 1; for (int k = r - 1; k > q; k--, i++) swap(a[i], a[k]); } void quicksort(int a[], int l, int r) { if (r <= l) return; int i, j; partition(a, l, r, i, j); quicksort(a, l, j); quicksort(a, i, r); } void printarr(int a[], int n) { for (int i = 0; i < n; ++i) printf("%d ", a[i]); printf("\n"); } int main() { int n; scanf("%d", &n); int ar[n]; for (int i = 0; i < n; i++) scanf("%d", &ar[i]); printf("Before Sorting: "); printarr(ar, n); quicksort(ar, 0, n - 1); printf("After Sorting: "); printarr(ar, n); return 0; } ================================================ FILE: Algorithms/Sorting/Bead_Sort/Bead_Sort.php ================================================ using namespace std; void beadSort(int *a, int len) { int max = a[0]; for (int i = 1; i < len; i++) if (a[i] > max) max = a[i]; char beads[max*len]; memset(beads, 0, sizeof(beads)); for (int i = 0; i < len; i++) for (int j = 0; j < a[i]; j++) beads[i*max +j] = 1; for (int j = 0; j < max; j++) { int sum = 0; for (int i=0; i < len; i++) { sum += beads[i*max +j]; beads[i*max +j] = 0; } for (int i = len - sum; i < len; i++) beads[i*max +j] = 1; } for (int i = 0; i < len; i++) { int j; for (j = 0; j < max && beads[i*max +j]; j++); a[i] = j; } } int main() { int n; cout<<"enter the no of element in array :"; cin>>n; cout<<"enter the elements: "; int a[n]; for(int i=0;i>a[i]; beadSort(a, n); for (int i = 0; i < n; i++) printf("%d ", a[i]); return 0; } ================================================ FILE: Algorithms/Sorting/Bead_Sort/README.md ================================================ ## BEAD SORTING: Bead Sort is also known as Gravity Sort. This algorithm was inspired from natural phenomenons and was designed keeping in beads of abacus in mind falling under the influence of gravity. **For Example:** 1. Imagine a abacus sorted in a pattern of 7,2,1,4,2. Now, imagine that this is the position of the beads at time t = 0 and with every passing second the beads will fall down by one level provided there is no bead already present below them. In such a case, they just rest upon the bead below them. 2. Now, at time t = 1 the bottom 2 beads in the first two rods from the left stay at their positions while the second bead from the top from the second rod comes down by one level to rest upon the bead below it. The beads in the 3rd and 4th rod at level 2 come down to level 1. Simultaneously, the beads in the rods 3 to 7 come down by one level. Now, the numbers from top to bottom become: 2, 6, 2, 2, 4. 3. This goes on till time t = 4 where we get the sorted sequence of numbers from top to bottom which is: 1, 2, 2, 4, 7. So, INPUT: 7,2,1,4,2. OUTPUT: 2,6,2,2,4. ================================================ FILE: Algorithms/Sorting/Bead_Sort/bead_sort.py ================================================ def bead_sort(obj): if all([type(x) == int and x >= 0 for x in obj]): ref = [range(x) for x in obj] #for reference else: raise ValueError("All elements must be positive integers") inter = [] #for intermediate ind = 0 #for index prev = sum([1 for x in ref if len(x) > ind]) #prev for previous while prev: inter.append(range(prev)) ind += 1 prev = sum([1 for x in ref if len(x) > ind]) ind = 0 prev = sum([1 for x in inter if len(x) > ind]) out = [] while prev: out.append(prev) ind += 1 prev = sum([1 for x in inter if len(x) > ind]) out = out[::-1] return out a=[2,4,3,5,1] print(bead_sort(a)) ================================================ FILE: Algorithms/Sorting/Binary_Insertion_Sort/Binary Insertion Sort.c ================================================ // C program for implementation of binary insertion sort,Time Complexity : O(n^2) #include int binarySearch(int a[], int item, int low, int high) { if (high <= low) return (item > a[low])? (low + 1): low; int mid = (low + high)/2; if(item == a[mid]) return mid+1; if(item > a[mid]) return binarySearch(a, item, mid+1, high); return binarySearch(a, item, low, mid-1); } // Function to sort an array a[] of size 'n' void insertionSort(int a[], int n) { int i, loc, j, k, selected; for (i = 1; i < n; ++i) { j = i - 1; selected = a[i]; // find location where selected sould be inseretd loc = binarySearch(a, selected, 0, j); // Move all elements after location to create space while (j >= loc) { a[j+1] = a[j]; j--; } a[j+1] = selected; } } int main() { int n,i; scanf("%d",&n); int arrr[n]; for (i = 0; i < n; i++) scanf("%d",&a[i]); insertionSort(a, n); printf("Sorted array: \n"); for (i = 0; i < n; i++) printf("%d ",a[i]); return 0; } ================================================ FILE: Algorithms/Sorting/Binary_Insertion_Sort/Binary_Insertion_Sort.cpp ================================================ // C program for implementation of binary insertion sort #include int binarySearch(int a[], int item, int low, int high) { if (high <= low) return (item > a[low])? (low + 1): low; int mid = (low + high)/2; if(item == a[mid]) return mid+1; if(item > a[mid]) return binarySearch(a, item, mid+1, high); return binarySearch(a, item, low, mid-1); } // Function to sort an array a[] of size 'n' void insertionSort(int a[], int n) { int i, loc, j, k, selected; for (i = 1; i < n; ++i) { j = i - 1; selected = a[i]; // find location where selected sould be inseretd loc = binarySearch(a, selected, 0, j); // Move all elements after location to create space while (j >= loc) { a[j+1] = a[j]; j--; } a[j+1] = selected; } } int main() { int a[] = {37, 23, 0, 17, 12, 72, 31, 46, 100, 88, 54}; int n = sizeof(a)/sizeof(a[0]), i; insertionSort(a, n); printf("Sorted array: \n"); for (i = 0; i < n; i++) printf("%d ",a[i]); return 0; } ================================================ FILE: Algorithms/Sorting/Binary_Insertion_Sort/Binary_Insertion_Sort.py ================================================ import bisect def binsertion_sort(arr): ''' Author: Kinshuk Dua (@kinshukdua) Python program to perform binary insertion sort Comparison complexity O(nlogn) Sorting complexity O(n^2) ''' for i in range(1,len(arr)): bisect.insort(arr, arr.pop(i), 0, i) return #testing arr = [5,4,3,2,1] binsertion_sort(arr) print(arr) ================================================ FILE: Algorithms/Sorting/Binary_Insertion_Sort/Readme.md ================================================ # BINARY INSERTION SORTING Binary search is used to reduce the number of comparisons in Insertion sort. This modification is known as Binary Insertion Sort. Binary Insertion Sort use binary search to find the proper location to insert the selected item at each iteration. In insertion sort, it takes O(i) at ith iteration in worst case. Using binary search, it is reduced to O(log i). **For Example:** If we know insertion sort and binary search already, then its pretty straight forward. When we insert a piece in insertion sort, we must compare to all previous pieces.Like if we want to move this [2] to the correct place, we would have to compare to 7 pieces before we find the right place. [1][3][3][3][4][4][5] ->[2]<- [11][0][50][47] However, if we start the comparison at the half way point (like a binary search), then we will only compare to 4 pieces! This can be done because we know the left pieces are already in order. ================================================ FILE: Algorithms/Sorting/Bitonic_Search/BitonicSort.java ================================================ /* Java program for Bitonic Sort. Size of input should always be a power of 2. */ public class BitonicSort { /* Sorts a bitonic sequence recursively in ascending order, if arr = 1, and in descending order otherwise (means arr=0). The sequence to be sorted starts at index position low, the parameter cnt is the number of elements to be sorted.*/ void merge(int a[], int low, int cnt, int arr) { if (cnt>1) { int k = cnt/2; for (int i=low; i a[j]) agrees with the direction, then a[i] and a[j] are interchanged. */ void swap(int a[], int i, int j, int arr) { if ( (a[i] > a[j] && arr == 1) || (a[i] < a[j] && arr == 0)) { // Swap elements int temp = a[i]; a[i] = a[j]; a[j] = temp; } } /* A bitonic sequence is produced by recursively sorting its two halves in opposite sorting orders, and then calls merge to make them in the same order */ void bitonicSort(int a[], int low, int cnt, int arr) { if (cnt>1) { int k = cnt/2; // sort in ascending order since arr here is 1 bitonicSort(a, low, k, 1); // sort in descending order since arr here is 0 bitonicSort(a,low+k, k, 0); // Will merge wole sequence in ascending order // since arr=1. merge(a, low, cnt, arr); } } /* bitonicSort is called here for sorting the entire array of length N in ASCENDING order */ void sort(int a[], int N, int up) { bitonicSort(a, 0, N, up); } /* A utility function to print array of size n */ static void printArray(int arr[]) { int n = arr.length; for (int i=0; i using namespace std; /*The parameter dir indicates the sorting direction, ASCENDING or DESCENDING; if (a[i] > a[j]) agrees with the direction, then a[i] and a[j] are interchanged.*/ void compAndSwap(int a[], int i, int j, int dir) { if (dir==(a[i]>a[j])) swap(a[i],a[j]); } /*It recursively sorts a bitonic sequence in ascending order, if dir = 1, and in descending order otherwise (means dir=0). The sequence to be sorted starts at index position low, the parameter cnt is the number of elements to be sorted.*/ void bitonicMerge(int a[], int low, int cnt, int dir) { if (cnt>1) { int k = cnt/2; for (int i=low; i1) { int k = cnt/2; // sort in ascending order since dir here is 1 bitonicSort(a, low, k, 1); // sort in descending order since dir here is 0 bitonicSort(a, low+k, k, 0); // Will merge wole sequence in ascending order // since dir=1. bitonicMerge(a,low, cnt, dir); } } /* Caller of bitonicSort for sorting the entire array of length N in ASCENDING order */ void sort(int a[], int N, int up) { bitonicSort(a,0, N, up); } // Driver code int main() { int a[]= {3, 7, 4, 8, 6, 2, 1, 5}; int N = sizeof(a)/sizeof(a[0]); int up = 1; // means sort in ascending order sort(a, N, up); printf("Sorted array: \n"); for (int i=0; i= xi+1….. >= xn-1** 1. A sequence, sorted in increasing order is considered Bitonic with the decreasing part as empty. Similarly, decreasing order sequence is considered Bitonic with the increasing part as empty. 2. A rotation of Bitonic Sequence is also bitonic. **EXAMPLE:** Converting 3, 7, 4, 8, 6, 2, 1, 5 into Bitonic sequence, 1. Consider each 2-consecutive elements as bitonic sequence and apply bitonic sort on each 2- pair elements. In next step, take two 4 element bitonic sequences and so on. 2. Two 4 element bitonic sequences : A(3,7,8,4) and B(2,6,5,1) with comparator length as 2. 3. After this step, we’ll get Bitonic sequence of length 8. OUTPUT: 1, 2, 3, 4, 5, 6, 7, 8. ================================================ FILE: Algorithms/Sorting/Bitonic_Search/bitonic_search.py ================================================ def compAndSwap(a, i, j, dire): if (dire == 1 and a[i] > a[j]) or (dire == 0 and a[i] < a[j]): a[i], a[j] = a[j], a[i] def bitonic_merge(a, low, cnt, dire): if cnt > 1: k = int(cnt / 2) for i in range(low, low + k): compAndSwap(a, i, i + k, dire) bitonic_merge(a, low, k, dire) bitonic_merge(a, low + k, k, dire) def bitonic_sort(a, low, cnt, dire): if cnt > 1: k = int(cnt / 2) bitonic_sort(a, low, k, 1) bitonic_sort(a, low + k, k, 0) bitonic_merge(a, low, cnt, dire) def sort(a, N, up): bitonic_sort(a, 0, N, up) if __name__ == "__main__": a = [] n = int(input().strip()) for i in range(n): a.append(int(input().strip())) up = 1 sort(a, n, up) print("\n\nSorted array is") for i in range(n): print("%d" % a[i]) ================================================ FILE: Algorithms/Sorting/Brick_Sort/BrickSort.js ================================================ /* A JavaScript program to perform Brick Sort */ // A utility function to sort the array values function swap(arr, first_Index, second_Index) { var temp = arr[first_Index]; arr[first_Index] = arr[second_Index]; arr[second_Index] = temp; } // A function to perform the Brick Sort function brickSort(arr) { if (arr.length < 1) return 0; var arrayLength = arr.length; var isSorted = false; while(!isSorted){ isSorted = true; // Perform Bubble sort on odd indexed element for (let i=1; i<=arrayLength-2; i=i+2) { if (arr[i] > arr[i+1]) { swap(arr,i,i+1); isSorted = false; } } // Perform Bubble sort on even indexed element for (let i=0; i<=arrayLength-2; i=i+2) { if (arr[i] > arr[i+1]) { swap(arr,i,i+1); isSorted = false; } } } return arr; } console.log(brickSort([3, 0, 2, 5, -1, 4, 1])); ================================================ FILE: Algorithms/Sorting/Brick_Sort/Brick_Sort.c ================================================ // A C++ Program to implement Odd-Even Brick Sort // #include using namespace std; // A function to sort the algorithm using Odd Even sort void oddEvenSort(int arr[], int n) { bool isSorted = false; // Initially array is unsorted while (!isSorted) { isSorted = true; // Perform Bubble sort on odd indexed element for (int i=1; i<=n-2; i=i+2) { if (arr[i] > arr[i+1]) { swap(arr[i], arr[i+1]); isSorted = false; } } // Perform Bubble sort on even indexed element for (int i=0; i<=n-2; i=i+2) { if (arr[i] > arr[i+1]) { swap(arr[i], arr[i+1]); isSorted = false; } } } return; } // A utility function ot print an array of size n void printArray(int arr[], int n) { for (int i=0; i < n; i++) cout << arr[i] << " "; cout << "\n"; } // Driver program to test above functions. int main() { int arr[] = {34, 2, 10, -9}; int n = sizeof(arr)/sizeof(arr[0]); oddEvenSort(arr, n); printArray(arr, n); return (0); } ================================================ FILE: Algorithms/Sorting/Brick_Sort/Readme.md ================================================ # BRICK SORT Brick Sorting is basically variation of Bubble Sorting. It is divided into two phases Odd and Even Phase. In the odd phase,bubble sort is performed on odd indexed elements and in the even phase,bubble sort is performed on even indexed elements. **Example:** Let's take Unsorted Array A={3, 2, 3, 8, 5, 6, 4, 1}. Sorting will perfromed in 8 steps: 1. Pairing in even number - [3 2],[3 8],[5 6],[4 1]. 2. Now in odd number - [2],[3 3],[8 5],[6 1],[4]. 3. Similarly following step 1 and 2 - [2 3],[3 5],[8 1],[6 4]. 4. [2],[3 3],[5 1],[8 4],[6]. 5. [2 3],[3 1],[5 4],[8 6]. 6. [2],[3 1],[3 4],[5 6],[8]. 7. [2 1],[3 3],[4 5],[6 8]. 8. [1],[2 3],[3 4],[5 6],8. OUTPUT: [1 2],[3 3],[4 5],[6 8] - {1, 2, 3, 3, 4, 5, 6, 8}. ================================================ FILE: Algorithms/Sorting/Brick_Sort/brickSort.py ================================================ def brickSort(array, n): isSorted = 0 while isSorted == 0: isSorted = 1 temp = 0 for i in range(1, n - 1, 2): if array[i] > array[i + 1]: array[i], array[i + 1] = array[i + 1], array[i] isSorted = 0 for i in range(0, n - 1, 2): if array[i] > array[i + 1]: array[i], array[i + 1] = array[i + 1], array[i] isSorted = 0 return arr = [23,45,67,89] n = len(arr) brickSort(arr, n); for i in range(0, n): print(arr[i], end=' ') ================================================ FILE: Algorithms/Sorting/Bubble_Sort/BubbleSort.js ================================================ function swap(arr, first_Index, second_Index) { var temp = arr[first_Index]; arr[first_Index] = arr[second_Index]; arr[second_Index] = temp; } function bubbleSort(arr) { if (arr.length < 1) return 0; var arrayLength = arr.length; for (let i = 0; i < arrayLength; i++) { for (let j = 0, end = arrayLength - i; j < end; j++) { if (arr[j] > arr[j + 1]) { swap(arr, j, j + 1); } } } return arr; } console.log(bubbleSort([3, 0, 2, 5, -1, 4, 1])); ================================================ FILE: Algorithms/Sorting/Bubble_Sort/BubbleSort.scala ================================================ object BubbleSortAscApp { //main function def main(args: Array[String]): Unit = { //Passing list to be sorted to bubble sort function println(bubbleSortAsc(List(3,1,6,8,2))) println(bubbleSortAsc(List("z", "c", "a", "b"))) } // Bubble sort function def bubbleSortAsc[T <% Ordered[T]](myData: List[T]): List[T] = myData match { case Nil => Nil case _ => { val (max, remainingData) = calcMax(myData) bubbleSortAsc(remainingData) ::: List(max) } } //calculating max each iteration def calcMax[T <% Ordered[T]](myData: List[T]): (T,List[T]) = myData match { case (Nil) => (null.asInstanceOf[T], Nil) case (head :: Nil) => (head, Nil) case (head :: tail) => { val (tailMax, tailRemaining) = calcMax(tail) if (tailMax >= head) (tailMax, head :: tailRemaining) else (head, tailMax :: tailRemaining) } } } ================================================ FILE: Algorithms/Sorting/Bubble_Sort/Bubble_Sort.c ================================================ #include int main() { int count, temp, i, j, number[30]; printf("How many numbers are u going to enter?:\n "); scanf("%d",&count); printf("Enter %d numbers: ",count); for(i=0;i=0;i--){ for(j=0;j<=i;j++){ if(number[j]>number[j+1]){ temp=number[j]; number[j]=number[j+1]; number[j+1]=temp; } } } printf("Sorted elements: "); for(i=0;i arr[i + 1]) { temp= arr[i + 1]; arr[i + 1] = arr[i]; arr[i] = temp; } } } Console.WriteLine("Sorted:"); foreach (int p in arr) Console.Write(p + " "); Console.Read(); } } } ================================================ FILE: Algorithms/Sorting/Bubble_Sort/Bubble_Sort.py ================================================ # This is the Python version of Bubble Sort # Code is contributed by: Harsh Udai. # # Bubble sort is an Sorting Algorithm which takes compelxity: O(n^2) array=[5,4,3,2,1,6] for i in range(0,len(array)): for j in range(0,len(array)-1): if(array[j]>array[j+1]): # swaps if greater element is before the smaller one temp=array[j] array[j]=array[j+1] array[j+1]=temp print(array) ================================================ FILE: Algorithms/Sorting/Bubble_Sort/Bubble_sort_optimised.cpp ================================================ // Optimized implementation of Bubble sort #include using namespace std; #define IOS ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(0) void swap(int *xp, int *yp) { int temp = *xp; *xp = *yp; *yp = temp; } // An optimized version of Bubble Sort void bubbleSort(int arr[], int n) { int i, j; bool swapped; for (i = 0; i < n-1; i++) { swapped = false; for (j = 0; j < n-i-1; j++) { if (arr[j] > arr[j+1]) { swap(&arr[j], &arr[j+1]); swapped = true; } } // IF no two elements were swapped by inner loop, then break if (swapped == false) break; } } /* Function to print an array */ void printArray(int arr[], int size) { int i; for (i=0; i < size; i++) cout< using namespace std; void bubble_sort(int arr[],int n) { for(int i = 0;i>n; int arr[n]; for(int i =0;i>arr[i]; bubble_sort(arr,n); } ================================================ FILE: Algorithms/Sorting/Bubble_Sort/bubble_sort.java ================================================ class Bubble { void Sort(int array[]) { int n = array.length; for (int i = 0; i < n-1; i++) for (int j = 0; j < n-i-1; j++) if (array[j] > array[j+1]) { int temp = array[j]; array[j] = array[j+1]; array[j+1] = temp;// swapping temp and array } } void printarrayay(int array[])//to print the array { int n = array.length; for (int i=0; i (9 7 8 6) -> (9 8 7 6) ================================================ FILE: Algorithms/Sorting/Bucket_Sort/BucketSort.c ================================================ // Bucket sort in C #include #include #define NARRAY 10 // Array size #define NBUCKET 6 // Number of buckets #define INTERVAL 10 // Each bucket capacity struct Node { int data; struct Node *next; }; void BucketSort(int arr[]); struct Node *InsertionSort(struct Node *list); void print(int arr[]); void printBuckets(struct Node *list); int getBucketIndex(int value); // Sorting function void BucketSort(int arr[]) { int i, j; struct Node **buckets; // Create buckets and allocate memory size buckets = (struct Node **)malloc(sizeof(struct Node *) * NBUCKET); // Initialize empty buckets for (i = 0; i < NBUCKET; ++i) { buckets[i] = NULL; } // Fill the buckets with respective elements for (i = 0; i < NARRAY; ++i) { struct Node *current; int pos = getBucketIndex(arr[i]); current = (struct Node *)malloc(sizeof(struct Node)); current->data = arr[i]; current->next = buckets[pos]; buckets[pos] = current; } // Print the buckets along with their elements for (i = 0; i < NBUCKET; i++) { printf("Bucket[%d]: ", i); printBuckets(buckets[i]); printf("\n"); } // Sort the elements of each bucket for (i = 0; i < NBUCKET; ++i) { buckets[i] = InsertionSort(buckets[i]); } printf("-------------\n"); printf("Bucktets after sorting\n"); for (i = 0; i < NBUCKET; i++) { printf("Bucket[%d]: ", i); printBuckets(buckets[i]); printf("\n"); } // Put sorted elements on arr for (j = 0, i = 0; i < NBUCKET; ++i) { struct Node *node; node = buckets[i]; while (node) { arr[j++] = node->data; node = node->next; } } return; } // Function to sort the elements of each bucket struct Node *InsertionSort(struct Node *list) { struct Node *k, *nodeList; if (list == 0 || list->next == 0) { return list; } nodeList = list; k = list->next; nodeList->next = 0; while (k != 0) { struct Node *ptr; if (nodeList->data > k->data) { struct Node *tmp; tmp = k; k = k->next; tmp->next = nodeList; nodeList = tmp; continue; } for (ptr = nodeList; ptr->next != 0; ptr = ptr->next) { if (ptr->next->data > k->data) break; } if (ptr->next != 0) { struct Node *tmp; tmp = k; k = k->next; tmp->next = ptr->next; ptr->next = tmp; continue; } else { ptr->next = k; k = k->next; ptr->next->next = 0; continue; } } return nodeList; } int getBucketIndex(int value) { return value / INTERVAL; } void print(int ar[]) { int i; for (i = 0; i < NARRAY; ++i) { printf("%d ", ar[i]); } printf("\n"); } // Print buckets void printBuckets(struct Node *list) { struct Node *cur = list; while (cur) { printf("%d ", cur->data); cur = cur->next; } } // Driver code int main(void) { int array[NARRAY] = {42, 32, 33, 52, 37, 47, 51, 28, 44, 39}; printf("Initial array: "); print(array); printf("-------------\n"); BucketSort(array); printf("-------------\n"); printf("Sorted array: "); print(array); return 0; } /*Output: Initial array: 42 32 33 52 37 47 51 28 44 39 ------------- Bucket[0]: Bucket[1]: Bucket[2]: 28 Bucket[3]: 39 37 33 32 Bucket[4]: 44 47 42 Bucket[5]: 51 52 ------------- Bucktets after sorting Bucket[0]: Bucket[1]: Bucket[2]: 28 Bucket[3]: 32 33 37 39 Bucket[4]: 42 44 47 Bucket[5]: 51 52 ------------- Sorted array: 28 32 33 37 39 42 44 47 51 52 */ ================================================ FILE: Algorithms/Sorting/Bucket_Sort/BucketSort.java ================================================ // Bucket sort in Java import java.util.ArrayList; import java.util.Collections; import java.util.Scanner; public class BucketSort { public void bucketSort(float[] arr, int n) { if (n <= 0) return; @SuppressWarnings("unchecked") ArrayList[] bucket = new ArrayList[n]; // Create empty buckets for (int i = 0; i < n; i++) bucket[i] = new ArrayList(); // Add elements into the buckets for (int i = 0; i < n; i++) { int bucketIndex = (int) arr[i] * n; bucket[bucketIndex].add(arr[i]); } // Sort the elements of each bucket for (int i = 0; i < n; i++) { Collections.sort((bucket[i])); } // Get the sorted array int index = 0; for (int i = 0; i < n; i++) { for (int j = 0, size = bucket[i].size(); j < size; j++) { arr[index++] = bucket[i].get(j); } } } // Driver code public static void main(String[] args) { BucketSort b = new BucketSort(); Scanner s = new Scanner(System.in); // Create a Scanner object System.out.println("Enter no of elemets"); int n=s.nextInt(); ArrayList[] arr = new ArrayList[n]; for(int i=0;i { for (let i = 1; i < arr.length; i++) { const value = arr[i]; let lastIndex = i - 1; while (lastIndex >= 0 && arr[lastIndex] > value) { arr[lastIndex + 1] = arr[lastIndex]; lastIndex--; } arr[lastIndex + 1] = value; }; return arr; }; const sortBucketPositive = (arr) => { const length = arr.length; const maxValue = Math.max(...arr); const divider = Math.ceil((maxValue + 1) / length); const buckets = []; // Place array values inside buckets for (let i = 0; i < length; i++) { const value = arr[i]; const bucketIndex = Math.floor(value / divider); // If bucket does not exist // Instantiate a new array inside the buckets array if (!buckets[bucketIndex]) { buckets[bucketIndex] = []; }; buckets[bucketIndex].push(value); }; // Iterate through buckets and perform insertion sort for (let i = 0; i < length; i++) { // Ignore empty buckets if (!buckets[i]) { continue; } buckets[i] = sortInsertion(buckets[i]); }; // Merge and return buckets return buckets.flat(); }; // This bucket sort implementation works with both positive and negative values const sortBucket = (arr) => { const positiveArr = []; const absNegativeArr = []; // Split array into two arrays // An array containing the positive values // And an array containing the absolute value of all the negative values for (let i = 0; i < arr.length; i++) { const value = arr[i]; if (value >= 0) { positiveArr.push(value); } else { absNegativeArr.push(Math.abs(value)); } }; const sortedPositiveArr = sortBucketPositive(positiveArr); const sortedNegativeArr = sortBucketPositive(absNegativeArr).reverse().map(x => -x); return sortedNegativeArr.concat(sortedPositiveArr); }; // Driver Code // Test Cases: // Standard shuffled array // Backwards array // Already sorted array // Empty array // Array of length 1 // Exclusively negative elements // Negative and positive elements // Equal values const arrays = [ [3, 8, 9, 10, 2, 6, 4, 5, 7, 1], [10, 9, 8, 7, 6, 5, 4, 3, 2, 1], [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], [3], [-1, -2, -5, -4, -10, -8, -3, -9, -6, -7], [10, -3, -8, 12, 6], [5, 5, 3, 2] ]; for (let i = 0; i < arrays.length; i++) { const arr = arrays[i]; const sortedArr = sortBucket(arr); console.log(`${arr} => Bucket Sorted = ${sortedArr}!`); }; ================================================ FILE: Algorithms/Sorting/Bucket_Sort/BucketSort.py ================================================ def bucket_sort(input_list): # Find maximum value in the list and use length of the list to determine which value in the list goes into which bucket max_value = max(input_list) size = max_value/len(input_list) # Create n empty buckets where n is equal to the length of the input list buckets_list= [] for x in range(len(input_list)): buckets_list.append([]) # Put list elements into different buckets based on the size for i in range(len(input_list)): j = int (input_list[i] / size) if j != len (input_list): buckets_list[j].append(input_list[i]) else: buckets_list[len(input_list) - 1].append(input_list[i]) # Sort elements within the buckets using Insertion Sort for z in range(len(input_list)): insertion_sort(buckets_list[z]) # Concatenate buckets with sorted elements into a single list final_output = [] for x in range(len (input_list)): final_output = final_output + buckets_list[x] return final_output ================================================ FILE: Algorithms/Sorting/Bucket_Sort/README.md ================================================ ## BUCKET SORT Bucket sort is mainly useful when input is uniformly distributed over a range. In the Bucket Sorting technique, the data items are distributed in a set of buckets. Each bucket can hold a similar type of data. After distributing, each bucket is sorted using another sorting algorithm. After that, all elements are gathered on the main list to get the sorted form. The complexity of the Bucket Sort Technique : 1. Time Complexity: O(n + k) for best case and average case and O(n^2) for the worst case. 2. Space Complexity: O(nk) for worst case **FOR EXAMPLE:** Input: A list of unsorted data: 0.25 0.36 0.58 0.41 0.29 0.22 0.45 0.79 0.01 0.69 Array before Sorting: 0.25 0.36 0.58 0.41 0.29 0.22 0.45 0.79 0.01 0.69 Output: Array after Sorting: 0.01 0.22 0.25 0.29 0.36 0.41 0.45 0.58 0.69 0.79 ================================================ FILE: Algorithms/Sorting/Bucket_Sort/bucket_sort.cpp ================================================ // C++ program to sort an array using bucket sort #include #include #include using namespace std; void bucketSort(float arr[], int n) { vector b[n]; for (int i = 0; i < n; i++) { int bi = n * arr[i]; b[bi].push_back(arr[i]); } for (int i = 0; i < n; i++) sort(b[i].begin(), b[i].end()); int index = 0; for (int i = 0; i < n; i++) for (int j = 0; j < b[i].size(); j++) arr[index++] = b[i][j]; } int main() { float arr[] = { 0.897, 0.565, 0.656, 0.1234, 0.665, 0.3434 }; int n = sizeof(arr) / sizeof(arr[0]); bucketSort(arr, n); cout << "Sorted array is \n"; for (int i = 0; i < n; i++) cout << arr[i] << " "; return 0; } ================================================ FILE: Algorithms/Sorting/Bucket_Sort/bucketsort.php ================================================ = 0 && $fn($key, $elements[$j]) ) { $elements[$j + 1] = $elements[$j]; // shift right $j = $j - 1; } $elements[$j + 1] = $key; } } function comparison_function(&$a, &$b) { return $a < $b; } function bucket_sort(&$elements) { $n = sizeof($elements); $buckets = array(); // Initialize the buckets. for ($i = 0; $i < $n; $i++) { $buckets[$i] = array(); } // Put each element into matched bucket. foreach ($elements as $el) { array_push($buckets[ceil($el/10)], $el); } // Sort elements in each bucket using insertion sort. $j = 0; for ($i = 0; $i < $n; $i++) { // sort only non-empty bucket if (!empty($buckets[$i])) { insertion_sort($buckets[$i]); // Move sorted elements in the bucket into original array. foreach ($buckets[$i] as $el) { $elements[$j++] = $el; } } } } $a = array(-1,0,10,15,-2); bucket_sort($a); // Sort the elements echo "\nSorted Array :\n"; var_dump($a); ?> ================================================ FILE: Algorithms/Sorting/Bucket_Sort/bucketsort.rb ================================================ # arr array to be sorted # n number of elements in array # buckets instance of buckets # m elements in a are supposed between 0..m - 1 # def bucket_sort(arr, n, buckets, m) for j in 0...m buckets[j] = 0 end for i in 0...n buckets[arr[i]] += 1 end i = 0 for j in 0...m for k in 0...buckets[j] arr[i] = j i += 1 end end end ================================================ FILE: Algorithms/Sorting/Bucket_Sort/bucketsortinC.c ================================================ /* * C Program to Sort Array using Bucket Sort */ #include /* Function for bucket sort */ void Bucket_Sort(int array[], int n) { int i, j; int count[n]; for (i = 0; i < n; i++) count[i] = 0; for (i = 0; i < n; i++) (count[array[i]])++; for (i = 0, j = 0; i < n; i++) for(; count[i] > 0; (count[i])--) array[j++] = i; } /* End of Bucket_Sort() */ /* The main() begins */ int main() { int array[100], i, num; printf("Enter the size of array : "); scanf("%d", &num); printf("Enter the %d elements to be sorted:\n",num); for (i = 0; i < num; i++) scanf("%d", &array[i]); printf("\nThe array of elements before sorting : \n"); for (i = 0; i < num; i++) printf("%d ", array[i]); printf("\nThe array of elements after sorting : \n"); Bucket_Sort(array, num); for (i = 0; i < num; i++) printf("%d ", array[i]); printf("\n"); return 0; } ================================================ FILE: Algorithms/Sorting/Circle_Sort/Circle_Sort.c ================================================ #include #include int circle_sort_inner(int *start, int *end) { int *p, *q, t, swapped; if (start == end) return 0; for (swapped = 0, p = start, q = end; p *q) t = *p, *p = *q, *q = t, swapped = 1; return swapped | circle_sort_inner(start, q) | circle_sort_inner(p, end); } void circle_sort(int a[], int n) { while (circle_sort_inner(a, a + (n - 1))) { ; } } int main(void) { int N , i ,j; printf("Enter Size of Array :- \n"); scanf("%d",&N); int A[N]; for(i = 0 ; i < N;i++) scanf("%d",&A[i]); circle_sort(A, N); printf("Sorted Array :- \n"); for(i = 0 ; i < N;i++) printf("%d ",A[i]); printf("\n"); return 0; } ================================================ FILE: Algorithms/Sorting/Circle_Sort/Circle_Sort.cs ================================================ // C# program to implement circle sort using System; class Program { /// /// Main application function. /// public static void Main() { int[] arr = { -32, 41, 6, -2, 16, 0, 23 }; // Calling circle Sort function // to sort the array CircleSort(arr); // Display the sorted array for (int i = 0; i < arr.Length-1; i++) Console.Write(arr[i] + " "); } public static void CircleSort(int[] array) { var swapMade = false; do { swapMade = CircleSort(array, 0, array.Length - 1); } while (swapMade); } /// /// Runs circle sort on provided array /// /// array to be sorted /// Index to start at /// Index to end at private static bool CircleSort(int[] array, int lowIndex, int highIndex) { bool swapMade = false; if (lowIndex == highIndex) return swapMade; var subArrayLength = highIndex - lowIndex; var midPoint = subArrayLength / 2; int currentLowIndex = lowIndex; int currentHighIndex = highIndex; while (currentLowIndex < currentHighIndex) { if (array[currentLowIndex] > array[currentHighIndex]) { var tempLowValue = array[currentLowIndex]; array[currentLowIndex] = array[currentHighIndex]; array[currentHighIndex] = tempLowValue; swapMade = true; } currentLowIndex++; currentHighIndex--; } swapMade |= CircleSort(array, lowIndex, lowIndex + midPoint); swapMade |= CircleSort(array,lowIndex + midPoint + 1, highIndex); return swapMade; } } ================================================ FILE: Algorithms/Sorting/Circle_Sort/Circle_Sort.java ================================================ import java.util.Scanner; class circleSortClass { boolean circleSortInner(int a[], int low, int high) { boolean swapped = false; if (low == high) return false; int l = low, h = high; int mid = (high - low) / 2; boolean left, right; while (l < h) { if (a[l] > a[h]) { swap (a,l,h); swapped = true; } l++; h--; } if (l == h) if (a[l] > a[h + 1]) { swap (a,l,h + 1); swapped = true; } left = circleSortInner (a, low, low + mid); right = circleSortInner (a, low + mid + 1, high); return swapped || left || right; } void circleSort (int a[], int n) { while (circleSortInner (a, 0, n - 1)); } void swap(int arr[],int l,int h) { int temp=arr[l]; arr[l]=arr[h]; arr[h]=temp; } // Driver program public static void main(String[] args) { int arr[]; Scanner sc=new Scanner(System.in); System.out.println("Enter number of elements to be sorted:"); int n=sc.nextInt(); arr = new int[n]; System.out.println("Enter "+n+" elements"); for (int i=0;i 0 end self end private def _circle_sort!(lo, hi, swaps=0) return swaps if lo == hi low, high = lo, hi mid = (lo + hi) / 2 while lo < hi if self[lo] > self[hi] self[lo], self[hi] = self[hi], self[lo] swaps += 1 end lo += 1 hi -= 1 end if lo == hi && self[lo] > self[hi+1] self[lo], self[hi+1] = self[hi+1], self[lo] swaps += 1 end swaps + _circle_sort!(low, mid) + _circle_sort!(mid+1, high) end end ary = [6, 7, 8, 9, 2, 5, 3, 4, 1] puts "before sort: #{ary}" puts " after sort: #{ary.circle_sort!}" ================================================ FILE: Algorithms/Sorting/Circle_Sort/README.md ================================================ ## Circle Sort Circle sort algorithm can be visualized by drawing concentric circles on an array of integers. The elements of the array lying on the same circle diametrically opposite to each other are compared and if found in the wrong order they are swapped. This goes on in a recursive fashion in which the array is divided into sub-arrays on which the above process is repeated until we get pairs of sorted elements which when put together form a sorted array. **In short below two steps are repeated while there are swap operations involved in the steps.** 1. Compare the first element to the last element, then the second element to the second last element, etc. 2. Then split the array in two and recurse until there is only one single element in the array. **For Example** A = {6,5,3,1,8,7,2,4} 1st element is swipped with last similarly 2nd element with second last and the divides the arrays into 2 parts : X = {4,2,3,1} and Y = {8,7,5,6} Again swipping of elements takes place in similar circular manner and divides the arrays in futher 2-2 parts : P = {1,2} Q = {3,4} R = {6,5} S = {7,8} After swipping {6,5} Final output is : A = {1,2,3,4,5,6,7,8} ================================================ FILE: Algorithms/Sorting/Cocktail_Sort/Cocktail_Sort.c ================================================ // C implementation of Cocktail Sort #include //Swap Utility Func void swap(int *a, int *b){ int temp = *a; *a = *b; *b = temp; } // Sorts arrar a[0..n-1] using Cocktail sort void CocktailSort(int a[], int n) { int swapped = 1; int start = 0; int end = n - 1; int i; while (swapped) { swapped = 0; for (i = start; i < end; ++i) { if (a[i] > a[i + 1]) { swap(&a[i], &a[i + 1]); swapped = 1; } } if (!swapped) break; swapped = 0; --end; for (i = end - 1; i >= start; --i) { if (a[i] > a[i + 1]) { swap(&a[i], &a[i + 1]); swapped = 1; } } ++start; } } /* Prints the array */ void printArray(int a[], int n) { int i; for (i = 0; i < n; i++) printf("%d ", a[i]); printf("\n"); } // Driver code int main() { int n,i; int arr[10000]; scanf("%d", &n); for(i=0;i using namespace std; void cocktailSort(int arr[], int n){ bool flag = true; int start = 0, end = n-1; while(flag){ flag = false; for(int i = start; i arr[i+1]){ swap(arr[i], arr[i+1]); flag = true; } } if(!flag){ //if nothing has changed simply break the loop break; } flag = false; end--; //decrease the end pointer for(int i = end - 1; i >= start; i--){ //scan from right to left if(arr[i] > arr[i+1]){ swap(arr[i], arr[i+1]); flag = true; } } start++; } } main() {int n; cin>>n; int a[n]; for(int i=0;i>a[i]; cout << "Sorted Sequence "; cocktailSort(a, n); for(int i = 0; i l[ i + 1 ]) { int temp = l[i]; l[i] = l[i+1]; l[i+1] = temp; k = 1; } } // To check the array status if it is sorted the k is 0 and controls moves out of loop. if (k == 0) { break; } else { k = 1; // the last index is decreased by 1 as largets element in array is sorted in each try. last--; } for (int i = last - 1; i >= first; i--) { // for loop performs the backward sort on the array if (l[ i ] > l[ i + 1 ]) { int temp = l[i]; l[i] = l[i+1]; l[i+1] = temp; k = 1; } } // the first index is increased by 1 after backward sort. first++; }while (k == 1); } void printArray(int a[]) { // this funtion prints the sorted array elements. int n = a.length; for (int i = 0; i < n; i++) System.out.print(a[i] + " "); } public static void main(String[] args) { Cocktailsort ob = new Cocktailsort(); // a denotes the unsorted array. int a[] = { 5, 1, 4, 2, 8, 0, 2 , 5, 3, 1}; // n is the variable used to get the size of array. int n = a.length; // cocktail sort function is called to sort the array. ob.cocktailsort(a,n); // To print the sorted array, printarray is called with parameter a i.e. sorted array ob.printArray(a); } } ================================================ FILE: Algorithms/Sorting/Cocktail_Sort/Cocktail_Sort.py ================================================ # cocktailsort is the function used to sort array # it is just like bubble sort with less complexity comparatively def cocktailsort(l): # first indicates the first index of the array first = 0 # k is the variable that counts the length of the array k = len(l) # last indicates the last index element of the array last = k - 1 # t variable is used to denote if array is sorted after the sorting process. # it is initialised 1 to check if array is sorted after every iteration t = 1 # temp is used as third variable to exchange the values temp = 0 while t != 0: # t is set to 0 when loop conditions comes true # both forward and backward sort runs simultaneously t = 0 # this for loop will do the forward sort # the greatest element after each pass will be at the last index for i in range(first, last, 1): if l[i] < l[i + 1]: continue else: temp = l[i] l[i] = l[i + 1] l[i + 1] = temp t = 1 # t is initialised to 1 to chech if the loop was sorted or not in the forward sort # if value of t was not changed the control will jump off the loop # else the control will move to the backward sort if t == 0: break else: t = 0 # value of last is decreased everytime that shows the greatest element is found after forward sort last -= 1 # the next loop will do the backward sort in the array for i in range(last, first - 1, -1): if l[i] < l[i + 1]: continue else: temp = l[i] l[i] = l[i + 1] l[i + 1] = temp # t is set to 1 to show array has completed one backward sort pass. t = 1 # value of first variable is increased everytime as smallest element is found after backward sort first += 1 # when both the sorting is done the array is returned return l # sample array is taken a = [23, 1, 5, 32, 122, 76, 45] c = cocktailsort(a) print("New Array: ") for i in a: print(i, end=" ") # output-> New Array: 1 5 23 32 45 76 122 ================================================ FILE: Algorithms/Sorting/Cocktail_Sort/README.md ================================================ ## This folder is empty. ================================================ FILE: Algorithms/Sorting/Cocktail_Sort/cocktail_sort.js ================================================ var inputArray = []; var size = prompt('Enetr the size: '); for(var i=0; i nums[i + 1]) { let temp = nums[i]; nums[i] = nums[i + 1]; nums[i+1] = temp; is_Sorted = true; } } if (!is_Sorted) break; is_Sorted = false; for (let j = nums.length - 1; j > 0; j--){ if (nums[j-1] > nums[j]) { let temp = nums[j]; nums[j] = nums[j - 1]; nums[j - 1] = temp; is_Sorted = true; } } } console.log("Sorted array:") console.log(nums); ================================================ FILE: Algorithms/Sorting/Comb_Sort/Comb_Sort.c ================================================ #include #include #include int newGap(int gap) { gap = (gap * 10) / 13; if (gap == 9 || gap == 10) gap = 11; if (gap < 1) gap = 1; return gap; } void combsort(int a[], int aSize) { int gap = aSize; for (;;) { gap = newGap(gap); bool swapped = false; for (int i = 0; i < aSize - gap; i++) { int j = i + gap; if (a[i] > a[j]) { int temp=a[i]; a[i]=a[i + gap]; a[i + gap]=temp; swapped = true; } } if (gap == 1 && !swapped) break; } } int main() { int i , N; printf("Enter Size of Array :-\n"); scanf("%d",&N); int A[N]; printf("Enter Array Elements :-\n"); for(i = 0 ;i < N;i++) scanf("%d",&A[i]); combsort(A , N); printf("Sorted Array :-\n"); for(i = 0 ;i < N;i++) printf("%d ",A[i]); printf("\n"); return 0; } ================================================ FILE: Algorithms/Sorting/Comb_Sort/Comb_Sort.cpp ================================================ include #include using namespace std; void display(int *array, int size){ for(int i = 0; i array[i+gap]){ swap(array[i], array[i+gap]); flag = true; } } } } int main(){ int n; cout << "Enter the number of elements: "; cin >> n; int arr[n]; //create an array with given number of elements cout << "Enter elements:" << endl; for(int i = 0; i> arr[i]; } cout << "Array before Sorting: "; display(arr, n); combSort(arr, n); cout << "Array after Sorting: "; display(arr, n); } ================================================ FILE: Algorithms/Sorting/Comb_Sort/README.md ================================================ ## This folder is empty. ================================================ FILE: Algorithms/Sorting/Comb_Sort/comb.py ================================================ def getNextGap(gap): gap = (gap * 10)/13 if gap < 1: return 1 return gap def combSort(array_to_sort): gap = n = len(array_to_sort) to_swap = 1 while gap !=1 or to_swap == 1: gap = getNextGap(gap) to_swap = 0 for i in range(0, n-gap): if array_to_sort[i] > array_to_sort[i + gap]: array_to_sort[i], array_to_sort[i + gap] = array_to_sort[i + gap], array_to_sort[i] to_swap = 1 array_to_sort = [2,3,24,45,2,11,5,42,24] combSort(array_to_sort) print ("Array after applying comb sort") for i in range(len(array_to_sort)): print (array_to_sort[i]), ================================================ FILE: Algorithms/Sorting/Comb_Sort/comb_sort.rb ================================================ # The gap starts with a large value and shrinks by a factor of 1.3 in every iteration until it reaches the value 1. def comb_sort(arr) gap = arr.length while gap > 1 i = 0 gap /= 1.3 gap = gap.to_i while arr[i + gap] if arr[i] > arr[i + gap] temp = arr[i] arr[i] = arr[i + gap] arr[i + gap] = temp end i += 1 end end arr end ================================================ FILE: Algorithms/Sorting/Counting_Sort/Count_sort.py ================================================ """Count Sort Time Complexity : O(n) Space Complexity : O(n+k), k is range of input data It can work on negative no. also """ def count_sort(ls): mx=max(ls) mi=min(ls) rang=(mx-mi+1) #range of input data count=[0]*rang #count list out=['Null']*len(ls) #output list intialised with NUll values #calculating frequency for i in ls: count[i-mi]=count[i-mi]+1 #cumulative sum of Frequency for i in range(1,len(count)): count[i]=count[i]+count[i-1] #output the data in out array in sorted order for i in range(len(ls)-1,-1,-1): out[count[ls[i]-mi]-1]=ls[i] count[ls[i]-mi]=count[ls[i]-mi]-1 #copy the content of out list to original list for i in range(len(out)): ls[i]=out[i] return ls if __name__ == "__main__": ls=list(map(int,input("Enter the array :: ").split())) ls= count_sort(ls) print(ls) ================================================ FILE: Algorithms/Sorting/Counting_Sort/Counting_Sort.c ================================================ #include #include void countSort(int arr[], int len) { int* output = (int*) malloc(len * sizeof(int)); // Create a count array to store count of inidividul numbers int count[10], i; // Store count of each character for (i = 0; i < len; ++i) ++count[arr[i]]; // Change count[i] so that count[i] contains cumulative count for (i = 1; i < 10; ++i) count[i] += count[i - 1]; // Build the sorted array for (i = 0; i < len; ++i) { output[count[arr[i]] - 1] = arr[i]; --count[arr[i]]; } for (i = 0; i < len; i++) arr[i] = output[i]; } int main() { //Assumption: Array only contains numbers from 0-9 int arr[] = {4,3,2,1,4,2,1,5,6,4}; int n = sizeof(arr)/sizeof(arr[0]); countSort(arr, n); printf("Sorted Array:"); for(int i = 0; i < n; i++) { printf("%d ",arr[i]); } return 0; } ================================================ FILE: Algorithms/Sorting/Counting_Sort/Counting_Sort.cs ================================================ using System; class Program { /// /// Sorts the integers in the given array using the Counting SOrt algorithm. /// public static int[] CountingSort(int[] arrayToSort) { int[] sortedArray = new int[arrayToSort.Length]; int minimumValue = arrayToSort[0]; int maximumValue = arrayToSort[0]; for (int i = 1; i < arrayToSort.Length; i++) { if (arrayToSort[i] < minimumValue) { minimumValue = arrayToSort[i]; } else if (arrayToSort[i] > maximumValue) { maximumValue = arrayToSort[i]; } } int[] counts = new int[((maximumValue - minimumValue) + 1)]; for (int i = 0; i < arrayToSort.Length; i++) { counts[(arrayToSort[i] - minimumValue)] += 1; } counts[0] -= 1; for (int i = 1; i < counts.Length; i++) { counts[i] = (counts[i] + counts[(i - 1)]); } for (int i = arrayToSort.Length - 1; i > -1; i--) { sortedArray[(counts[(arrayToSort[i] - minimumValue)]--)] = arrayToSort[i]; } return sortedArray; } /// /// Main application function. /// static void Main() { int[] arrayToSort; string userInput; Console.WriteLine("Enter the integers that you want to sort as a comma delimited string:"); userInput = Console.ReadLine(); string[] splittedItems = userInput.Split(new string[] { " ", ",", ";", "|" }, StringSplitOptions.RemoveEmptyEntries); if (splittedItems.Length == 0) { Program.ExitAfterInvalidInput(); } arrayToSort = new int[splittedItems.Length]; for (int i = 0; i < splittedItems.Length; i++) { int parsedInteger; if (int.TryParse(splittedItems[i], out parsedInteger) == false) { Program.ExitAfterInvalidInput(); } arrayToSort[i] = parsedInteger; } int[] sortedArray = Program.CountingSort(arrayToSort); Console.WriteLine(); Console.WriteLine(string.Format("Unsorted : {0}", string.Join(", ", userInput))); Console.WriteLine(string.Format("Sorted : {0}", string.Join(", ", sortedArray))); } /// /// Informs the user that an invalid value has been entered and exits the program. /// private static void ExitAfterInvalidInput() { Console.WriteLine("You've entered an invalid value. Exiting..."); Environment.Exit(1); } } ================================================ FILE: Algorithms/Sorting/Counting_Sort/Counting_Sort.java ================================================ package algo_ds_101.Algorithms.Sorting_Algorithms.Counting_Sort; import java.io.*; import java.util.*; class Counting_Sort { public static void main(String[] args) { int n, k = 0, i,j; int []A=new int[15]; int []B=new int[15]; int []C=new int[100]; System.out.println("Enter the number of input : "); Scanner sc = new Scanner(System.in); n=sc.nextInt(); System.out.println("\nEnter the elements to be sorted :\n"); for (i = 1; i <= n; i++) { A[i]=sc.nextInt(); if (A[i] > k) { k = A[i]; } } System.out.println("\n"); for (i = 0; i <= k; i++) C[i] = 0; for (j = 1; j <= n; j++) C[A[j]] = C[A[j]] + 1; for (i = 1; i <= k; i++) C[i] = C[i] + C[i-1]; for (j = n; j >= 1; j--) { B[C[A[j]]] = A[j]; C[A[j]] = C[A[j]] - 1; } System.out.println("The Sorted array is : "); for (i = 1; i <= n; i++) System.out.println(B[i]); } } ================================================ FILE: Algorithms/Sorting/Counting_Sort/Counting_sort.js ================================================ function counting_sort(arrin) { let arrout = new Array(arrin.length) //Creates the output array let arrcount = new Array(arrin.reduce( (prev, cur) => { return biggest = prev > cur ? prev : cur; } )).fill(0) //Creates the counting array (number = index - 1, value = quantity) //Gets the numbers quatities in their respective index arrin.forEach(val => arrcount[val - 1] += 1) let startpos = 0 //Starting position to fill with numbers arrcount.forEach((val, index) => { if (val != 0) { //If this number exists in the input array, its quantity is different than 0 //Fill the output array with the number by its quantity beggining in the starting position //and ending after the number quantity arrout.fill(index + 1, startpos, startpos + val) startpos += val //Changes the starting position to the last known position for the next number } }) return arrout //Return the sorted array } //Example of this algorithm let example_input = [1, 4, 1, 2, 7, 5, 2] let output = counting_sort(example_input) console.log(`${example_input} sorted is ${output}`) //Author -> GuilhermeOliveiraCasagrande ================================================ FILE: Algorithms/Sorting/Counting_Sort/README.md ================================================ ## This folder is empty. ================================================ FILE: Algorithms/Sorting/Counting_Sort/counting_sort.py ================================================ def countingSort(array): size = len(array) output = [0] * size count = [0] * 10 for i in range(0, size): count[array[i]] += 1 for i in range(1, 10): count[i] += count[i - 1] i = size - 1 while i >= 0: output[count[array[i]] - 1] = array[i] count[array[i]] -= 1 i -= 1 for i in range(0, size): array[i] = output[i] data = [4, 2, 2, 8, 3, 3, 1] countingSort(data) print("Sorted Array in Ascending Order: ") print(data) ================================================ FILE: Algorithms/Sorting/Counting_Sort/countingsort.py ================================================ def countSort(arr): output = [0 for i in range(256)] count = [0 for i in range(256)] ans = ["" for _ in arr] for i in arr: count[ord(i)] += 1 for i in range(256): count[i] += count[i-1] for i in range(len(arr)): output[count[ord(arr[i])]-1] = arr[i] count[ord(arr[i])] -= 1 for i in range(len(arr)): ans[i] = output[i] return ans arr = "abfhuervbvnonvioebvoavnioscd" ans = countSort(arr) print("Sorted character array is %s" %("".join(ans)) ) ================================================ FILE: Algorithms/Sorting/Cycle_Sort/CYCLESort.cs ================================================ using System; //MyCode class GFG { // Function sort the array using Cycle sort public static void cycleSort(int[] arr, int n) { // count number of memory writes int writes = 0; // traverse array elements and // put it to on the right place for (int cycle_start = 0; cycle_start <= n - 2; cycle_start++) { // initialize item as starting point int item = arr[cycle_start]; // Find position where we put the item. // We basically count all smaller elements // on right side of item. int pos = cycle_start; for (int i = cycle_start + 1; i < n; i++) if (arr[i] < item) pos++; // If item is already in correct position if (pos == cycle_start) continue; // ignore all duplicate elements while (item == arr[pos]) pos += 1; // put the item to it's right position if (pos != cycle_start) { int temp = item; item = arr[pos]; arr[pos] = temp; writes++; } // Rotate rest of the cycle while (pos != cycle_start) { pos = cycle_start; // Find position where we put the element for (int i = cycle_start + 1; i < n; i++) if (arr[i] < item) pos += 1; // ignore all duplicate elements while (item == arr[pos]) pos += 1; // put the item to it's right position if (item != arr[pos]) { int temp = item; item = arr[pos]; arr[pos] = temp; writes++; } } } } // Driver program to test above function public static void Main() { int[] arr = { 1, 8, 3, 9, 10, 10, 2, 4 }; int n = arr.Length; // Function calling cycleSort(arr, n); Console.Write("After sort : "); for (int i = 0; i < n; i++) Console.Write(arr[i] + " "); } } ================================================ FILE: Algorithms/Sorting/Cycle_Sort/Cyclesort.py ================================================ def cycleSort(array): writes = 0 # Loop through the array to find cycles to rotate. for cycleStart in range(0, len(array) - 1): item = array[cycleStart] # Find where to put the item. pos = cycleStart for i in range(cycleStart + 1, len(array)): if array[i] < item: pos += 1 # If the item is already there, this is not a cycle. if pos == cycleStart: continue # Otherwise, put the item there or right after any duplicates. while item == array[pos]: pos += 1 array[pos], item = item, array[pos] writes += 1 # Rotate the rest of the cycle. while pos != cycleStart: # Find where to put the item. pos = cycleStart for i in range(cycleStart + 1, len(array)): if array[i] < item: pos += 1 # Put the item there or right after any duplicates. while item == array[pos]: pos += 1 array[pos], item = item, array[pos] writes += 1 return writes # driver code arr = [1, 8, 3, 9, 10, 10, 2, 4 ] n = len(arr) cycleSort(arr) print("After sort : ") for i in range(0, n) : print(arr[i], end = \' \') ================================================ FILE: Algorithms/Sorting/Cycle_Sort/README.md ================================================ ## This folder is empty. ================================================ FILE: Algorithms/Sorting/Cycle_Sort/cyclesort.c ================================================ void cycleSort(int arr[], int n) { // count number of memory writes int writes = 0; // traverse array elements and put it to on // the right place for (int cycle_start = 0; cycle_start <= n - 2; cycle_start++) { // initialize item as starting point int item = arr[cycle_start]; // Find position where we put the item. We basically // count all smaller elements on right side of item. int pos = cycle_start; for (int i = cycle_start + 1; i < n; i++) if (arr[i] < item) pos++; // If item is already in correct position if (pos == cycle_start) continue; // ignore all duplicate elements while (item == arr[pos]) pos += 1; // put the item to it's right position if (pos != cycle_start) { swap(item, arr[pos]); writes++; } // Rotate rest of the cycle while (pos != cycle_start) { pos = cycle_start; // Find position where we put the element for (int i = cycle_start + 1; i < n; i++) if (arr[i] < item) pos += 1; // ignore all duplicate elements while (item == arr[pos]) pos += 1; // put the item to it's right position if (item != arr[pos]) { swap(item, arr[pos]); writes++; } } } // Number of memory writes or swaps // cout << writes << endl ; } // Driver program to test above function int main() { int arr[] = { 1, 8, 3, 9, 10, 10, 2, 4 }; int n = sizeof(arr) / sizeof(arr[0]); cycleSort(arr, n); cout << "After sort : " << endl; for (int i = 0; i < n; i++) cout << arr[i] << " "; return 0; } ================================================ FILE: Algorithms/Sorting/Cycle_Sort/stoogesort.java ================================================ import java.io.*; public class stooge { // Function to implement stooge sort static void stoogesort(int arr[], int l, int h) { if (l >= h) return; if (arr[l] > arr[h]) { int t = arr[l]; arr[l] = arr[h]; arr[h] = t; } if (h - l + 1 > 2) { int t = (h - l + 1) / 3; stoogesort(arr, l, h - t); stoogesort(arr, l + t, h); stoogesort(arr, l, h - t); } } public static void main(String args[]) { int arr[] = { 2, 4, 5, 3, 1 }; int n = arr.length; stoogesort(arr, 0, n - 1); for (int i = 0; i < n; i++) System.out.print(arr[i] + " "); } } ================================================ FILE: Algorithms/Sorting/Gnome_Sort/Gnome_Sort.cs ================================================ // C# Program to implement Gnome Sort using System; class GFG { static void gnomeSort(int[] arr, int n) { int index = 0; while (index < n) { if (index == 0) index++; if (arr[index] >= arr[index - 1]) index++; else { int temp = 0; temp = arr[index]; arr[index] = arr[index - 1]; arr[index - 1] = temp; index--; } } return; } // Driver program to test above functions. public static void Main() { int[] arr = { 34, 2, 10, -9 }; // Function calling gnomeSort(arr, arr.Length); Console.Write("Sorted sequence after applying Gnome sort: "); for (int i = 0; i < arr.Length; i++) Console.Write(arr[i] + " "); } } // This code is contributed by Sam007 ================================================ FILE: Algorithms/Sorting/Gnome_Sort/Gnome_Sort.java ================================================ // Java Program to implement Gnome Sort import java.util.Arrays; public class GFG { static void gnomeSort(int arr[], int n) { int index = 0; while (index < n) { if (index == 0) index++; if (arr[index] >= arr[index - 1]) index++; else { int temp = 0; temp = arr[index]; arr[index] = arr[index - 1]; arr[index - 1] = temp; index--; } } return; } // Driver program to test above functions. public static void main(String[] args) { int arr[] = { 34, 2, 10, -9 }; gnomeSort(arr, arr.length); System.out.print("Sorted sequence after applying Gnome sort: "); System.out.println(Arrays.toString(arr)); } } // Code Contributed by Mohit Gupta_OMG ================================================ FILE: Algorithms/Sorting/Gnome_Sort/Gnome_Sort.php ================================================ = $arr[$index - 1]) $index++; else { $temp = 0; $temp = $arr[$index]; $arr[$index] = $arr[$index - 1]; $arr[$index - 1] = $temp; $index--; } } echo "Sorted sequence ", "after Gnome sort: "; for ($i = 0; $i < $n; $i++) echo $arr[$i] . " "; echo "\n"; } // Driver Code $arr = array(34, 2, 10, -9); $n = count($arr); gnomeSort($arr, $n); // This code is contributed // by Sam007 ?> ================================================ FILE: Algorithms/Sorting/Gnome_Sort/Gnome_Sort.py ================================================ # Python program to implement Gnome Sort # A function to sort the given list using Gnome sort def gnomeSort( arr, n): index = 0 while index < n: if index == 0: index = index + 1 if arr[index] >= arr[index - 1]: index = index + 1 else: arr[index], arr[index-1] = arr[index-1], arr[index] index = index - 1 return arr # Driver Code arr = [ 34, 2, 10, -9] n = len(arr) arr = gnomeSort(arr, n) print "Sorted seqquence after applying Gnome Sort :", for i in arr: print i, # Contributed By Harshit Agrawal ================================================ FILE: Algorithms/Sorting/Gnome_Sort/gnomeSort.java ================================================ //Implementation of gnome sort in java import java.util.Arrays; class gnomeSort { void gnomeSort(int[] nums) { int i=1; int j=2; while(i < nums.length) { if ( nums[i-1] <= nums[i] ) { i = j; j++; } else { int tmp = nums[i-1]; nums[i-1] = nums[i]; nums[i--] = tmp; i = (i==0) ? j++ : i; } } } // Method to test above public static void main(String args[]) { gnomeSort ob = new gnomeSort(); int nums[] = {7, -5, 3, 2, 1, 0, 45}; System.out.println("Original Array:"); System.out.println(Arrays.toString(nums)); ob.gnomeSort(nums); System.out.println("Sorted Array"); System.out.println(Arrays.toString(nums)); } } ================================================ FILE: Algorithms/Sorting/Heap_Sort/Heap_Sort.js ================================================ var heapSort = function(array) { var swap = function(array, firstIndex, secondIndex) { var temp = array[firstIndex]; array[firstIndex] = array[secondIndex]; array[secondIndex] = temp; }; var maxHeap = function(array, i) { var l = 2 * i; var r = l + 1; var largest; if (l < array.heapSize && array[l] > array[i]) { largest = l; } else { largest = i; } if (r < array.heapSize && array[r] > array[largest]) { largest = r; } if (largest != i) { swap(array, i, largest); maxHeap(array, largest); } }; var buildHeap = function(array) { array.heapSize = array.length; for (var i = Math.floor(array.length / 2); i >= 0; i--) { maxHeap(array, i); } }; buildHeap(array); for (var i = array.length-1; i >= 1; i--) { swap(array, 0, i); array.heapSize--; maxHeap(array, 0); console.log(a + " "); } }; var a = [6, 5, 3, 1, 8, 7, 2, 4]; heapSort(a); ================================================ FILE: Algorithms/Sorting/Heap_Sort/Heap_Sort.swift ================================================ private extension Int { var parent: Int { return (self - 1) / 2 } var leftChild: Int { return (self * 2) + 1 } var rightChild: Int { return (self * 2) + 2 } } class SortingAlgorithms { private init() {} public static func heapSort(_ array: inout [DataType]) { if array.count < 2 { return } buildHeap(&array) shrinkHeap(&array) } private static func buildHeap(_ array: inout [DataType]) { for index in 1.. 0 && array[child] > array[parent] { swap(child, with: parent, in: &array) child = parent parent = child.parent } } } private static func shrinkHeap(_ array: inout [DataType]) { for index in stride(from: array.count - 1, to: 0, by: -1) { swap(0, with: index, in: &array) var parent = 0 var leftChild = parent.leftChild var rightChild = parent.rightChild while parent < index { var maxChild = -1 if leftChild < index { maxChild = leftChild } else { break } if rightChild < index && array[rightChild] > array[maxChild] { maxChild = rightChild } guard array[maxChild] > array[parent] else { break } swap(parent, with: maxChild, in: &array) parent = maxChild leftChild = parent.leftChild rightChild = parent.rightChild } } } private static func swap(_ firstIndex: Int, with secondIndex: Int, in array: inout [DataType]) { let temp = array[firstIndex] array[firstIndex] = array[secondIndex] array[secondIndex] = temp } } var myArray = [3,4,1,2] SortingAlgorithms.heapSort(&myArray) print(myArray) ================================================ FILE: Algorithms/Sorting/Heap_Sort/Max_heap_sort.cpp ================================================ /* Author : codewithrathi */ /*Problem Statement : Implement Heap sort to sort given set of values using max heap.*/ #include using namespace std; void downadj(int heap[],int i,int n) //down adjust { int l=2*i,r=2*i+1; int max=i; if(lheap[max]) { max=l; } if(rheap[max]) { max=r; } if(max!=i) { swap(heap[i],heap[max]); downadj(heap,max,n); } } void show(int arr[],int n,int x) //print array { if(x==1) { cout<<"ELEMENTS IN MAX HEAP IS AS :\n\n"; } else { cout<<"SORTED ARRAY IS :\n\n"; } for(int i=1;i<=n;i++) { cout<<"At position : "< \t"; cout<1 && heap[i]>heap[i/2]) { swap(heap[i],heap[i/2]); i=i/2; } } void insert(int a[],int x) //construct max heap (Step 1) { int heap[x+1],n,i; heap[0]=0,i=1; while(i<(x+1)) { n=heap[0]; heap[n+1]=a[i]; heap[0]=n+1; upadj(heap,n+1); i++; } show(heap,heap[0],1); n=heap[0]; while(n>1) { swap(heap[1],heap[n]); //(step 2) n--; //(step 3) downadj(heap,1,n); //(step 4) } show(heap,heap[0],2); } int main() { int n; cout<<"****************************************************\n"; cout<<"IMPLEMENTATION OF HEAP SORT TO SORT USING MAX HEAP \n"; cout<<"****************************************************\n"; cout<<"\nEnter the Number of elements in Array ?\n"; cin>>n; int a[n+1]; a[0]=n; for(int i=1;i>a[i]; } insert(a,n); cout<<"\nOPERATION COMPLETED!! THANK YOU"; return 0; } /* ----------------------------------------------------------------------------------------------------------------------------- OUTPUT : **************************************************** IMPLEMENTATION OF HEAP SORT TO SORT USING MAX HEAP **************************************************** Enter the Number of elements in Array ? 11 Enter the element 1 1 Enter the element 2 3 Enter the element 3 5 Enter the element 4 4 Enter the element 5 6 Enter the element 6 13 Enter the element 7 10 Enter the element 8 9 Enter the element 9 8 Enter the element 10 15 Enter the element 11 17 ELEMENTS IN MAX HEAP IS AS : At position : 1 ------> 17 At position : 2 ------> 15 At position : 3 ------> 10 At position : 4 ------> 8 At position : 5 ------> 13 At position : 6 ------> 3 At position : 7 ------> 6 At position : 8 ------> 1 At position : 9 ------> 5 At position : 10 ------> 4 At position : 11 ------> 9 SORTED ARRAY IS : At position : 1 ------> 1 At position : 2 ------> 3 At position : 3 ------> 4 At position : 4 ------> 5 At position : 5 ------> 6 At position : 6 ------> 8 At position : 7 ------> 9 At position : 8 ------> 10 At position : 9 ------> 13 At position : 10 ------> 15 At position : 11 ------> 17 OPERATION COMPLETED!! THANK YOU ...Program finished with exit code 0 Press ENTER to exit console. */ ================================================ FILE: Algorithms/Sorting/Heap_Sort/README.md ================================================ ## Heap Sort Implementations - [Python Implementation](heap-sort.py) ================================================ FILE: Algorithms/Sorting/Heap_Sort/heap-sort.c ================================================ #include void swap(int *a, int *b) { int t=*a; *a=*b; *b=t; } // heapify void heapify(int arr[], int n, int i) { int largest = i; int l = 2*i + 1; int r = 2*i + 2; if (l < n && arr[l] > arr[largest]) largest = l; if (r < n && arr[r] > arr[largest]) largest = r; if (largest != i) { swap(&arr[i], &arr[largest]); heapify(arr, n, largest); } } // heap sort void heapSort(int arr[], int n) { for (int i = n / 2 - 1; i >= 0; i--) heapify(arr, n, i); for (int i=n-1; i>0; i--) { swap(&arr[0], &arr[i]); heapify(arr, i, 0); } } /* A utility function to print array of size n */ void printArray(int arr[], int n) { for (int i=0; i= 0; $i--){ $count = count($array) - 1; build_heap($array, $i, $count); } //swaping of nodes for ($i = (count($array) - 1); $i >= 1; $i--) { $tmp_var = $array[0]; $array [0] = $array [$i]; $array [$i] = $tmp_var; build_heap($array, 0, $i - 1); } } $array = array(9,8,7,6,5,4,3,2,1,0,10,1000,0); heap_sort($array); print_r($array); ?> ================================================ FILE: Algorithms/Sorting/Heap_Sort/heap-sort.py ================================================ ''' Input format: contents of the array Output format: Sorted Array Time Complexity: O(NlogN) Space Complexity: O(N) **Sample Input Output** Enter the elements of the array: 2 3 1 4 5 6 8 9 Sorted array is: 1 2 3 4 5 6 8 9 ''' # Python program for implementation of Heap Sort # Maintaining max heap def heapify(arr, n, index): largest = index # Initialize largest as root left = 2 * index + 1 # left = 2 * index + 1 right = 2 * index + 2 # right = 2 * index + 2 # See if left child of root exists and is # greater than root if left < n and arr[index] < arr[left]: largest = left # See if right child of root exists and is # greater than root if right < n and arr[largest] < arr[right]: largest = right # Change root, if needed if largest != index: arr[index],arr[largest] = arr[largest],arr[index] # swap # recursively build max heap heapify(arr, n, largest) # The main function to sort an array of given size def heapSort(arr): n = len(arr) # Build a maxheap. # Since last parent will be at ((n//2)-1) we can start at that location. for i in range(n // 2 - 1, -1, -1): heapify(arr, n, i) # One by one extract elements for i in range(n-1, 0, -1): arr[i], arr[0] = arr[0], arr[i] # swap heapify(arr, i, 0) # Driver code to test above arr = list(map(int,input("Enter the elements of the array: ").split())) heapSort(arr) n = len(arr) print ("Sorted array is: ",end=" ") print(*arr) ================================================ FILE: Algorithms/Sorting/Heap_Sort/heap-sort.rb ================================================ def heap_sort(array) size = array.length #Adding an empty element at beginning of array to be the root root_array = [nil] + array i = size / 2 while i > 0 do heapify(root_array, i, size) i -= 1 end while size > 1 do root_array[1], root_array[size] = root_array[size], root_array[1] size -= 1 heapify(root_array, 1, size) end root_array.shift #getting rid of the initial nil root_array end def heapify(a, parent, limit) root = a[parent] while (child_node = 2 * parent) <= limit do if child_node < limit and a[child_node] < a[child_node + 1] child_node += 1 end break if root >= a[child_node] a[parent] = a[child_node] parent = child_node end a[parent] = root end ================================================ FILE: Algorithms/Sorting/Heap_Sort/heap_sort.cpp ================================================ // C++ program for implementation of Heap Sort #include using namespace std; void heapify(int arr[], int n, int i) { int largest = i; int l = 2*i +1; int r = 2*i +2; if(l < n && arr[l] > arr[largest]) largest = l; if(r < n && arr[r] > arr[largest]) largest = r; if(largest != i) { swap(arr[i], arr[largest]); heapify(arr, n, largest); } } void heapSort(int arr[], int n) { for (int i = n/2 - 1; i>=0; i--) heapify(arr, n, i); for (int i=n-1; i>=0; i--) { swap(arr[0], arr[i]); heapify(arr, i, 0); } } void printArray(int arr[], int n) { for (int i=0; i array[max] { max = l } if r < n && array[r] > array[max] { max = r } if max != i { array[i], array[max] = array[max], array[i] heapify(array, n, max) } } // HeapSort will modify/sorted the original array func HeapSort(array []int, n int) { for i := n/2 - 1; i >= 0; i-- { heapify(array, n, i) } for i := n - 1; i >= 0; i-- { array[0], array[i] = array[i], array[0] heapify(array, i, 0) } } func main() { array := []int{1, 4, 3, 8, 12, 1, 9, 10, 3, 11, 0, 3} HeapSort(array, len(array)) for _, values := range array { fmt.Printf("%d ", values) } fmt.Println() } ================================================ FILE: Algorithms/Sorting/Heap_Sort/heap_sort.java ================================================ // Java program for implementation of Heap Sort public class HeapSort { public void sort(int arr[]) { int n = arr.length; for (int i = n / 2 - 1; i >= 0; i--) heapify(arr, n, i); for (int i=n-1; i>0; i--) { int temp = arr[0]; arr[0] = arr[i]; arr[i] = temp; heapify(arr, i, 0); } } void heapify(int arr[], int n, int i) { int largest = i; int l = 2*i + 1; int r = 2*i + 2; if (l < n && arr[l] > arr[largest]) largest = l; if (r < n && arr[r] > arr[largest]) largest = r; if (largest != i) { int swap = arr[i]; arr[i] = arr[largest]; arr[largest] = swap; heapify(arr, n, largest); } } static void printArray(int arr[]) { int n = arr.length; for (int i=0; i nxt_element) and (j >= 0): InputList[j+1] = InputList[j] j=j-1 InputList[j+1] = nxt_element list = [19,2,31,45,30,11,121,27] insertion_sort(list) print(list) ================================================ FILE: Algorithms/Sorting/Insertion_Sort/Insertion Sort.cpp ================================================ // C++ program for insertion sort #include using namespace std; /* Function to sort an array using insertion sort*/ void insertionSort(int arr[], int n) { int i, key, j; for (i = 1; i < n; i++) { key = arr[i]; j = i - 1; /* Move elements of arr[0..i-1], that are greater than key, to one position ahead of their current position */ while (j >= 0 && arr[j] > key) { arr[j + 1] = arr[j]; j = j - 1; } arr[j + 1] = key; } } // A utility function to print an array of size n void printArray(int arr[], int n) { int i; for (i = 0; i < n; i++) cout << arr[i] << " "; cout << endl; } /* Driver code */ int main() { int arr[] = { 5, 13, 11, 15, 16 }; int n = sizeof(arr) / sizeof(arr[0]); insertionSort(arr, n); printArray(arr, n); return 0; } ================================================ FILE: Algorithms/Sorting/Insertion_Sort/InsertionSort.java ================================================ // Java program for implementation of Insertion Sort class InsertionSort { // Function to sort the array void sort(int arr[]) { int n = arr.length; for (int i = 1; i < n; ++i) { int key = arr[i]; int j = i - 1; while (j >= 0 && arr[j] > key) { arr[j + 1] = arr[j]; j = j - 1; } arr[j + 1] = key; } } // Function to print array of size n. static void printArray(int arr[]) { int n = arr.length; for (int i = 0; i < n; ++i) System.out.print(arr[i] + " "); System.out.println(); } // Driver method public static void main(String args[]) { int arr[] = { 5, 4, 3, 2, 1 }; InsertionSort obj = new InsertionSort(); //Creating object of the class obj.sort(arr); // Calling sort function printArray(arr); // Call function that print array } } ================================================ FILE: Algorithms/Sorting/Insertion_Sort/InsertionSort.py ================================================ def insertionSort(arr): for i in range(1, len(arr)): key = arr[i] # Move elements of arr[0..i-1], that are greater than key, # to one position ahead of their current position j = i-1 while j >=0 and key < arr[j] : arr[j+1] = arr[j] j -= 1 arr[j+1] = key # main arr = ['t','u','t','o','r','i','a','l'] insertionSort(arr) print ("The sorted array is:") for i in range(len(arr)): print (arr[i]) ================================================ FILE: Algorithms/Sorting/Insertion_Sort/InsertionSort.scala ================================================ package com.dsa.scala object InsertionSort { def main (args: Array[String]): Unit = { val intArray = Array(20, 35, -15, 7, 55, 1, -22) println("**********InsertionSort Scala**********") println("Unsorted array") var i = 0 for (firstUnsortedIndex <- 1 until intArray.length by 1) { var newElement = intArray(firstUnsortedIndex) i = firstUnsortedIndex for (i <- firstUnsortedIndex until 0 by 1 if intArray(i - 1) > newElement) { intArray(i) = intArray(i - 1) } intArray(i) = newElement } println("Sorted array - By Insertion sort") insertionSort(intArray.toList).foreach(println) } def insertionSort[A] (la: List[A])(implicit ord: Ordering[A]): List[A] = { println("inside insertionSort method") def insert (la: List[A], a: A) = { val (h, t) = la.span(ord.lt(_, a)) h ::: (a :: t) } la./:(List[A]()) { (acc, a) => insert(acc, a) } } } ================================================ FILE: Algorithms/Sorting/Insertion_Sort/Insertion_Sort.cpp ================================================ //Insertoion sort presumes the the array till curr index is sorted and places the curr element in the sort part at its correct place #include using namespace std; void insertionsort(int arr[],int len){ for(int curr=1;curr=0 and arr[pos]>key){ //while end if array finishes or we encounter element smaller than curr arr[pos+1]=arr[pos]; //shifting element at pos by 1 if its bigger than element at curr pos--; } arr[pos+1]=key; //pos is the index of element smaller than curr therefore we place key at pos+1 } } int main(){ int len; cout<<"Enter the number of elements to sort: "; cin>>len; int arr[len]={0}; cout<<"Enter the elements to sort: \n"; for(int idx=0;idx>arr[idx]; } insertionsort(arr,len); cout<<"Sorted array: "; for(int idx=0;idx Int { var left = min var right = max while left <= right { let middle = left + (right-left)/2 if (value == numbers[middle]){ return middle } if (value < numbers[middle]) { right = middle - 1 } else { left = middle+1 } } return left } //Insertion Sort Function func insertionSort(input_array: [Int]) -> [Int] { var sorted_array = input_array for i in 0.. using namespace std; void Insertion_sort(int a[],int n){ for(int i = 1; i <= n - 1; i++){ int e = a[i]; int j = i -1; while(j >= 0 and a[j]> e){ a[j+1] = a[j]; j = j - 1; } a[j+1] = e; } } int main(){ int n; cin>>n; int arr[1000]; for(int i = 0; i < n; i++){ cin>>arr[i]; } Insertion_sort(arr,n); for(int i = 0; i < n; i++){ cout<= 0 and k < a[j]: a[j + 1] = a[j] j -= 1 a[j + 1] = k if __name__ == "__main__": n = int(input("Enter the number of elements in the array: ")) lst = list(map(int, input("\nEnter the numbers : ").strip().split()))[:n] print("Before sorted: ", end="\n") print(lst) insertion_sort(lst) print("After sorting: ", end="\n") print(lst) except EOFError as e: print(end="") # end code # contributer -> souvick roy ================================================ FILE: Algorithms/Sorting/Insertion_Sort/insertion_sort.ts ================================================ /** *This class contians information to sort a number array using insertion sort. * *@class InsertionSort *@constructor **/ export class InsertionSort{ constructor(){ } /** *This method contains logic to sort a partially sorted array in O(n) time. *@method sort *@param {Array} arr The array to be sorted. *@return {Array} arr THe sorted array. **/ public sort(arr:number[]):number[]{ if(arr!==undefined){ for(let i:number = 0; i< arr.length; i++){ let j = i-1; let key = arr[i]; while(j>-1 && arr[j]>key){ arr[j+1] = arr[j]; j--; } arr[j+1] = key; } return arr; } } } ================================================ FILE: Algorithms/Sorting/Merge_Sort/Application of Merge Sort/Count_Inversions.c ================================================ #include #include long long int merge(long long int a[], long long int start, long long int mid, long long int end) { long long int i=start,j=mid,k=0; long long int temp[end-start+1]; long long int count=0,len=mid; while(i using namespace std; long long merge(long long a[], long long start, long long mid, long long end) { long long i=start,j=mid,k=0; long long temp[end-start+1]; long long count=0,len=mid; while(i>n; long long a[n]; for(int i=0; i>a[i]; long long ans=merge_sort(a,0,n-1); cout< #define max 10 int a[11] = { 23, 34, 17, 24, 29, 31, 33, 35, 42, 54, 0 }; int b[10]; //merging function void merging(int low, int mid, int high) { int l1, l2, i; for(l1 = low, l2 = mid + 1, i = low; l1 <= mid && l2 <= high; i++) { if(a[l1] <= a[l2]) b[i] = a[l1++]; else b[i] = a[l2++]; } while(l1 <= mid) b[i++] = a[l1++]; while(l2 <= high) b[i++] = a[l2++]; for(i = low; i <= high; i++) a[i] = b[i]; } //sorting part void sort(int low, int high) { int mid; if(low < high) { mid = (low + high) / 2; sort(low, mid); sort(mid+1, high); merging(low, mid, high); } else { return; } } int main() { int i; printf(" Before sorting\n"); for(i = 0; i <= max; i++) printf("%d ", a[i]); sort(0, max); printf("\nAfter sorting\n"); for(i = 0; i <= max; i++) printf("%d ", a[i]); } ================================================ FILE: Algorithms/Sorting/Merge_Sort/MERGE_SORT.cpp ================================================ #include using namespace std; // Merge two subarrays L and M into arr void merge(int arr[], int p, int q, int r) { // Create L ← A[p..q] and M ← A[q+1..r] int n1 = q - p + 1; int n2 = r - q; int L[n1], M[n2]; for (int i = 0; i < n1; i++) L[i] = arr[p + i]; for (int j = 0; j < n2; j++) M[j] = arr[q + 1 + j]; // Maintain current index of sub-arrays and main array int i, j, k; i = 0; j = 0; k = p; // Until we reach either end of either L or M, pick larger among // elements L and M and place them in the correct position at A[p..r] while (i < n1 && j < n2) { if (L[i] <= M[j]) { arr[k] = L[i]; i++; } else { arr[k] = M[j]; j++; } k++; } // When we run out of elements in either L or M, // pick up the remaining elements and put in A[p..r] while (i < n1) { arr[k] = L[i]; i++; k++; } while (j < n2) { arr[k] = M[j]; j++; k++; } } // Divide the array into two subarrays, sort them and merge them void mergeSort(int arr[], int l, int r) { if (l < r) { // m is the point where the array is divided into two subarrays int m = l + (r - l) / 2; mergeSort(arr, l, m); mergeSort(arr, m + 1, r); // Merge the sorted subarrays merge(arr, l, m, r); } } // Print the array void printArray(int arr[], int size) { for (int i = 0; i < size; i++) cout << arr[i] << " "; cout << endl; } // Driver program int main() { int arr[] = {6, 5, 12, 10, 9, 1}; int size = sizeof(arr) / sizeof(arr[0]); mergeSort(arr, 0, size - 1); cout << "Sorted array: \n"; printArray(arr, size); return 0; } ================================================ FILE: Algorithms/Sorting/Merge_Sort/MERGE_SORT.java ================================================ /* Java program for Merge Sort */ class MergeSort { // Merges two subarrays of arr[]. // First subarray is arr[l..m] // Second subarray is arr[m+1..r] void merge(int arr[], int l, int m, int r) { // Find sizes of two subarrays to be merged int n1 = m - l + 1; int n2 = r - m; /* Create temp arrays */ int L[] = new int[n1]; int R[] = new int[n2]; /*Copy data to temp arrays*/ for (int i = 0; i < n1; ++i) L[i] = arr[l + i]; for (int j = 0; j < n2; ++j) R[j] = arr[m + 1 + j]; /* Merge the temp arrays */ // Initial indexes of first and second subarrays int i = 0, j = 0; // Initial index of merged subarry array int k = l; while (i < n1 && j < n2) { if (L[i] <= R[j]) { arr[k] = L[i]; i++; } else { arr[k] = R[j]; j++; } k++; } /* Copy remaining elements of L[] if any */ while (i < n1) { arr[k] = L[i]; i++; k++; } /* Copy remaining elements of R[] if any */ while (j < n2) { arr[k] = R[j]; j++; k++; } } // Main function that sorts arr[l..r] using // merge() void sort(int arr[], int l, int r) { if (l < r) { // Find the middle point int m = (l + r) / 2; // Sort first and second halves sort(arr, l, m); sort(arr, m + 1, r); // Merge the sorted halves merge(arr, l, m, r); } } /* A utility function to print array of size n */ static void printArray(int arr[]) { int n = arr.length; for (int i = 0; i < n; ++i) System.out.print(arr[i] + " "); System.out.println(); } // Driver method public static void main(String args[]) { int arr[] = { 12, 11, 13, 5, 6, 7 }; System.out.println("Given Array"); printArray(arr); MergeSort ob = new MergeSort(); ob.sort(arr, 0, arr.length - 1); System.out.println("\nSorted array"); printArray(arr); } } /* This code is contributed by Abhay Bhatt */ ================================================ FILE: Algorithms/Sorting/Merge_Sort/MERGE_SORT.js ================================================ function mergeSort(array,half = array.length/2){ if(array.length < 2){ return array } const left = array.splice(0,half); //left part of array return merger(mergeSort(left),mergeSort(array)) } function merger(left,right){ const arr = []; while(left.length && right.length){ if(left[0] < right [0]){ arr.push(left.shift()) }else{ arr.push(right.shift()) } } return [...arr,...left,...right]; } console.log(mergeSort([3,6,7,3,4,5,7,8,1])); ================================================ FILE: Algorithms/Sorting/Merge_Sort/MergeSort.scala ================================================ package com.dsa.scala.functionalDataStructuresAndAlgorithms object MergeSortGeneric { def main (args: Array[String]): Unit = { val inputList = List(1, 9, 2, 7, 3, 6, 8, 5) val mergetSort_ASC_int = mergeSort((x: Int, y: Int) => x < y) _ val mergetSort_DESC_int = mergeSort((x: Int, y: Int) => x > y) _ val mergetSort_ASC_Double = mergeSort((x: Double, y: Double) => x < y) _ val mergetSort_DESC_Double = mergeSort((x: Double, y: Double) => x > y) _ val sortedList_ASC = mergetSort_ASC_int(inputList) val sortedList_DESC = mergetSort_DESC_int(inputList) println(sortedList_ASC) // List(1, 2, 3, 5, 6, 7, 8, 9) println(sortedList_DESC) // List(9, 8, 7, 6, 5, 3, 2, 1) val inputListDouble = inputList.map(_.toDouble) val sortedList_ASC_Double = mergetSort_ASC_Double(inputListDouble) val sortedList_DESC_Double = mergetSort_DESC_Double(inputListDouble) println(sortedList_ASC_Double) // List(1.0, 2.0, 3.0, 5.0, 6.0, 7.0, 8.0, 9.0) println(sortedList_DESC_Double) // List(9.0, 8.0, 7.0, 6.0, 5.0, 3.0, 2.0, 1.0) } def mergeSort[T] (min: (T, T) => Boolean)(ls: List[T]): List[T] = { def merge (xs: List[T], ys: List[T]): List[T] = { (xs, ys) match { case (_, Nil) => xs case (Nil, _) => ys case (x :: xs1, y :: ys1) => if (min(x, y)) x :: merge(xs1, ys) else y :: merge(xs, ys1) } } val n = ls.length / 2 if (n == 0) ls else { val (ys, zs) = ls.splitAt(n) merge(mergeSort(min)(ys), mergeSort(min)(zs)) } } } ================================================ FILE: Algorithms/Sorting/Merge_Sort/Non_recursive_merge_sort.cpp ================================================ #include #include #include #include void merge(int *a, int size, int low, int high, int mid) { int i, j, k; int *c = new int[size]; i = low; k = low; j = mid + 1; while (i <= mid && j <= high) { if (a[i] < a[j]) { c[k] = a[i]; k++; i++; } else { c[k] = a[j]; k++; j++; } } while (i <= mid) { c[k] = a[i]; k++; i++; } while (j <= high) { c[k] = a[j]; k++; j++; } for (i = low; i < k; i++) { a[i] = c[i]; } } void mergeSortIterative(int* arr, int size, int low, int high) { int mid; for (int i = 2; i <= size; i *= 2) { for (int x = 0; x < size; x += i) { int newHigh; if (x + i - 1 < size - 1) { newHigh = x + i - 1; } else { newHigh = size - 1; } mid = (newHigh - low) / 2; merge(arr, size, x, newHigh, mid); } } return ; } int main() { std::ifstream inFile; std::string inFileName; int count = 0; int *myIterative; int index; int nums = 0; // Get filename from user std::cout << "Enter the input filename: " << std::endl; std::cin >> inFileName; // Open input file inFile.open(inFileName.c_str(), std::ios::app); // process input file while (!inFile) { // the file could not be found and opened //display error message std::cout << "Could not access file" << std::endl; std::cin >> inFileName; } while (inFile >> index) { count++; } myIterative = new int[count]; inFile.clear(); inFile.seekg(0, inFile.beg); while (inFile >> index) { myIterative[nums] = index; nums++; } for (int x = 0; x < nums; x++) { std::cout << "Given integers Iterative: " << myIterative[x] << std::endl; std::cout << x << std::endl; } mergeSortIterative(myIterative, nums, 0, nums - 1); for (int x = 0; x < nums; x++) { std::cout << "Sorted Iterative Array: " << myIterative[x] << std::endl; std::cout << x << std::endl; } return 0; } ================================================ FILE: Algorithms/Sorting/Merge_Sort/README.md ================================================ ## Merge Sort Merge sorting is a type of sorting technique in which an array is divided in two halves till its size become one and then it merges the two sorted halves. For example: [5 8 4 6 2] -> [5 8 4] [6 2] -> [5 8] [4] [6] [2] -> [5] [8] [4] [6] [2] -> [4 5 6 8] [2] -> [2 4 5 6 8] ================================================ FILE: Algorithms/Sorting/Merge_Sort/mergeSort.py ================================================ # Python program for implementation of MergeSort def mergeSort(arr): if len(arr) >1: mid = len(arr)//2 # Finding the mid of the array L = arr[:mid] # Dividing the array elements R = arr[mid:] # into 2 halves mergeSort(L) # Sorting the first half mergeSort(R) # Sorting the second half i = j = k = 0 # Copy data to temp arrays L[] and R[] while i < len(L) and j < len(R): if L[i] < R[j]: arr[k] = L[i] i+= 1 else: arr[k] = R[j] j+= 1 k+= 1 # Checking if any element was left while i < len(L): arr[k] = L[i] i+= 1 k+= 1 while j < len(R): arr[k] = R[j] j+= 1 k+= 1 # Code to print the list def printList(arr): for i in range(len(arr)): print(arr[i], end =" ") print() # driver code to test the above code if __name__ == '__main__': arr = [5, 11, 53, 15, 67, 7] print ("Input array is:", end ="\n") printList(arr) mergeSort(arr) print("Sorted array is: ", end ="\n") printList(arr) ================================================ FILE: Algorithms/Sorting/Merge_Sort/merge_Sort.rb ================================================ def merge_sort(unsorted_array) # if array only has one element or fewer there is nothing to do if unsorted_array.length <=1 return unsorted_array else # dividing and then merge-sorting the halves mid = unsorted_array.length/2 first_half = merge_sort(unsorted_array.slice(0...mid)) second_half = merge_sort(unsorted_array.slice(mid...unsorted_array.length)) merge(first_half, second_half) end end def merge(left_array, right_array) sorted_array = [] # If either array is empty we don't need to compare them while !left_array.empty? && !right_array.empty? do # we are shifting out the compared/used values so we don't repeat if left_array[0] < right_array[0] sorted_array.push(left_array.shift) else sorted_array.push(right_array.shift) end end #concat appends elements of another array to an array return sorted_array.concat(left_array).concat(right_array) end ================================================ FILE: Algorithms/Sorting/Merge_Sort/mergesort.sh ================================================ #!/bin/bash MergeSort (){ local a=("$@") if [ ${#a[@]} -eq "1" ] then r=("${a[@]}") echo "${r[@]}" elif [[ "${#a[@]}" -eq "2" ]] then if [[ "${a[0]}" -gt "${a[1]}" ]] then local t=("${a[1]}" "${a[0]}") echo "${t[@]}" else r=("${a[@]}") echo "${r[@]}" fi else local p=$(( ${#a[@]} / 2 )) local m1=() m1=($(MergeSort "${a[@]::p}")) local m2=() m2=($(MergeSort "${a[@]:p}")) local ret=() while true do if [ ${#m1[@]} -gt 0 ] && [ ${#m2[@]} -gt 0 ] then if [ "${m1[0]}" -le "${m2[0]}" ] then ret=("${ret[@]}" "${m1[0]}") m1=("${m1[@]:1}") else ret=("${ret[@]}" "${m2[0]}") m2=("${m2[@]:1}") fi elif [ "${#m1[@]}" -gt 0 ] then ret=("${ret[@]}" "${m1[@]}") unset m1 elif [ "${#m2[@]}" -gt 0 ] then ret=("${ret[@]}" "${m2[@]}") unset m2 else break fi done echo "${ret[@]}" fi } a=(5 9 1 3 4 6 6 3 2) MergeSort "${a[@]}" ================================================ FILE: Algorithms/Sorting/Merge_Sort/non_recursive_merge_sort.c ================================================ #include #include #include #include struct Element{ // this is the structure of element to be stored in stack int left; //left index of array int right; //right index of array int state; //state = 0 represents the array needs to be split and 1 represents that to merge }; struct Stack{ //Structure for Stack int top; struct Element array[10000]; //array of Element }; int IsEmpty(struct Stack *stack){ if(stack->top == -1){ return 1; } return 0; } int Push(struct Stack *stack, struct Element val){ // val is of type struct Element stack->top += 1; stack->array[stack->top] = val; return 0; } struct Element Top(struct Stack *stack){ if(IsEmpty(stack)){ struct Element empty={0,0,0}; // to return an empty element return empty; // this if condition will never come true because only for } // non empty stacks, we will call Top and Pop. else{ return stack->array[stack->top]; } } struct Element Pop(struct Stack *stack){ if(stack->top == -1){ struct Element empty= {0,0,0}; return empty; } else{ struct Element item = stack->array[stack->top] ; stack->top -= 1; return item; } } void merge(int* A,int* B, int n, int left, int mid, int right){ //This is the basic merge function, no change int p = left, q=mid+1 ,r =left; while(r<=right){ if(p<=mid && q<=right){ if(A[p]<=A[q]){ B[r]=A[p]; r=r+1, p=p+1; continue; } else{ B[r] =A[q]; r=r+1, q=q+1; continue; } } else if(p<=mid && q>right){ B[r]= A[p]; r=r+1, p=p+1; continue; } else if(p>mid && q<=right){ B[r]=A[q]; r=r+1, q=q+1; continue; } } for(int i=left; i<=right;i++){ A[i]=B[i]; } } void merge_sort(int* A,int* B, int n){ //we will call this function only once for an array struct Stack stack; //therefore new stack is defined once for every array stack.top = -1; struct Element parent_array = {0,n-1,0}; //parent_array represents the array with left = 0, right = n-1 Push(&stack, parent_array); while(!IsEmpty(&stack)){ struct Element current_array = Pop(&stack); //current_array is the one we are working with if(current_array.state == 0){ //the array needs to be split current_array.state =1; //the state is changed to 1 meaning we have consdered state=0 int mid = (current_array.left +current_array.right)/2; if(current_array.right <= current_array.left){ //for singleton do nothing continue; } struct Element lchild_array = {current_array.left, mid, 0};//lchild_array and rchild_array are two subarrays struct Element rchild_array = {mid+1, current_array.right, 0}; // of current_array Push(&stack, current_array); Push(&stack, rchild_array); Push(&stack, lchild_array); } else{ //if state = 1, we need to merge the subarray int mid = (current_array.left +current_array.right)/2; merge(A,B,n, current_array.left, mid, current_array.right); } } } int main() { int t; scanf("%d",&t); for(int i=0; i len(a)-1]) merge(a, left, mid, right) left = left + current_size*2 current_size = 2 * current_size def merge(a, l, m, r): n1 = m - l + 1 n2 = r - m L = [0] * n1 R = [0] * n2 for i in range(0, n1): L[i] = a[l + i] for i in range(0, n2): R[i] = a[m + i + 1] i, j, k = 0, 0, l while i < n1 and j < n2: if L[i] > R[j]: a[k] = R[j] j += 1 else: a[k] = L[i] i += 1 k += 1 while i < n1: a[k] = L[i] i += 1 k += 1 while j < n2: a[k] = R[j] j += 1 k += 1 a = list(map(int, input("Enter the numbers: ").split())) print("Given list is ") print(a) mergeSort(a) print("Sorted list is ") print(a) ================================================ FILE: Algorithms/Sorting/Merge_Sort_on_Doubly_Linked_List/Mergesort_doubly.c ================================================ #include #include struct Node { int data; struct Node *next, *prev; }; struct Node *split(struct Node *head); // Function to merge two linked lists struct Node *merge(struct Node *first, struct Node *second) { // If first linked list is empty if (!first) return second; // If second linked list is empty if (!second) return first; // Pick the smaller value if (first->data < second->data) { first->next = merge(first->next,second); first->next->prev = first; first->prev = NULL; return first; } else { second->next = merge(first,second->next); second->next->prev = second; second->prev = NULL; return second; } } // Function to do merge sort struct Node *mergeSort(struct Node *head) { if (!head || !head->next) return head; struct Node *second = split(head); // Recur for left and right halves head = mergeSort(head); second = mergeSort(second); // Merge the two sorted halves return merge(head,second); } // A utility function to insert a new node at the // beginning of doubly linked list void insert(struct Node **head, int data) { struct Node *temp = (struct Node *)malloc(sizeof(struct Node)); temp->data = data; temp->next = temp->prev = NULL; if (!(*head)) (*head) = temp; else { temp->next = *head; (*head)->prev = temp; (*head) = temp; } } // A utility function to print a doubly linked list in // both forward and backward directions void print(struct Node *head) { struct Node *temp = head; printf("Forward Traversal using next poitner\n"); while (head) { printf("%d ",head->data); temp = head; head = head->next; } printf("\nBackward Traversal using prev pointer\n"); while (temp) { printf("%d ", temp->data); temp = temp->prev; } } // Utility function to swap two integers void swap(int *A, int *B) { int temp = *A; *A = *B; *B = temp; } // Split a doubly linked list (DLL) into 2 DLLs of // half sizes struct Node *split(struct Node *head) { struct Node *fast = head,*slow = head; while (fast->next && fast->next->next) { fast = fast->next->next; slow = slow->next; } struct Node *temp = slow->next; slow->next = NULL; return temp; } // Driver program int main(void) { struct Node *head = NULL; insert(&head,5); insert(&head,20); insert(&head,4); insert(&head,3); insert(&head,30); insert(&head,10); head = mergeSort(head); printf("\n\nLinked List after sorting\n"); print(head); return 0; } ================================================ FILE: Algorithms/Sorting/Merge_Sort_on_Doubly_Linked_List/Mergesort_doubly.cpp ================================================ #include using namespace std; class Node { public: int data; Node *next, *prev; }; Node *split(Node *head); Node *merge(Node *first, Node *second) { if (!first) return second; if (!second) return first; if (first->data < second->data) { first->next = merge(first->next,second); first->next->prev = first; first->prev = NULL; return first; } else { second->next = merge(first,second->next); second->next->prev = second; second->prev = NULL; return second; } } Node *mergeSort(Node *head) { if (!head || !head->next) return head; Node *second = split(head); head = mergeSort(head); second = mergeSort(second); return merge(head,second); } void insert(Node **head, int data) { Node *temp = new Node(); temp->data = data; temp->next = temp->prev = NULL; if (!(*head)) (*head) = temp; else { temp->next = *head; (*head)->prev = temp; (*head) = temp; } } void print(Node *head) { Node *temp = head; cout<<"Forward Traversal using next poitner\n"; while (head) { cout << head->data << " "; temp = head; head = head->next; } cout << "\nBackward Traversal using prev pointer\n"; while (temp) { cout << temp->data << " "; temp = temp->prev; } } void swap(int *A, int *B) { int temp = *A; *A = *B; *B = temp; } Node *split(Node *head) { Node *fast = head,*slow = head; while (fast->next && fast->next->next) { fast = fast->next->next; slow = slow->next; } Node *temp = slow->next; slow->next = NULL; return temp; } int main(void) { Node *head = NULL; insert(&head, 5); insert(&head, 20); insert(&head, 4); insert(&head, 3); insert(&head, 30); insert(&head, 10); head = mergeSort(head); cout << "Linked List after sorting\n"; print(head); return 0; } ================================================ FILE: Algorithms/Sorting/Merge_Sort_on_Doubly_Linked_List/Mergesort_doubly.java ================================================ class LinkedList { static Node head; static class Node { int data; Node next, prev; Node(int d) { data = d; next = prev = null; } } void print(Node node) { Node temp = node; System.out.println("Forward Traversal using next pointer"); while (node != null) { System.out.print(node.data + " "); temp = node; node = node.next; } System.out.println("\nBackward Traversal using prev pointer"); while (temp != null) { System.out.print(temp.data + " "); temp = temp.prev; } } Node split(Node head) { Node fast = head, slow = head; while (fast.next != null && fast.next.next != null) { fast = fast.next.next; slow = slow.next; } Node temp = slow.next; slow.next = null; return temp; } Node mergeSort(Node node) { if (node == null || node.next == null) { return node; } Node second = split(node); node = mergeSort(node); second = mergeSort(second); return merge(node, second); } Node merge(Node first, Node second) { if (first == null) { return second; } if (second == null) { return first; } if (first.data < second.data) { first.next = merge(first.next, second); first.next.prev = first; first.prev = null; return first; } else { second.next = merge(first, second.next); second.next.prev = second; second.prev = null; return second; } } public static void main(String[] args) { LinkedList list = new LinkedList(); list.head = new Node(10); list.head.next = new Node(30); list.head.next.next = new Node(3); list.head.next.next.next = new Node(4); list.head.next.next.next.next = new Node(20); list.head.next.next.next.next.next = new Node(5); Node node = null; node = list.mergeSort(head); System.out.println("Linked list after sorting :"); list.print(node); } } ================================================ FILE: Algorithms/Sorting/Merge_Sort_on_Doubly_Linked_List/Mergesort_doubly.py ================================================ class Node: def __init__(self,data): self.data=data; self.next=None; self.previous=None; class DoubleLinkedList: def __init__(self): self.start=None; def merge(self,a,b): if (a==None): return b; if (b==None): return a; if (a.data < b.data): a.next=self.merge(a.next,b); a.next.previous=a; a.previous=None; return a; else: b.next=self.merge(a,b.next); (b.next).previous=b; b.previous=None; return b; def mergesort(self,head): if (head==None): return head; if (head.next==None): return head; b = self.div(head); head = self.mergesort(head); b = self.mergesort(b); return self.merge(head,b); def div(self,head): first=last=head; while(True): if (first.next==None): break; if ((first.next).next==None): break; first=(first.next).next; last=last.next; t=last.next; last.next=None; return t; def insert(self,d): n=Node(d); n.next=self.start; if (self.start!=None): self.start.previous=n; self.start=n; def display(self,node): t=node; while(node!=None): print (node.data); t=node; node=node.next; ob=DoubleLinkedList(); inp=int(input("Enter the number of nodes you want to enter:")); for i in range(inp): j=int(input("Enter the data of the node:")); ob.insert(j); ob.start=ob.mergesort(ob.start) print ("\nDisplaying the double linked list after merge sort (in ascending order):"); ob.display(ob.start); ================================================ FILE: Algorithms/Sorting/Pancake_Sort/PancakeSort.java ================================================ import java.util.Arrays; /** * @author Alessandro Arosio - 05/10/2020 17:28 */ public class PancakeSort { public static void main(String[] args) { int[] result = pancakeSort(new int[]{-32, 41, 6, -2, 16, 0, 23}); Arrays.stream(result).forEach(System.out::println); } static int[] pancakeSort(int[] arr) { int i = arr.length; int len = arr.length; while (i >= 0) { int pos = findGreatestElement(arr, 0, len); flip(arr, pos); flip(arr, len - 1); len--; i--; } return arr; } public static void flip(int[] arr, int k) { int i = 0; int j = k; while (i < k) { int tempArray = arr[j]; arr[j] = arr[i]; arr[i] = tempArray; i++; j--; } } public static int findGreatestElement(int[] arr, int start, int end) { int maxValue = Integer.MIN_VALUE; int maxPosition = 0; for (int i = start; i < end; i++) { if (arr[i] >= maxValue) { maxValue = arr[i]; maxPosition = i; } } return maxPosition; } } ================================================ FILE: Algorithms/Sorting/Pancake_Sort/Pancake_Sort.c ================================================ #include #include //functio to reverse the array. void flip(int arr[], int i) { int temp, start = 0; while (start < i) { temp = arr[start]; arr[start] = arr[i]; arr[i] = temp; start++; i--; } } //function to find maximum in the array int findMax(int arr[], int n) { int mi, i; for (mi = 0, i = 0; i < n; ++i) if (arr[i] > arr[mi]) mi = i; return mi; } //function to perform PancakeSort int pancakeSort(int *ar, int n) { //the main idea behind the algo is //take the greatest element to the first position //then flip the aray from the end //so that greatest element becomes last element //and then reduce the curr_size //perfrom these operations till the array get sorted. for (int curr_size = n; curr_size > 1; curr_size--) { int mi = findMax(ar, curr_size); if (mi != curr_size - 1) { //this calls for flipping the array elements. flip(ar, mi); flip(ar, curr_size - 1); } } return 0; } int main() { //input no. of elements required in array ar int n; scanf("%d", &n); int ar[n]; //input elements in the array for (int i = 0; i < n; i++) scanf("%d", &ar[i]); //Pancake Sort Algorithm //The idea behind this algorithm is similar to that of selection sort. //the only thing we must perform is flipping the array elements from (0,i) //our aim is to sort the array and not focus on time complexity //thus total time complexity of this code : O(n^2); //total O(n) flips will be performed. pancakeSort(ar, n); for (int i = 0; i < n; i++) printf("%d ", ar[i]); printf("\n"); return 0; } ================================================ FILE: Algorithms/Sorting/Pancake_Sort/Pancake_Sort.c++ ================================================ #include using namespace std; void flip(int arr[], int i) { int temp, start = 0; while (start < i) { temp = arr[start]; arr[start] = arr[i]; arr[i] = temp; start++; i--; } } int findMax(int arr[], int n) { int mi, i; for (mi = 0, i = 0; i < n; ++i) { if (arr[i] > arr[mi]) mi = i; } return mi; } void pancakeSort(int *arr, int n) { for (int curr_size = n; curr_size > 1; --curr_size) { int mi = findMax(arr, curr_size); if (mi != curr_size-1) { flip(arr, mi); flip(arr, curr_size-1); } } } void printArray(int arr[], int n) { for (int i = 0; i < n; ++i) cout<< arr[i]<<" "; cout << "\n"; } int main() { int N,i,j; cout << "Enter Size of Array :- " << "\n"; cin >> N; int A[N]; cout << "Enter Array Elements:- " << "\n"; for(i = 0 ; i < N;i++) cin >> A[i]; pancakeSort(A, N); cout<<"Sorted Array "<<"\n"; printArray(A, N); return 0; } ================================================ FILE: Algorithms/Sorting/Pancake_Sort/Pancake_Sort.cs ================================================ // C# program to implement stooge sort using System; class Program { /// /// Main application function. /// public static void Main() { int[] arr = { -32, 41, 6, -2, 16, 0, 23 }; // Calling pancake Sort function // to sort the array PancakeSort(arr); // Display the sorted array for (int i = 0; i < arr.Length-1; i++) Console.Write(arr[i] + " "); } /// /// Runs pancake sort on provided array /// /// array to be sorted public static int[] PancakeSort(int[] array) { for (var subArrayLength = array.Length - 1; subArrayLength >= 0; subArrayLength--) { // get the position of the maximum element of the subarray var indexOfMax = IndexOfMax(array, subArrayLength); if (indexOfMax != subArrayLength) { // flip the array to the maximum element index // the maximum element of the subarray will be located at the beginning Flip(array, indexOfMax); // flip the entire subarray Flip(array, subArrayLength); } } return array; } /// /// method to get the index of the maximum subarray element /// /// array to be searched /// Max index /// Index of max element private static int IndexOfMax(int[] array, int n) { int result = 0; for (var i = 1; i <= n; ++i) { if (array[i] > array[result]) { result = i; } } return result; } /// /// method for flipping the array /// /// Array to be modified /// Index of last item to be flipped private static void Flip(int[] array, int end) { for (var start = 0; start < end; start++, end--) { var temp = array[start]; array[start] = array[end]; array[end] = temp; } } } ================================================ FILE: Algorithms/Sorting/Pancake_Sort/Pancake_Sort.js ================================================ function pancakeSort(arr){ findMaxIndex = (arr2, k) => { let max = -Infinity let maxIndex = 0 for(let i = 0; i < k; i++){ if(arr2[i] >= max){ max = arr2[i] maxIndex = i } } return maxIndex } flip = (arr3, k2) => { let i = 0 while (i < k2) { let temp = arr3[k2] arr3[k2] = arr3[i] arr3[i] = temp i++ k2-- } return arr3 } let i = arr.length while(i > 1){ let maxIndex = findMaxIndex(arr, i) if(maxIndex !== i - 1){ flip(arr, maxIndex) flip(arr, i - 1) } i-- } return arr } pancakeSort([4,3,1,2,5,6]);//[1,2,3,4,5,6] ================================================ FILE: Algorithms/Sorting/Pancake_Sort/Pancake_Sort.py ================================================ input_vector = [3,6,8,3,1,4,8,9,5,3,2,5,8,9,1] def pancake_sort(nums): arr_len = len(nums) while arr_len > 1: mi = nums.index(max(nums[0:arr_len])) nums = nums[mi::-1] + nums[mi+1:len(nums)] nums = nums[arr_len-1::-1] + nums[arr_len:len(nums)] arr_len -= 1 return nums print(pancake_sort(input_vector)) ================================================ FILE: Algorithms/Sorting/Pancake_Sort/Pancake_Sort.rb ================================================ class Array def pancake_sort! num_flips = 0 (self.size-1).downto(1) do |end_idx| max = self[0..end_idx].max max_idx = self[0..end_idx].index(max) next if max_idx == end_idx if max_idx > 0 self[0..max_idx] = self[0..max_idx].reverse end self[0..end_idx] = self[0..end_idx].reverse end self end end p a = (1..9).to_a.shuffle p a.pancake_sort! ================================================ FILE: Algorithms/Sorting/Pancake_Sort/README.md ================================================ ## This folder is empty. ================================================ FILE: Algorithms/Sorting/Patience_Sort/PatienceSort.cs ================================================ using System; using System.Collections.Generic; // To compile: csc PatienceSort.cs namespace PatienceSort { class Program { //Example: static void Main(string[] args) { // Expected input: // One line, n: ammount of integer numbers to sort // next n lines: A new number // Example: // 4 // 3 // 1 // 2 // 4 // Prints the following output: // 1 2 3 4 int n = Convert.ToInt32(Console.ReadLine()); int[] numbers = new int[n]; for(var i = 0; i < n; i++) numbers[i] = Convert.ToInt32(Console.ReadLine()); // We pass the array numbers. At the end of the function, it should be sorted PatienceSort(ref numbers); // Print output array foreach (var i in numbers) Console.Write(i.ToString() + ' '); Console.WriteLine(); } /* Patience sort works the same way as the "Patience" card game. We start with a deck of cards (a number array in this case) and, for each card, we search the left-most pile such that the card at the top of the pile is higher or equal to out current card. If we can't find such pile, we start a new one after the rightmost pile with only the current card, and so on until we run out of cards When there's no more cards, we take the smallest visible card (aka the smallest card at the top of some pile) and take it, and we repeat until there's no more piles. The resulting sequence of cards turns out to be sorted :) The following is a simulation of a 'Patience' game. */ static void PatienceSort(ref int[] numbers) { // The list of piles, the maximum number of piles we could have is // n (the number of elements in the array), when all elements // are sorted in increasing order. (Note that C# could increase the // size of the list, but we prefer to allocate space only once) List> piles = new List>(numbers.Length); // For each number, find the pile such that // its top is greater or equal, and put // this number as its top foreach(var i in numbers) { // 'pushed' checks if there's a stack that can hold our // current number, if it does not exist, push a new one var pushed = false; foreach(var pile in piles) if (pile.Peek() >= i) { pile.Push(i); pushed = true; break; // We only care about the left-most } if (!pushed) { // Since we couldn't add this number to any pile, we create a new one // with just this number var newStack = new Stack(); newStack.Push(i); piles.Add(newStack); } } var nextNum = 0; // next array position int minPile = 0; // the index of the pile with the smallest top var empty = false; while(!empty) // We stop when every pile is empty { var min = int.MaxValue; empty = true; // We search linearly the minimum until there's no more numbers for(var i = 0; i < piles.Count; i++){ var pile = piles[i]; empty = empty && pile.Count == 0; if(pile.Count == 0) continue; // If the pile is empty, we skip it if(pile.Peek() <= min) { min = pile.Peek(); minPile = i; } } // If we found a new number, add it in its corresponding position if(!empty) { numbers[nextNum] = piles[minPile].Pop(); nextNum++; } } } } } ================================================ FILE: Algorithms/Sorting/Patience_Sort/Patience_sort.cpp ================================================ //The code is in C #include #include //sorting function int* patienceSort(int* arr, int size) { //variables and array declaration int decks[size][size], min, pickedRow; //Dynamic memory allocation int *count = (int*)calloc(sizeof(int),size); int *sortedArr = (int*)malloc(size*sizeof(int)); //creating a pile just like in the game of solitaire for(int i = 0; i < size; i++) { for(int j = 0; j < size; j++) { if(count[j] == 0 || (count[j] > 0 && decks[j][count[j] - 1] >= arr[i])) { decks[j][count[j]] = arr[i]; count[j]++; break; } } } //setting up initial stage min = decks[0][count[0] - 1]; pickedRow = 0; //check for the minimum value number from the top-most elements in each pile //and popping that least element in sorted array list for(int i = 0; i < size; i++) { for(int j = 0; j < size; j++) { if(count[j] > 0 && decks[j][count[j] - 1] < min){ min = decks[j][count[j] - 1]; pickedRow = j; } } sortedArr[i] = min; count[pickedRow]--; for(int j = 0; j < size; j++) if(count[j] > 0) { min = decks[j][count[j] - 1]; pickedRow = j; break; } } //freeing up the allocated memory free(count); free(decks); return sortedArr; } int main (void) //(int argC,char* argV[]) { int *arr, *sortedArr; int sizeOfarray; printf("Enter the size of array: "); scanf("%d", &sizeOfarray); //dynamic mermory allocation to array arr = (int*)malloc((sizeOfarray) * sizeof(int)); //array input printf("Enter %d elements of array (each seperated by a space): ", sizeOfarray); for(int i = 0; i < sizeOfarray; i++) { scanf("%d", &arr[i]); } //function call sortedArr = patienceSort(arr, sizeOfarray); printf("The sorted array is: "); //printing the sorted array for(int i = 0; i < sizeOfarray; i++) { printf("%d ", sortedArr[i]); } free(arr); } ================================================ FILE: Algorithms/Sorting/Patience_Sort/README.md ================================================

Patience Sort

## Problem statement Write a program for *Patience sort*

### About In computer science, *Patience sorting* is a sorting algorithm inspired by and named after, the card game patience.
This game begins with a shuffled deck of cards. These cards are dealt one by one into a sequence of piles on the table, according to the following rules:
- Initially, there are no piles. - The first card dealt forms a new pile consisting of the single card. - Each subsequent card is placed on the leftmost existing pile whose top card has a value greater than or equal the new card's value, or to the right of all of the existing piles, thus forming a new pile. - When there are no more cards remaining to deal, the game ends.
This card game is turned into a two-phase sorting algorithm, as follows: - Given an array of n elements from some totally ordered domain, consider this array as a collection of cards. - Simulate the patience sorting game. - When the game is over, recover the sorted sequence by repeatedly picking off the minimum visible card. - In other words, perform a k-way merge of the p piles, each of which is internally sorted.
### *Note*: A variant of the algorithm efficiently computes the length of a longest increasing subsequence in a given array.
Checkout the code for better understanding.

### Sample Input-1 ``` 4 -21 22 1 0 ``` ### Sample Ouput ``` The sorted array is: -21 0 1 22 ```
### Sample Input-2 ``` 10 4 3 5 1 4 7 9 8 0 -1 ``` ### Sample Ouput ``` The sorted array is: -1 0 1 3 4 4 5 7 8 9 ```
### Contributed by [*Sarthak Luthra*](https://github.com/sarthak-21) ================================================ FILE: Algorithms/Sorting/Patience_sort.py ================================================ #Patience sort algorithm to sort given list in python def new_stack(val): #create new stack newl=[] newl.append(val) return newl def patience_sort(t,n): #gives sorted list ans=[] for j in range(n): mn=100000 flag=0 for i in range(len(t)): if len(t[i])>0: x=t[i].pop() if x=l[i]: flag=1 t[j].append(y) t[j].append(l[i]) break else: t[j].append(y) if flag!=1: fir=new_stack(l[i]) t.append(fir) print('Sorted list using patience sorting algorithm: ') patience_sort(t,n) ================================================ FILE: Algorithms/Sorting/Pigeonhole_Sort/PigeonholeSort.cpp ================================================ /* C program to implement Pigeonhole Sort */ #include using namespace std; /* Sorts the array using pigeonhole algorithm */ void pigeonholeSort(int arr[], int n) { // Find minimum and maximum values in arr[] int min = arr[0], max = arr[0]; for (int i = 1; i < n; i++) { if (arr[i] < min) min = arr[i]; if (arr[i] > max) max = arr[i]; } int range = max - min + 1; // Find range // Create an array of vectors. Size of array // range. Each vector represents a hole that // is going to contain matching elements. vector holes[range]; // Traverse through input array and put every // element in its respective hole for (int i = 0; i < n; i++) holes[arr[i]-min].push_back(arr[i]); // Traverse through all holes one by one. For // every hole, take its elements and put in // array. int index = 0; // index in sorted array for (int i = 0; i < range; i++) { vector::iterator it; for (it = holes[i].begin(); it != holes[i].end(); ++it) arr[index++] = *it; } } // Driver program to test the above function int main() { int arr[] = {8, 3, 2, 7, 4, 6, 8}; int n = sizeof(arr)/sizeof(arr[0]); pigeonholeSort(arr, n); printf("Sorted order is : "); for (int i = 0; i < n; i++) printf("%d ", arr[i]); return 0; } ================================================ FILE: Algorithms/Sorting/Pigeonhole_Sort/PigeonholeSort.ts ================================================ /* PigeonholeSort Implementation in Typescript It is suitable for sorting elements where number of elements is approximately the same as the number of possible values */ const pigeonholeSort = (array: number[]): number[] => { const max = Math.max(...array); const min = Math.min(...array); const range = max - min + 1; let phole = new Array(range).fill(0); for (let i = 0; i < array.length; i++) { phole[array[i] - min]++; } let index = 0; for (let j = 0; j < range; j++) { while (phole[j]-- > 0) { array[index++] = j + min; } } return array; }; const array = [9, 4, 2, 5, 1, 7, 8, 6]; console.log(pigeonholeSort(array)); ================================================ FILE: Algorithms/Sorting/Pigeonhole_Sort/Pigeonhole_Sort.c ================================================ #include #include void pigeonhole_sort(int arr[], int num, int min, int max) { int size,i,j,k,count; size = max - min + 1; int holes[size]; for(i=0;i 0) { arr[k] = count + min; k=k+1; } } int main() { int i,n, c, d, t; printf("Enter the number of Elements : "); scanf("%d",&n); int array[n]; printf("Enter the elements to be sorted :\n"); for (i = 0; i < n; i++) scanf("%d",&array[i]); int min = array[0] , max = array[0]; for (i = 1; i < n; i++) { if(min > array[i]) min = array[i]; if(max < array[i]) max = array[i]; } pigeonhole_sort(array, n,min,max); printf("Sorted Array :\n"); for(i = 0; i < n; i++) printf("%d ",array[i]); printf("\n"); return 0; } ================================================ FILE: Algorithms/Sorting/Pigeonhole_Sort/Pigeonhole_Sort.java ================================================ import java.lang.*; import java.util.*; public class Pigeonhole_Sort { public static void pigeonhole_sort(int arr[], int n) { int min = arr[0]; int max = arr[0]; int range, i, j, index; for(int a=0; a max) max = arr[a]; if(arr[a] < min) min = arr[a]; } range = max - min + 1; int[] phole = new int[range]; Arrays.fill(phole, 0); for(i = 0; i0) arr[index++]=j+min; } public static void main(String[] args) { Pigeonhole_Sort sort = new Pigeonhole_Sort(); Scanner obj = new Scanner(System.in); int N , i; System.out.print("Enter Size of Array :- "); N = obj.nextInt(); int A[] = new int[N]; System.out.print("Enter Array Elements :- "); for(i = 0;i < N;i++) A[i] = obj.nextInt(); System.out.print("Sorted order is : "); sort.pigeonhole_sort(A,A.length); for(i=0 ; i 0: holes[count] -= 1 a[i] = count + my_min i += 1 a = [8, 3,1,2,3,4,5,4, 6, 8] print("Sorted order is : ", end =" ") pigeonhole_sort(a) for i in range(0, len(a)): print(a[i], end =" ") ================================================ FILE: Algorithms/Sorting/Quick_Select/QuickSelect.cpp ================================================ /** * Finding Kth largest element in an array using QuickSelect algorithm */ class Solution { public: int findKthLargest(vector& nums, int k) { return findKthLargest(nums, 0, nums.size()-1, nums.size()-k); } int findKthLargest(vector& nums, int left, int right ,int k) { int pivot = nums[right]; int leftMark = left; for (int i = left; i& A, int i, int j) { int tmp = A[i]; A[i] = A[j]; A[j] = tmp; } }; ================================================ FILE: Algorithms/Sorting/Quick_Select/Quick_Select.js ================================================ function partition(array3, l, r){ var x = array3[r], i = l,temp; for (var j = l; j <= r - 1; j++) { if (array3[j] <= x) { temp = array3[i]; array3[i] = array3[j]; array3[j] = temp; i++; } } temp = array3[i]; array3[i] = array3[j]; array3[j] = temp; return i; } function termFinder(array1, l, r, k){ if (k > 0 && k <= r - l + 1) { var index = partition(array1, l, r); if (index - l == k - 1){ return array1[index]; } if (index - l > k - 1){ return termFinder(array1, l, index - 1, k); } return termFinder(array1, index + 1, r,k - index + l - 1); } return "error"; } var array1 = []; var length1 = parseInt(prompt("Enter length of array -> ")); for(var i=0;i ")); } var num1 = parseInt(prompt("Enter value of k for 'k th' smallest element -> ")); alert("K-th smallest element is " + termFinder(array1,0, length1-1,num1)); ================================================ FILE: Algorithms/Sorting/Quick_Select/Quick_Select.php ================================================ 'int': # Time complexity : O(N*logK) # Space complexity : O(K) heap = [] for i in nums : heapq.heappush(heap, i) if len(heap) > k : heapq.heappop(heap) return heapq.heappop(heap) def findKthLargest(self, nums: 'List[int]', k: 'int') -> 'int': # Time complexity : O(N) # Space complexity : O(1) def partition(l, r, i): start = l pivot = nums[i] nums[i], nums[start] = nums[start], nums[i] l += 1 while l <= r : while l<=r and nums[l] <= pivot : l += 1 while l<=r and nums[r] > pivot : r -= 1 if l < r : nums[l], nums[r] = nums[r], nums[l] l += 1 r -= 1 nums[r], nums[start] = nums[start], nums[r] return r def select(l, r, k_smallest): if l == r : return nums[l] i = random.randint(l, r) i = partition(l, r, i) if k_smallest == i : return nums[i] elif k_smallest > i : return select(i+1, r, k_smallest) else : return select(l, i-1, k_smallest) return select(0, len(nums)-1, len(nums)-k) ================================================ FILE: Algorithms/Sorting/Quick_Select/README.md ================================================ ## This folder is empty. ================================================ FILE: Algorithms/Sorting/Quick_Select/quick_select.java ================================================ class quick_select { public int kthLargest(int[] arr, int k) { int n = arr.length; int left = 0; int right = n - 1; Random rand = new Random(0); while (left <= right) { int choosenPivotIndex = rand.nextInt(right - left + 1) + left; int finalIndexOfChoosenPivot = partition(arr, left, right, choosenPivotIndex); if (finalIndexOfChoosenPivot == n - k) { return arr[finalIndexOfChoosenPivot]; } else if (finalIndexOfChoosenPivot > n - k) { right = finalIndexOfChoosenPivot - 1; } else { left = finalIndexOfChoosenPivot + 1; } } return -1; } private int partition(int[] arr, int left, int right, int pivotIndex) { int pivotValue = arr[pivotIndex]; int lesserItemsTailIndex = left; swap(arr, pivotIndex, right); for (int i = left; i < right; i++) { if (arr[i] < pivotValue) { swap(arr, i, lesserItemsTailIndex); lesserItemsTailIndex++; } } swap(arr, right, lesserItemsTailIndex); return lesserItemsTailIndex; } private void swap(int[] arr, int first, int second) { int temp = arr[first]; arr[first] = arr[second]; arr[second] = temp; } ================================================ FILE: Algorithms/Sorting/Quick_Select/quick_select.rb ================================================ # @param {Integer[]} nums # @param {Integer} k # @return {Integer} def find_kth_largest(nums, k) n = nums.size quick_select(nums, 0, n - 1, n - k) # Kth largest is at n - 1 - (k - 1) = (n - k)th index end def quick_select(a, p, r, k) # Note the k here refers to (n - k) from the question stand-point return a[p] if p == r # Base case of recursion q = rand_partition(a, p, r) # Pick the pivot using random partition if k < q quick_select(a, p, q - 1, k) # kth smallest is in the lower partition elsif k > q quick_select(a, q + 1, r, k) # kth smallest is in the higher partition else a[q] # if q == k return Pivot as the kth smallest end end def partition(a, p, r) i = p - 1 # Choose the index before the pth index pivot = a[r] # Choose the last element as pivot p.upto(r - 1) do |j| # Loop from p to r-1 moving elements to either side of pivot next if a[j] > pivot # Move to next element if element is already > than pivot element i += 1 # Increment index i for current placement index a[i], a[j] = a[j], a[i] # Swap elements at pivot placement index with the current index j end a[i + 1], a[r] = a[r], a[i + 1] # Move the pivot to its final place: index before which all elements < pivot i + 1 # return pivot index end def rand_partition(a, p, r) i = rand(p..r) # Pick a random index between p and r a[i], a[r] = a[r], a[i] # Swap the last element with the one at i partition(a, p, r) # Return result of partition() end ================================================ FILE: Algorithms/Sorting/Quick_Sort/QuickSort.java ================================================ // Java program for implementation of QuickSort class QuickSort { // This function takes last element as pivot. int partition(int arr[], int low, int high) { int pivot = arr[high]; int i = (low-1); // index of smaller element for (int j=low; j " + array); // var arrayAfterQuickSort = quickSort(array); // console.log("Array after QuickSort: " + arrayAfterQuickSort); ================================================ FILE: Algorithms/Sorting/Quick_Sort/QuickSort.py ================================================ # This is the Python version of Quick Sort # Code is contributed by: Italo Vinicius. # # Quick sort is an Sorting Algorithm which takes compelxity: O(n log n) # This function takes last element as pivot, places # the pivot element at its correct position in sorted # array, and places all smaller (smaller than pivot) # to left of pivot and all greater elements to right # of pivot def partition(arr,low,high): i = ( low-1 ) # index of smaller element pivot = arr[high] # pivot for j in range(low , high): # If current element is smaller than the pivot if arr[j] < pivot: # increment index of smaller element i = i+1 arr[i],arr[j] = arr[j],arr[i] arr[i+1],arr[high] = arr[high],arr[i+1] return ( i+1 ) # Function to do Quick sort def quickSort(arr,low,high): if low < high: # pi is partitioning index, arr[p] is now # at right place pi = partition(arr,low,high) # Separately sort elements before # partition and after partition quickSort(arr, low, pi-1) quickSort(arr, pi+1, high) if __name__ == "__main__": arr = list(map(int,input().split())) quickSort(arr,0,len(arr)-1) ================================================ FILE: Algorithms/Sorting/Quick_Sort/Quick_Sort.cpp ================================================ /* C++ implementation of QuickSort */ #include using namespace std; // A utility function to swap two elements void swap(int* a, int* b) { int t = *a; *a = *b; *b = t; } int partition (int arr[], int low, int high) { int pivot = arr[high]; // pivot int i = (low - 1); // Index of smaller element for (int j = low; j <= high - 1; j++) { // If current element is smaller than the pivot if (arr[j] < pivot) { i++; // increment index of smaller element swap(&arr[i], &arr[j]); } } swap(&arr[i + 1], &arr[high]); return (i + 1); } void quickSort(int arr[], int low, int high) { if (low < high) { int pi = partition(arr, low, high); quickSort(arr, low, pi - 1); quickSort(arr, pi + 1, high); } } /* Function to print an array */ void printArray(int arr[], int size) { int i; for (i = 0; i < size; i++) cout << arr[i] << " "; cout << endl; } // Driver Code int main() { int arr[] = {10, 7, 8, 9, 1, 5}; int n = sizeof(arr) / sizeof(arr[0]); quickSort(arr, 0, n - 1); cout << "Sorted array: \n"; printArray(arr, n); return 0; } ================================================ FILE: Algorithms/Sorting/Quick_Sort/Quick_Sort.go ================================================ package main import "fmt" func swap(num1 *int, num2 *int) { var val int val = *num1 *num1 = *num2 *num2 = val } func partition(elements []int, low int, high int) int { var pivot int pivot = elements[high] var i int i = low var j int for j = low; j < high; j++ { if elements[j] <= pivot { swap(&elements[i], &elements[j]) i++ } } swap(&elements[i], &elements[high]) return i } func quickSort(elements []int, low int, high int) { if low < high { var part int part = partition(elements, low, high) quickSort(elements, low, part-1) quickSort(elements, part+1, high) } } func main() { var num int fmt.Print("Enter Number of Elements: ") fmt.Scan(&num) var array = make([]int, num) var i int for i = 0; i < num; i++ { fmt.Scan(&array[i]) } fmt.Print("Elements: ", array, "\n") quickSort(array, 0, num-1) fmt.Print("Sorted Elements: ", array, "\n") } ================================================ FILE: Algorithms/Sorting/Quick_Sort/Quick_Sort.sh ================================================ #!/bin/bash # Bubble Sort Array sorting algortihm in O(n^2) complexity # E.g. Array Size = 6 # Elements: # 1 # 7 # 8 # 14 # 12 # 21 # Sorted Array: # 1 # 7 # 8 # 12 # 14 # 21 echo "Enter Array Size" read len # taking input from user echo "Provide Number for an Array:" for (( i = 0; i < $len; i++ )) do read arr[$i] done # Bubble Sort Logic for (( i = 0; i < $len ; i++ )) do for (( j = $i; j < $len; j++ )) do if [ ${arr[$i]} -gt ${arr[$j]} ]; then temp=${arr[$i]} arr[$i]=${arr[$j]} arr[$j]=$temp fi done done # Printing the sorted number echo "Sorted Array: " for (( i=0; i < $len; i++ )) do echo ${arr[$i]} done ================================================ FILE: Algorithms/Sorting/Quick_Sort/README.md ================================================ ## QUICK SORT Quick sorting is almost similar like merge sorting but in quick sorting the element named pivot is chose which can be any element of the array. There are many different versions of quicksort that pick pivot in different ways. After choosing pivot all the elements are compared with the pivot element and if it satisfies the condition the two adjacent get swapped otherwise it remain as it is. a. Always pick first element as pivot. b. Always pick last element as pivot (implemented below) c. Pick a random element as pivot. d. Pick median as pivot. **For example:** [3 5 9 7] in this lets 7 be the pivot. Condition is (pivot < number) then swap. 7 is greater than 3: No change [3 5 9 7]. 7 > 5: No change [3 5 9 7]. 9 > 7: Swap [3 5 7 9] Output: [3 5 7 9] ================================================ FILE: Algorithms/Sorting/Quick_Sort/quicksort.C ================================================ #include int partition(int a[], int beg, int end); void quickSort(int a[], int beg, int end); void main() { int i; int arr[10]={90,23,101,45,65,28,67,89,34,29}; quickSort(arr, 0, 9); printf("\n The sorted array is: \n"); for(i=0;i<10;i++) printf(" %d\t", arr[i]); } int partition(int a[], int beg, int end) { int left, right, temp, loc, flag; loc = left = beg; right = end; flag = 0; while(flag != 1) { while((a[loc] <= a[right]) && (loc!=right)) right--; if(loc==right) flag =1; else if(a[loc]>a[right]) { temp = a[loc]; a[loc] = a[right]; a[right] = temp; loc = right; } if(flag!=1) { while((a[loc] >= a[left]) && (loc!=left)) left++; if(loc==left) flag =1; else if(a[loc] < a[left]) { temp = a[loc]; a[loc] = a[left]; a[left] = temp; loc = left; } } } return loc; } void quickSort(int a[], int beg, int end) { int loc; if(beg int partition(int a[], int beg, int end); void quickSort(int a[], int beg, int end); void main() { int i; int arr[10]={90,23,101,45,65,28,67,89,34,29}; quickSort(arr, 0, 9); printf("\n The sorted array is: \n"); for(i=0;i<10;i++) printf(" %d\t", arr[i]); } int partition(int a[], int beg, int end) { int left, right, temp, loc, flag; loc = left = beg; right = end; flag = 0; while(flag != 1) { while((a[loc] <= a[right]) && (loc!=right)) right--; if(loc==right) flag =1; else if(a[loc]>a[right]) { temp = a[loc]; a[loc] = a[right]; a[right] = temp; loc = right; } if(flag!=1) { while((a[loc] >= a[left]) && (loc!=left)) left++; if(loc==left) flag =1; else if(a[loc] < a[left]) { temp = a[loc]; a[loc] = a[left]; a[left] = temp; loc = left; } } } return loc; } void quickSort(int a[], int beg, int end) { int loc; if(beg //Function to get maximum value in the array... int max(int arr[], int n) { int max = arr[0]; for (int i = 1; i < n; i++) if (arr[i] > max) max = arr[i]; return max; } //Counting Sort... void counting_sort(int arr[], int n, int j) { int output[n]; int i, count[10] = { 0 }; for (i = 0; i < n; i++) count[(arr[i] / j) % 10]++; for (i = 1; i < 10; i++) count[i] += count[i - 1]; for (i = n - 1; i >= 0; i--) { output[count[(arr[i] / j) % 10] - 1] = arr[i]; count[(arr[i] /j) % 10]--; } for (i = 0; i < n; i++) arr[i] = output[i]; } // Radix Sort... void radix_sort(int arr[], int n) { // Finding the number of digits... int m = max(arr, n); // Performing counting sort for every digit... for (int j = 1; m / j > 0; j *= 10) counting_sort(arr, n, j); } int main() { int n = 10; // Size of the array... // The elements of the array... int arr[] = { 12, 89, 45, 4, 11, 67, 32, 100, 3, 33 }; radix_sort(arr, n); // Printing the array after performing radix sort on it... for (int i = 0; i < n; i++) printf("%d ",arr[i]); return 0; } /* This code is contributed by Mayukh Mitra */ ================================================ FILE: Algorithms/Sorting/Radix_Sort/RadixSort.java ================================================ public class Radix_Sort { public static void main(String[] args) { int i; Scanner sc = new Scanner(System.in); int[] a = {90,23,101,45,65,23,67,89,34,23}; radix_sort(a); System.out.println("\n The sorted array is: \n"); for(i=0;i<10;i++) System.out.println(a[i]); } static int largest(inta[]) { int larger=a[0], i; for(i=1;i<10;i++) { if(a[i]>larger) larger = a[i]; } returnlarger; } static void radix_sort(inta[]) { int bucket[][]=newint[10][10]; int bucket_count[]=newint[10]; int i, j, k, remainder, NOP=0, divisor=1, larger, pass; larger = largest(a); while(larger>0) { NOP++; larger/=10; } for(pass=0;pass= 0: index = (arr[i] / exp1) output[count[int(index % 10)] - 1] = arr[i] count[int(index % 10)] -= 1 i -= 1 # Copying the output array to arr[], # so that arr now contains sorted numbers i = 0 for i in range(0, len(arr)): arr[i] = output[i] # Method to do Radix Sort def radixSort(arr): # Find the maximum number to know number of digits max1 = max(arr) # Do counting sort for every digit. Note that instead # of passing digit number, exp is passed. exp is 10^i # where i is current digit number exp = 1 while max1 / exp > 0: countingSort(arr, exp) exp *= 10 if __name__ == "__main__": arr = list(map(int,input().split())) radixSort(arr) print(' '.join(str(x) for x in arr)) ================================================ FILE: Algorithms/Sorting/Radix_Sort/Radix_Sort.js ================================================ // helper function to get the last nth digit of a number var getDigit = function (num, nth) { // get last nth digit of a number var remainder = 0; while (nth--) { remainder = num % 10 num = Math.floor((num - remainder) / 10) } return remainder } // radixSort function radixSort(list) { var max = Math.floor(Math.log10(Math.max.apply(Math, list))), //get the length of digits of the max value in this array digitBuckets = [], index = 0; for (var i = 0; i < max + 1; i++) { // rebuild the digit buckets according to this digit digitBuckets = [] for (var j = 0; j < list.length; j++) { var digit = getDigit(list[j], i + 1); digitBuckets[digit] = digitBuckets[digit] || []; digitBuckets[digit].push(list[j]); } // rebuild the list according to this digit index = 0 for (var t = 0; t < digitBuckets.length; t++) { if (digitBuckets[t] && digitBuckets[t].length > 0) { for (j = 0; j < digitBuckets[t].length; j++) { list[index++] = digitBuckets[t][j]; } } } } return list } var array = [76, 45, 89, 23, 9]; radixSort(array); //OUTPUT //[ 9, 23, 45, 76, 89 ] //O(kn) where k is the number of bits required to represent the largest element in the array and n is the number of element ================================================ FILE: Algorithms/Sorting/Radix_Sort/Radix_Sort.rb ================================================ def counting_sort(input_arr, exp) count_arr = Array.new(10, 0) result = Array.new(input_arr.size) m = 10 ** (exp+1) n = 10 ** exp input_arr.each do |item| count_arr[(item % m) / n] += 1 end for i in 1...10 count_arr[i] = count_arr[i-1] + count_arr[i] end i = input_arr.size - 1 until i < 0 do item = input_arr[i] count_arr[(item % m) / n] -= 1 result[count_arr[(item % m) / n]] = item i -= 1 end result end def radix_sort(arr) maximum = arr.max exp = 0 until maximum == 0 do exp += 1 maximum = maximum / 10 end for i in 0...exp do arr = counting_sort(arr, i) end arr end array = [170, 45, 75, 90, 802, 24, 2, 66] array = radix_sort(array) print array puts # Output # [2, 24, 45, 66, 75, 90, 170, 802] ================================================ FILE: Algorithms/Sorting/Radix_Sort/Radix_sort.cs ================================================ using System; namespace Radix_Sort { class Program { static void Sort(int[] arr) { int i, j; int[] tmp = new int[arr.Length]; for (int shift = 31; shift > -1; --shift) { j = 0; for (i = 0; i < arr.Length; ++i) { bool move = (arr[i] << shift) >= 0; if (shift == 0 ? !move : move) arr[i-j] = arr[i]; else tmp[j++] = arr[i]; } Array.Copy(tmp, 0, arr, arr.Length-j, j); } } static void Main(string[] args) { int[] arr = new int[] { 2, 5, -4, 11, 0, 18, 22, 67, 51, 6 }; Console.WriteLine("\nOriginal array : "); foreach (var item in arr) { Console.Write(" " + item); } Sort(arr); Console.WriteLine("\nSorted array : "); foreach (var item in arr) { Console.Write(" " + item); } Console.WriteLine("\n"); } } } ================================================ FILE: Algorithms/Sorting/Radix_Sort/radixSort.php ================================================ = 0; $i--) { $output[$count[ ($arr[$i] / $exp) % 10 ] - 1] = $arr[$i]; $count[ ($arr[$i] / $exp) % 10 ]--; } // Copy the output array to arr[], so // that arr[] now contains sorted numbers // according to current digit for ($i = 0; $i < $size; $i++) $arr[$i] = $output[$i]; } // The main function to that sorts arr[] // of size n using Radix Sort function radixsort(&$arr, $size) { // Find the maximum number to know // number of digits $m = max($arr); // Do counting sort for every digit. Note // that instead of passing digit number, // exp is passed. exp is 10^i where i is // current digit number for ($exp = 1; $m / $exp > 0; $exp *= 10) countSort($arr, $size, $exp); } // Function to print an array function printArray(&$arr,$size) { for ($i = 0; $i < $size; $i++) echo $arr[$i] . " "; } // Input is given here $arr = array(170, 43, 77, 90, 21, 820, 2, 65); $size = count($arr); // Function Call radixsort($arr, $size); printArray($arr, $size); ?> ================================================ FILE: Algorithms/Sorting/Radix_Sort/radixsort.cpp ================================================ #include using namespace std; int max(int arr[], int n) { int max = arr[0]; for (int i = 1; i < n; i++) if (arr[i] > max) max = arr[i]; return max; } void counting_sort(int arr[], int n, int j) { int output[n]; int i, count[10] = { 0 }; for (i = 0; i < n; i++) count[(arr[i] / j) % 10]++; for (i = 1; i < 10; i++) count[i] += count[i - 1]; for (i = n - 1; i >= 0; i--) { output[count[(arr[i] / j) % 10] - 1] = arr[i]; count[(arr[i] /j) % 10]--; } for (i = 0; i < n; i++) arr[i] = output[i]; } void radix_sort(int arr[], int n) { int m = max(arr, n); for (int j = 1; m / j > 0; j *= 10) counting_sort(arr, n, j); } int main() { int n = 10; int arr[] = { 12, 89, 45, 4, 11, 67, 32, 100, 3, 33 }; radix_sort(arr, n); for (int i = 0; i < n; i++) cout<<"\t "< using namespace std; void swapping(int &a, int &b) { //swap the content of a and b int temp; temp = a; a = b; b = temp; } void display(int *array, int size) { for(int i = 0; i> n; int arr[n]; //create an array with given number of elements cout << "Enter elements:" << endl; for(int i = 0; i> arr[i]; } cout << "Array before Sorting: "; display(arr, n); selectionSort(arr, n); cout << "Array after Sorting: "; display(arr, n); } ================================================ FILE: Algorithms/Sorting/Selection_Sort/README.md ================================================ ## Selection Sort In selection sort array is first divided into two part sorted and unsorted part. Then in unsorted part the minimum number is checked and shifted to first position similarly this process is carried till the array is sorted. For example: [8 3 6 2] -> |[8 3 6 2] -> [2]|[8 3 6] -> [2 3]|[8 6] -> [2 3 6]|[8] -> [2 3 6 8]. ================================================ FILE: Algorithms/Sorting/Selection_Sort/Selection Sort.py ================================================ A = [2,3,80,45,6,111] for i in range(len(A)): min = i for j in range(i+1, len(A)): if A[min] > A[j]: min = j A[i], A[min] = A[min],A[i] for i in range(len(A)): print(A[i],end = " ") ================================================ FILE: Algorithms/Sorting/Selection_Sort/SelectionSort.java ================================================ // Java program for implementation of Selection Sort class SelectionSort { void sort(int arr[]) { int n = arr.length; for (int i = 0; i < n-1; i++) { // Find the minimum element in unsorted array int min_idx = i; for (int j = i+1; j < n; j++) if (arr[j] < arr[min_idx]) min_idx = j; // Swap the found minimum element with the first // element int temp = arr[min_idx]; arr[min_idx] = arr[i]; arr[i] = temp; } } // Prints the array void printArray(int arr[]) { int n = arr.length; for (int i=0; i Nil case head :: Nil => List(head) case head :: tail => { val minElem = tail.min val indexOfMinElem = tail.indexOf(minElem) if(head <= minElem) { head :: selectionSortAsc(tail) } else { val (tailHalf1, tailHalf2) = tail.splitAt(indexOfMinElem) tailHalf2.head :: selectionSortAsc(tailHalf1 ::: head :: tailHalf2.tail) } } } } ================================================ FILE: Algorithms/Sorting/Selection_Sort/Selection_Sort.cpp ================================================ //Selection sort, sort the array by swapping the curr element with the smallest element from indexes curr+1 to len-1 #include using namespace std; void selection_sort(int a[],int n){ for(int i=0;i>n; int a[1000]; for(int i=0;i>a[i]; } selection_sort(a,n); for(int i=0;i arr[j] { minIndex = j } } var temp = arr[minIndex] arr[minIndex] = arr[i] arr[i] = temp } fmt.Print("After Sorting: ") printArray(arr, n) } func printArray(arrs [100]int, n int) { for i := 0; i < n; i++ { fmt.Print(strconv.Itoa(arrs[i]) + " ") } fmt.Println("") } func main() { fmt.Print("How many number : ") var no = 0 fmt.Scanln(&no) var arr [100]int fmt.Print("Enter array values : ") for i := 0; i < no; i++ { fmt.Scanf("%d", &arr[i]) } fmt.Print("Before Sorting: ") printArray(arr, no) selectionSort(arr, no) } ================================================ FILE: Algorithms/Sorting/Selection_Sort/selection sort.cs ================================================ // C# program for implementation // of Selection Sort using System; class GFG { static void sort(int []arr) { int n = arr.Length; // One by one move boundary of unsorted subarray for (int i = 0; i < n - 1; i++) { // Find the minimum element in unsorted array int min_idx = i; for (int j = i + 1; j < n; j++) if (arr[j] < arr[min_idx]) min_idx = j; // Swap the found minimum element with the first // element int temp = arr[min_idx]; arr[min_idx] = arr[i]; arr[i] = temp; } } // Prints the array static void printArray(int []arr) { int n = arr.Length; for (int i=0; i int main(){ /* Here i & j for loop counters, temp for swapping, * count for total number of elements, number[] to * store the input numbers in array. You can increase * or decrease the size of number array as per requirement */ int i, j, count, temp, number[25]; printf("How many numbers u are going to enter?: "); scanf("%d",&count); printf("Enter %d elements: ", count); // Loop to get the elements stored in array for(i=0;inumber[j]){ temp=number[i]; number[i]=number[j]; number[j]=temp; } } } printf("Sorted elements: "); for(i=0;i #include int main() { //input size of the array ar int n; scanf("%d", &n); int ar[n]; //input elements in ar[n] for (int i = 0; i < n; i++) scanf("%d", &ar[i]); //shell sort algorithm //shell sort is a variation of insertion sort. //gap = [n/2], floor value. //we try to sort elements with this gap //we continue reducing the gap until it reaches 1. //complexity becomes O(n*logn) int gap, i, j, temp; for (gap = n / 2; gap >= 1; gap /= 2) { for (i = gap; i < n; i++) { temp = ar[i]; j = i - gap; while (j >= 0 && ar[j] > temp) { ar[j + gap] = ar[j]; j = j - gap; } ar[j + gap] = temp; } } for (int i = 0; i < n; i++) printf("%d ", ar[i]); printf("\n"); return 0; } ================================================ FILE: Algorithms/Sorting/Shell_Sort/Shell_Sort.cpp ================================================ // The Shell Sort Algorithm in C++ using namespace std; #include // Shell Sort Algorithm in a Function void ShellSort(int sortArray[], int size) { for (int gap = size / 2; gap > 0; gap /= 2) { for (int i = gap; i < size; i++) { int temp = sortArray[i]; int j; for (j = i; j >= gap && sortArray[j - gap] > temp; j -= gap) { sortArray[j] = sortArray[j - gap]; } sortArray[j] = temp; } } } int main() { cout << "\n"; // Requesting Array Size to the User int size; cout << "Enter the size of the array: "; cin >> size; // Requesting Array Elements to the User int sortArray[size]; cout << "Enter the array elements: \n"; for (int i = 0; i < size; i++) { cin >> sortArray[i]; } cout << "\n"; // OUTPUT Array before Shell Sort cout << "Array BEFORE the Shell Sort: "; cout << "["; for (int i = 0; i < size; i++) { cout << sortArray[i] << ", "; } cout << "\b\b"; cout << "]"; cout << "\n\n"; // Applying the Shell Sort Algorithm cout << "Applying the Shell Sort Algorithm...\n"; ShellSort(sortArray, size); cout << "\n"; // OUTPUT Array after Shell Sort cout << "Array AFTER the Shell Sort: "; cout << "["; for (int i = 0; i < size; i++) { cout << sortArray[i] << ", "; } cout << "\b\b"; cout << "]"; cout << endl; cout << "\n\n"; return 0; } ================================================ FILE: Algorithms/Sorting/Shell_Sort/Shell_Sort.cs ================================================ class ShellSort { static void printArray(int []arr) { int n = arr.Length; for (int i=0; i 0; gap /= 2) { for (int i = gap; i < n; i += 1) { int temp = arr[i]; int j; for (j = i; j >= gap && arr[j - gap] > temp; j -= gap) arr[j] = arr[j - gap]; arr[j] = temp; } } return 0; } public static void Main() { int []arr = {12, 34, 54, 2, 3}; Console.Write("Array before sorting :\n"); printArray(arr); ShellSort ob = new ShellSort(); ob.sort(arr); Console.Write("Array after sorting :\n"); printArray(arr); } } ================================================ FILE: Algorithms/Sorting/Shell_Sort/Shell_Sort.java ================================================ import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class ShellSort { private static void shellSort(Comparable[] arr) { //Sort arr[] into increasing order int N = arr.length; int h = 1; while(h < N/3) h = 3*h+1; // 1, 4, 13, 40, 121, 364, 1093, ... while(h >= 1) { //h-sort the array for(int i=h; i=h && lessThan(arr[j], arr[j-h]); j-=h) swap(arr, j, j-h); } h = h/3; } } private static boolean lessThan(Comparable first, Comparable second) { return first.compareTo(second) < 0; } private static void swap(Comparable[] arr, int first, int second) { // Swaps two elements in the array. Comparable temp = arr[first]; arr[first] = arr[second]; arr[second] = temp; } private static void printSortedArray(Comparable[] arr) { // Print the sorted array as output, on a single line. for(int i=0; i { for (var h = array.length; h > 0; h = parseInt(h / 2)) { for (var i = h; i < array.length; i++) { var k = array[i]; for (var j = i; j >= h && k < array[j - h]; j -= h) array[j] = array[j - h]; array[j] = k; } } return array; }; var array = [8, 3, 5, 9, 1, 5, 9, 2, 3, 8, 4]; console.log(shellSort(array)); ================================================ FILE: Algorithms/Sorting/Shell_Sort/Shell_Sort.swift ================================================ func ShellSort(_ items: [Int]) -> [Int] { var result = items let length = result.count var h = 1 while h < length / 3 { h = 3 * h + 1 } while h >= 1 { for i in h..0: for j in range(gap,n): key=a[j] i=j while i>0 and a[i-gap]>key: a[i]=a[i-gap] i=i-gap a[i]=key gap=gap//2 return a a=[2,7,4,6,1,8,5] print(shell(a)) ================================================ FILE: Algorithms/Sorting/Shell_Sort/shell_sort.sh ================================================ shellsort() { arr=("$@") len=${#arr[@]} gap=$(( $n / 2 )) while [ $gap -gt 0 ]; do for((ind=$gap;$ind<$n;ind++)); do temp=${arr[$ind]} j=$ind while [[ $j -ge $gap && ${arr[$(( $j - $gap ))]} -gt $temp ]]; do arr[$j]=${arr[$(( $j - $gap ))]} j=$(( $j - $gap )) done arr[$j]=$temp done gap=$(( $gap / 2 )) done echo ${arr[@]} } echo -n "Enter the total numbers: " read n echo "Enter numbers: " i=0 while [ $i -lt $n ] do read a[$i] i=`expr $i + 1` done shellsort ${a[@]} ================================================ FILE: Algorithms/Sorting/Stooge_Sort/README.md ================================================ ## This folder is empty. ================================================ FILE: Algorithms/Sorting/Stooge_Sort/Stooge_Sort.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApp1 { // C# program to implement stooge sort using System; class Program { /// /// Main application function. /// public static void Main() { int[] arr = { 2, 4, 5, 3, 1 }; int n = arr.Length; // Calling Stooge Sort function // to sort the array StoogeSort(ref arr); // Display the sorted array for (int i = 0; i < n; i++) Console.Write(arr[i] + " "); } /// /// Runs stooge sort on provided array /// /// array to be sorted /// Low index of current sort /// High index of current sort public static void StoogeSort(ref int[] arr) { StoogeSort(ref arr,0,arr.Length-1); } /// /// Runs stooge sort on provided array /// /// array to be sorted /// Low index of current sort /// High index of current sort public static void StoogeSort(ref int[] arr, int lowIndex, int highIndex, int? depth = 0) { int arrayLength = (highIndex - lowIndex + 1); //if there are not 2 items here, we are done if (arrayLength <= 1) return; // If first element is smaller // than last, swap them if (arr[lowIndex] > arr[highIndex]) { int tempLowIndexValue = arr[lowIndex]; arr[lowIndex] = arr[highIndex]; arr[highIndex] = tempLowIndexValue; } //if only 2 values, we know we are done. start to end recursion if (arrayLength == 2) return; int thirdOfArrayLength = (highIndex - lowIndex + 1) / 3; // Recursively sort first // 2/3 elements StoogeSort(ref arr, lowIndex, highIndex - thirdOfArrayLength, depth +1); // Recursively sort last // 2/3 elements StoogeSort(ref arr, lowIndex +thirdOfArrayLength, highIndex, depth + 1); // Recursively sort first // 2/3 elements again to // confirm StoogeSort(ref arr, lowIndex, highIndex - thirdOfArrayLength, depth + 1); } } } ================================================ FILE: Algorithms/Sorting/Stooge_Sort/Stooge_Sort.go ================================================ package main import "fmt" var arr = []int{1, 44, 37, 6, 54, 81, 21, 66} func main() { fmt.Println("Before Sorting:", arr) stoogesort(arr) fmt.Println("After Stooge Sort: ", arr) } func stoogesort(arr []int) { end := len(arr) - 1 if arr[end] < arr[0] { arr[0], arr[end] = arr[end], arr[0] } if end > 1 { t := len(arr) / 3 stoogesort(arr[:len(arr)-t]) stoogesort(arr[t:]) stoogesort(arr[:len(arr)-t]) } } ================================================ FILE: Algorithms/Sorting/Stooge_Sort/Stooge_Sort.py ================================================ """ Stooge Sort in Python The stooge function takes three parameters: - number_list: list to order - first: Index of the first item to be ordered on the list. Default is zero. - last: Index of the last item to be ordered on the list. The stooge function returns the ordered list """ from typing import List from math import ceil def stooge(number_list: List[int], last: int, first: int = 0): length = last - first + 1 # Swap first value with last value if first > last if number_list[first] > number_list[last]: n = number_list[first] number_list[first] = number_list[last] number_list[last] = n # If the length of the section of the list that's being ordered is > 3 # perform stooge on the first 2/3 of the list, then the last 2/3 of the list # and finally the first 2/3 of the list again if last - first + 1 > 2: third = ceil((last - first + 1) / 3) stooge(number_list, last - third) stooge(number_list, last, first + third) stooge(number_list, last - third) return number_list ================================================ FILE: Algorithms/Sorting/Strand_Sort/README.md ================================================ ## Strand Sort First, begin a sublist by moving the first item from the original list to the sublist. For each subsequent item in the original list, if it is greater than the last item of the sublist, remove it from the original list and append it to the sublist. Merge the sublist into a final, sorted list. Repeatedly extract and merge sublists until all items are sorted. Handle two or fewer items as special cases. For Example : Input : ip[] = {10, 5, 30, 40, 2, 4, 9} Output : op[] = {2, 4, 5, 9, 10, 30, 40} ================================================ FILE: Algorithms/Sorting/Strand_Sort/Strand_Sort.cpp ================================================ ''' Strand Sort is a sorting algorithm that works in O(n) time if list is already sorted and works in O(n*n) in worst case. ''' #include using namespace std; //Templates start here #define pb push_back #define mp make_pair #define F first #define S second #define ll long long #define fo(i, j, k, in) for (int i = j; i < k; i += in) #define refo(i, j, k, in) for (int i = j; i >= k; i -= in) #define rep(i, j) fo(i, 0, j, 1) #define rerep(i, j) fo(i, j, 0, 1) #define all(cont) cont.begin(), cont.end() #define reall(cont) cont.end(), cont.begin() #define foreach(it, l) for (auto it = l.begin() l it != l.end(); it++) #define in(A, B, C) assert(B <= A && A <= C) #define MOD (int)1e9 #define MOD7 1000000007 #define PI 3.1415926535897932384626433832795 typedef pair PII; typedef pair PLL; typedef vector VI; typedef vector VL; typedef vector VS; typedef vector VII; typedef vector VLL; typedef vector VVI; typedef vector VVL; typedef map MPII; typedef map MPLL; typedef set SETI; typedef multiset MSETI; //Templates end here //I'm not using my templates for better understanding, else above templates can be easily used, you can alse benefit yourself just copy above templates and use them void strandSort(list &ip, list &op) { if (ip.empty()) return; list sublist; sublist.push_back(ip.front()); ip.pop_front(); for (auto it = ip.begin(); it != ip.end(); ) { if (*it > sublist.back()) { sublist.push_back(*it); it = ip.erase(it); } else it++; } op.merge(sublist); strandSort(ip, op); } int main(void) { list ip{10, 5, 30, 40, 2, 4, 9}; list op; strandSort(ip, op); for (auto x : op) cout << x << " "; return 0; } ================================================ FILE: Algorithms/Sorting/Strand_Sort/Strand_sort.java ================================================ import java.util.*; public class Strand_sort { public static void main(String args[]) { Scanner sc= new Scanner(System.in); List given_array = new ArrayList(); List temp = new ArrayList(); List temp2 = new ArrayList(); List output = new ArrayList(); System.out.println("How many number do you want to enter :"); int i,j,max,no=sc.nextInt(); System.out.println("Enter your values :"); for(i=0;i=max) { temp.add(given_array.get(i)); max=given_array.get(i); given_array.remove(i); i--; } } for(i=0,j=0;ioutput.get(i)) { temp2.add(output.get(i)); output.remove(i); } else { temp2.add(temp.get(i)); temp.remove(i); } } if(temp.size()!=0) { temp2.addAll(temp); temp.clear(); } else if(output.size()!=0) { temp2.addAll(output); output.clear(); } output.addAll(temp2); temp2.clear(); } System.out.println("Output: "+output); } } ================================================ FILE: Algorithms/Sorting/Strand_Sort/strand_sort.c ================================================ #include typedef struct node_t *node, node_t; struct node_t { int v; node next; }; typedef struct { node head, tail; } slist; void push(slist *l, node e) { if (!l->head) l->head = e; if (l->tail) l->tail->next = e; l->tail = e; } node removehead(slist *l) { node e = l->head; if (e) { l->head = e->next; e->next = 0; } return e; } void join(slist *a, slist *b) { push(a, b->head); a->tail = b->tail; } void merge(slist *a, slist *b) { slist r = {0}; while (a->head && b->head) push(&r, removehead(a->head->v <= b->head->v ? a : b)); join(&r, a->head ? a : b); *a = r; b->head = b->tail = 0; } void sort(int *ar, int len) { node_t all[len]; for (int i = 0; i < len; i++) all[i].v = ar[i], all[i].next = i < len - 1 ? all + i + 1 : 0; slist list = {all, all + len - 1}, rem, strand = {0}, res = {0}; for (node e = 0; list.head; list = rem) { rem.head = rem.tail = 0; while ((e = removehead(&list))) push((!strand.head || e->v >= strand.tail->v) ? &strand : &rem, e); merge(&res, &strand); } for (int i = 0; res.head; i++, res.head = res.head->next) ar[i] = res.head->v; } void show(const char *title, int *x, int len) { printf("%s ", title); for (int i = 0; i < len; i++) printf("%3d ", x[i]); putchar('\n'); } int main(void) { int n; printf("Enter size of array "); scanf("%d", &n); int x[n]; for(int i = 0; i < n; ++i) { scanf("%d", &x[i]); } # define SIZE sizeof(x)/sizeof(int) show("before sort:", x, SIZE); sort(x, sizeof(x)/sizeof(int)); show("after sort: ", x, SIZE); return 0; } ================================================ FILE: Algorithms/Sorting/Strand_Sort/strand_sort.ts ================================================ function strandSort(arrin: number[]): number[] { /* if the array has no elements, then it dosent need to be sorted */ if (arrin.length == 0) return let arrout: number[] = [] /* is the same as let subarr: number[], arrout: number[] = [] but to run the JS compiled code without undefined error, I did this */ while (arrin.length != 0) { let subarr: number[] = [] /* Start the new iteration with a new subarray */ subarr.push(arrin.shift()) /* Get the first element into subarray */ arrin.forEach((num) => { if (num > subarr[0]) { subarr.push(num) /* Add every element bigger than the first element to the subarray*/ } }) /* Remove from input array elements that where added to the subarray*/ arrin = arrin.filter(num => subarr.indexOf(num) == -1) /* Find out if we concat the subarray before or after the output array */ if (arrout.length == 0 || arrout[arrout.length - 1] > subarr[0]) { arrout = subarr.concat(arrout) } else { arrout = arrout.concat(subarr) } } return arrout /* Retun the output array */ } console.log(strandSort([10, 5, 30, 40, 2, 4, 9])) /* Example input strandSort([10, 5, 30, 40, 2, 4, 9]) */ /* Example output {2, 4, 5, 9, 10, 30, 40} */ ================================================ FILE: Algorithms/Sorting/Tim_Sort/README.md ================================================ ##Tim Sorting Algorithm TimSort algorithm is a sorting technique widely used in programming. Java and python use this algorithm in their built-in sort() methods. It is a combined hybrid of two other sorting techniques – Insertion-Sort and Merge-Sort While TimSort is a complex algorithm in itself, where it looks for an ideal minimum size called “minrun”, performs “galloping” in merge-sort to avoid iterations for pre-sorted elements, etc., this post deals with a simple and basic implementation. It is, however, noteworthy that merge sort is most efficient when the size of the array is a power of 2. Take for instance an array of size 16, which is 2^4. Hence, in each recursion or iteration (depends on the implementation of merge-sort), the array splits into 2 equal subarrays. This happens until we are left with 16 single elements. These are then reconstructed to get the sorted array. Also, note that insertion sort works best when the size of the array is less. Hence in TimSort, minrun is usually set between 32 and 64. In this implementation, since we are not finding minrun, we are taking 32 as minrun. And from the previous point, we understand that the algorithm is more efficient when (size_of_arr/32) is a power of 2. ================================================ FILE: Algorithms/Sorting/Tim_Sort/Tim_Sort.c ================================================ //C Program for Tim Sort #include const int run = 32; //Function to find minimum of two numbers int min (int a, int b) { if (a < b) return a; else return b; } //function implementing insertion sort void insertionSort (int a[], int low, int high) { int i, j, temp; for (i = low + 1; i <= high; i++) { temp = a[i]; j = i - 1; while (a[j] > temp && j >= low) a[j + 1] = a[j--]; a[j + 1] = temp; } } //function implementing merge sort void merge (int a[], int left, int mid, int right) { int len1 = mid - left + 1; int len2 = right - mid; int low[len1], high[len2]; int i, j, k; for (i = 0; i < len1; i++) low[i] = a[left + i]; for (i = 0; i < len2; i++) high[i] = a[mid + 1 + i]; i = 0; j = 0; k = left; while (i < len1 && j < len2) { if (low[i] <= high[j]) a[k] = low[i++]; else a[k] = high[j++]; k++; } while (i < len1) a[k++] = low[i++]; while (j < len2) a[k++] = high[j++]; } void timSort (int a[], int n) { int i, size, low, mid, high; for (i = 0; i < n; i += run) insertionSort (a, i, min ((i + 31), (n - 1))); for (size = run; size < n; size = 2 * size) { for (low = 0; low < n; low += 2 * size) { mid = low + size - 1; high = min ((low + 2 * size - 1), (n - 1)); merge (a, low, mid, high); } } } void main () { int a[50] , n, i; //Get number of elements from user printf("Enter number of elements to be sorted:"); scanf("%d",&n); //Get elements from user into array printf("Enter the elements:"); for(i=0;i= left && arr[j] > temp) { arr[j + 1] = arr[j]; j--; } arr[j + 1] = temp; } } public static void merge(int[] arr, int l,int m, int r) { int len1 = m - l + 1, len2 = r - m; int[] left = new int[len1]; int[] right = new int[len2]; for (int x = 0; x < len1; x++) { left[x] = arr[l + x]; } for (int x = 0; x < len2; x++) { right[x] = arr[m + 1 + x]; } int i = 0; int j = 0; int k = l; while (i < len1 && j < len2) { if (left[i] <= right[j]) { arr[k] = left[i]; i++; } else { arr[k] = right[j]; j++; } k++; } while (i < len1) { arr[k] = left[i]; k++; i++; } while (j < len2) { arr[k] = right[j]; k++; j++; } } public static void timSort(int[] arr, int n) { for (int i = 0; i < n; i += RUN) { insertionSort(arr, i, Math.min((i + 31), (n - 1))); } for (int size = RUN; size < n; size = 2 * size) { for (int left = 0; left < n; left += 2 * size) { int mid = left + size - 1; int right = Math.min((left + 2 * size - 1), (n - 1)); merge(arr, left, mid, right); } } } public static void printArray(int[] arr, int n) { for (int i = 0; i < n; i++) { System.out.print(arr[i] + " "); } System.out.print("\n"); } public static void main(String[] args) { int n; Scanner sc=new Scanner(System.in); System.out.print("Enter the number of elements : "); n=sc.nextInt(); int[] arr = new int[n]; System.out.println("Enter the elements of the array: "); for(int i=0; i=start and elem #include #include using namespace std; // Class to represent a graph class Graph { // No. of vertices' int V; // Pointer to an array containing adjacency listsList list* adj; // A function used by topologicalSort void topologicalSortUtil(int v, bool visited[], stack& Stack); public: // Constructor Graph(int V); // function to add an edge to graph void addEdge(int v, int w); // prints a Topological Sort of // the complete graph void topologicalSort(); }; Graph::Graph(int V) { this->V = V; adj = new list[V]; } void Graph::addEdge(int v, int w) { // Add w to v’s list. adj[v].push_back(w); } // A recursive function used by topologicalSort void Graph::topologicalSortUtil(int v, bool visited[], stack& Stack) { // Mark the current node as visited. visited[v] = true; // Recur for all the vertices // adjacent to this vertex list::iterator i; for (i = adj[v].begin(); i != adj[v].end(); ++i) if (!visited[*i]) topologicalSortUtil(*i, visited, Stack); // Push current vertex to stack // which stores result Stack.push(v); } // The function to do Topological Sort. // It uses recursive topologicalSortUtil() void Graph::topologicalSort() { stack Stack; // Mark all the vertices as not visited bool* visited = new bool[V]; for (int i = 0; i < V; i++) visited[i] = false; // Call the recursive helper function // to store Topological // Sort starting from all // vertices one by one for (int i = 0; i < V; i++) if (visited[i] == false) topologicalSortUtil(i, visited, Stack); // Print contents of stack while (Stack.empty() == false) { cout << Stack.top() << " "; Stack.pop(); } } // Driver Code int main() { // Create a graph given in the above diagram Graph g(6); g.addEdge(5, 2); g.addEdge(5, 0); g.addEdge(4, 0); g.addEdge(4, 1); g.addEdge(2, 3); g.addEdge(3, 1); cout << "Following is a Topological Sort of the given " "graph \n"; // Function Call g.topologicalSort(); return 0; } ================================================ FILE: Algorithms/Sorting/Topological_Sort/Topological_sort.cs ================================================ // Topological_sort algorithm. using System; using System.Collections.Generic; // Class represents a directed graph // using adjacency list representation class Graph { // for vertices private int V; // Adjacency List as ArrayList // of ArrayList's private List > adj; Graph(int v) { V = v; adj = new List >(v); for (int i = 0; i < v; i++) adj.Add(new List()); } // Function to add an edge into the graph public void AddEdge(int v, int w) { adj[v].Add(w); } // A recursive function used by topologicalSort void TopologicalSortUtil(int v, bool[] visited, Stack stack) { visited[v] = true; foreach(var vertex in adj[v]) { if (!visited[vertex]) TopologicalSortUtil(vertex, visited, stack); } // Push current vertex to // stack which stores result stack.Push(v); } void TopologicalSort() { Stack stack = new Stack(); // Mark all the vertices as not visited var visited = new bool[V]; for (int i = 0; i < V; i++) { if (visited[i] == false) TopologicalSortUtil(i, visited, stack); } // Print contents of stack foreach(var vertex in stack) { Console.Write(vertex + " "); } } public static void Main(string[] args) { // Create a graph given // in the above diagram Graph g = new Graph(6); g.AddEdge(5, 2); g.AddEdge(5, 0); g.AddEdge(4, 0); g.AddEdge(4, 1); g.AddEdge(2, 3); g.AddEdge(3, 1); // Function Call g.TopologicalSort(); } } /* output is: 5 4 3 2 1 0 * time complexity : O(V+E) * auxiliary space: O(V) */ ================================================ FILE: Algorithms/Sorting/Topological_Sort/Topological_sort.py ================================================ from collections import defaultdict #Class to represent a graph class Graph: def __init__(self,vertices): self.graph = defaultdict(list) #dictionary containing adjacency List self.V = vertices #No. of vertices # function to add an edge to graph def addEdge(self,u,v): self.graph[u].append(v) # A recursive function used by topologicalSort def topologicalSortUtil(self,v,visited,stack): # Mark the current node as visited. visited[v] = True # Recur for all the vertices adjacent to this vertex for i in self.graph[v]: if visited[i] == False: self.topologicalSortUtil(i,visited,stack) # Push current vertex to stack which stores result stack.insert(0,v) # The function to do Topological Sort. It uses recursive # topologicalSortUtil() def topologicalSort(self): # Mark all the vertices as not visited visited = [False]*self.V stack =[] # Call the recursive helper function to store Topological # Sort starting from all vertices one by one for i in range(self.V): if visited[i] == False: self.topologicalSortUtil(i,visited,stack) # Print contents of stack print stack g= Graph(6) g.addEdge(5, 2); g.addEdge(5, 0); g.addEdge(4, 0); g.addEdge(4, 1); g.addEdge(2, 3); g.addEdge(3, 1); print "Following is a Topological Sort of the given graph" g.topologicalSort() ================================================ FILE: Algorithms/Sorting/Tree_Sort/README.md ================================================ ## This folder is empty. ================================================ FILE: Algorithms/Sorting/Tree_Sort/Tree_Sort.c ================================================ // C++ program to implement Tree Sort #include using namespace std; struct Node { int key; struct Node *left, *right; }; // A utility function to create a new BST Node struct Node *newNode(int item) { struct Node *temp = new Node; temp->key = item; temp->left = temp->right = NULL; return temp; } // Stores inoder traversal of the BST // in arr[] void storeSorted(Node *root, int arr[], int &i) { if (root != NULL) { storeSorted(root->left, arr, i); arr[i++] = root->key; storeSorted(root->right, arr, i); } } /* A utility function to insert a new Node with given key in BST */ Node* insert(Node* node, int key) { /* If the tree is empty, return a new Node */ if (node == NULL) return newNode(key); /* Otherwise, recur down the tree */ if (key < node->key) node->left = insert(node->left, key); else if (key > node->key) node->right = insert(node->right, key); /* return the (unchanged) Node pointer */ return node; } // This function sorts arr[0..n-1] using Tree Sort void treeSort(int arr[], int n) { struct Node *root = NULL; // Construct the BST root = insert(root, arr[0]); for (int i=1; i using namespace std; struct tree{ int info; tree *Left, *Right; }; tree *root; class TreeSort{ public: int no_of_elements; int elements[10]; public: void getarray(); void sortit(); void insert1(int); tree *insert2(tree *, tree *); void display(tree *); }; void TreeSort::getarray(){ cout<<"How many elements? "; cin>>no_of_elements; cout<<"Insert array of element to sort: "; for(int i=0;i>elements[i]; } } void TreeSort::sortit(){ for(int i = 0; i < no_of_elements; i++){ insert1(elements[i]); } } tree* TreeSort::insert2(tree *temp,tree *newnode){ if(temp==NULL){ temp=newnode; } else if(temp->info < newnode->info){ insert2(temp->Right,newnode); if(temp->Right==NULL) temp->Right=newnode; } else{ insert2(temp->Left,newnode); if(temp->Left==NULL) temp->Left=newnode; } return temp; } void TreeSort::insert1(int n){ tree *temp=root,*newnode; newnode=new tree; newnode->Left=NULL; newnode->Right=NULL; newnode->info=n; root=insert2(temp,newnode); } /* Inorder traversal */ void TreeSort::display(tree *t = root){ if(root==NULL){ cout<<"Nothing to display"; }else if(t!=NULL){ display(t->Left); cout<info<<" "; display(t->Right); } } int main(){ TreeSort TS; TS.getarray(); TS.sortit(); TS.display(); return 0; } ================================================ FILE: Algorithms/Sorting/Tree_Sort/treesort.java ================================================ class Node{ int value; Node left; Node right; Node(int value){ this.value = value; left = null; right = null; } } // Class for Binary Search Tree class BST{ Node node; BST(int value){ node = new Node(value); } public Node insert(Node node, int value){ if(node == null){ return new Node(value); } // Move to left for value less than parent node if(value < node.value){ node.left = insert(node.left, value); } // Move to right for value greater than parent node else if(value > node.value){ node.right = insert(node.right, value); } return node; } // For traversing in order public void inOrder(Node node){ if(node != null){ // recursively traverse left subtree inOrder(node.left); System.out.print(node.value + " "); // recursively traverse right subtree inOrder(node.right); } } } public class TreeSort { public static void main(String[] args) { int[] arr = {65, 68, 82, 42, 10, 75, 25, 47, 32, 72}; System.out.println("Original array- " + Arrays.toString(arr)); // start creating tree with element at index 0 as root node BST bst = new BST(arr[0]); for(int num : arr){ bst.insert(bst.node, num); } System.out.print("Sorted Array after Tree sort- "); bst.inOrder(bst.node); System.out.println(); } } ================================================ FILE: Algorithms/Sorting/Wave_Sort/Wave_Sort.py ================================================ def sortInWave(arr_demo, n): arr_demo.sort() for i in range(0,n-1,2): arr_demo[i], arr_demo[i+1] = arr_demo[i+1], arr_demo[i] return arr_demo arr = [] print("Please Enter no of elements in array") n = int(input()) print("Please Enter elements of the array") for i in range(n): sample = int(input()) arr.append(sample) sortInWave(arr, len(arr)) ================================================ FILE: Algorithms/Sorting/Wave_Sort/wave_sort.c ================================================ //wave sort in c #include #include //C function to SWAP two reference pointers/values void swap(int *x, int *y) { int temp = *x; *x = *y; *y = temp; } //C function to implement WAVE SORT void sortInWave(int arr[], int n) { //elements are arranged in the order //sequence a1 >= a2 <= a3 >= a4 <= a5 >= a6 and so on. for (int i = 0; i < n; i += 2) { if (i > 0 && arr[i - 1] > arr[i] ) swap(&arr[i], &arr[i - 1]); if (i < n - 1 && arr[i] < arr[i + 1] ) swap(&arr[i], &arr[i + 1]); } } int main() { int n; scanf("%d", &n); int ar[n]; for (int i = 0; i < n; i++) scanf("%d", &ar[i]); sortInWave(ar, n); //Time complexity of this algorithm : // O(n) time by doing a "single traversal". for (int i = 0; i < n; i++) printf("%d ", ar[i]); printf("\n"); return 0; } ================================================ FILE: Algorithms/Sorting/Wave_Sort/wave_sort.cpp ================================================ using namespace std; #include //UTILITY FUNCS void printArray(int arr[], int size) { cout << "The array = [ "; for (int i = 0; i < size; i++) { cout << arr[i] << " "; } cout << "]" << endl; return; } //UTILITY FUNCS============== void swap(int *x, int *y) { int temp = *x; *x = *y; *y = temp; return; } // SORT========================== void waveSort(int arr[], int size) { for (int i = 0; i < size; i += 2) { if (i >= 1) { if (arr[i - 1] >= arr[i]) { swap(&arr[i - 1], &arr[i]); } } if (i <= size - 1) { if (arr[i] < arr[i + 1]) { swap(&arr[i], &arr[i + 1]); } } } return; } //MAIN FUNCTION===================== int main() { int size; cout << "Enter size of array: "; cin >> size; int arr[size]; cout << "Enter " << size << " elements of array:" << endl; for (int i = 0; i < size; i++) { cin >> arr[i]; } cout << "Before sort: "; printArray(arr, size); waveSort(arr, size); cout << "After sort: "; printArray(arr, size); return 0; } ================================================ FILE: Algorithms/Stack-Algorithm/Next_Greater_Element.cpp ================================================ // Aviral Gupta #include using namespace std; const double PI = 3.14159265358979323846; #define LM 1e18 #define ll long long int #define ld long double #define ms(dp,val) memset(dp,val,sizeof(dp)) #define all(t) t.begin(), t.end() #define inrange(i, a, b) ((i >= min(a, b)) && (i <= max(a, b))) #define pb push_back #define mp make_pair #define fi first #define se second #define f(i,n) for(int i=0;i= mod) c -= mod; return c; } typedef pair pii; typedef pair pll; typedef vector vi; typedef vector< pll > vpi; typedef vector vl; typedef vector vb; typedef vector vs; void next_greater(vector &A) { stack s; int n=A.size(); int ng[n]; s.push(0); for(int i=1;iA[s.top()]) { ng[s.top()]=i; s.pop(); } s.push(i); } while(!s.empty()) { ng[s.top()]=-1; s.pop(); } for(int i=0;i"<>n; vector a(n); for (int i = 0; i < n; i++) { cin>>a[i]; } next_greater(a); } ================================================ FILE: Algorithms/Stack-Algorithm/RemoveKDigitsToGetSmallestPossibleInteger.java ================================================ import java.util.Scanner; import java.util.Stack; public class RemoveKDigitsToGetSmallestPossibleInteger{ public static void main(String[]args){ //create scanner Scanner kb=new Scanner(System.in); //prompt user System.out.println("Provide an integer to make smallest possible with k removals"); //read in input integer String input=kb.next(); System.out.println("Please provide an integer k representing how many digits to remove from your integer"); int k=kb.nextInt(); System.out.println(removeKdigits(input, k)); } public static String removeKdigits(String num, int k) { //make a stack of characters Stacks=new Stack(); //set the number of elements removed so far to be 0 int count=0; //create our string to return String str=""; //loop over the length of our string for(int i=0; i than what is already on the stack we push the stack and move forward an element. We do this because we want to ensure we get the largest element we can to remove. For example, if we had 089, 1 as our input, we would want to return 8 rather than 9. So, we have to keep adding the next element as long as it is larger than the current one to our stack so we remove it from our string before the current element. This is of course always true, since if we end up with a fixed length num-k, if we will always wind up with the same length, so if we remove anything before this largest element, we will move the largest element left 1 position in the string, so we would have simply been better off ommitting this largest element instead since the preceding element was smaller. (Example: 089, we are better off removing 9 as opposed to 8, because otherwise, 9 gets shifted into 8's position, but 9 is larger than 8, so we are better off simply removing the 9 to begin with). Also, note that we go left to right over our string since the digits on the left of an integer hold greater value than those on the right, so we favor choosing those to remove first if possible */ while(i!=num.length() && (s.isEmpty() || s.peek() after pushing 9, we want to move something smaller than 9 to the left, since it would make our integer smaller, so we do so by popping 9, which in effect would give us 80 for this example. */ while(count!=k && i!=num.length()&&!s.isEmpty() && s.peek()>num.charAt(i)){ s.pop(); count++; } /*after the previous loop finishes, we can push the next character onto our stack, since if we aren't out of bounds, we know our next element must no longer be smaller than the current one. */ if (i!= num.length()) s.push(num.charAt(i)); } /*if we didn't remove k elements, then the final k of them must exist at the end. and thus, must exist at the top of our stack, so we can pop all the remaining elements until we get to k off the stack. */ while(count #include using namespace std; string simplifyPath(string path) { stack stk; string tmp; stringstream ss(path); while (getline(ss, tmp, '/')) { if (tmp == "" || tmp == ".") continue; if (tmp == ".." && !stk.empty()) stk.pop(); else if (tmp != "..") stk.push(tmp); } string res; while (!stk.empty()) { res = "/" + stk.top() + res; stk.pop(); } return res == "" ? "/" : res; } int main() { string path; cout << "Enter a valid path for file: "; cin >> path; string res = simplifyPath(path); cout << res; return 0; } ================================================ FILE: Algorithms/Stack-Algorithm/balanced_brackets_stack.cpp ================================================ #include using namespace std; bool isBalanced(string str) { stack s; for(int i = 0; i < str.length(); i++) { if(str[i] == '(' ) //push if opeening bracket is encountered s.push(str[i]); else { if(s.empty()) //if stack is empty return 0 return 0; s.pop();// pop the last element in stack } } if(!s.empty()) // if still stack has some brackets remaining return 0 return 0; return 1; } int main() { string bracSeq = "(()"; cout << isBalanced(bracSeq); return 0; } ================================================ FILE: Algorithms/Stack-Algorithm/immediate_smaller_element.cpp ================================================ /*Given an integer array of size N. For each element in the array, check whether the right adjacent element (on the next immediate position) of the array is smaller. If next element is smaller, print that element. If not, then print -1. Input: The first line of input contains an integer T denoting the number of test cases. T testcases follow. Each testcase contains 2 lines of input: The first line contains an integer N, where N is the size of array. The second line contains N integers(elements of the array) sperated with spaces. Output: For each test case, print the next immediate smaller elements for each element in the array. Constraints: 1 ≤ T ≤ 200 1 ≤ N ≤ 107 1 ≤ arr[i] ≤ 1000 Example: Input 2 5 4 2 1 5 3 6 5 6 2 3 1 7 Output 2 1 -1 3 -1 -1 2 -1 1 -1 -1 */ #include using namespace std; int main(){ int t; cin>>t; while(t--){ int n; cin>>n; int a[n]; for(int i=0;i>a[i]; for(int i=0;ia[i+1]) cout< using namespace std; int main(){ int t; cin>>t; while(t--){ string str; cin>>str; stack s; s.push(-1); int result=0; for(int i=0;i #include int check_anagram(char [], char []); int main() { char a[1000], b[1000]; printf("Enter two strings\n"); gets(a); gets(b); if (check_anagram(a, b)) { printf("The strings are anagrams.\n"); getch(); } else { printf("The strings aren't anagrams.\n"); getch(); } return 0; } int check_anagram(char a[], char b[]) { int first[26] = {0}, second[26] = {0}, c=0; // Calculating frequency of characters of the first string while (a[c] != '\0') { if(isupper(a[c])) { a[c]=tolower(a[c]); } first[a[c]-'a']++; c++; } c = 0; while (b[c] != '\0') { if(isupper(b[c])) { b[c]=tolower(b[c]); } second[b[c]-'a']++; c++; } // Comparing the frequency of characters for (c = 0; c < 26; c++) { if (first[c] != second[c]) { return 0; } } return 1; } ================================================ FILE: Algorithms/String/Anagram/anagram.java ================================================ import java.util.Arrays; public class AnagramProgram { static void isAnagram(String s1, String s2) { // Removing all white spaces from s1 and s2 String copyOfs1 = s1.replaceAll("s", ""); String copyOfs2 = s2.replaceAll("s", ""); // Initially setting status as true boolean status = true; if (copyOfs1.length() != copyOfs2.length()) { // Setting status as false if copyOfs1 and copyOfs2 doesn't have same length status = false; } else { // Changing the case of characters of both copyOfs1 and copyOfs2 and converting them to char array char[] s1Array = copyOfs1.toLowerCase().toCharArray(); char[] s2Array = copyOfs2.toLowerCase().toCharArray(); // Sorting both s1Array and s2Array Arrays.sort(s1Array); Arrays.sort(s2Array); // Checking whether s1Array and s2Array are equal status = Arrays.equals(s1Array, s2Array); } // Output if (status) { System.out.println(s1 + " and " + s2 + " are anagrams"); } else { System.out.println(s1 + " and " + s2 + " are not anagrams"); } } public static void main(String[] args) { isAnagram("Mother In Law", "Hitler Woman"); } } ================================================ FILE: Algorithms/String/Anagram/anagram.py ================================================ #This is a function to check anagrams using sorted() which is an inbuilt function in python def check(s1, s2): if(sorted(s1)== sorted(s2)): print("The strings are anagrams.") else: print("The strings are not anagrams.") s1 ="listen" s2 ="silent" check(s1, s2) ================================================ FILE: Algorithms/String/Anagram/anagram.swift ================================================ import Foundation func isAnagram(_ firstWord: String, _ secondWord: String) -> Bool { // check length of both words, if length is not the same, they cannot be anagrams let firstWordCopy = NSString(string: firstWord).replacingOccurrences(of: " ", with: "").lowercased() let secondWordCopy = NSString(string: secondWord).replacingOccurrences(of: " ", with: "").lowercased() if firstWordCopy.count != secondWordCopy.count { return false; } return firstWordCopy.sorted().elementsEqual(secondWordCopy.sorted()) } print("Enter the first word: ") let firstWord = readLine(strippingNewline: true) ?? "" print("Enter the second word: ") let secondWord = readLine(strippingNewline: true) ?? "" print(isAnagram(firstWord, secondWord)) ================================================ FILE: Algorithms/String/Anagram/anagrams.sh ================================================ # Follwing function does: # Removal of all alphanumerics, Convert all lowercase to uppercase, Sort the string preprocessing() { fold -w1 <<< "${1//[^[:alnum:]]/}" | tr '[:upper:]' '[:lower:]' | sort | tr -d '\n' } # function to check if given 2 arguments are anagrams isAnagram() { a=$(preprocessing "$1") b=$(preprocessing "$2") [[ $a = $b ]] && echo "Strings $1 and $2 are Anagrams to each other" || echo "String $1 and $2 are not Anagrams"; } echo "Enter two Strings: " read a read b isAnagram $a $b ================================================ FILE: Algorithms/String/Isomorphic/Isomorphic-String.java ================================================ import java.util.*; class Main { // Find if strings 'X' and 'Y' are Isomorphic or not public static boolean isIsomorphic(String X, String Y) { // base case if (X == null || Y == null) { return false; } // if 'X' and 'Y' have different lengths, they cannot be isomorphic if (X.length() != Y.length()) { return false; } // use a map to store a mapping from characters of string 'X' to string 'Y' Map map = new HashMap<>(); // use set to store a pool of already mapped characters Set set = new HashSet<>(); for (int i = 0; i < X.length(); i++) { char x = X.charAt(i), y = Y.charAt(i); // if `x` is seen before if (map.containsKey(x)) { // return false if the first occurrence of `x` is mapped to a // different character if (map.get(x) != y) { return false; } } // if `x` is seen for the first time (i.e., it isn't mapped yet) else { // return false if `y` is already mapped to some other char in 'X' if (set.contains(y)) { return false; } // map `y` to `x` and mark it as mapped map.put(x, y); set.add(y); } } return true; } public static void main(String[] args) { Scanner sc= new Scanner(System.in); System.out.println("Enter string x"); String X = sc.nextLine(); sc.nextLine(); System.out.println("Enter string y"); String Y = sc.nextLine(); if (isIsomorphic(X, Y)) { System.out.print(X + " and " + Y + " are Isomorphic"); } else { System.out.print(X + " and " + Y + " are not Isomorphic"); } } } ================================================ FILE: Algorithms/String/Isomorphic/isomorphic.cpp ================================================ #include #include #include #include using namespace std; // Find if strings 'X' and 'Y' are Isomorphic or not bool isIsomorphic(string X, string Y) { // if 'X' and 'Y' have different lengths, they cannot be isomorphic if (X.length() != Y.length()) { return false; } // use a map to store a mapping from characters of string 'X' to string 'Y' unordered_map map; // use set to store a pool of already mapped characters unordered_set set; for (int i = 0; i < X.length(); i++) { char x = X[i], y = Y[i]; // if `x` is seen before if (map.find(x) != map.end()) { // return false if the first occurrence of `x` is mapped to a // different character if (map[x] != y) { return false; } } // if `x` is seen for the first time (i.e., it isn't mapped yet) else { // return false if `y` is already mapped to some other char in 'X' if (set.find(y) != set.end()) { return false; } // map `y` to `x` and mark it as mapped map[x] = y; set.insert(y); } } return true; } int main() { cout<<"Enter String X:"; string X; cin>>X; cout<<"Enter String Y:"; string Y; cin>>Y; if (isIsomorphic(X, Y)) { cout << X << " and " << Y << " are Isomorphic"; } else { cout << X << " and " << Y << " are not Isomorphic"; } return 0; } ================================================ FILE: Algorithms/String/KMP/KMP_Algorithm.php ================================================ ================================================ FILE: Algorithms/String/KMP/kmp.cpp ================================================ // C++ program for implementation of KMP pattern searching // algorithm #include void computeLPSArray(string pat, int M, string lps); // Prints occurrences of txt[] in pat[] void KMPSearch(string pat, string txt) { int M = pat.size(); int N = txt.size(); // create lps[] that will hold the longest prefix suffix // values for pattern int lps[M]; // Preprocess the pattern (calculate lps[] array) computeLPSArray(pat, M, lps); int i = 0; // index for txt[] int j = 0; // index for pat[] while (i < N) { if (pat[j] == txt[i]) { j++; i++; } if (j == M) { printf("Found pattern at index %d ", i - j); j = lps[j - 1]; } // mismatch after j matches else if (i < N && pat[j] != txt[i]) { // Do not match lps[0..lps[j-1]] characters, // they will match anyway if (j != 0) j = lps[j - 1]; else i = i + 1; } } } // Fills lps[] for given patttern pat[0..M-1] void computeLPSArray(string pat, int M, string lps) { // length of the previous longest prefix suffix int len = 0; lps[0] = 0; // lps[0] is always 0 // the loop calculates lps[i] for i = 1 to M-1 int i = 1; while (i < M) { if (pat[i] == pat[len]) { len++; lps[i] = len; i++; } else // (pat[i] != pat[len]) { // This is tricky. Consider the example. // AAACAAAA and i = 7. The idea is similar // to search step. if (len != 0) { len = lps[len - 1]; // Also, note that we do not increment // i here } else // if (len == 0) { lps[i] = 0; i++; } } } } // Driver program to test above function int main() { string txt,pat; cin>>txt>>pat; KMPSearch(pat, txt); return 0; } ================================================ FILE: Algorithms/String/KMP/kmp.js ================================================ 'use strict' test(); // Fills lps[] for given patttern pattern[0..M-1] function buildLPSArray(pattern, M) { let lps = [0]; // First element is always 0 let prefixIndex = 0; let suffixIndex = 1; while(suffixIndex < M) { if(pattern[prefixIndex] === pattern[suffixIndex]){ prefixIndex++; lps[suffixIndex] = prefixIndex; suffixIndex++; } else if (prefixIndex === 0){ lps[suffixIndex] = 0; suffixIndex++; } else { prefixIndex = lps[prefixIndex - 1]; } } return lps; } // Mathc the pattern in a given text function KMPSearch(text, pattern) { const M = pattern.length; const N = text.length; // Create lps[] (longest proper prefix which is also suffix) that will hold the longest prefix suffix // and preprocess it const lps = buildLPSArray(pattern, M); let textIndex = 0; let patterndIndex = 0; while(textIndex < N){ if(text[textIndex] === pattern[patterndIndex]) { if(patterndIndex === M - 1) { return true; } textIndex++; patterndIndex++; } else if(patterndIndex > 0) { patterndIndex = lps[patterndIndex - 1]; } else { patterndIndex = 0; textIndex++; } } return false; } // Test function test() { let text = prompt("Write the text:").split(""); let pattern = prompt("Write the pattern:").split(""); console.log(KMPSearch(text, pattern)); } ================================================ FILE: Algorithms/String/LCS/LCS.py ================================================ A = input("Sequence 1: ") B = input("Sequence 2: ") c = [] def LCS(A,B,m,n): if m==0 or n==0: return 0 elif A[m-1] == B[n-1]: return 1 + LCS(A,B,m-1,n-1) else: return max(LCS(A,B,m,n-1),LCS(A,B,m-1,n)) print(LCS(A,B,len(A),len(B))) ================================================ FILE: Algorithms/String/LCS/lcs.cpp ================================================ #include using namespace std; void lcs( char *X, char *Y, int m, int n ) { int count=0; int L[m+1][n+1]; for (int i=0; i<=m; i++) { for (int j=0; j<=n; j++) { //count++; if (i == 0 || j == 0) L[i][j] = 0; else if (X[i-1] == Y[j-1]) { count++; L[i][j] = L[i-1][j-1] + 1; } else L[i][j] = max(L[i-1][j], L[i][j-1]); } } int index = L[m][n]; char lcs[index+1]; lcs[index] = '\0'; int i = m, j = n; while (i > 0 && j > 0) { if (X[i-1] == Y[j-1]) { lcs[index-1] = X[i-1]; i--; j--; index--; } else if (L[i-1][j] > L[i][j-1]) i--; else j--; } cout << "\nLCS of " << X << " and " << Y << " is " << lcs< #include void print(char* str, int low, int high) { for (int i = low; i <= high; ++i) printf("%c", str[i]); } void longestSubstr(char* str) { int maxLength = 1; int start = 0; int len = strlen(str); int low, high; for (int i = 1; i < len; ++i) { low = i - 1; high = i; while (low >= 0 && high < len && str[low] == str[high]) { if (high - low + 1 > maxLength) { start = low; maxLength = high - low + 1; } --low; ++high; } low = i - 1; high = i + 1; while (low >= 0 && high < len && str[low] == str[high]) { if (high - low + 1 > maxLength) { start = low; maxLength = high - low + 1; } --low; ++high; } } printf("Longest palindrome substring is: "); print(str, start, start + maxLength - 1); } // Driver program to test above functions int main() { char s[1000], i; int n; printf("enter the length of string \n"); scanf("%d", &n); printf("Please enter your string \n"); for(i = 0; i < n; i++){ scanf("%c", &s[i]); } longestSubstr(s); return 0; } ================================================ FILE: Algorithms/String/LPS/longest_palindromic_substring.cpp ================================================ #include #include using namespace std; string expandAroundCenter(string s, int c1, int c2) { int l = c1, r = c2; int n = s.length(); while (l >= 0 && r <= n-1 && s[l] == s[r]) { l--; r++; } return s.substr(l+1, r-l-1); } string LPS(string A) { int n = A.length(); if (n == 0) return ""; string longest = A.substr(0, 1); // a single char itself is a palindrome for (int i = 0; i < n-1; i++) { //for possible odd length palindrome- string p1 = expandAroundCenter(A, i, i); if (p1.length() > longest.length()) longest = p1; //for possible even length palindrome- string p2 = expandAroundCenter(A, i, i+1); if (p2.length() > longest.length()) longest = p2; } return longest; } int main() { string s; getline(cin, s); string answer = LPS(s); cout << answer; return 0; } ================================================ FILE: Algorithms/String/LPS/longest_palindromic_substring.java ================================================ //using dynamic programming approach to solve import java.util.Scanner; class Solution { public static String longestPalindrome(String s) { int n=s.length(); //2-d array to store the palindrome status of each substring -> memory[i][j]=1 iff substring s(i,j) is palindrome otheriwise memory[i][j]=0 int[][] memory = new int[n][n]; int maxLen=1; //maxLen stores current maximum length of palindrome substring int start=0; //start stores the start index of the current longest palindrome string for(int i=n-1;i>=0;i--) { for(int j=i;j2, it is a palindrome if substring s(i+1,j-1) is a palindrome and s(i)==s(j) if(memory[i+1][j-1]==1 && s.charAt(j)==s.charAt(i)) { memory[i][j]=1; int len = j-i+1; if(len>=maxLen) { maxLen=len; start=i; } } } } return s.substring(start,start+maxLen); //returning longest palindrome substring } public static void main(String[] args) { System.out.print("\nEnter a String : "); Scanner scan = new Scanner(System.in); str = scan.next(); System.out.println(longestPalindrome(str)); } } ================================================ FILE: Algorithms/String/LPS/longest_palindromic_substring.js ================================================ const readline = require('readline'); const rl = readline.createInterface({ input: process.stdin, output: process.stdout, }); rl.question( 'Input a string to find the longest palindromic substring: ', (str) => { console.log( `The longest palindromic substring is: ${longestPalSubstr(str)}` ); rl.close(); } ); // Examples // HeyrailataLiarLiveonoevilBye ==> railataliar // Ratsliveonnoevilstar ==> ratsliveonnoevilstar // abraCadabra ==> aca function longestPalSubstr(str) { const n = str.length; // length of input string const s = str.toLowerCase(); // the new string in lowercase to work with // Set a matrix to check substrings (default values to false) // - matrix[i][j] will be false if substring str[i..j] is not palindrome // - otherwise, matrix[i][j] will be true const matrix = new Array(n); for (let i = 0; i < n; i++) { matrix[i] = Array(n).fill(false); } // All substrings of length 1 are palindromes let maxLength = 1; for (let i = 0; i < n; i++) { matrix[i][i] = true; } // Check for substring of length 2. let start = 0; for (let i = 0; i < n - 1; i++) { if (s[i] === s[i + 1]) { matrix[i][i + 1] = true; start = i; maxLength = 2; } } // Check for lengths greater than 2. // k is length of substring for (let k = 3; k <= n; k++) { // Starting index for (let i = 0; i < n - k + 1; i++) { // Ending index of substring from starting index i and length k const j = i + k - 1; // Checking for substring from ith index to jth index // if str.charAt(i+1) to str.charAt(j-1) is a palindrome if (matrix[i + 1][j - 1] && s[i] === s[j]) { matrix[i][j] = true; if (k > maxLength) { start = i; maxLength = k; } } } } return s.slice(start, start + maxLength); } ================================================ FILE: Algorithms/String/LPS/longest_palindromic_substring.py ================================================ def longestPalSubstr(string): """ This function prints the longest palindrome substring (LPS) of string. It also returns the length of the longest palindrome :param string: The string to check for palindrome """ maximumLength = 1 start = 0 length = len(string) low = 0 high = 0 # One by one consider every character as center point of # even and length palindromes for i in range(1, length): # Find the longest even length palindrome with center # points as i-1 and i. low = i - 1 high = i while((low >= 0) and (high < length) and (string[low] == string[high])): if (high - low + 1 > maximumLength): start = low maximumLength = high - low + 1 low -= 1 high += 1 # Find the longest odd length palindrome with center # point as i low = i - 1 high = i + 1 while ((low >= 0) and (high < length) and (string[low] == string[high])): if high - low + 1 > maximumLength: start = low maximumLength = high - low + 1 low -= 1 high += 1 print("Longest palindrome substring is: {}".format(string[start:start + maximumLength])) # Driver program to test above functions string = "anaqwertyuioppoiuytrewqksl" longestPalSubstr(string) ================================================ FILE: Algorithms/String/LPS/longest_palindromic_substring.rb ================================================ puts "Enter the String:" input = gets.chomp puts "Entered String is: '#{input}'." n = input.length table = Array.new(n) { Array.new(n, false) } max_len = 1 i = 0 while (i < n) table[i][i] = true i = i + 1 end start = 0 i = 0 while i < n - 1 if (input[i] == input[i + 1]) table[i][i + 1] = true start = i max_len = 2 end i = i + 1 end k = 3 while k <= n i = 0 while i < (n - k + 1) j = i + k - 1 if (table[i + 1][j - 1] and input[i] == input[j]) table[i][j] = true if k > max_len start = i max_len = k end end i = i + 1 end k = k + 1 end puts "Longest palindromic substring is #{input[start..start+max_len-1]}" ================================================ FILE: Algorithms/String/Palindrome/Palindrome.c ================================================ /** * @author Ytalo Ramon */ #include "stdio.h" #include "stdlib.h" #include "string.h" #define STRINGSIZE 11 int is_palindrome(char *word); int main(int argc, char const *argv[]){ char inputs[STRINGSIZE][STRINGSIZE] = { "ana", "carl", "anaa", "level", "levell", "a", "deified", "deiffied", "civicc", "tesett", "vuc" }; for(int i = 0; i < STRINGSIZE; i++) printf("\"%s\" is palindrome ? %s\n", inputs[i], is_palindrome(inputs[i]) ? "Yes" : "NO"); return 0; } int is_palindrome(char *word){ int i = -1, j = strlen(word); while (i < j && word[++i] == word[--j]); return j <= i; } ================================================ FILE: Algorithms/String/Palindrome/Palindrome.cs ================================================ using System; namespace palindrome { public class Test { public static void Main() { string inp, rev=""; inp = Console.ReadLine(); for(int i=inp.Length-1 ; i>=0;i--) rev = rev + inp[i].ToString(); if(rev.ToLower() == inp.ToLower()) Console.WriteLine("True"); else Console.WriteLine("False"); } } } ================================================ FILE: Algorithms/String/Palindrome/Palindrome.java ================================================ public class palindrome { static boolean isPalindrome(String word) { int length = word.length(); for(int i = 0; i < length/2; i++) { if(word.charAt(i) != word.charAt(length - 1 - i)) { return false; } } return true; } public static void main(String[] args) { System.out.println(isPalindrome("Hello")); System.out.println(isPalindrome("Kayak")); } } ================================================ FILE: Algorithms/String/Palindrome/isPalindrome.cpp ================================================ #include using namespace std; // Check whether the string is palindrome or not considering // only Alpha-Numeric Characters ignoring cases int main() { string s; cin>>s; int l=0,r=s.size()-1; while(l=r) break; if(isupper(s[l])) s[l] = tolower(s[l]); if(isupper(s[r])) s[r] = tolower(s[r]); if(s[l]==s[r]) l++,r--; else break; } if(l ") text, _ := reader.ReadString('\n') // convert CRLF to LF text = strings.Replace(text, "\n", "", -1) if strings.Compare(text, reverse(text)) == 0 { fmt.Println("Palindome!") } else { fmt.Println("Nope.") } } } ================================================ FILE: Algorithms/String/Palindrome/palindrome.java ================================================ public class palindrome { static boolean isPalindrome(String word) { int length = word.length(); for(int i = 0; i < length/2; i++) { if(word.charAt(i) != word.charAt(length - 1 - i)) { return false; } } return true; } public static void main(String[] args) { System.out.println(isPalindrome("Hello")); System.out.println(isPalindrome("Kayak")); } } ================================================ FILE: Algorithms/String/Palindrome/palindrome.js ================================================ const readline = require('readline'); const r1 = readline.createInterface({ input: process.stdin, output: process.stdout }); r1.question('Input a word to check if it is a palindrome: ', (word) => { const isPalindrome = palindromeCheck(word); if (!isPalindrome) { console.log('It is NOT a palindrome!') } else { console.log('It is a palindrome!'); } process.exit(1); }); function palindromeCheck(word) { return word.split('').reverse().join('') === word; } ================================================ FILE: Algorithms/String/Palindrome/palindrome.php ================================================ Bool{ let char = Array(string) for i in 0.. { const isPalindrome: boolean = palindromeCheck(answer); if (!isPalindrome) { console.log('It is NOT a palindrome!') } else { console.log('It is a palindrome!'); } process.exit(1); }); ================================================ FILE: Algorithms/String/Palindrome/palindromecheck.go ================================================ package main import ( "fmt" "strings" ) func Reverse(s string) (result string) { for _, v := range s { result = string(v) + result } return } func isPalindrome(str string) interface{} { if str == Reverse(str) { return true } return false } func main() { var str string fmt.Print("Enter a string: ") fmt.Scan(&str) if isPalindrome(strings.ToUpper(str)) == true { fmt.Print(str, " is a palindrome.") } else { fmt.Print(str, " is not a palindrome.") } } ================================================ FILE: Algorithms/String/README.md ================================================ ## This folder is empty. ================================================ FILE: Algorithms/String/Rabin-Karp/RabinKarpAlgo.java ================================================ public class RabinKarb { // d is the number of characters in the input alphabet public final static int d = 256; //pat -> pattern static void search(String pat, String txt, int primeNum) { int M = pat.length(); int N = txt.length(); int i, j; int p = 0; int t = 0; int h = 1; //assigning the value to the h,t,p for (i = 0; i < M-1; i++) h = (h*d)%primeNum; for (i = 0; i < M; i++) { p = (d*p + pat.charAt(i))%primeNum; t = (d*t + txt.charAt(i))%primeNum; } // Triversing the pattern 1 by 1 for (i = 0; i <= N - M; i++) { if ( p == t ) { /* Check for characters one by one */ for (j = 0; j < M; j++) { if (txt.charAt(i+j) != pat.charAt(j)) break; } if (j == M) System.out.println("Pattern found at index " + i); } // Calculate hash value for next window of text: Remove if ( i < N-M ) { t = (d*(t - txt.charAt(i)*h) + txt.charAt(i+M))%primeNum; // We might get negative value of t, converting it // to positive if (t < 0) t = (t + primeNum); } } } /* Main Method */ public static void main(String[] args) { String txt = "enjoy the life as well as coding :)"; String pattern = "as"; // A prime number int primeNum = 101; // Function Call search(pattern, txt, primeNum); } } ================================================ FILE: Algorithms/String/Rabin-Karp/Rabin_Karp.cpp ================================================ /* Following program is a C++ implementation of Rabin Karp Algorithm given in the CLRS book */ #include using namespace std; // d is the number of characters in the input alphabet #define d 256 /* pat -> pattern txt -> text q -> A prime number */ void search(char pat[], char txt[], int q) { int M = strlen(pat); int N = strlen(txt); int i, j; int p = 0; // hash value for pattern int t = 0; // hash value for txt int h = 1; // The value of h would be "pow(d, M-1)%q" for (i = 0; i < M - 1; i++) h = (h * d) % q; // Calculate the hash value of pattern and first // window of text for (i = 0; i < M; i++) { p = (d * p + pat[i]) % q; t = (d * t + txt[i]) % q; } // Slide the pattern over text one by one for (i = 0; i <= N - M; i++) { // Check the hash values of current window of text // and pattern. If the hash values match then only // check for characters on by one if ( p == t ) { /* Check for characters one by one */ for (j = 0; j < M; j++) { if (txt[i+j] != pat[j]) break; } // if p == t and pat[0...M-1] = txt[i, i+1, ...i+M-1] if (j == M) cout<<"Pattern found at index "<< i< n) return -1; const hash = (charCode: number, exp: number) => { return charCode * Math.pow(base, exp) % prime; }; // hash the pattern and first window for (let i = 0; i < m; i++) { h += hash(pattern.charCodeAt(i), m - i - 1); wh += hash(text.charCodeAt(i), m - i - 1); } h %= prime; wh %= prime; // traverse word for (let i = 0; i <= (n - m); i++) { if (h === wh && pattern === text.substring(i, i + m)) { return i; } else { wh -= hash(text.charCodeAt(i), m - 1); wh *= base; wh %= prime; wh += text.charCodeAt(i + m); wh %= prime; } } return -1; }; ================================================ FILE: Algorithms/String/Rabin-Karp/Rabin_karp.c ================================================ #include #include #include #define MOD 1000000007 // selected prime number int main(){ char pattern[10000], text[1000]; printf("Enter Text:-\n"); scanf("%[^\n]%*c",text); printf("Enter Pattern to be searched :- \n"); scanf("%[^\n]%*c",pattern); int l1 = strlen(pattern), l2 = strlen(text); long long hp = 0, ht = 0, val = 1; long long random = rand()%(MOD-1) + 1; // generating random value x for(int i=0; i= 0 ;i++){ if(i != 0){ long long new_ht = (random*ht-val*text[i-1]+text[l1+i-1])%MOD; new_ht = (new_ht + MOD)%MOD; ht = new_ht; } if(hp == ht){ int j; for (j = 0; j < l1 ; j++){ if (text[i+j] != pattern[j]) break; } if(j == l1) printf("Pattern found at index :- %d\n",i);//output all indices where pattern was //found in text } } return 0; } ================================================ FILE: Algorithms/String/Rabin-Karp/rabin_karp.py ================================================ d=256 def search(pat, txt, q): M = len(pat) N = len(txt) i = 0 j = 0 p = 0 t = 0 h = 1 for i in range(M-1): h = (h * d)% q for i in range(M): p = (d * p + ord(pat[i]))% q t = (d * t + ord(txt[i]))% q for i in range(N-M + 1): if p == t: for j in range(M): if txt[i + j] != pat[j]: break j+= 1 if j == M: print("Pattern found at index " + str(i)) if i < N-M: t = (d*(t-ord(txt[i])*h) + ord(txt[i + M]))% q if t < 0: t = t + q txt = "ABCDEGHABC" pat = "ABC" q = 101 search(pat, txt, q) ================================================ FILE: Algorithms/String/SCS/SCS.cpp ================================================ //DP - LCS // Tabulation #include #include #include #include using namespace std; int static t[1001][1001]; int LCS(string X,string Y,int n,int m) { for(int i=0;i>X>>Y; // memset(t,-1,sizeof(t)); cout<<"Shortest common subsequence between two string is "< using namespace std; typedef long long ll; void count_sort(vector&p,vector&c) { ll n=p.size(); vectorcnt(n); for(auto x:c) cnt[x]++; vectorpos(n),p_new(n); pos[0]=0; for(ll i=1;i>s; s=s+"$"; ll n=s.size(); vector p(n),c(n); //k=0 { std::vector>a(n) ; for(ll i=0;ic_new(n); c_new[p[0]]=0; for(ll i=1;iprev={c[p[i-1]],c[(p[i-1]+(1<now={c[p[i]],c[(p[i]+(1<= lev[v]: u = memo[u][i] if u == v: return v for i in range(log, -1, -1): if memo[u][i] != memo[v][i]: u = memo[u][i] v = memo[v][i] return memo[u][0] print("Enter Number of Nodes") n = input() log = math.ceil(math.log(n, 2)) g = [[] for i in range(n + 1)] memo = [[-1 for i in range(log + 1)] for j in range(n + 1)] lev = [0 for i in range(n + 1)] print("Enter The Edges") for i in range (1, (2*n-1)): m = input() n = input() g[m].append(n) dfs(1, 1, memo, lev, log, g) print("Enter The Edges to find LCA") e1 = input() e2 = input() print("The LCA is", lca(e1, e2, log, lev, memo)) ================================================ FILE: Algorithms/Tree/Binary_Lifting/Binary-Lifting.cpp ================================================ /* Binary Lifting is an algorithm to compute the LCA of two nodes in a tree in O(logn) time complexity. For each node we precompute some of its ancestors above it. Specifically, let's store those ancestor in the array anc, therefore anc[i][j] represents the 2^j th ancestor of the ith node. After pre-calculation of this array, we can determine the LCA of any two nodes in O(logn) time. Time :- For each query, O(logn), n is number of nodes Space :- O(n.logn) */ #include using namespace std; /* timer variabel keeps the track of the order of visit of nodes in our DFS traversal the incoming of dfs and outgoing of a function from the function stack is stored in vin & vout */ int n, u, v, m, tim, cnt; vector vin, vout; vector> adj, anc; void dfs(int ver, int par) { // time at which this particular instance is pushed into function-call stack vin[ver] = ++tim; // 2^0 = 1-st ancestore, or direct parent of the ver vertex anc[ver][0] = par; // the 2^i-th ancestor of ver is the 2^(i-1)-th ancestor of the 2^(i-1)th ancestor of ver // which is already calculated during the dfs traversal for(int i = 1; i <= cnt; ++i) anc[ver][i] = anc[anc[ver][i - 1]][i - 1]; for(int &edge : adj[ver]) { if(edge == par) continue; dfs(edge, ver); } // time at which this particular instance is popped out of function-call stack vout[ver] = ++tim; } // intialising the ancestors of all nodes as the root void precompute(int root) { tim = 0; cnt = floor(log2(n)) + 1; vin.assign(n + 1, 0); vout.assign(n + 1, 0); anc.assign(n + 1, vector(cnt + 1, root)); dfs(root, root); } bool is_Ancestor(int v1, int v2) { return (vin[v1] <= vin[v2] && vout[v1] >= vout[v2]); } int LCA(int v1, int v2) { // check if these are ancestors of each other if(is_Ancestor(v1, v2)) return v1; if(is_Ancestor(v2, v1)) return v2; /* Iterate through all the ancestors of one of the node, then two cases arise - If they have same ancestor, this is one of the possiblities of the answer - If they don't, bring the pointer of first node to this node, and start searching the ancestor of this node for the lowest common one */ for(int i = cnt; i >= 0; --i) { if(!is_Ancestor(anc[v1][i], v2)) v1 = anc[v1][i]; } return anc[v1][0]; } /* POINTS TO NOTE :- # I'll be assuming 1 based indexing of nodes # This implementation is by assuming the tree is rooted at node 1 # adj is the adjacency list of the tree-graph # anc is the array of ancestors of any node */ int main() { cout << "Enter the number of nodes : "; cin >> n; adj.assign(n + 1, vector()); cout << "Enter the edges :- "; for(int i = 1; i < n; ++i) { cin >> u >> v; adj[u].push_back(v); adj[v].push_back(u); } precompute(1); cout << "Enter number of queries : "; cin >> m; while(m--) { cout << "Enter the two vertexes : "; cin >> u >> v; cout << "The LCA of " << u << " and " << v << " is " << LCA(u, v) << endl; } return 0; } ================================================ FILE: Algorithms/Tree/GenericTreeImplementation/GenericTree.c ================================================ #include #include #include #include typedef int element; typedef struct node { element data; struct node *firstchild; struct node *nextsibling; }*GenericTree; GenericTree create() { return NULL; } int isEmpty(GenericTree gt) { return (gt==NULL); } GenericTree build(element e, GenericTree firstchild, GenericTree nextsibling) { GenericTree tree; tree=(GenericTree)malloc(sizeof(struct node)); if(!tree) return NULL; tree->data=e; tree->firstchild=firstchild; tree->nextsibling=nextsibling; return tree; } int nodeCount(GenericTree tree) { if(!tree) return 0; return 1+nodeCount(tree->firstchild)+nodeCount(tree->nextsibling); } int nodeSum(GenericTree tree) { if(!tree) return 0; return tree->data+nodeSum(tree->firstchild)+nodeSum(tree->nextsibling); } int nbS(GenericTree tree) { int count=0; while(tree) { tree=tree->nextsibling; count++; } return count; } int nbC(GenericTree tree) { int count=0; if(tree) tree=tree->firstchild; while(tree) { count++; tree=tree->nextsibling; } return count; } int main() { GenericTree sample=build(1,build(2,NULL,build(3,build(4,NULL,NULL), build(5,build(6,NULL,build(7,build(8,NULL, build(9,NULL,NULL)),NULL)),build(10,build(11,NULL, build(12,NULL,build(13,NULL,NULL))),NULL)))),NULL); printf("Number of nodes: %d\n",nodeCount(sample)); printf("Sum of nodes: %d\n",nodeSum(sample)); printf("Neighbour Siblings: %d\n",nbS(sample)); printf("Neighbour Children: %d\n",nbC(sample)); return 0; } ================================================ FILE: Algorithms/Tree/GenericTreeImplementation/GenericTree.cpp ================================================ #include #include #include using namespace std; class treenode{ public: int data; vector children; treenode(int data){ this->data = data; } ~treenode(){ for (int i = 0; i < children.size(); i++) { delete children[i]; } } }; treenode* takeinput(){ queue pendingnodes; cout<<"enter root data"<>rootdata; treenode* root = new treenode(rootdata); pendingnodes.push(root); while (!pendingnodes.empty()) { treenode* currentnode = pendingnodes.front(); pendingnodes.pop(); cout<<"enter no of child of "<data<>n; for (int i = 0; i < n; i++) { int currentchilddata; cout<<"enter "<data<>currentchilddata; treenode* childnode = new treenode(currentchilddata); currentnode->children.push_back(childnode); pendingnodes.push(childnode); } } return root; } void printtree(treenode* root){ queue pendingnodes; pendingnodes.push(root); while (!pendingnodes.empty()) { treenode* currentnode = pendingnodes.front(); pendingnodes.pop(); string tobeprinted = to_string(currentnode->data)+":"; for (int i = 0; i < currentnode->children.size(); i++) { tobeprinted += to_string(currentnode->children[i]->data)+","; pendingnodes.push(currentnode->children.at(i)); } cout< child; Node(int d) { this.d = d; child = new ArrayList<>(); } } private Node r; GenericTreeImplementation() { Scanner s = new Scanner(System.in); this.r = good(s, null, 0); } private Node good(Scanner s, Node parent, int i) { if (parent == null) { System.out.println("Enter info for root node"); } else { System.out.println("Enter info for " + i + "th child of " + parent.d); } int d = s.nextInt(); Node node = new Node(d); System.out.println("Enter the number of child for" + node.d); int n = s.nextInt(); for (int k = 0; k < n; k++) { Node children = good(s, node, k); node.child.add(children); } return node; } } ================================================ FILE: Algorithms/Tree/LCA/LCA.cpp ================================================ /* Leetcode Problem Link: https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/ */ /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: TreeNode *lowestCommonAncestor(TreeNode *root, TreeNode *p, TreeNode *q) { if (root == NULL || root == p || root == q) return root; TreeNode *left = lowestCommonAncestor(root->left, p, q); TreeNode *right = lowestCommonAncestor(root->right, p, q); if (left == NULL) return right; if (right == NULL) return left; return root; } }; ================================================ FILE: Algorithms/Tree/LCA/LCA.cs ================================================ using System; // A binary tree node public class Node { public int data; public Node left, right; public Node(int item) { data = item; left = right = null; } } public class BinaryTree { public Node root; /* Function to find LCA of n1 and n2. The function assumes that both n1 and n2 are present in BST */ public virtual Node lca(Node node, int n1, int n2) { if (node == null) { return null; } // If both n1 and n2 are smaller than root, then LCA lies in left if (node.data > n1 && node.data > n2) { return lca(node.left, n1, n2); } // If both n1 and n2 are greater than root, then LCA lies in right if (node.data < n1 && node.data < n2) { return lca(node.right, n1, n2); } return node; } /* Driver program to test lca() */ public static void Main(string[] args) { // Let us construct the BST shown in the above figure BinaryTree tree = new BinaryTree(); tree.root = new Node(20); tree.root.left = new Node(8); tree.root.right = new Node(22); tree.root.left.left = new Node(4); tree.root.left.right = new Node(12); tree.root.left.right.left = new Node(10); tree.root.left.right.right = new Node(14); int n1 = 10, n2 = 14; Node t = tree.lca(tree.root, n1, n2); Console.WriteLine("LCA of " + n1 + " and " + n2 + " is " + t.data); n1 = 14; n2 = 8; t = tree.lca(tree.root, n1, n2); Console.WriteLine("LCA of " + n1 + " and " + n2 + " is " + t.data); n1 = 10; n2 = 22; t = tree.lca(tree.root, n1, n2); Console.WriteLine("LCA of " + n1 + " and " + n2 + " is " + t.data); } } ================================================ FILE: Algorithms/Tree/LCA/LCA.js ================================================ // Lowest Common Ancestor of a Binary Tree /** * Definition for a binary tree node. * function TreeNode(val) { * this.val = val; * this.left = this.right = null; * } */ /** * @param {TreeNode} root * @param {TreeNode} p * @param {TreeNode} q * @return {TreeNode} */ var lowestCommonAncestor = function (root, p, q) { if (!root || root === p || root === q) return root; var left = LCA(root.left, p, q); // left traversal var right = LCA(root.right, p, q); // right traversal return left && right ? root : left || right; }; ================================================ FILE: Algorithms/Tree/LCA/LCA.py ================================================ # Leetcode Problem Link: # https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/ # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode': if root == None or root == p or root == q: return root left = self.lowestCommonAncestor(root.left,p,q) right = self.lowestCommonAncestor(root.right,p,q) if left == None: return right if right == None: return left return root ================================================ FILE: Algorithms/Tree/Max_Heap_Construction/minmaxheap.cpp ================================================ #include using namespace std; void min_heapify(int *heap,int i,int n) { int j, temp; temp = heap[i]; j = 2 * i; while (j <= n) { if (j < n && heap[j+1] < heap[j]) j = j + 1; if (temp < heap[j]) break; else if (temp >= heap[j]) { heap[j/2] = heap[j]; j = 2 * j; } } heap [j/2] = temp; return; } void build_minheap(int *heap, int n) { int i; for(i = n/2; i >= 1; i--) { min_heapify(heap,i,n); } } void max_heapify(int *heap, int i, int n) { int j, temp; temp = heap[i]; j = 2 * i; while (j <= n) { if (j < n && heap[j+1] > heap[j]) j = j + 1; if (temp > heap[j]) break; else if (temp <= heap[j]) { heap[j / 2] = heap[j]; j = 2 * j; } } heap[j/2] = temp; return; } void build_maxheap(int *heap,int n) { int i; for(i = n/2; i >= 1; i--) { max_heapify(heap,i,n); } } int main() { int n, i, ch; cout<<"\n ENTER THE SIZE OF HEAP :"; cin>>n; int heap[20]; cout<<"\n ENTER THE ELEMENTS : "; for (i = 1; i <= n; i++) { cin>>heap[i]; } do { cout<<"\n\n\t\t OPERATIONS MENU\n\t\t1.Min Heap\n\t\t2.Max Heap\n\t\t3.Exit "; cout<<"\n ENTER YOUR CHOICE :"; cin>>ch; switch(ch) { case 1: { build_minheap(heap, n); cout<<"Min Heap\n"; for (i = 1; i <= n; i++) { cout<left); int rightNodeToNode=maxPathSum_(root->right); int max_=max(leftNodeToNode,rightNodeToNode)+root->val; maxSum= max(maxSum,max(leftNodeToNode+rightNodeToNode+root->val,max(root->val,max_))); return max(max_,root->val); } int maxPathSum(TreeNode* root) { maxPathSum_(root); return maxSum; } }; ================================================ FILE: Algorithms/Tree/Max_Path_Sum_BST/Max_Path_Sum_BST.py ================================================ """Max Path Sum In Binary Tree - Write a function that takes in a Binary Tree and returns its max path sum. A path is a collection of connected nodes in a tree where no node is connected to more than two other nodes; a path sum is the sum of the values of the nodes in a particular path. Each BinaryTree node has an integer value , a left child node, and a right child node. Children nodes can either be BinaryTree nodes themselves or None / null .""" # For dynamic user input import unittest numberList = [] n = int(input("Enter the list size : ")) print("\n") for i in range(0, n): print("Enter number at location", i, ":") item = int(input()) numberList.append(item) print("User List is ", numberList) class TestProgram(unittest.TestCase): def test_case_1(self): test = BinaryTree(1).insert(numberList) maxPathSum(test) class BinaryTree: def __init__(self, value): self.value = value self.left = None self.right = None def insert(self, values, i=0): if i >= len(values): return queue = [self] while len(queue) > 0: current = queue.pop(0) if current.left is None: current.left = BinaryTree(values[i]) break queue.append(current.left) if current.right is None: current.right = BinaryTree(values[i]) break queue.append(current.right) self.insert(values, i + 1) return self # O(N) T | O(1) S def maxPathSum(tree): _, maxSum = findMaxSum(tree) return maxSum def findMaxSum(tree): if tree is None: return(0, float("-inf")) leftSumAsBranch, leftMaxPathSum = findMaxSum(tree.left) rightSumAsBranch, rightMaxPathSum = findMaxSum(tree.right) maxChildSumAsBranch = max(leftSumAsBranch, rightSumAsBranch) value = tree.value maxSumAsBranch = max(maxChildSumAsBranch+value, value) maxSumUsingRootNode = max( maxSumAsBranch, leftSumAsBranch + value + rightSumAsBranch) runningMaxPathSum = max( leftMaxPathSum, rightMaxPathSum, maxSumUsingRootNode) return (maxSumAsBranch, runningMaxPathSum) ================================================ FILE: Algorithms/Tree/Min_Heap_Construction/README.md ================================================ ### Min Heap Construction Implement a MinHeap class that supports: - Building a Min Heap from an input array of integers. - Inserting integers in the heap. - Removing the heap's minimum / root value. - Peeking at the heap's minimum / root value. - Sifting integers up and down the heap, which is to be used when inserting and removing values. Note that the heap should be represented in the form of an array. ================================================ FILE: Algorithms/Tree/Min_Heap_Construction/min-heap-construc.cpp ================================================ using System; using System.Collections.Generic; public class Program { public class MinHeap { public List heap = new List(); public MinHeap(List array) { heap = buildHeap(array); } //O(n) time | O(1) space public List buildHeap(List array) { int firstParentIdx = (array.Count - 2) / 2; for (int currentIdx = firstParentIdx; currentIdx >= 0; currentIdx--) { siftDown(currentIdx, array.Count - 1, array); } return array; } // O(log(n)) time | O(1) space public void siftDown(int currentIdx, int endIdx, List heap) { int childOneIdx = currentIdx * 2 + 1; while (childOneIdx <= endIdx) { int childTwoIdx = currentIdx * 2 + 2 <= endIdx ? currentIdx * 2 + 2 : -1; int idxToSwap; if (childTwoIdx != -1 && heap[childTwoIdx] < heap[childOneIdx]) { idxToSwap = childTwoIdx; } else { idxToSwap = childOneIdx; } if (heap[idxToSwap] < heap[currentIdx]) { swap(currentIdx, idxToSwap, heap); currentIdx = idxToSwap; currentIdx = currentIdx * 2 + 1; } else { return; } } } //O(log(n)) time | O(1) space public void siftUp(int currentIdx, List heap) { int parentIdx = (currentIdx - 1) / 2; while (currentIdx > 0 && heap[currentIdx] < heap[parentIdx]) { swap(currentIdx, parentIdx, heap); currentIdx = parentIdx; parentIdx = (currentIdx - 1) / 2; } } public int Peek() { return heap[0]; } public int Remove() { swap(0, heap.Count - 1, heap); int valueToRemove = heap[heap.Count - 1]; heap.RemoveAt(heap.Count - 1); siftDown(0, heap.Count - 1, heap); return valueToRemove; } public void Insert(int value) { heap.Add(value); siftUp(heap.Count - 1, heap); } public void swap(int i, int j, List heap) { int temp = heap[j]; heap[j] = heap[i]; heap[i] = temp; } } } ================================================ FILE: Algorithms/Tree/Min_Heap_Construction/min-heap-construc.py ================================================ class MinHeap: def __init__(self, array): self.heap = self.buildHeap(array) # O(N)T | O(1)S def buildHeap(self, array): firstParentIdx = (len(array)-2) // 2 for currIdx in reversed(range(firstParentIdx+1)): self.siftDown(currIdx, len(array)-1, array) return array # O(logN)T | O(1)S def siftDown(self, currIdx, endIdx, heap): childOneIdx = currIdx*2 + 1 while childOneIdx <= endIdx: childTwoIdx = currIdx*2 + 2 if currIdx*2 + 2 <= endIdx else -1 if childTwoIdx != -1 and heap[childTwoIdx] < heap[childOneIdx]: idxToSwap = childTwoIdx else: idxToSwap = childOneIdx if heap[idxToSwap] < heap[currIdx]: self.swap(currIdx, idxToSwap, heap) currIdx = idxToSwap childOneIdx = currIdx*2+1 else: return # O(logN)T | O(1)S def siftUp(self, currIdx, heap): parentIdx = (currIdx-1) // 2 while currIdx > 0 and heap[currIdx] < heap[parentIdx]: self.swap(currIdx, parentIdx, heap) currIdx = parentIdx parentIdx = (currIdx-1) // 2 # O(1)T | O(1)S def peek(self): # Write your code here. return self.heap[0] # O(logN)T | O(1)S def remove(self): self.swap(0, len(self.heap)-1, self.heap) valueToRemove = self.heap.pop() self.siftDown(0,len(self.heap)-1,self.heap) return valueToRemove # O(logN)T | O(1)S def insert(self, value): self.heap.append(value) self.siftUp(len(self.heap)-1,self.heap) def swap(self,i,j,heap): heap[i],heap[j]=heap[j],heap[i] ================================================ FILE: Algorithms/Tree/README.md ================================================ # This folder is empty. ================================================ FILE: Algorithms/Tree/Sorted-Array-To-BST/Sorted-Array-To-BST.cpp ================================================ #include using namespace std; /* A Binary Tree node */ class TNode { public: int data; TNode* left; TNode* right; }; TNode* newNode(int data); /* A function that constructs Balanced Binary Search Tree from a sorted array */ TNode* sortArrayToBST(int arr[], int start, int end) { /* Base Case */ if (start > end) return NULL; /* Get the middle element and make it root */ int mid = (start + end)/2; TNode *root = newNode(arr[mid]); /* Recursively construct the left subtree and make it left child of root */ root->left = sortArrayToBST(arr, start, mid - 1); /* Recursively construct the right subtree and make it right child of root */ root->right = sortArrayToBST(arr, mid + 1, end); return root; } /* Helper function that allocates a new node with the given data and NULL left and right pointers. */ TNode* newNode(int data) { TNode* node = new TNode(); node->data = data; node->left = NULL; node->right = NULL; return node; } /* A utility function to print preorder traversal of BST */ void preOrder(TNode* node) { if (node == NULL) return; cout << node->data << " "; preOrder(node->left); preOrder(node->right); } // Driver Code int main() { int n; cin>>n; int arr[n]; for(i=0;i>arr; } /* Convert List to BST */ TNode *root = sortArrayToBST(arr, 0, n-1); cout << "PreOrder Traversal of constructed BST \n"; preOrder(root); return 0; } ================================================ FILE: Algorithms/Tree/Sorted_Array_To_BST/SortedArrayToBST.java ================================================ class Node { int data; Node left, right; Node(int d) { data = d; left = right = null; } } class BinaryTree { Node sortedArrayToBST(int arr[], int start, int end) { if (start > end) { return null; } /* Get the middle element and make it root */ int mid = (start + end) / 2; Node node = new Node(arr[mid]); //Construct the left subtree and make it //left child of root using recursion node.left = sortedArrayToBST(arr, start, mid - 1); //Construct the right subtree and make it //right child of root using recursion node.right = sortedArrayToBST(arr, mid + 1, end); return node; } //Print preorder traversal of BST void preOrder(Node node) { if (node == null) { return; } System.out.print(node.data + " "); preOrder(node.left); preOrder(node.right); } } public class SortedArrayToBST { public static void main(String[] args) { Scanner sc = new Scanner(System.in); BinaryTree tree = new BinaryTree(); System.out.println("Please Enter the Size of the Array:"); int n = sc.nextInt(); int arr[] = new int[n]; for(int i=0; i %s \n", Arrays.toString(arr)); System.out.println("\nGenerating BST from Sorted Array...."); Node root = tree.sortedArrayToBST(arr, 0, n - 1); System.out.println("\nPreorder traversal of generated BST"); tree.preOrder(root); } } /* * OUTPUT=> * * Please Enter the Size of the Array: * 6 * Enter Array element 1: * 46 * Enter Array element 2: * 88 * Enter Array element 3: * 15 * Enter Array element 4: * 76 * Enter Array element 5: * 31 * Enter Array element 6: * 62 * * Processing Array.... * Sorted Array -> [15, 31, 46, 62, 76, 88] * * Generating BST from Sorted Array.... * * Preorder traversal of generated BST * 46 15 31 76 62 88 * */ ================================================ FILE: Algorithms/Tree/Validate_BST/Validate_BST.cpp ================================================ #include #define MIN -1000 #define MAX 1000 using namespace std; // helper structures and functions struct node { struct node * left; struct node * right; int val; int maxTillNow; int minTillNow; node(int k): val(k), left(NULL), right(NULL), maxTillNow(MIN), minTillNow(MAX) {} }; int max(int a, int b){ return a > b ? a : b; } int min(int a, int b){ return a < b ? a : b; } // This method sets the min and max at each node // when the node represents a root of a subtree starting from that node // this a a resursive // dfs // implementation void setMaxMinTillNode( node * root){ if(root == NULL){ return; } int ansMx = root->val; int ansMn = root->val; if( root->left != NULL){ setMaxMinTillNode(root->left); ansMx = max(ansMx, root->left->maxTillNow); ansMn = min(ansMn, root->left->minTillNow); } if( root->right != NULL){ setMaxMinTillNode(root->right); ansMx = max(ansMx, root->right->maxTillNow); ansMn = min(ansMn, root->right->minTillNow); } root->maxTillNow = ansMx; root->minTillNow = ansMn; } // this method checks the current node with the min of the right subtree and with the max of left subtree // the is a resursive // dfs // implementation bool isBST(node * root){ if( root == NULL ){ false; } if( root->left == NULL && root->right == NULL){ return true; } bool leftResult = true; if( root->left != NULL){ if( root->val < root->left->maxTillNow){ leftResult = false; return leftResult; } leftResult = isBST(root->left); } bool rightResult = true; if( root->right != NULL){ if( root->val > root->right->minTillNow){ rightResult = false; return rightResult; } rightResult = isBST(root->right); } return leftResult && rightResult; } // this is the driver function int main() { // your code goes here node * root = new node(4); node * a = new node(1); node * b = new node(2); node * c = new node(3); node * d = new node(5); root->left = b; b->left = a; b->right = c; root->right = d; setMaxMinTillNode(root); cout << "Is the Tree a Valid BST? Ans:" << ( isBST(root) ? "yes :)" : "nops :(") << endl; node * e = new node(1); d->right = e; setMaxMinTillNode(root); cout << "Is the Tree a Valid BST? Ans:" << ( isBST(root) ? "yes :)" : "nops :(") << endl; e->val = 10; setMaxMinTillNode(root); cout << "Is the Tree a Valid BST? Ans:" << ( isBST(root) ? "yes :)" : "nops :(") << endl; return 0; } ================================================ FILE: Algorithms/Tree/Validate_BST/Validate_BST.cs ================================================ using System; internal class Node { public int value; public Node left, right; public Node(int item) { value = item; left = right = null; } } public class Validate_BST { static bool IsBST( Node node, int currentMinimum = Int32.MinValue, int currentMaximum = Int32.MaxValue) { if (node == null) { return true; } if (node.value < currentMinimum || node.value > currentMaximum) { return false; } return (IsBST(node.left, currentMinimum, node.value - 1) && IsBST(node.right, node.value + 1, currentMaximum)); } public static void Main(string[] args) { Node treeRoot1 = new Node(7); treeRoot1.left = new Node(5); treeRoot1.right = new Node(8); treeRoot1.left.left = new Node(4); treeRoot1.left.right = new Node(6); Console.WriteLine(IsBST(treeRoot1) ? "This tree is a BST" : "This tree is not a BST"); Node treeRoot2 = new Node(2); treeRoot2.left = new Node(6); treeRoot2.left.right = new Node(5); treeRoot2.right = new Node(1); treeRoot2.right.left = new Node(8); treeRoot2.right.right = new Node(10); Console.WriteLine(IsBST(treeRoot2) ? "This tree is a BST" : "This tree is not a BST"); } } ================================================ FILE: Algorithms/Tree/Validate_BST/Validate_BST.java ================================================ import java.util.*; class Node { //class describing structure of the tree node int value; Node left; Node right; Node(int value) { this.value = value; left = right = null; } } class Solution { //Recursive functions to determine whether given tree is valid BST or not public boolean isValidBST(Node root) { return helper(root,null,null); } public boolean helper(Node root, Integer small, Integer large) { if(root==null) return true; if(small!=null && root.val<=small) return false; if(large!=null && root.val>=large) return false; return helper(root.left,small,root.val) && helper(root.right,root.val,large); } } public class Validate_BST { //main class public static void main(String[] args){ Scanner scanner = new Scanner(System.in); Solution object = new Solution(); Node TreeRoot1 = new Node(10); TreeRoot1.left = new Node(5); TreeRoot1.right = new Node(12); TreeRoot1.left.left = new Node(4); TreeRoot1.left.right = new Node(6); boolean answer1 = object.isValidBST(TreeRoot1); if(answer1==true) System.out.println("Tree is a valid BST"); else System.out.println("Tree is not a valid BST"); Node TreeRoot2 = new Node(2); TreeRoot2.left = new Node(6); TreeRoot2.right = new Node(1); TreeRoot2.left.right = new Node(5); TreeRoot2.right.left = new Node(8); TreeRoot2.right.right = new Node(11); boolean answer2 = object.isValidBST(TreeRoot2); if(answer2==true) System.out.println("Tree is a valid BST"); else System.out.println("Tree is not a valid BST"); } } ================================================ FILE: Algorithms/Tree/level_traversing/level_traversing.php ================================================ val = $val; $this->left = $left; $this->right = $right; } } class Solution {//Recursive solution for level order traversal /** * @param TreeNode $root * @return Integer[][] */ function levelOrder($root) { $res = []; $level = 0; $this->helper($root, $res, $level); return $res; } function helper($node, &$mainList, $level) { if (is_null($node)) return; $size = count($mainList); if ($level > $size) { $cur = array($node->val); $mainList[$level] = $cur; } else { $mainList[$level][] = $node->val; } $this->helper($node->left, $mainList, $level+1); $this->helper($node->right, $mainList, $level+1); } } ?> ================================================ FILE: Algorithms/Tree/level_traversing/level_traversing.py ================================================ # author: Karthik Hegde # date: 2/10/2021 # Level order traversal on BST implementation in python from collections import deque from typing import List, Optional import sys #Definition for a binary tree node. class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right def levelOrder(root: TreeNode) -> List[List[int]]: traversal = [] if not root: # if root doesn't exist return traversal queue = deque([root]) # level order traversal while(queue): level_lst =[] queue_len = len(queue) for i in range(queue_len): node = queue.popleft() print(node.val) level_lst.append(node.val) if (node.left): # if node.left exists queue.append(node.left) if (node.right): # if node.right exists queue.append(node.right) traversal.append(level_lst) return traversal ## ---- taking input and running -----### def recurse_input(i, node_lst): if (i>=len(node_lst) or node_lst[i]=='None'): return None root = TreeNode(int(node_lst[i])) root.left = recurse_input(2*i+1, node_lst) root.right = recurse_input(2*i+2, node_lst) return root def run(): ## as input pls give a list of ints # in the input list, children of element at index i are elements at 2*i + 1 and 2*i + 2 # if particular node is null, type None # example input: 0 1 2 None 5 6 None None None 8 ''' 0 / \ 1 2 /\ / 5 6 / 8 ''' node_lst = sys.stdin.readline().split() root = recurse_input(0, node_lst) lst = levelOrder(root) print(lst) if __name__ == "__main__": run() ================================================ FILE: CNAME ================================================ dsa.ahampriyanshu.com ================================================ FILE: CODE_OF_CONDUCT.md ================================================ # Contributor Covenant Code of Conduct ## Our Pledge In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation. ## Our Standards Examples of behavior that contributes to creating a positive environment include: * Using welcoming and inclusive language * Being respectful of differing viewpoints and experiences * Gracefully accepting constructive criticism * Focusing on what is best for the community * Showing empathy towards other community members Examples of unacceptable behavior by participants include: * The use of sexualized language or imagery and unwelcome sexual attention or advances * Trolling, insulting/derogatory comments, and personal or political attacks * Public or private harassment * Publishing others' private information, such as a physical or electronic address, without explicit permission * Other conduct which could reasonably be considered inappropriate in a professional setting ## Our Responsibilities Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior. Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful. ## Scope This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers. ## Enforcement Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at ahampriyanshu@gmail.com. All complaints will be reviewed and investigated and will result in a response that is deemed necessary and appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately. Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership. ## Attribution This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html [homepage]: https://www.contributor-covenant.org For answers to common questions about this code of conduct, see https://www.contributor-covenant.org/faq ================================================ FILE: CONTRIBUTING.md ================================================ # Contributing Guidelines ## Naming Convention * Title Case (not camel case, lowercase or uppercase) * ``-`` or no-space in between the words (not ``_`` , whitespace, or anything else) | Example | | |-- |-- | heapsort.cpp | ❌ | Heap-sort.cpp | ❌ | heap_sort.cpp | ❌ | heap sort.cpp | ❌❌❌ | Heap-Sort.cpp | ✅ | HeapSort.cpp | ✅ ## Here are some suggestions you should be following while contributing to this repository: * Always verify if the issue you wish to create already exists or not. * Ask for the issue that you plan to complete. * Commit message should be of the stated syntax. * Do not commit multiple files. * In ``algorithms`` always commit programs that take dynamic input and more preferably through stdin over reading a file. * When naming the functions or variables use meaningfull name instead of a1,a2,a3. * Every PR would be reviewed before it gets merged. ================================================ FILE: CONTRIBUTORS.md ================================================ ### Contributors
Priyanshu
Priyanshu Tiwari
Vimlesh
Vimlesh Kumar
Nirali
Nirali Sanghvi
Vaibhav
Vaibhav Shukla
p-davide/
p-davide
Chinmay
Chinmay Mehta
Jayant
Jayant Goel
MONISHA
MONISHA MANDAL
Gautam
Gautam Jain
Subham
Subham Mohanty
huisenbr/
huisenbr
Samkit
Samkit Shah
Aakash
Aakash Deep Soni
Vaibhav
Vaibhav Sharma
Anshmish/
Anshmish
Ayush
Ayush Sharma
Happy
Happy singh
Meet
Meet Rajesh Gor
abkabd/
abkabd
manvendra3/
manvendra3
Archit
Archit garg
Antonio
Antonio Torres
Deepak2417/
Deepak2417
Harshal
Harshal S Zodape
Mohanish
Mohanish Kashiwar
Pratik
Pratik Sanghavi
Rudransh24/
Rudransh24
Shristi
Shristi Negi
Toulik
Toulik Das
Adaa
Adaa Mgbede
hanyangl/
hanyangl
Pranjal
Pranjal Agrawal
Shadab
Shadab Ali
esheetaparulekar/
esheetaparulekar
Thomas
Thomas Biedermann
Manishita
Manishita Choudhary
Aayush
Aayush Sharma
Prodip
Prodip Kumar Paul
Tanuj
Tanuj Sharma
sanjiti0606/
sanjiti0606
b1ackd0t/
b1ackd0t
Soundarya
Soundarya Khanapur
Yogesh
Yogesh Vaishnav
Geetansh
Geetansh Jindal
BYZANTINE26/
BYZANTINE26
Aarti
Aarti singh
Abhinav
Abhinav Tiwari
Akshat
Akshat Jain
Deepak
Deepak Kumar Giri
Meghna
Meghna Saxena
Rahul
Rahul Sunil
Rushikesh
Rushikesh Tote
Sandip
Sandip Dutta
Sanika/
Sanika
Sidj581/
Sidj581
Yash
Yash Sharma
harlansgs/
harlansgs
Luis
Luis Diaz
JayavardhaniKathika/
JayavardhaniKathika
Ronit
Ronit Raj
Jayanta
Jayanta Saren
Alessandro
Alessandro Arosio
Daniele
Daniele De Martino
Hrithik
Hrithik Raj
Jaswant
Jaswant Singh
KKghub/
KKghub
Rachel
Rachel Leona
Rezwan
Rezwan Al Kaoser
Vivek
Vivek Raman
Vladyslav
Vladyslav Nekriach
anshupatel06/
anshupatel06
cuber485/
cuber485
harshita-sharma11/
harshita-sharma11
Rhea/
Rhea
taresh18/
taresh18
Ankit
Ankit Sanghvi
Marko/
Marko
git12121/
git12121
Amulya/
Amulya
Vardan
Vardan Narula
AjinkyaSahu/
AjinkyaSahu
Arihant
Arihant Bansal
DIV1SINGH/
DIV1SINGH
Davi
Davi Fontenele
Diadochokinetic/
Diadochokinetic
Folashade/
Folashade
Himanshu
Himanshu Mishra
Khusboo
Khusboo Bothra
Krishna
Krishna Kumar
Lakshitha
Lakshitha Wisumperuma
Misha
Misha Kushka
Nehal
Nehal Gupta
Sachin
Sachin Jindal
Tushar
Tushar Diwakar
Vikas
Vikas Tiwari
VishwaroopShah/
VishwaroopShah
adrputra/
adrputra
aishuo07/
aishuo07
Betsy
Betsy Stevens
Sai
Sai Suraj
Gerardo
Gerardo A. Abantao Jr.
nikhiltanna/
nikhiltanna
prajwlr/
prajwlr
rebelfire888/
rebelfire888
Yuvraj
Yuvraj Singh
Junead
Junead Khan
parthzz/
parthzz
Raj
Raj Anand
Aditya
Aditya Prakash
Adrika
Adrika
Apoorva/
Apoorva
Aryan/
Aryan
Avninder
Avninder Preet Singh
David
David Davó
Dwij
Dwij Mehta
Gerald
Gerald Amezcua
Hans
Hans Holani
Himanshu
Himanshu Hansaria
Jack
Jack Kendall
KNVS
KNVS Sai Sneha
Kader
Kader M.
KamalAres/
KamalAres
Nihal
Nihal Ahamed
Mihir
Mihir Mahajani
Mikadore/
Mikadore
Nayanika/
Nayanika
Reyad
Reyad Khan
Sachin19k/
Sachin19k
Sayantan
Sayantan Pal
Sudipta
Sudipta Banik
ulieckstein/
ulieckstein
VRINDA
VRINDA GOYAL
J.Y.
J.Y. Ramon Almeida G.
aanneettgg/
aanneettgg
bobbysaprey420/
bobbysaprey420
Aarti
Aarti Rathi
bharatchhipa/
bharatchhipa
SayaniG371/
SayaniG371
Deep
Deep Dhar
DHTALAN/
DHTALAN
harshitashankar/
harshitashankar
Hemang
Hemang Sinha
Juliana
Juliana Sinai
lucid-dreem/
lucid-dreem
maityankan10/
maityankan10
Mario
Mario Martinez
Rohan
Rohan Brid
sbhavya18/
sbhavya18
Utkarsh
Utkarsh Gupta
Sourab
Sourab Maity
Ashish
Ashish garg
Bryan
Bryan Wu
Alejandro
Alejandro Myrick
ashivamj2105/
ashivamj2105
Abhishek
Abhishek Kumar
Aditya
Aditya Gonnade
Aishwarya
Aishwarya Singh
Aman
Aman Jain
Arsenic/
Arsenic
Atharv
Atharv Phadnis
Chandresh
Chandresh Singh
Dandy
Dandy Naufaldi
Daniel
Daniel Otulagun
GGolfz/
GGolfz
Garima
Garima Mishra
Gaurav/
Gaurav
Geoff
Geoff George
Guilherme
Guilherme Andrade
Nimish
Nimish Srivastava
PRANESH
PRANESH GUPTA
Parjanya
Parjanya Aditya Shukla
Parth
Parth Gupta
Priya
Priya Mandal
Divyansh
Divyansh Singh
Rishabh
Rishabh Jain
SalmonKing72/
SalmonKing72
Shreyash0713/
Shreyash0713
Shubham
Shubham Goswami
Soumik
Soumik Mukherjee
Swastika
Swastika Sarangi
Tanishq
Tanishq R Porwar
Upamanyu
Upamanyu Das
Vaishnavi
Vaishnavi Shah
Varadraj
Varadraj Galgali
Vinay
Vinay Pathak
Yatindra
Yatindra Kumar Srivastava
Aditya
Aditya Malik
ashima0699/
ashima0699
brane/
brane
demonslayer99/
demonslayer99
Dipankar
Dipankar Goswami
vrenzolaverace/
vrenzolaverace
Shruti
Shruti Jain
harshitgupta2000/
harshitgupta2000
Harshit
Harshit Suthar
manan288/
manan288
Jaya
Jaya Ganesh Kumar Gudipati
krishnmohan
krishnmohan Baghel
kugiyasan/
kugiyasan
Melissa
Melissa Huerta Dev
Rashmi
Rashmi garg
Rohan
Rohan Gupta
swat-rash/
swat-rash
Syamil
Syamil Abdillah
yogesh-kansal/
yogesh-kansal
Etienne
Etienne Plante
Ajeya
Ajeya Bhat
Alifbhanvadiya14/
Alifbhanvadiya14
Enzo
Enzo Robaina
Rahul
Rahul Raj
Aditi
Aditi Mandloi
3t8/
3t8
AdhitiS/
AdhitiS
Aditya
Aditya Harsh
Ajinkya
Ajinkya Jeurkar
Alexander/
Alexander
Alexsey
Alexsey Ramzaev
Alvin
Alvin Uday
Amit
Amit Kumar Agarwal
Aniket
Aniket Rochwani
Ankit
Ankit Goel
Ankur
Ankur Kayal
Arjan/
Arjan
Arjun
Arjun Gaud
Atithi
Atithi kumari
War
War Machine
Ayush
Ayush Jain
Ayush
Ayush Singh
Chakradhar
Chakradhar Palaparthi
DCoder/
DCoder
Devanshi
Devanshi Jain
Digislaw/
Digislaw
Divyansh
Divyansh Garg
Elsha
Elsha E. Kwee
Enrique
Enrique García Torres
Gauri
Gauri Mishra
Harikesh
Harikesh Pallantla
Harsh-1906/
Harsh-1906
Ishan
Ishan Gala
Ítalo
Ítalo Vinícius
Jaynish007/
Jaynish007
JimmyFromRobotics/
JimmyFromRobotics
Joao
Joao Pedro Campos Silva
Kartik
Kartik Kumar Thakur
Keval
Keval Prajapati
Kishore/
Kishore
Lee
Lee Jun Yong
Luis
Luis F. Talavera R.
Mahima
Mahima Sawant
Manan
Manan Jain
megabyte98/
megabyte98
Mariano
Mariano Echavarria
Matheus
Matheus Pereira
Mayur
Mayur Selukar
Mohit/
Mohit
SNIPERSHOTAA/
SNIPERSHOTAA
MrNaif2018/
MrNaif2018
NEENA-XAVIER/
NEENA-XAVIER
Naman
Naman Mittal
Nathan
Nathan Pickard
Neha
Neha Kumari
Nikitha
Nikitha Rangineni
Nimesha
Nimesha Dilini
Omkar
Omkar Prabhune
Onkar
Onkar Gagare
Ose
Ose Oaiya
Pranjal
Pranjal Bansal
Prasheel-IITI/
Prasheel-IITI
Rajwrita/
Rajwrita
Rishika
Rishika Soni
Sahil
Sahil Kesarwani
Sayan
Sayan Majhi
ShubhamJamuar/
ShubhamJamuar
Shweta
Shweta Singh
Siddharth
Siddharth Shah
SnehjeetBenz/
SnehjeetBenz
Souraprabha
Souraprabha Ganguly
Sudesh
Sudesh Kumar
Sumit
Sumit Kumar Sahu
Sushantrimurti/
Sushantrimurti
Swarn10/
Swarn10
Swati
Swati Gupta
Yash
Yash Raj Singh Bisht
The
The Black Cat
Tomáš
Tomáš Lokša
William
William Gooch
Yash
Yash khandelwal
Yashodhan
Yashodhan Joshi
Yatharth
Yatharth Vyas
aanshi18/
aanshi18
Aayushi
Aayushi Agarwal
abhinav889/
abhinav889
ABHINAV
ABHINAV JONNADA
Abid/
Abid
Afeefa
Afeefa Abdullah Manjanoor
Alejandro
Alejandro Aragon
alkatrivedi/
alkatrivedi
Anuva
Anuva Bhattacharjee
aorellano/
aorellano
Dhruv
Dhruv Arora
ayush_manglani/
ayush_manglani
Deepam
Deepam Priyadarshi
erikkvalvik/
erikkvalvik
Anwaar
Anwaar Khalid
gourav
gourav majee
Brandon/
Brandon
Jyoti
Jyoti Gambhir
Aman
Aman Parauliya
pmanca/
pmanca
pradyumn
pradyumn sharma
Pulkit
Pulkit Sapra
Mayank
Mayank Goyal
Rishab
Rishab Purkayastha
rishikeshreddyakkireddy/
rishikeshreddyakkireddy
Lakshmi
Lakshmi Sairam Kakarla
shagun/
shagun
shockedeel/
shockedeel
sourabh
sourabh kumar
Souvick
Souvick roy
Aryamaan
Aryamaan jain
subhadeep1912/
subhadeep1912
superconscript/
superconscript
Rafael
Rafael Vieira Rosenzvaig
venkyvt7/
venkyvt7
Dheeraj
Dheeraj Bhagchandani
Gagan-Shenoy/
Gagan-Shenoy
KevinMathewTh/
KevinMathewTh
Kinshuk
Kinshuk Dua
Mayank
Mayank Jha
Kunal
Kunal D. Sonawane
ASHMITA
ASHMITA DE
Aaryan
Aaryan Gupta
Abantika20/
Abantika20
Abhay
Abhay Bhatt
Abheet
Abheet Arora
Abhishek
Abhishek Shukla
Adil-S786/
Adil-S786
Aditya
Aditya Krishna
Akaash
Akaash Trivedi
amishaagarwal1998/
amishaagarwal1998
AnaGVF/
AnaGVF
Ankit
Ankit Juyal
ankurj00/
ankurj00
Ace117MC/
Ace117MC
Anshu
Anshu Sinha
Anshul
Anshul Agarwal
Anshul
Anshul Bhatia
Anu9518/
Anu9518
Apoorv
Apoorv Lodhi
Apostolos
Apostolos Diavolitsis
Apurva
Apurva Chandra Bhaskar
ArchanaDhaker/
ArchanaDhaker
Archit
Archit Gupta
Arpit
Arpit Mallick
Ashutosh
Ashutosh Kumar
Ashwin
Ashwin G
Aviral
Aviral Gupta
Balaguru
Balaguru Ragupathi
Bhushan
Bhushan Mhatre
Bidya
Bidya Dasgupta
Uchechukwu
Uchechukwu Nwafor
Chirag
Chirag Jagad
Chitresh
Chitresh Goel
Christopher
Christopher Servius
CommitIt55/
CommitIt55
DIVYANSH
DIVYANSH GARG
Deepjyot
Deepjyot Kaur
Devenkapoor7303/
Devenkapoor7303
Dheeraj/
Dheeraj
Divya
Divya Agarwal
Divyansh
Divyansh Rastogi
Divyessh
Divyessh Maheshwari
Durgesh
Durgesh Ahire
dvir019/
dvir019
Garvit
Garvit Banga
Girish
Girish Thatte
Gitansh
Gitansh Kapoor
Goutham
Goutham R
Kevin
Kevin Wu
Guy
Guy Greenleaf
Ahmed
Ahmed Hanafy
Harsh
Harsh Kumar
HarshUdai/
HarshUdai
Harsh
Harsh Vardhan
Harshgupta5901/
Harshgupta5901
Harshith
Harshith Venkatesh
Himanshu
Himanshu Nishal
Himanshu-Nagle/
Himanshu-Nagle
Hritik
Hritik Jaiswal
Hyun
Hyun Ji Lee
I
I Gusti Agung Vivekananda
Janav/
Janav
Jatin
Jatin Garg
choijean/
choijean
Jo
Jo Dunham
Joyeta
Joyeta Saha
Juan
Juan Manuel Otegui
Kashish888/
Kashish888
Kasi
Kasi Raj
Kelvin
Kelvin Wong
Krishna
Krishna Biswakarma
Kriti
Kriti Gandotra
Kritika
Kritika Pathak
Lakshay
Lakshay Singhal
LuanDevecchi/
LuanDevecchi
Lucas
Lucas Bivar
Luis
Luis Arturo García Gonzalez
Luis
Luis De Anda
M
M Satyagovind
Manas
Manas Uniyal
Manas173/
Manas173
Manav
Manav Arora
Manav
Manav Gupta
Marvin
Marvin Javier
Mayukh
Mayukh Mitra
Mika/
Mika
Mini/
Mini
Mohit
Mohit Pandey
Mukund
Mukund Bhole
Neeraj
Neeraj Ap
NILADRI
NILADRI BIT
Nidhi
Nidhi Nivedita
Nishit
Nishit Bansal
Omar
Omar Ahmed
PUSHPASINGH00/
PUSHPASINGH00
poloso/
poloso
PIYUSH
PIYUSH BIST
Patrick
Patrick Ofili
Pavnesh
Pavnesh Chaturvedi
pranjalkumar153/
pranjalkumar153
Priyank
Priyank Kumar
Priyanka
Priyanka Yadav
================================================ FILE: Collection/ArrayDeque/ArrayDeque.java ================================================ import java.util.*; /* ArrayDeque abstract data structure :- An ArrayDeque (also known as an "Array Double Ended Queue", pronounced as "ArrayDeck") is a special kind of a growable array that allows us to add or remove an element from both sides. The ArrayDeque data structure is implemented in java collections framework through the ArrayDeque interface We can also say that ArrayDeque is a collections framework API that realizes the ArrayDeque abstract data structure */ public class ArrayDequeDemo { public static void main(String[] args) { Scanner in = new Scanner(System.in); // Creating an ArrayDeque of integers ArrayDeque ArrDq = new ArrayDeque(); // We can also create an ArrayDeque of other data types like Character or String etc. System.out.println("Instruction Format : command_ name element_value"); System.out.println("1. Add an element to the front or left end of ArrayDeque : command-> \"addFirst value\". Example \"addFirst 20\" will add 20 to the front of ArrayDeque"); System.out.println("2. Add an element to the end or right end of ArrayDeque : command-> \"addLast value\" .Example \"addLast 50\" will add 50 to the rear end of ArrayDeque"); System.out.println("3. Remove the element at the front or left end of ArrayDeque : command-> \"removeFirst\""); System.out.println("4. Remove the element at the rear end or right end of ArrayDeque : command-> \"removeLast\""); System.out.println("5. Show the present size of the ArrayDeque : command-> \"size\""); System.out.println("6. Check if the ArrayDeque is empty : command-> \"isEmpty\""); System.out.println("7. Exit the program: command-> \"Exit\""); // Note that the method names are same the commands to do a specific operation on ArrayDeque while(true) { String[] command = in.nextLine().split(" "); boolean got_value = false; try { String command_name = command[0]; int value = 0; int output = 0; if (command.length > 1) { value = Integer.parseInt(command[1]); got_value = true; } switch(command_name) { case "addFirst" : // addFirst method adds an element to the front (left) end of the ArrayDeque if (got_value) ArrDq.addFirst(value); else throw new NumberFormatException(); break; case "addLast" : // addLast method adds an element to the rear (right) end of the ArrayDeque if (got_value) ArrDq.addLast(value); else throw new NumberFormatException(); break; case "removeFirst" : // removeFirst method removes and returns an element from the front (left) end of the ArrayDeque output = ArrDq.removeFirst(); System.out.println("Removed " + output + " from the front of the ArrayDeque"); break; case "removeLast" : // removeLast method removes and return an element from the rear (right) end of the ArrayDeque output = ArrDq.removeLast(); System.out.println("Removed " + output + " from the end of the ArrayDeque"); break; case "size" : // size method returns the present size of ArrayDeque output = ArrDq.size(); System.out.println("Size of the ArrayDeque is : " + output); break; case "isEmpty" : // isEmpty method returns a boolean true if the ArrayDeque is empty else it return false Boolean empty = ArrDq.isEmpty(); if (empty) System.out.println("Array deque is Empty"); else System.out.println("Array deque is not Empty"); break; case "Exit": in.close(); return; default : System.out.println("Please enter a valid command"); } System.out.println("ArrayDeque : "); System.out.println(ArrDq); } catch(NumberFormatException e) { System.out.println("Please enter a valid number"); } catch(Exception e) { System.out.println("Exception :" + e.getMessage()); } } } } ================================================ FILE: Collection/ArrayDeque/README.md ================================================ # This folder is empty. ================================================ FILE: Collection/ArrayList/ArrayList .java ================================================ import java.util.ArrayList; import java.util.Collections; import java.util.Scanner; public class Arraylist { public static void main(String[] args) { Scanner sc = new Scanner(System.in); //Array List implementation ArrayList number = new ArrayList(); //Entering elements from 1 to 5 using add method for(int i=1;i<=5;i++) { number.add(i); } //size() method can be used to tell number of elements in the list for(int i=0;i newlist = new ArrayList(); for(int i=10;i<=15;i++) { newlist.add(i); } //To add another list elements to previous list number.addAll(newlist); //To delete all elements in a list newlist.clear(); System.out.println(); //To check whether the list is empty or not if(newlist.isEmpty()) { System.out.println("The list is empty"); } //To get index of an element int index = number.indexOf(new Integer(7)); //To remove the element with index number.remove(index); //We can also sort an list using Collections.sort(number); for(int i=0;i hashMap = new HashMap<>(); System.out.println("Instructions:"); System.out.println("\t1. Add value: \""+COMMAND_ADD+" key value\" . Example: \"a name Rezwan\" here, key = 'name' , value = 'Rezwan' "); System.out.println("\t2. Show value: \""+COMMAND_VALUE+" key_name_here\""); System.out.println("\t3. Remove value: \""+COMMAND_REMOVE+" key_name_here\""); System.out.println("\t4. check if key exists : \""+COMMAND_IS_KEY_EXISTS+" key_name_here\""); System.out.println("\t5. check if value exists : \""+COMMAND_IS_VALUE_EXISTS+" value_name_here\""); System.out.println("\t7. See ALl Keys : \""+COMMAND_ALL_KEY+"\""); System.out.println("\t8. See ALl Values : \""+COMMAND_ALL_VALUE+"\""); System.out.println("\t9. See current HashMap conditions: \""+COMMAND_SHOW+"\""); System.out.println("\t10. Size of the HashMap: \""+COMMAND_SIZE+"\""); System.out.println("\t11. Exit program: \""+COMMAND_QUIT+"\""); while (true) { // dividing the command string and number value String[] tempCommand = myScanner.nextLine().split(" "); try{ String commandName = String.valueOf(tempCommand[0]); String str1 = "", str2 = ""; if(tempCommand.length == 2){ str1 = String.valueOf(tempCommand[1]); } else if(tempCommand.length == 3){ str1 = String.valueOf(tempCommand[1]); str2 = String.valueOf(tempCommand[2]); } //checking command name and performing accordingly switch (commandName){ case COMMAND_ADD: hashMap.put(str1, str2); System.out.println(str1+ "-" +str2 + " added"); break; case COMMAND_VALUE: System.out.println( hashMap.get(str1) + " is the value of KEY = "+ str1); break; case COMMAND_REMOVE: hashMap.remove(str1); System.out.println( "Pair of " +str1 + " KEY is removed"); break; case COMMAND_IS_KEY_EXISTS: if(hashMap.containsKey(str1)){ System.out.println(str1 + " key exists in the hashmap"); } else{ System.out.println(str1 + " key doesn't exist in the hashmap"); } break; case COMMAND_IS_VALUE_EXISTS: if(hashMap.containsValue(str1)){ System.out.println(str1 + " value exists in the hashmap"); } else{ System.out.println(str1 + " value doesn't exist in the hashmap"); } break; case COMMAND_ALL_KEY: System.out.println("All Keys: "+hashMap.keySet()); break; case COMMAND_ALL_VALUE: System.out.println("All Values: "+hashMap.values()); break; case COMMAND_SIZE: System.out.println("HashMap size is "+hashMap.size()+" right now"); break; case COMMAND_SHOW: System.out.println(hashMap); break; case COMMAND_QUIT: return; default: System.out.println("Invalid command format"); break; } } catch (NumberFormatException e){ System.out.println("Invalid command format"); } catch (Exception e){ System.out.println("Exception: "+ e.getMessage()); } } } } ================================================ FILE: Collection/HashMap/README.md ================================================ # This folder is empty. ================================================ FILE: Collection/HashSet/HashSet.java ================================================ import java.util.HashSet; import java.util.Iterator; import java.util.Scanner; class HashSetDemo { //constant command strings private static final String COMMAND_ADD= "a"; private static final String COMMAND_REMOVE = "r"; private static final String COMMAND_IS_VALUE_EXISTS = "?v"; private static final String COMMAND_ALL_VALUE = "av"; private static final String COMMAND_ITERATE_ALL_VALUE = "i"; private static final String COMMAND_CLEAR = "c"; private static final String COMMAND_SIZE = "si"; private static final String COMMAND_SHOW = "sh"; private static final String COMMAND_QUIT= "q"; public static void main(String[] args) { Scanner myScanner = new Scanner(System.in); // HashSet ensure there is no duplicate value in it HashSet hashSet = new HashSet<>(); System.out.println("Instructions:"); System.out.println("\t1. Add value: \""+COMMAND_ADD+" value\" . Example: \"a 44\" here, 44 is added"); System.out.println("\t2. Remove value: \""+COMMAND_REMOVE+" value_here\""); System.out.println("\t3. check if value exists : \""+COMMAND_IS_VALUE_EXISTS+" value_here\""); System.out.println("\t4. See ALl Values : \""+COMMAND_ALL_VALUE+"\""); System.out.println("\t5. Iterate through all values : \""+COMMAND_ITERATE_ALL_VALUE+"\""); System.out.println("\t6. Clear HashSet : \""+COMMAND_CLEAR+"\""); System.out.println("\t7. See current HashSet conditions: \""+COMMAND_SHOW+"\""); System.out.println("\t8. Size of the HashSet: \""+COMMAND_SIZE+"\""); System.out.println("\t9. Exit program: \""+COMMAND_QUIT+"\""); while (true) { // dividing the command string and number value String[] tempCommand = myScanner.nextLine().split(" "); try{ String commandName = String.valueOf(tempCommand[0]); int value = 0; if(tempCommand.length == 2){ value = Integer.parseInt(tempCommand[1]); } //checking command name and performing accordingly switch (commandName){ case COMMAND_ADD: if(hashSet.add(value)){ System.out.println(value+ " is added to the hashset"); } else{ System.out.println(value+ " is already on the hashset"); } break; case COMMAND_REMOVE: if(hashSet.remove(value)){ System.out.println(value+ " is removed from hashset"); } else{ System.out.println(value+ " remove failed"); } break; case COMMAND_IS_VALUE_EXISTS: if(hashSet.contains(value)){ System.out.println(value + " value exists in the hashset"); } else{ System.out.println(value + " value doesn't exist in the hashset"); } break; case COMMAND_ALL_VALUE: System.out.println("All Values: "+hashSet); break; case COMMAND_ITERATE_ALL_VALUE: Iterator i = hashSet.iterator(); int c = 1; while (i.hasNext()){ System.out.println("Serial "+ c + " is : " +i.next()); c++; } System.out.println("----------------"); break; case COMMAND_SIZE: System.out.println("HashSet size is "+hashSet.size()+" right now"); break; case COMMAND_SHOW: System.out.println(hashSet); break; case COMMAND_QUIT: return; default: System.out.println("Invalid command format"); break; } } catch (NumberFormatException e){ System.out.println("Invalid command format"); } catch (Exception e){ System.out.println("Exception: "+ e.getMessage()); } } } } ================================================ FILE: Collection/HashSet/README.md ================================================ # This folder is empty. ================================================ FILE: Collection/LinkedList/LinkedHashSet/README.md ================================================ # This folder is empty. ================================================ FILE: Collection/LinkedList/LinkedList.java ================================================ // LinkedList is a very useful and famous data structure which is linear in nature. This data structure is used to add elements dynamically without any fixed memory size. // This feature makes it advantageous over simple arrays, where initially the array size gets fixed and which may result in unused extra memory or shortange of memory size. //Here we try to implement in-built LinkedList in java and see some of its methods like add(),addFist(),addLast(),remove(),removeFirst(),removeLast(),set()..etc. //This package has the LinkedList class(which implements List interface. import java.util.*; class LinkedListDemo{ public static void main(String args[]){ //This is how we initialise a linkedlist named 'list' with Data type as String which will be stored. LinkedList list=new LinkedList(); Scanner sc=new Scanner(System.in); System.out.println("Enter the number strings to be added in list initially"); int n=sc.nextInt(); while(n-->0){ String str=sc.next(); //Use this to input from user. list.add(str); //keep on adding the strings. } //The list elements get added one after the other and its printed as in order. System.out.println(list); // we can use other methods like addFirst() and addLast() to add elements at the beginning and the last System.out.println("Enter the string you want to add at the beginning"); String starting_str=sc.next(); list.addFirst(starting_str); System.out.println("Enter the string you want to add at the ending"); String ending_str=sc.next(); list.addLast(ending_str); System.out.println("Updated list->"+list); //Other common methods are removing elements from front and last; list.removeFirst(); list.removeLast(); System.out.println("Updated list after deleting first and last node->"+list); String str1=list.getFirst(); String str2=list.getLast(); System.out.println("First Node is"+str1); System.out.println("Last Node is"+str2); //Since its indexed, we can also set element at specified position and also remove by specifying the position System.out.println("Enter the index and String you want to insert at"); int ind=sc.nextInt(); String new_str=sc.next(); list.set(ind,new_str); list.addFirst("LinkedList DEMO from @PrakashAditya17::"); //Random string added here System.out.println("UPDATED LIST->"+list); System.out.println("Enter the position of any String you want to remove"); int ind_remove=sc.nextInt(); list.remove(ind_remove); //For iteration we can use use the following way. for(String ele : list) System.out.print(ele+","); } } ================================================ FILE: Collection/LinkedList/README.md ================================================ # This folder is empty. ================================================ FILE: Collection/Queue/Deque/Deque.java ================================================ import java.util.*; class DequeDemo{ //constant command strings private static final String COMMAND_ADDLAST = "al"; private static final String COMMAND_REMOVELAST = "rl"; private static final String COMMAND_ADDFIRST = "af"; private static final String COMMAND_REMOVEFIRST = "rf"; private static final String COMMAND_FIRSTVALUE = "f"; private static final String COMMAND_SHOWREMOVEFIRST = "srf"; private static final String COMMAND_SHOWREMOVELAST = "srl"; private static final String COMMAND_LASTVALUE = "l"; private static final String COMMAND_SIZE = "si"; private static final String COMMAND_SHOW = "sh"; private static final String COMMAND_QUIT= "q"; public static void main(String[] args) { Scanner myScanner = new Scanner(System.in); // Deque is an interface. there are two deque implementations : Deque arrayDeque = new ArrayDeque(); // 1. using ArrayDeque instance Deque linkedListDeque = new ArrayDeque(); //2. using LinkedList instance //Deque is a double ended queue. It's possible to add or remove element from both head and tail System.out.println("Instructions: \"command_name _value\" , for example: al 44"); System.out.println("\t1. Add value at the end command: \""+COMMAND_ADDLAST+"\" . Example: \"al 11\" will add 11 at the end"); System.out.println("\t2. Remove value from the end command: \""+COMMAND_REMOVELAST+"\" "); System.out.println("\t3. Add value at the beginning command: \""+COMMAND_ADDFIRST+"\""); System.out.println("\t4. Remove value from the beginning command: \""+COMMAND_REMOVEFIRST+"\""); System.out.println("\t5. First value: \""+COMMAND_FIRSTVALUE+"\""); System.out.println("\t6. Last value: \""+COMMAND_LASTVALUE+"\""); System.out.println("\t7. Show and Remove First value: \""+COMMAND_SHOWREMOVEFIRST+"\""); System.out.println("\t8. Show and Remove Last value: \""+COMMAND_SHOWREMOVELAST+"\""); System.out.println("\t9. Size of the Deque: \""+COMMAND_SIZE+"\""); System.out.println("\t10. See current Deque conditions: \""+COMMAND_SHOW+"\""); System.out.println("\t11. Exit program: \""+COMMAND_QUIT+"\""); while (true) { // dividing the command string and number value String[] tempCommand = myScanner.nextLine().split(" "); try{ String commandName = String.valueOf(tempCommand[0]); int value = 0; //if only command without value, then we need not try parsing value if(tempCommand.length > 1){ value = Integer.parseInt(tempCommand[1]); } //checking command name and performing accordingly boolean isDone = false; switch (commandName){ case COMMAND_ADDLAST: isDone = arrayDeque.offerLast(value); if(isDone){ System.out.println(value + " is added to last"); } break; case COMMAND_ADDFIRST: isDone = arrayDeque.offerFirst(value); if(isDone){ System.out.println(value + " is added to the first"); } break; case COMMAND_REMOVEFIRST: System.out.println(arrayDeque.removeFirst() + " is removed from first"); break; case COMMAND_FIRSTVALUE: System.out.println(arrayDeque.getFirst() + " is first value right now"); break; case COMMAND_SHOWREMOVEFIRST: System.out.println(arrayDeque.pollFirst() + " is first value which is just removed from deque."); break; case COMMAND_SHOWREMOVELAST : System.out.println(arrayDeque.pollLast() + " is last value which is just removed from deque."); break; case COMMAND_LASTVALUE: System.out.println(arrayDeque.getLast() + " is last value right now"); break; case COMMAND_SIZE: System.out.println("Deque size is "+arrayDeque.size()+" right now"); break; case COMMAND_SHOW: System.out.println(arrayDeque); break; case COMMAND_QUIT: return; default: System.out.println("Invalid command format"); break; } } catch (NumberFormatException e){ System.out.println("Invalid command format"); } catch (Exception e){ System.out.println("Exception: "+ e.getMessage()); } } } } ================================================ FILE: Collection/Queue/Deque/README.md ================================================ # This folder is empty. ================================================ FILE: Collection/Queue/PriorityQueue/PriorityQueue.java ================================================ import java.util.PriorityQueue; import java.util.Scanner; class PriorityQueueDemo{ //constant command strings private static final String COMMAND_ADD= "a"; private static final String COMMAND_REMOVE = "r"; private static final String COMMAND_FIRSTVALUE = "f"; private static final String COMMAND_SHOWREMOVE = "sr"; private static final String COMMAND_SIZE = "si"; private static final String COMMAND_SHOW = "sh"; private static final String COMMAND_QUIT= "q"; public static void main(String[] args) { Scanner myScanner = new Scanner(System.in); //the elements keeping on PriorityQueue must be implements Comparable interface. // In this case, Integer implements Comparable interface // PriorityQueue is automatically rearranged based on priority set by toCompare() overridden method PriorityQueue priorityQueue = new PriorityQueue(); System.out.println("Instructions: \"command_name _value\" , for example: a 44"); System.out.println("\t1. Add value: \""+COMMAND_ADD+"\" . Example: \"a 11\" will add 11 at the priority queue"); System.out.println("\t2. First/Peek value: \""+COMMAND_FIRSTVALUE+"\""); System.out.println("\t3. Remove First/Peek value: \""+COMMAND_REMOVE+"\""); System.out.println("\t4. Show and Remove First/Peek value: \""+COMMAND_SHOWREMOVE+"\""); System.out.println("\t5. Size of the Deque: \""+COMMAND_SIZE+"\""); System.out.println("\t6. See current Deque conditions: \""+COMMAND_SHOW+"\""); System.out.println("\t7. Exit program: \""+COMMAND_QUIT+"\""); while (true) { // dividing the command string and number value String[] tempCommand = myScanner.nextLine().split(" "); try{ String commandName = String.valueOf(tempCommand[0]); int value = 0; //if only command without value, then we need not try parsing value if(tempCommand.length > 1){ value = Integer.parseInt(tempCommand[1]); } //checking command name and performing accordingly boolean isDone = false; switch (commandName){ case COMMAND_ADD: isDone = priorityQueue.offer(value); if(isDone){ System.out.println(value + " is added"); } else{ System.out.println(value + " couldn't add !"); } break; case COMMAND_REMOVE: priorityQueue.remove(); System.out.println( "first value is removed from priority queue."); break; case COMMAND_FIRSTVALUE: System.out.println(priorityQueue.peek() + " is first value right now"); break; case COMMAND_SHOWREMOVE: System.out.println(priorityQueue.poll() + " is first value which is just removed from priority queue."); break; case COMMAND_SIZE: System.out.println("PriorityQueue size is "+priorityQueue.size()+" right now"); break; case COMMAND_SHOW: System.out.println(priorityQueue); break; case COMMAND_QUIT: return; default: System.out.println("Invalid command format"); break; } } catch (NumberFormatException e){ System.out.println("Invalid command format"); } catch (Exception e){ System.out.println("Exception: "+ e.getMessage()); } } } } ================================================ FILE: Collection/Queue/PriorityQueue/README.md ================================================ # This folder is empty. ================================================ FILE: Collection/Queue/Queue.java ================================================ import java.util.ArrayDeque; import java.util.Queue; import java.util.Scanner; public class Main { public static void main(String[] args) { //get dynamic inputs Scanner sc = new Scanner(System.in); String[] inputNumbers = sc.nextLine().split(" "); //define queue Queue q = new ArrayDeque(); // Add values to queue for (String n: inputNumbers) q.add(Integer.parseInt(n)); // Display contents of the queue. System.out.println("Elements of queue " + q); //To view the size of the queue int size = q.size(); System.out.println("Size of queue is: " + size); // To remove the head of queue. int removedele = q.remove(); System.out.println("removed element is: " + removedele); System.out.println("Elements of queue after remove " + q); // To view the head of queue without removing. int head = q.peek(); System.out.println("head of queue is: " + head); //To check if it is empty or not. System.out.println("Is queue empty : " + q.isEmpty()); //clearing the whole queue q.clear(); System.out.println("After clearing queue " + q); } } ================================================ FILE: Collection/Queue/README.md ================================================ # This folder is empty. ================================================ FILE: Collection/README.md ================================================ # Index * [ArrayList](ArrayList/) * [ArrayDeque](ArrayDeque/) * [Vector](Vector/) * [LinkedList](LinkedList/) * [HashSet](HashSet/) * [HashMap](HashMap/) * [Queue](Queue/) * [Stack](Stack/) ================================================ FILE: Collection/Stack/README.md ================================================ # This folder is empty. ================================================ FILE: Collection/Stack/StackCollection.java ================================================ import java.io.*; import java.util.*; public class StackCollection{ public static void main(String[] args) { Scanner input = new Scanner(System.in); Stack st = new Stack(); //create a object of class stack //Adding 5 elements to the stack int n = 5; for(int i=0;i vec = new Vector(n); for (int i = 0; i < n; i++) vec.add(sc.nextInt()); System.out.println(vec); vec.remove(0); System.out.println(vec); } } ================================================ FILE: DOCUMENTATION.md ================================================ # Title * Description # Sub Topics * [Name](Relative_path/) * [Name](Relative_path/) * [Name](Relative_path/) # Methods | Operation | Description |:--|:-- | Name | Desc | Name | Desc | Name | Desc # Time Complexity | Operation | Complexity |:--|:-- |Access | O() |Search | O() |Insertion | O() |Deletion | O() # Implementation | Language | View | Code |:--: |:--: |:--: | c++ | [Github](https://github.com/ahampriyanshu/algo_ds_101/blob/main/folder/subfolder/filename.ext) | [Raw](filename.cpp) | c | [Github](https://github.com/ahampriyanshu/algo_ds_101/blob/main/folder/subfolder/filename.ext) | [Raw](filename.c) | java | [Github](https://github.com/ahampriyanshu/algo_ds_101/blob/main/folder/subfolder/filename.ext) | [Raw](filename.java) | js | [Github](https://github.com/ahampriyanshu/algo_ds_101/blob/main/folder/subfolder/filename.ext) | [Raw](filename.js) | ts | [Github](https://github.com/ahampriyanshu/algo_ds_101/blob/main/folder/subfolder/filename.ext) | [Raw](filename.ts) | py | [Github](https://github.com/ahampriyanshu/algo_ds_101/blob/main/folder/subfolder/filename.ext) | [Raw](filename.py) | cs | [Github](https://github.com/ahampriyanshu/algo_ds_101/blob/main/folder/subfolder/filename.ext) | [Raw](filename.cs) | rb | [Github](https://github.com/ahampriyanshu/algo_ds_101/blob/main/folder/subfolder/filename.ext) | [Raw](filename.rb) | php | [Github](https://github.com/ahampriyanshu/algo_ds_101/blob/main/folder/subfolder/filename.ext) | [Raw](filename.php) | go | [Github](https://github.com/ahampriyanshu/algo_ds_101/blob/main/folder/subfolder/filename.ext) | [Raw](filename.go) | scala | [Github](https://github.com/ahampriyanshu/algo_ds_101/blob/main/folder/subfolder/filename.ext) | [Raw](filename.scala) | swift | [Github](https://github.com/ahampriyanshu/algo_ds_101/blob/main/folder/subfolder/filename.ext) | [Raw](filename.swift) | haskell | [Github](https://github.com/ahampriyanshu/algo_ds_101/blob/main/folder/subfolder/filename.ext) | [Raw](filename.haskell) | bash | [Github](https://github.com/ahampriyanshu/algo_ds_101/blob/main/folder/subfolder/filename.ext) | [Raw](filename.bash) | kotlin | [Github](https://github.com/ahampriyanshu/algo_ds_101/blob/main/folder/subfolder/filename.ext) | [Raw](filename.kotlin) ================================================ FILE: Data-Structures/Array/Array.c ================================================ #include #include int main() { int* ptr; int n; printf("Enter number of elements:\n"); scanf("%d",&n); // Dynamically allocate memory using malloc() ptr = (int*)malloc(n * sizeof(int)); // Get the elements of the array printf("Input the elements of the array\n"); for (int i = 0; i < n; ++i) { scanf("%d",&ptr[i]); } printf("The elements of the array are:\n"); for (int i = 0; i < n; ++i) { printf("%d ", ptr[i]); } return 0; } ================================================ FILE: Data-Structures/Array/Array.cpp ================================================ #include using namespace std; int main() { int n; //number of elements as input cin >> n; int arr[n]; //initiallize array for(int i =0;i> arr[i]; // input the elements } for(int i=0;i { const rl = readline.createInterface({ input: process.stdin, output: process.stdout, }); return new Promise((resolve, reject) => { try { rl.question(prompt, (answer) => { rl.close(); resolve(answer); }); } catch (error) { rl.close(); reject(error); } }); } async function main() { // Ask user the number of elements they want to enter const n = await readInput('How many elements do you want to enter: '); // Create a new array const array = new Array(parseInt(n)); // Ask user to enter up to `n` elements in the array // elements will be of type `string` for (let i = 0; i < array.length; i++) { array[i] = await readInput(`Enter element ${i}: `); } // Print the array console.log(array); } main(); ================================================ FILE: Data-Structures/Array/README.md ================================================ ## Array An array is a container to store a fixed number of items of the same data type under a single name. Each data item of the array can be accessed by using a number called an “index” or “subscript”. ## Types of Arrays 1. One Dimensional Array ## Declaration of Single Dimensional Array ```bash datatype arrayName [ size ] ; ``` ## Initialization of Single Dimensional Array ```bash datatype arrayName [ size ] = {value1, value2, ...} ; ``` ## Accessing Elements of Single Dimensional Array ```bash arrayName [ indexValue ] ``` 2. Two Dimensional Array ## Declaration of Two Dimensional Array ```bash datatype arrayName [ rowSize ] [ columnSize ] ; ``` ## Accessing Individual Elements of Two Dimensional Array ```bash arrayName [ rowIndex ] [ columnIndex ] ``` 3. Multi Dimensional Array ## Declaration of Multi Dimensional Array ```bash datatype arrayName [ 1stDimensionSize ] [ 2ndDimensionSize ] ... [ nthDimensionSize ] ; ``` ## Accessing Individual Elements of Multi Dimensional Array ```bash arrayName [ 1stDimensionIndex ] [ 2ndDimensionIndex ] ... [ nthDimensionIndex ] ; ``` ================================================ FILE: Data-Structures/Array/array_menudriven.cpp ================================================ // this code is contributed by Harsh Vardhan #include using namespace std; class Array { private: int *A; int size; int length; void swap(int *x,int *y); public: Array() { size=10; length=0; A=new int[size]; } Array(int sz) { size=sz; length=0; A=new int[size]; } ~Array() { delete []A; } void Display(); void Append(int x); void Insert(int index,int x); int Delete(int index); int LinearSearch(int key); int BinarySearch(int key); int Get(int index); void Set(int index,int x); int Max(); int Min(); int Sum(); float Avg(); void Reverse(); void Reverse2(); void InsertSort(int x); int isSorted(); void Rearrange(); Array* Merge(Array arr2); Array* Union(Array arr2); Array* Diff(Array arr2); Array* Inter(Array arr2); }; // function for displaying element of array void Array::Display() { int i; cout<<"\nElements are\n"; for(i=0;i=0 && index <=length) { for(i=length;i>index;i--) A[i]=A[i-1]; A[index]=x; length++; } } //function for deleting from an array int Array::Delete(int index) { int x=0; int i; if(index>=0 && index=0 && index=0 && index< length) A[index]=x; } //function for finding max element in an array int Array::Max() { int max=A[0]; int i; for(i=1;imax) max=A[i]; } return max; } //function for finding min element in an array int Array::Min() { int min=A[0]; int i; for(i=1;i=0;i--,j++) B[j]=A[i]; for(i=0;i=0 && A[i]>x) { A[i+1]= A[i]; i--; } A[i+1]=x; length++; } //function for checking is array is sorted or not int Array::isSorted() { int i; for(i=0;iA[i+1]) return 0; } return 1; } //function for rearrange element of array void Array::Rearrange() { int i,j; i=0; j= length-1; while(i=0)j--; if(iA[k++]=A[i++]; else arr3->A[k++]=arr2.A[j++]; } for(;iA[k++]=A[i]; for(;jA[k++]=arr2.A[j]; arr3->length=length+arr2.length; return arr3; } //function for finding union of array Array* Array::Union(Array arr2) { int i,j,k; i=j=k=0; Array *arr3=new Array(length+arr2.length); while(iA[k++]=A[i++]; else if(arr2.A[j]A[k++]=arr2.A[j++]; else { arr3->A[k++]=A[i++]; j++; } } for(;iA[k++]=A[i]; for(;jA[k++]=arr2.A[j]; arr3->length=k; return arr3; } //function for finding insertion of array Array* Array::Inter(Array arr2) { int i,j,k; i=j=k=0; Array *arr3=new Array(length+arr2.length); while(iA[k++]=A[i++]; j++; } } arr3->length=k; return arr3; } //function for finding diff of array Array* Array::Diff(Array arr2) { int i,j,k; i=j=k=0; Array *arr3=new Array(length+arr2.length); while(iA[k++]=A[i++]; else if(arr2.A[j]A[k++]=A[i]; arr3->length=k; return arr3; } //implementation of all above function by menu driven program int main() { Array *arr1; int ch,sz; int x,index; cout<<"Enter Size of Array"; scanf("%d",&sz); arr1=new Array(sz); do { cout<<"\n\nMenu\n"; cout<<"1. Insert\n"; cout<<"2. Delete\n"; cout<<"3. Search\n"; cout<<"4. Sum\n"; cout<<"5. Display\n"; cout<<"6.Exit\n"; cout<<"enter you choice "; cin>>ch; switch(ch) { case 1: cout<<"Enter an element and index "; cin>>x>>index; arr1->Insert(index,x); break; case 2: cout<<"Enter index "; cin>>index; x=arr1->Delete(index); cout<<"Deleted Element is"<>x; index=arr1->LinearSearch(x); cout<<"Element index "<Sum(); break; case 5: arr1->Display(); } }while(ch<6); return 0; } ================================================ FILE: Data-Structures/Graph/GraphUsingList.kt ================================================ import kotlin.collections.ArrayList class Node(val value: T) { val neighbors = ArrayList>() fun addNeighbor(node: Node) = neighbors.add(node) override fun toString(): String = value.toString() } class Graph { private val nodes = HashSet>() fun addNode(value: T) { val newNode = Node(value) nodes.add(newNode) } fun getNode(reference: T): Node? { return nodes.firstOrNull { it.value == reference } } fun addVertex(from: T, to: T) { getNode(to)?.let { getNode(from)?.addNeighbor(it) } } } fun Graph.bfs(reference: T): List { getNode(reference)?.let { referenceNode -> val visited = ArrayList>() val queue = ArrayList>() queue.add(referenceNode) while (queue.isNotEmpty()) { val node = queue.removeAt(0) if (!visited.contains(node)) { visited.add(node) node.neighbors .filter { !visited.contains(it) } .forEach { queue.add(it) } } } return visited.map { it.value } } return emptyList() } fun Graph.dfs(reference: T): List { getNode(reference)?.let { referenceNode -> val visited = ArrayList>() val stack = ArrayList>() stack.add(referenceNode) while (stack.isNotEmpty()) { val node = stack.removeAt(stack.lastIndex) if (!visited.contains(node)) { visited.add(node) node.neighbors .filter { !visited.contains(it) } .forEach { stack.add(it) } } } return visited.map { it.value } } return emptyList() } fun main() { val namesGraph = Graph() namesGraph.addNode("Minato") namesGraph.addNode("Obito") namesGraph.addVertex("Minato", "Obito") namesGraph.addNode("Kakashi") namesGraph.addVertex("Minato", "Kakashi") namesGraph.addNode("Rin") namesGraph.addVertex("Minato", "Rin") namesGraph.addNode("Naruto") namesGraph.addVertex("Kakashi", "Naruto") namesGraph.addNode("Sakura") namesGraph.addVertex("Kakashi", "Sakura") namesGraph.addNode("Sasuke") namesGraph.addVertex("Kakashi", "Sasuke") print(namesGraph.bfs("Minato")) print(namesGraph.dfs("Minato")) } ================================================ FILE: Data-Structures/Graph/README.md ================================================ # This folder is empty. ================================================ FILE: Data-Structures/Graph/UsingList.cpp ================================================ #include #include #include using namespace std; void displayAdjList(list adj_list[], int v) { for(int i = 0; i"; list :: iterator it; for(it = adj_list[i].begin(); it != adj_list[i].end(); ++it) { cout << *it << " "; } cout << endl; } } void add_edge(list adj_list[], int u, int v) { //add v into the list u, and u into list v adj_list[u].push_back(v); adj_list[v].push_back(u); } main(int argc, char* argv[]) { int v = 6; //there are 6 vertices in the graph //create an array of lists whose size is 6 list adj_list[v]; add_edge(adj_list, 0, 4); add_edge(adj_list, 0, 3); add_edge(adj_list, 1, 2); add_edge(adj_list, 1, 4); add_edge(adj_list, 1, 5); add_edge(adj_list, 2, 3); add_edge(adj_list, 2, 5); add_edge(adj_list, 5, 3); add_edge(adj_list, 5, 4); displayAdjList(adj_list, v); } ================================================ FILE: Data-Structures/Graph/UsingList.py ================================================ # graph implementation with adjacency list # undirected version class node(): def __init__(self, node_name): self.node_name = node_name # node_name is unique name of node. self.has_edge_to = [] # list which records the all edges of this node and their edge weights. def add_neigbor(self, neighbor): # neighbor is node name. not node object. self.has_edge_to.append(neighbor) def list_edges_of(self): return self.has_edge_to def get_node_name(self): return self.node_name def __str__(self): return str(self.node_name) class graph(): def __init__(self): self.adj_list_of_graph = {} # keys are node names. values are edge_lists of nodes self.node_num_in_graph = 0 self.nodes_object_list = [] def add_node(self, node_name): self.node_num_in_graph += 1 new_node = node(node_name) self.nodes_object_list.append(new_node) #self.adj_list_of_graph[new_node.get_node_name()] = new_node.list_edges_of() self.update_adj_list() return new_node def get_node(self, node_name_to_search): # return node which its name is node_name_to_search for x in self.nodes_object_list: if node_name_to_search == x.get_node_name(): return x return None def get_edges_of_node(self, node_name_to_search): return self.get_node(node_name_to_search).list_edges_of() # return self.adj_list_of_graph[node_name_to_search] def update_adj_list(self): for x in self.nodes_object_list: if x.get_node_name() in self.adj_list_of_graph.keys(): # node is exist in adj list. it is good. lets update its edge list. self.adj_list_of_graph[x.get_node_name()] = x.list_edges_of() else: # we need to cretae new row in adj list for this new node. self.adj_list_of_graph[x.get_node_name()] = x.list_edges_of() def add_edge(self, from_node, to_node): # in fact from and to notation is meaningless. b/c this is not directed graph. but i use them for convenience to modify. # from_node and to_node are node names. not node object self.exist_flag_of_from_node = False self.exist_flag_of_to_node = False for x in self.nodes_object_list: if from_node == x.node_name: # from_node is exist in graph. no need to create it again. self.exist_flag_of_from_node=True if to_node == x.node_name: # to_node is exist in graph. no need to create it again. self.exist_flag_of_to_node=True if not self.exist_flag_of_from_node: self.add_node(from_node) if not self.exist_flag_of_to_node: self.add_node(to_node) for ii,x in enumerate(self.nodes_object_list): if from_node == x.node_name: self.nodes_object_list[ii].add_neigbor(to_node) if to_node == x.node_name: self.nodes_object_list[ii].add_neigbor(from_node) self.update_adj_list() def get_all_node_objects_in_graph(self): return self.nodes_object_list.keys() def __iter__(self): return iter(self.nodes_object_list) def __contains__(self, node_name_to_search): flag=False for x in self.adj_list_of_graph.keys(): if node_name_to_search == x.node_name: flag=True return flag ########################################################## #### Breadth First Search (BFS) Algorithm from queue import Queue def bfs(graph, entry_node): visited = [] queue = Queue() queue.put(entry_node) while not queue.empty(): node = queue.get() if node.get_node_name() not in visited: visited.append(node.get_node_name()) j = graph.get_edges_of_node(node.get_node_name()) for jj in j: if not jj in visited: queue.put(graph.get_node(jj)) print(queue.empty()) print(visited) return visited ########################################################## ##### Depth First Search (DFS) Algorithm def dfs(graph, start): visited = [ ] stack = [start] # we will implement stack with python list while stack: # while stach is not empty node = stack.pop() if node.get_node_name() not in visited: visited.append(node.get_node_name()) j = graph.get_edges_of_node(node.get_node_name()) for jj in j: if not jj in visited: stack.append(graph.get_node(jj)) return visited ########################################################## g_instance_2 = graph() g_instance_2.add_node("A") g_instance_2.add_node("B") g_instance_2.add_node("C") g_instance_2.add_node("D") g_instance_2.add_node("E") g_instance_2.add_node("F") g_instance_2.add_edge("A","B") g_instance_2.add_edge("A","C") #g_instance_2.add_edge("B","A") g_instance_2.add_edge("B","D") g_instance_2.add_edge("B","E") #g_instance_2.add_edge("C","A") g_instance_2.add_edge("C","F") #g_instance_2.add_edge("E","B") g_instance_2.add_edge("E","F") #g_instance_2.add_edge("F","C") #g_instance_2.add_edge("F","E") #print(g_instance_2.adj_list_of_graph) for v in g_instance_2.adj_list_of_graph: print(v,g_instance_2.adj_list_of_graph[v]) visited = bfs(g_instance_2, g_instance_2.get_node("A")) print("bfs traversal:",visited) visited = dfs(g_instance_2,g_instance_2.get_node("A")) print("dfs traversal:", visited) ########################################################## ================================================ FILE: Data-Structures/Graph/UsingMatrix.cpp ================================================ #include #include #include #include using namespace std; int n=5; void DFS(int matrix[5][5], int visit[],int visitTo=0){ cout<<(char)(visitTo+65)<<" "; visit[visitTo]=1; for(int i=0; i<5; i++){ if(matrix[visitTo][i] && !visit[i]) DFS(matrix,visit,i); } } void BFS(int matrix[5][5], int visit[], int row=0){ int queue[n]; int top =-1, i, bottom =-1; visit[row]=1; queue[++bottom] = row; cout<<(char)(row+65)<<" "; while(top != bottom){ row= queue[++top]; for(i=0; i #include #define SIZE 40 struct node{ int vertex; struct node* next; }; //Creating a Node struct node* createNode(int v){ struct node* newNode = malloc( sizeof( struct node ) ); newNode->vertex = v; newNode->next = NULL; return newNode; }; struct Graph{ int numVertices; struct node** adjLists; int* visited; }; //Creating a Graph struct Graph* createGraph(int vertices){ struct Graph* graph = malloc( sizeof( struct Graph ) ); graph->numVertices = vertices; graph->adjLists = malloc( vertices * sizeof( struct node* )); graph->visited = malloc( vertices * sizeof(int) ); int i ; for( i = 0; i < vertices; i++){ graph->adjLists[i] = NULL; graph->visited[i] = 0; } return graph; } // Adding a Edge in a Graph void addEdge(struct Graph* graph, int src, int dest){ //Adding edge from source to destination struct node* newNode = createNode(dest); newNode->next = graph->adjLists[src]; graph->adjLists[src] = newNode; //Adding edge from destination to source newNode = createNode( src ); newNode->next = graph->adjLists[dest]; graph->adjLists[dest] = newNode; } struct queue{ int items[SIZE]; int front; int rear; }; // Creating a Queue struct queue* createQueue(){ struct queue* q = malloc( sizeof( struct queue) ); q->front = -1; q->rear = -1; return q; }; //Adding Elements into a Queue void enqueue( struct queue* q, int value ){ if( q->rear == SIZE - 1 ) printf("Queue is Full !!!"); else{ if( q->front == -1) q->front = 0; q->rear++; q->items[ q->rear ] = value; } } // Check weather a queue is empty int isEmpty( struct queue* q ){ if( q->rear == -1 ) return 1; else return 0; } //Removing Elements From Queue int dequeue( struct queue* q ){ int item; if( isEmpty( q ) ){ printf("Queue is Empty"); item = -1; } else { item = q->items[q->front]; q->front++; if( q->front > q->rear ){ // printf("Resetting Queue"); q->front = q->rear = -1; } } return item; } // Print the queue void printQueue( struct queue* q ){ int i = q->front; if( isEmpty(q) ){ printf("Queue is Empty"); }else{ printf("\nQueue Front: "); for( i = q->front; i < q->rear ; i++){ printf("%d", q->items[i]); } } } // Breadth First Search Algorithm void bfs( struct Graph* graph, int startVertex ){ struct queue* q = createQueue(); graph->visited[ startVertex ] = 1; enqueue( q, startVertex ); while ( !isEmpty(q) ){ // printQueue( q ); int currentVertex = dequeue( q ); printf("Visited : %d \n", currentVertex); struct node* temp = graph->adjLists[currentVertex]; while( temp ){ int adjVertex = temp->vertex; if( graph->visited[adjVertex] == 0 ){ graph->visited[adjVertex] = 1; enqueue( q, adjVertex ); } temp = temp->next; } } } //Depth First Search Algorithm void DFS(struct Graph* graph, int vertex){ struct node* adjList = graph->adjLists[vertex]; struct node* temp = adjList; graph->visited[vertex] = 1; printf("Visited %d \n", vertex); while( temp != NULL){ int connectedVertex = temp->vertex; if( graph->visited[connectedVertex] == 0 ){ DFS(graph , connectedVertex); } temp = temp->next; } } // It is the main calling function. int main(){ int vertices=0, edges = 0, src = 0 , dest = 0; printf("Enter the Number of Vertices:"); scanf("%d", &vertices ); struct Graph* graph = createGraph(vertices); printf("Enter the Number of Edges in a Graph: "); scanf("%d", &edges ); for( int i = 0 ; i < edges ; i++ ){ printf("Enter the Source and Destination of Edge %d :", i+1); scanf("%d%d", &src, &dest); addEdge( graph , src , dest); } printf("\n\n"); bfs( graph, 0); for( int i = 0; i < vertices; i++ ){ graph->visited[i] = 0; } printf("\n\n"); DFS(graph, 2); return 0; } ================================================ FILE: Data-Structures/HashMap/README.md ================================================ ## This folder is empty. ================================================ FILE: Data-Structures/HashSet/Hash-Set.c ================================================ /* * This is an implementation of HashSet Data structure */ #include #include #define HS_REHASH_LIM(x) (x / 2) #define HS_REHASH_FAC 2 typedef struct { long key; void *value; } hashpair; /* Hashset struct * size : the maximum amount of elements it can store * used : number of elements currently stored * start : pointer to start of hashset * hash : function pointer to a function which takes in a void pointer (key) and * return an long (hash) of that key */ typedef struct { int size; int used; hashpair *start; long (*hash)(void *); } Hashset; /* * Function to create Hashset structure * the structure received should be deleted after use by * using function hs_delete * Params : * size : Initial size allocated to hashset * hashfn : A function which takes in a void pointer (key) * and returns an long representing the hash of that key * Returns : A struct Hashset. * * This allocates the given size from heap memory using calloc, and stores its * pointer,as well as the compair function and hash function in the returning * structure */ Hashset make_hashset(int size, long (*hashfn)(void *)) { Hashset ret = { .size = size, .used = 0, .start = (hashpair *)calloc( size, sizeof(Hashset)), /* Use calloc so the returned memory will be * zeroed and if any errors or invalid access, * will be caught */ .hash = hashfn}; return ret; } /* * Internal function to rehash a Hashset and reallocate the keys and values * Should not be exposed * * this increases the current size of hashset by HS_REHASH_FAC factor, * and then rehashes all keys and puts then in this newly allocated memory * then frees the old memory */ int hs_add(Hashset *hs, void *value); // forward declaration static void rehash(Hashset *hs) { int size = hs->size; hashpair *temp = (hashpair *)calloc(size * HS_REHASH_FAC, sizeof(hashpair)); if (temp == NULL) { // If cannot allocate memory , just return return; } hashpair *newstart = temp; hashpair *oldstart = hs->start; // Change the HS info hs->start = newstart; hs->size = size * HS_REHASH_FAC; hs->used = 0; hashpair *iter = oldstart; // move all key-value pairs to new locations, using the hs_add function while (iter < oldstart + size) { // As we have calloc-ed the memory, both key and value being zero // means that the location was not allocated if (iter->key >= 0 || iter->value != NULL) { // If either is non-zero, add it to the new memory hs_add(hs, iter->value); } ++iter; } free(oldstart); } /* * Function to add a value to hasset * Note that once the hashset reaches its max used capacity, * this internally rehashes and reallocates the whole hashset * * Params : * hs : pointer to the hashset in which the pair is to be added * value : pointer to value / value (must be typecasted to void *) * * Returns : int : 0 if succeeded * -1 if failed */ int hs_add(Hashset *hs, void *value) { long key = hs->hash(value); int hash = key % hs->size; // bound the hash inside the size // If the used capacity of HS is more than max used allowed, reshah if (hs->used >= HS_REHASH_LIM(hs->size)) { rehash(hs); } // Start searching empty space at offset of hash hashpair *search = hs->start + hash; // loop until we find an empty space or we get to end of memory while (search->key >= 0 && search->value != NULL && search < hs->start + hs->size) { ++search; } if (search >= hs->start + hs->size) { return -1; // Failed to add } else { search->key = key; search->value = value; ++hs->used; } return 0; } /* * Function to check if given value exists in hashset * * Params : * hs : pointer to the hashset from which the value is to be retrieved * * Returns : 0 if value is not found in given hashset * 1 if value is found in hashset */ int hs_contains(Hashset *hs, void *value) { hashpair *start = hs->start; long key = hs->hash(value); int hash = (key % hs->size); // bound the hash in memory size // start searching for key at offset of hash hashpair *search = start + hash; // As we have calloc-ed the memory, both key and value being zero // means that the location was not allocated while (search->key >= 0 && search->value != NULL && search < start + hs->size) { // Compair the found and required key if (key == search->key) { return 1; } ++search; } return 0; } /* * A function to delete a perticular value from given hashset * Note : This only removes the value from hashset. * this returns the value as given to hs_add, * which if were manually allocated, must be manually freed by user. * * Params : * hs : A pointer to hashset from which value is to be deleted * value : the value as void *, which is to be removed * * Returns : if value is found : value as void* as given to hs_add * if value is not found : NULL */ void *hs_delete_key(Hashset *hs, void *value) { hashpair *start = hs->start; long key = hs->hash(value); int hash = (key % hs->size); // bound the hash in memory size // start searching for key at offset of hash hashpair *search = start + hash; // As we have calloc-ed the memory, both key and value being zero // means that the location was not allocated while (search->key >= 0 && search->value != NULL && search < start + hs->size) { if (key == search->key) { // if we found the key, save the key and value in structure // and set both in the HS to NULL void *ret = search->value; search->key = -1; search->value = NULL; --hs->used; return ret; } ++search; } // We did not find the required key, so return NULL in structure return NULL; } /* * A function to delete the hashset * frees the memory allocated to the hashset * Params : * hs : pointer to Hashset structure as returned by the make_hashset function * delfn : A function which takes in a void pointer (value) * This will be called on each value in Hashset. * Should be used to free the memory allocated to value, if * required * */ void hs_delete(Hashset *hs, void (*delfn)(void *)) { hashpair *start = hs->start; hashpair *iter = start; while (iter < start + hs->size) { // As we have calloc-ed the memory, both key and value being zero // means that the location was not allocated if (iter->key >= 0 || iter->value != NULL) { // call delfn on giving the key and value delfn(iter->value); } ++iter; } // Finally free the memory that was allocated to the HS free(start); hs->size = 0; hs->start = NULL; } // Tests static inline long __hash__(void *val) { return (long)val; } static inline void __del__( void *val) { /* do nothing as the values are just ints */ } void main() { // A Hasset for numbers Hashset hs = make_hashset(10, __hash__); hs_add(&hs, (void *)55); hs_add(&hs, (void *)23); hs_add(&hs, (void *)785); hs_add(&hs, (void *)78); if (hs_contains(&hs, (void *)5)) { printf("This is error\n"); } else { printf("Test 1 is correct\n"); } if (hs_contains(&hs, (void *)23)) { printf("Test 2 is correct\n"); } else { printf("This is error\n"); } long ret = (long)hs_delete_key(&hs, (void *)785); if (ret != 785) { printf("This is error\n"); } else { printf("Test 3 is correct\n"); } hs_delete(&hs, __del__); } ================================================ FILE: Data-Structures/HashSet/README.md ================================================ # This folder is empty. ================================================ FILE: Data-Structures/Heap/README.md ================================================ ================================================ FILE: Data-Structures/LinkedList/Circular_Linked_List/CircularLinkedList.c ================================================ #include #include #include #include struct node { int data; int key; struct node *next; }; struct node *head = NULL; struct node *current = NULL; bool isEmpty() { return head == NULL; } int length() { int length = 0; //if list is empty if(head == NULL) { return 0; } current = head->next; while(current != head) { length++; current = current->next; } return length; } //insert link at the first location void insertFirst(int key, int data) { //create a link struct node *link = (struct node*) malloc(sizeof(struct node)); link->key = key; link->data = data; if (isEmpty()) { head = link; head->next = head; } else { //point it to old first node link->next = head; //point first to new first node head = link; } } //delete first item struct node * deleteFirst() { //save reference to first link struct node *tempLink = head; if(head->next == head) { head = NULL; return tempLink; } //mark next to first link as first head = head->next; //return the deleted link return tempLink; } //display the list void printList() { struct node *ptr = head; printf("\n[ "); //start from the beginning if(head != NULL) { while(ptr->next != ptr) { printf("(%d,%d) ",ptr->key,ptr->data); ptr = ptr->next; } } printf(" ]"); } void main() { insertFirst(1,10); insertFirst(2,20); insertFirst(3,30); insertFirst(4,1); insertFirst(5,40); insertFirst(6,56); printf("Original List: "); //print list printList(); while(!isEmpty()) { struct node *temp = deleteFirst(); printf("\nDeleted value:"); printf("(%d,%d) ",temp->key,temp->data); } printf("\nList after deleting all items: "); printList(); } ================================================ FILE: Data-Structures/LinkedList/Circular_Linked_List/CircularLinkedList.java ================================================ public class CircularLinkedList { public Node head; public Node tail; public CircularLinkedList() { this.head = this.tail = null; } public boolean isEmpty() { return this.head == null; } public void addToTail(int el) { if (isEmpty()) { this.head = new Node(el); this.head.next = head; this.head.prev = head; this.tail = this.head; } else { this.tail.next = new Node(el, this.tail.next, this.tail); this.tail = this.tail.next; this.head.prev = this.tail; } } public void printAll() { Node temp; int i = 0; for (temp = head; i < 5; temp = temp.next, i += 1) { System.out.println(temp.info + " > " + temp.next.info + " > " + temp.prev.info); } System.out.println(); } } class Node { public int info; public Node next; public Node prev; public Node(int el) { this.info = el; this.next = null; this.prev = null; } public Node(int el, Node next, Node prev) { this.info = el; this.next = next; this.prev = prev; } } ================================================ FILE: Data-Structures/LinkedList/Circular_Linked_List/Circular_Link_List.cpp ================================================ #include #include using namespace std; class Node{ public: int data; Node *link; }; Node *head=NULL; void createNode(){ char ch; do{ Node *current; Node *new_node=new Node; cout<<"\nEnter the data:"; cin>>new_node->data; new_node->link=NULL; if (head==NULL){ head=new_node; current=new_node; } else{ current->link=new_node; current=new_node; current->link=head; } cout<<"\nDo you want to add more nodes?"; ch=getche(); }while(ch!='n'); } void print(){ Node *new_node; new_node=head; if (new_node==NULL){ cout<<"\nLink list is empty."; } else{ cout<<"\nData in list is as follows:"<data<<"\t"; new_node=new_node->link; while(new_node!=head){ cout<data<<"\t"; new_node=new_node->link; } cout<data<<"\t"; } } int main(){ createNode(); print(); } ================================================ FILE: Data-Structures/LinkedList/Circular_Linked_List/README.md ================================================ ## This folder is empty. ================================================ FILE: Data-Structures/LinkedList/Circular_Linked_List/circularLinkedList.js ================================================ function circularLinkedList() { //Node let Node = function(element) { this.element = element; this.next = null; } let length = 0; let head = null; //Other methods go here //Get element at specific index this.getElementAt = function(index) { if(index >= 0 && index <= length){ let node = head; for(let i = 0; i < index && node != null; i++){ node = node.next; } return node; } return undefined; } //Add new node this.append = function(element){ //Create new node const node = new Node(element); let current; //If head is empty //Then make new node head if(head === null){ head = node; }else{ //Else add the new node as the next node //And mark the next of new node to the head current = this.getElementAt(length - 1); current.next = node; } node.next = head; length++; } //Insert at given position this.insert = function(element, index){ if(index >= 0 && index <= length){ const node = new Node(element); let current = head; //Insert at head if(index === 0){ if(head === null){ head = node; node.next = head; }else{ node.next = current; current = this.getElementAt(length); head = node; current.next = head; } }else{ //Insert at given index (middle or end) const previous = this.getElementAt(index - 1); node.next = previous.next; previous.next = node; } length++; return true; } return false; } //Remove at any position this.removeAt = function (index) { if(index >= 0 && index < length){ let current = head; //Remove from head if(index === 0){ if(length === 1){ head = undefined; }else{ const removed = head; current = this.getElementAt(length - 1); head = head.next; current.next = head; current = removed; } }else{ //Remove at given index (middle or end) const previous = this.getElementAt(index - 1); current = previous.next; previous.next = current.next; } length--; return current.element; } return undefined; } //Get the indexOf item this.indexOf = function(elm){ let current = head, index = -1; //If element found then return its position while(current){ if(elm === current.element){ return ++index; } index++; current = current.next; } //Else return -1 return -1; }; //Find the item in the list this.isPresent = (elm) => { return this.indexOf(elm) !== -1; }; //Get the head this.getHead = function(){ return head; } //Delete an item from the list this.delete = (elm) => { return this.removeAt(this.indexOf(elm)); }; //Delete the first item from the list this.deleteHead = function(){ this.removeAt(0); } //Print item of the string this.toString = function(){ let current = head, string = ''; const temp = head.element; while(current){ if(temp === current.next.element){ string += current.element + (current.next ? '\n' : ''); break; } string += current.element + (current.next ? '\n' : ''); current = current.next; } return string; }; //Convert list to array this.toArray = function(){ let arr = [], current = head; const temp = head.element while(current){ //Break if first element detected if(temp === current.next.element){ arr.push(current.element); break; } arr.push(current.element); current = current.next; } return arr; }; //Check if list is empty this.isEmpty = function(){ return length === 0; }; //Get the size of the list this.size = function(){ return length; } }Copy Input: let cLL = new circularLinkedList(); cLL.append(20); cLL.append(30); cLL.append(40); cLL.append(50); console.log(cLL.removeAt(3)); cLL.insert(70, 3); cLL.deleteHead(); cLL.delete(70); console.log(cLL.toArray()); ================================================ FILE: Data-Structures/LinkedList/Circular_Linked_List/circularLinkedList.py ================================================ class Node: def __init__(self, data): self.data = data self.next = None class CircularLinkedList: def __init__(self, key): z = Node(key) z.next = z self.last = z def insert_after(n, a): n.next = a.next a.next = n def insert_at_last(l, n): n.next = l.last.next l.last.next = n l.last = n def delete(l, n): temp = l.last while temp.next != n: temp = temp.next if n == l.last: #last node if n.next == n: #only one node l.last = NULL else: #more than one node and last node temp.next = n.next l.last = temp #updating last pointer else: #not last node temp.next = n.next del n def traversal(l): temp = l.last a = str(temp.data)+"\t" temp = temp.next while temp != l.last: a = a + str(temp.data) + "\t" temp = temp.next print(a) if __name__ == '__main__': l = CircularLinkedList(10) a = Node(20) b = Node(30) c = Node(40) l.last.next = a a.next = b b.next = c c.next = l.last traversal(l) z = Node(50) insert_after(z, c) z = Node(25) insert_after(z, a) z = Node(100) insert_at_last(l, z) traversal(l) delete(l, l.last); delete(l, b); traversal(l); ================================================ FILE: Data-Structures/LinkedList/Circular_Linked_List/csharp/CircularLinkedList.cs ================================================ // https://www.csharpstar.com/circular-singly-linked-list-csharp/ using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace CircularLinkedList { class Circularlist { private int currentdata; private Circularlist nextdata; public Circularlist() { currentdata = 0; nextdata = this; } public Circularlist(int value) { currentdata = value; nextdata = this; } public Circularlist Insdata(int value) { Circularlist node = new Circularlist(value); if (this.nextdata == this) { node.nextdata = this; this.nextdata = node; } else { Circularlist temp = this.nextdata; node.nextdata = temp; this.nextdata = node; } return node; } public int Deldata() { if (this.nextdata == this) { System.Console.WriteLine("\nOnly one node..."); return 0; } Circularlist node = this.nextdata; this.nextdata = this.nextdata.nextdata; node = null; return 1; } public void Traverse() { Traverse(this); } public void Traverse(Circularlist node) { if (node == null) node = this; System.Console.WriteLine("Forward Direction..."); Circularlist snode = node; do { System.Console.WriteLine(node.currentdata); node = node.nextdata; } while (node != snode); } public int Gnodes() { return Gnodes(this); } public int Gnodes(Circularlist node) { if (node == null) node = this; int count = 0; Circularlist snode = node; do { count++; node = node.nextdata; } while (node != snode); System.Console.WriteLine("\nCurrent Node Value : " + node.currentdata.ToString()); System.Console.WriteLine("\nTotal nodes :" + count.ToString()); return count; } static void Main(string[] args) { Circularlist node1 = new Circularlist(100); node1.Deldata(); Circularlist node2 = node1.Insdata(200); node1.Deldata(); node2 = node1.Insdata(200); Circularlist node3 = node2.Insdata(300); Circularlist node4 = node3.Insdata(400); Circularlist node5 = node4.Insdata(500); node1.Gnodes(); node3.Gnodes(); node5.Gnodes(); node1.Traverse(); node5.Deldata(); node2.Traverse(); node1.Gnodes(); node2.Gnodes(); node5.Gnodes(); Console.Read(); } } } ================================================ FILE: Data-Structures/LinkedList/Doubly_Linked_List/Double linked List circular with double headers C++/LDLCCED.cbp ================================================ ================================================ FILE: Data-Structures/LinkedList/Doubly_Linked_List/Double linked List circular with double headers C++/LDLCCED.layout ================================================ ================================================ FILE: Data-Structures/LinkedList/Doubly_Linked_List/Double linked List circular with double headers C++/dllist.cpp ================================================ #include "dllist.h" DLList::DLList() { header = new DLNode; if(header == nullptr) { throw ListException("Memoria no disponible an inicializar la lista"); } header ->setPrev(header); header ->setNext(header); } bool DLList::isEmpty() { return header->getNext() == header; } void DLList::print() { DLNode* aux = header->getNext(); while(aux != header) { aux->getData().toString(); aux = aux->getNext(); } } DLNode* DLList::insertData(DLNode *p, Agent&e) { if(p != nullptr && !isValidPos(p)) { throw ListException("Posicion invalida al tratar de insertar"); } if(p == nullptr) { p = header; } DLNode* aux; try { aux= new DLNode(e); } catch(NodeException ex) { throw ListException(ex.what()); } if(aux == nullptr) { throw ListException("Memoria no disponible al insertar"); } if(p == nullptr) { aux->setPrev(nullptr); aux->setNext(header); if(header != nullptr) { header->setPrev(aux); } header=aux; } else { aux->setPrev(p); aux->setNext(p->getNext()); if(p->getNext() != nullptr) { p->getNext()->setPrev(aux); } p->setNext(aux); } return aux; } bool DLList::isValidPos(DLNode* p) { if(p == nullptr || isEmpty()) { return false; } DLNode* aux=header; do { if(aux==p) { return true; } aux = aux->getNext(); } while(aux != header); return false; } ///******* DLNode *DLList::getPrevPos(DLNode*p) { if(!isValidPos(p)||p==header->getNext()) { return nullptr; } return p->getPrev(); } DLNode *DLList::getNextPos(DLNode* p) { if(!isValidPos(p)||p==header->getPrev()) { return nullptr; } return p->getNext(); } DLNode *DLList::findData(Agent& e) { DLNode* aux= header->getNext(); while(aux!= header) { if(aux->getData()== e) { return aux; } aux=aux->getNext(); } return nullptr; } void DLList::deleteData(DLNode*p) { if(!isValidPos(p)) { throw ListException("Posiccion no valida al tratar de eliminar"); } p->getPrev()->setNext(p->getNext()); p->getNext()->setPrev(p->getPrev()); delete p; } void DLList::deleteAll() { DLNode* aux; while(header->getNext()!= header) { aux= header->getNext(); header->setNext(header->getNext()->getNext()); delete aux; } header->setNext(header); } DLList::~DLList() { deleteAll(); delete header; } DLList::DLList(DLList& l) : DLList() { DLNode* aux= l.header->getNext(); while(aux != l.header) { insertData(getLastPos(), aux->getData()); aux=aux->getNext(); } } ///******* DLNode* DLList::getFirstPos() { if(isEmpty()) { return nullptr; } return header -> getNext(); } DLNode* DLList::getLastPos() { if(isEmpty()) { return nullptr; } return header -> getPrev(); } Agent& DLList::retrieve(DLNode* p) { if(!isValidPos(p)) { throw ListException("Posicion invalida al usar retrieve "); } return p->getData(); } void DLList::sortByName() { sortByName(getFirstPos(),getLastPos()); } void DLList::sortByDepartment() { sortByDepartment(getFirstPos(),getLastPos()); } void DLList::exchange(DLNode*a, DLNode*b) { Agent* aux = a->getDataPtr(); a->setDataPtr(b->getDataPtr()); b->setDataPtr(aux); } void DLList::sortByName(DLNode*leftP, DLNode*rightP) { if(leftP==rightP) { return; } DLNode* pivot = rightP; DLNode* i= leftP; DLNode* j= rightP; while(i != j) { while(i != j && i->getData().getName()<=pivot->getData().getName()) { i = i->getNext(); } while(i != j && j->getData().getName()>=pivot->getData().getName()) { j = j->getPrev(); } if(i != j) { exchange(i,j); } } if(i != pivot) { exchange(i,pivot); } if(i != leftP) { sortByName(leftP, i->getPrev()); } if(i != rightP) { sortByName(i->getNext(),rightP); } } void DLList::sortByDepartment(DLNode*leftP, DLNode*rightP) { if(leftP==rightP) { return; } DLNode* pivot = rightP; DLNode* i= leftP; DLNode* j= rightP; while(i != j) { while(i != j and i->getData().getDepart()<=pivot->getData().getDepart()) { i = i->getNext(); } while(i != j and j->getData().getDepart()>=pivot->getData().getDepart()) { j = j->getPrev(); } if(i != j) { exchange(i,j); } } if(i != pivot) { exchange(i,pivot); } if(i != leftP) { sortByDepartment(leftP, i->getPrev()); } if(i != rightP) { sortByDepartment(i->getNext(),rightP); } } void DLList::writeToDisk(const std::string& fileName) { std::ofstream myFile; myFile.open(fileName, myFile.trunc); if(!myFile.is_open()) { throw ListException("No se pudo Abrir el Archivo"+ fileName + "Para escritura"); } DLNode* aux = header->getNext(); while(aux != header) { myFile << aux->getData()<getData().getClientList().writeToDisk(aux->getData().getAgentNum()); aux=aux->getNext(); } myFile.close(); } void DLList::readFromDisk(const std::string& fileName) { std::ifstream myFile; Agent myAgent; DLNode* myPos; myFile.open(fileName); if(!myFile.is_open()) { throw ListException("No se pudo Abrir el Archivo"+ fileName + "Para escritura"); } deleteAll(); while(myFile>>myAgent) { myPos=insertData(getLastPos(), myAgent); myPos->getData().getClientList().readFromDisk(myAgent.getAgentNum()); } myFile.close(); } ================================================ FILE: Data-Structures/LinkedList/Doubly_Linked_List/Double linked List circular with double headers C++/dllist.h ================================================ #ifndef DLLIST_H_INCLUDED #define DLLIST_H_INCLUDED #include #include #include "listexception.h" #include"dlnode.h" #include"agent.h" class DLList { private: DLNode* header; bool isValidPos(DLNode*); void exchange(DLNode*, DLNode*); void sortByName(DLNode*, DLNode*); void sortByDepartment(DLNode*, DLNode*); public: DLList(); DLList(DLList&); ~DLList(); bool isEmpty(); DLNode* insertData(DLNode*,Agent&); void deleteData( DLNode*); DLNode* getFirstPos(); DLNode* getLastPos(); DLNode* getPrevPos( DLNode*); DLNode* getNextPos( DLNode*); DLNode* findData(Agent&); void deleteAll(); Agent& retrieve( DLNode*); void sortByName(); void sortByDepartment(); void print(); void writeToDisk(const std::string&); void readFromDisk(const std::string&); }; #endif // DLLIST_H_INCLUDED ================================================ FILE: Data-Structures/LinkedList/Doubly_Linked_List/Double linked List circular with double headers C++/dlnode.cpp ================================================ #include "dlnode.h" DLNode::DLNode() { prev = next = nullptr; dataPtr = nullptr; } DLNode::~DLNode(){ delete dataPtr; } DLNode::DLNode(Agent& s):DLNode() { dataPtr = new Agent(s); if(dataPtr == nullptr) { throw NodeException("Memoria no disponible al inicializar nodo"); } } Agent* DLNode::getDataPtr() { return dataPtr; } Agent& DLNode::getData() { if(dataPtr==nullptr) { throw NodeException("Dato Inexistente, o memoria no disponible") } return *dataPtr; } DLNode* DLNode::getPrev() { return prev; } DLNode* DLNode::getNext() { return next; } void DLNode::setDataPtr(Agent*p) { dataPtr = p; } void DLNode::setData(Agent&s) { if(dataPtr == nullptr) { dataPtr = new Agent(s); if(dataPtr == nullptr) { throw NodeException("Memoria no disponible al inicializar nodo"); } } else { *dataPtr = s; } } void DLNode::setPrev( DLNode*p) { prev = p; } void DLNode::setNext( DLNode*n) { next = n; } ================================================ FILE: Data-Structures/LinkedList/Doubly_Linked_List/Double linked List circular with double headers C++/dlnode.h ================================================ #ifndef DLNODE_H_INCLUDED #define DLNODE_H_INCLUDED #include "agent.h" #include "nodeexception.h" class DLNode { private: Agent* dataPtr; DLNode*prev; DLNode*next; public: DLNode(); DLNode(Agent&); ~DLNode(); Agent* getDataPtr(); Agent& getData(); DLNode* getNext(); DLNode* getPrev(); void setDataPtr(Agent*); void setData( Agent&); void setNext( DLNode*); void setPrev( DLNode*); }; #endif // DLNODE_H_INCLUDED ================================================ FILE: Data-Structures/LinkedList/Doubly_Linked_List/Double linked List circular with double headers C++/listexception.h ================================================ #ifndef ListException_H_INCLUDED #define ListException_H_INCLUDED #include #include class ListException : public std::exception { private: std::string msg; public: explicit ListException(const char* message) : msg(message) {} explicit ListException(const std::string& message) : msg(message) {} ~ListException() throw () {} virtual const char* what() const throw () { return msg.c_str(); } }; template class List { private: T data[arraySize]; int last; bool isPosValidate(int); public: List(); }; #endif // ListException_H_INCLUDED ================================================ FILE: Data-Structures/LinkedList/Doubly_Linked_List/Double linked List circular with double headers C++/main.cpp ================================================ #include using namespace std; int main() { cout << "Hello world!" << endl; return 0; } ================================================ FILE: Data-Structures/LinkedList/Doubly_Linked_List/Double linked List circular with double headers C++/nodeexception.h ================================================ #ifndef NODEEXCEPTION_H_INCLUDED #define NODEEXCEPTION_H_INCLUDED #include #include class NodeException : public std::exception { private: std::string msg; public: explicit NodeException(const char* message) : msg(message) {} explicit NodeException(const std::string& message) : msg(message) {} NodeException() throw () {} virtual const char* what() const throw () { return msg.c_str(); } }; template class Node { private: T data[arraySize]; int last; bool isPosValidate(int); public: Node(); }; #endif // NODEEXCEPTION_H_INCLUDED ================================================ FILE: Data-Structures/LinkedList/Doubly_Linked_List/DoubleLinkedList.java ================================================ class DoubleLinkedList { private T value; private LinkedList next; private LinkedList prev; public LinkedList(LinkedList prev, T value, LinkedList next) { SetPrev(prev); SetValue(value); SetNext(next); } public LinkedList(T value) { this(null, value, null); } public LinkedList GetPrev() { return prev; } public T GetValue() { return value; } public LinkedList GetNext() { return next; } public void SetPrev(LinkedList prev) { this.prev = prev; } public void SetValue(T value) { this.value = value; } public void SetNext(LinkedList next) { this.next = next; } } ================================================ FILE: Data-Structures/LinkedList/Doubly_Linked_List/DoublyLinkedList.cs ================================================ using System; using System.Collections.Generic; /// /// A DoublyLinkedList /// namespace DataStructures { public class DoublyLinkedListNode { // Constructs a new node with the specified value. public DoublyLinkedListNode(T value) { Value = value; Next = null; Prev = null; } // The node value public T Value { get; set; } // The next node in the Doubly linked list (null if last node) public DoublyLinkedListNode Next { get; set; } public DoublyLinkedListNode Prev { get; set; } } /// /// A Doubly linked list collection capable of basic operations such as /// Add, Remove, Check, Search, IsEmpty, Size, Insert and Index /// public class DoublyLinkedList { /// /// Adds the specified value to the tail of the doublylinked list /// public int Add(T item) { DoublyLinkedListNode node = new DoublyLinkedListNode(item); if (count == 0) { head = node; tail = head; } else { node.Prev = tail; tail.Next = node; tail = node; } return ++count; } /// /// Inserts the specified item at the specified index /// /// /// public void Insert(int index, T item) { if (index > count + 1 || (count == 0 && index > 0) || index < 0) { throw new IndexOutOfRangeException("Index out of range."); } if (count == 0 || index == count) { Add(item); return; } var currentIndex = 0; DoublyLinkedListNode current = head; DoublyLinkedListNode node = new DoublyLinkedListNode(item); while (currentIndex <= index) { if(currentIndex == index) { DoublyLinkedListNode previous = current.Prev; if (previous == null) head = node; node.Prev = previous; node.Next = current; //previous.Next = node; current.Prev = node; count++; return; } current = current.Next; currentIndex++; } return; } /// /// Removes a VALUE from the list if found. /// public bool Remove(T item) { var check = false; DoublyLinkedListNode node = new DoublyLinkedListNode(item); // Checks if only one item is in the list // and if the item is the same as the item to be removed if (count == 1 && item.Equals(head.Value)) { check = true; head = null; tail = head; } // Iterates through the doublylinked list to check for the item while (Check(item)) { check = true; DoublyLinkedListNode current = head; while (current != null) { if (current.Value.Equals(item)) { DoublyLinkedListNode previous = current.Prev; DoublyLinkedListNode next = current.Next; if (previous == null) { head = next; next.Prev = null; } else if (next == null) { tail = previous; previous.Next = null; } else { previous.Next = current.Next; next.Prev = current.Prev; } count--; } current = current.Next; } } return check; } /// /// Returns true if the list contains the specified item, /// false otherwise. /// public bool Check(T item) { DoublyLinkedListNode current = head; while (current != null) { if (current.Value.Equals(item)) { return true; } current = current.Next; } return false; } /// /// Returns item if the list contains the specified item /// /// Returns item if found public T Search(T item) { if (!Check(item)) { throw new InvalidOperationException("Item not found in list."); } DoublyLinkedListNode current = head; while (current != null) { if (current.Value.Equals(item)) { return current.Value; } current = current.Next; } return item; } /// /// Returns true if the list is empty, otherwise false. /// public bool isEmpty() { return count == 0; } /// /// Checks for the length of list /// /// Length of list public int Size() { return count; } /// /// Finds the index of the specified item /// /// /// the index of item public int Index(T item) { if (!Check(item)) { throw new InvalidOperationException("Item not in list"); } DoublyLinkedListNode current = head; var currentIndex = 0; while (currentIndex != count) { if (current.Value.Equals(item)) { return currentIndex; } current = current.Next; currentIndex++; } return -1; } /// /// Length of list, zero if list is empty /// public int count { get; private set; } /// /// The first node in the list or null if empty /// private DoublyLinkedListNode head { get; set; } /// /// The last node in the list or null if empty /// private DoublyLinkedListNode tail { get; set; } } } ================================================ FILE: Data-Structures/LinkedList/Doubly_Linked_List/DoublyLinkedList.hs ================================================ module DoublyLinkedLists where import Prelude hiding (last, elem) -- Implementation without a header/trailer sentinel, meaning some operations -- take O(n) instead of O(1). data DList a = Empty | Node { prev :: DList a , elem :: a , next :: DList a } deriving (Eq) instance Show a => Show (DList a) where show (Node Empty x Empty) = "[" ++ show x ++ "]" show (Node Empty x next) = "[" ++ show x ++ "," ++ show next show (Node _ x Empty) = show x ++ "]" show (Node _ x next) = show x ++ "," ++ show next show Empty = "[]" fromList :: [a] -> DList a fromList = append Empty where append :: DList a -> [a] -> DList a append _ [] = Empty append prev (x:xs) = head where head = Node prev x tail tail = append head xs size :: DList a -> Int size Empty = 0 size (Node _ _ next) = 1 + size next isEmpty :: DList a -> Bool isEmpty Empty = True isEmpty _ = False first :: DList a -> Maybe a first Empty = Nothing first (Node _ a _) = Just a last :: Eq a => DList a -> Maybe a last Empty = Nothing last (Node _ a next) | next == Empty = Just a | otherwise = last next addFirst :: a -> DList a -> DList a addFirst x Empty = Node Empty x Empty addFirst x (Node prev y next) = let newFirst = Node Empty x newSecond newSecond = Node newFirst y next in newFirst -- WIP: doesnt work for lists with length > 1 addLast :: a -> DList a -> DList a addLast x Empty = Node Empty x Empty addLast x list = let last' = lastNode list secondToLast = Node (prev last') (elem last') newLast newLast = Node secondToLast x Empty in rewind newLast where lastNode :: DList a -> DList a lastNode Empty = Empty lastNode (Node prev x Empty) = Node prev x Empty lastNode (Node _ _ next) = lastNode next rewind :: DList a -> DList a rewind Empty = Empty rewind (Node Empty x next) = Node Empty x next rewind (Node prev _ _) = rewind prev ================================================ FILE: Data-Structures/LinkedList/Doubly_Linked_List/DoublyLinkedList_C++_Template/DLL.h ================================================ #include /* Class DLList is Double Linked List without a sentinel node Class Sentinel is Double Linked List using a sentinel node If you want to know more about sentinel node, here is the explanation from Wikipedia https://en.wikipedia.org/wiki/Sentinel_node#:~:text=The%20list%20starts%20out%20with,previous%20pointers%20point%20to%20itself.&text=In%20a%20non%2Dempty%20list,the%20tail%20of%20the%20list. */ /* DLL Class without a sentinel node */ template class DLL { struct Node { T m_data; Node* m_next; Node* m_prev; Node(const T& data = T{}, Node* next = nullptr, Node* prev = nullptr) { m_data = data; m_next = next; m_prev = prev; } }; Node* m_front; Node* m_back; public: DLL() { m_front = nullptr; m_back = nullptr; } void push_front(const T& data); void push_back(const T& data); void pop_front(); void pop_back(); void print() const; void reversePrint() const; ~DLL(); }; template void DLL::push_front(const T& data) { Node* nn = new Node(data, m_front); if (m_front != nullptr) { m_front->m_prev = nn; } else { m_back = nn; } m_front = nn; } template void DLL::push_back(const T& data) { Node* nn = new Node(data, nullptr, m_back); if (m_back != nullptr) { m_back->m_next = nn; } else { m_front = nn; } m_back = nn; } template void DLL::pop_front() { if (m_front != nullptr) { Node* rm = m_front; m_front = rm->m_next; if (m_front != nullptr) { m_front->m_prev = nullptr; } else { m_back = nullptr; } delete rm; } } template void DLL::pop_back() { if (m_back != nullptr) { Node* rm = m_back; m_back = rm->m_prev; if (m_back != nullptr) { m_back->m_next = nullptr; } else { m_front = nullptr; } delete rm; } } template void DLL::print() const { Node* curr = m_front; while (curr != nullptr) { std::cout << curr->m_data << " "; curr = curr->m_next; } if (!m_front) { std::cout << "empty list"; } std::cout << std::endl; } template void DLL::reversePrint() const { Node* curr = m_back; while (curr != nullptr) { std::cout << curr->m_data << " "; curr = curr->m_prev; } if (!m_back) { std::cout << "empty list"; } std::cout << std::endl; } template DLL::~DLL() { while (m_front) { Node* it = m_front; m_front = it->m_next; delete it; } } /* Sentinel Class using a sentinel node */ template class Sentinel { struct Node { T m_data; Node* m_next; Node* m_prev; Node(const T& data = T{}, Node* next = nullptr, Node* prev = nullptr) { m_data = data; m_next = next; m_prev = prev; } }; Node* m_front; Node* m_back; public: Sentinel() { m_front = new Node(); m_back = new Node(); m_front->m_next = m_back; m_back->m_prev = m_front; } void push_front(const T& data); void push_back(const T& data); void pop_front(); void pop_back(); void print() const; void reversePrint() const; ~Sentinel(); }; template void Sentinel::push_front(const T& data) { Node* nn = new Node(data, m_front->m_next, m_front); m_front->m_next->m_prev = nn; m_front->m_next = nn; } template void Sentinel::push_back(const T& data) { Node* nn = new Node(data, m_back, m_back->m_prev); m_back->m_prev->m_next = nn; m_back->m_prev = nn; } template void Sentinel::pop_front() { //if its an empty list... note that it means //front sentinel's next node is the back sentinel if (m_front->m_next != m_back) { Node* rm = m_front->m_next; Node* B = rm->m_next; m_front->m_next = B; B->m_prev = m_front; delete rm; } } template void Sentinel::pop_back() { if (m_back->m_prev != m_front) { Node* rm = m_back->m_prev; rm->m_prev->m_next = m_back; m_back->m_prev = rm->m_prev; delete rm; } } template void Sentinel::print() const { Node* curr = m_front->m_next; while (curr != m_back) { std::cout << curr->m_data << " "; curr = curr->m_next; } if (m_front->m_next == m_back) { std::cout << "empty list"; } std::cout << std::endl; } template void Sentinel::reversePrint() const { Node* curr = m_back->m_prev; while (curr != m_front) { std::cout << curr->m_data << " "; curr = curr->m_prev; } if (m_back->m_prev == m_front) { std::cout << "empty list"; } std::cout << std::endl; } template Sentinel::~Sentinel() { while (m_front != m_back) { Node* it = m_front; m_front = it->m_next; delete it; } } ================================================ FILE: Data-Structures/LinkedList/Doubly_Linked_List/DoublyLinkedList_C++_Template/DLLtest.cpp ================================================ /* tester */ #include "DLL.h" #include int main(void) { DLL regular; Sentinel sentinel; /* DLL class test */ std::cout << "testing regular doubly linked list" << std::endl; // test push_front(); for (int i = 0; i < 3; i++) { regular.push_front(i); regular.print(); } regular.reversePrint(); //test push_back(); for (int i = 3; i < 6; i++) { regular.push_back(i); regular.print(); } regular.reversePrint(); //test pop_front() & pop_back() for (int i = 0; i < 7; i++) { if (i % 2 == 0) { regular.pop_front(); } else { regular.pop_back(); } regular.print(); } regular.reversePrint(); //test push_back(); for (int i = 0; i < 3; i++) { regular.push_back(i); regular.print(); } regular.reversePrint(); for (int i = 3; i < 6; i++) { regular.push_front(i); regular.print(); } regular.reversePrint(); //test pop_front() for (int i = 0; i < 7; i++) { if (i % 2) { regular.pop_front(); } else { regular.pop_back(); } regular.print(); } regular.reversePrint(); for (int i = 0; i < 3; i++) { regular.push_front(i); regular.print(); } regular.reversePrint(); /* Sentinel class test */ std::cout << "testing sentinel list" << std::endl; //test push_front() for (int i = 0; i < 3; i++) { sentinel.push_front(i); sentinel.print(); } sentinel.reversePrint(); //test push_back() for (int i = 3; i < 6; i++) { sentinel.push_back(i); sentinel.print(); } sentinel.reversePrint(); //test pop_front() & pup_back() for (int i = 0; i < 7; i++) { if (i % 2 == 0) { sentinel.pop_front(); } else { sentinel.pop_back(); } sentinel.print(); } sentinel.reversePrint(); for (int i = 0; i < 3; i++) { sentinel.push_back(i); sentinel.print(); } sentinel.reversePrint(); for (int i = 3; i < 6; i++) { sentinel.push_front(i); sentinel.print(); } sentinel.reversePrint(); for (int i = 0; i < 7; i++) { if (i % 2) { sentinel.pop_front(); } else { sentinel.pop_back(); } sentinel.print(); } sentinel.reversePrint(); for (int i = 0; i < 3; i++) { sentinel.push_front(i); sentinel.print(); } sentinel.reversePrint(); return 0; } ================================================ FILE: Data-Structures/LinkedList/Doubly_Linked_List/Doubly_Linked_List.py ================================================ class Node: def __init__(self, value): self.value = value self.prev = None self.next = None class DoublyLinkedList: def __init__(self): self.head = None self.tail = None def setHead(self, node): # O(1) T | O (1) S if self.head is None: self.head = node self.tail = node return self.insertBefore(self.head, node) def setTail(self, node): # O(1) T | O(1) S if self.tail is None: self.setHead(node) self.insertAfter(self.tail, node) def insertBefore(self, node, nodeToInsert): # O(1) T | O(1) S # First we gotta tackle case that what if n=there is no linked list therefore no node. In that case, we were asked to insert a node before something that does not exist and hence, we gotta return if (nodeToInsert == self.head and nodeToInsert == self.tail): return self.remove(nodeToInsert) nodeToInsert.prev = node.prev nodeToInsert.next = node if node.prev is None: self.head = nodeToInsert else: node.prev.next = nodeToInsert node.prev = nodeToInsert def insertAfter(self, node, nodeToInsert): # O(1) T | O(1) S if (nodeToInsert == self.head and nodeToInsert == self.tail): return self.remove(nodeToInsert) nodeToInsert.prev = node nodeToInsert.next = node.next if node.next is None: self.tail = nodeToInsert else: node.next.prev = nodeToInsert node.next = nodeToInsert def insertAtPosition(self, position, nodeToInsert): # O(P) T | O(1) S if position == 1: self.setHead(nodeToInsert) return currentPosition = 1 node = self.head while node is not None and currentPosition != position: currentPosition += 1 node = node.next if node is not None: self.insertBefore(node, nodeToInsert) else: self.setTail(nodeToInsert) def removeNodesWithValue(self, value): # O(N) T | O(1) S node = self.head while node is not None: nodeToRemove = node node = node.next if nodeToRemove.value == value: self.remove(nodeToRemove) def remove(self, node): # O(1) T | O(1) S if (node == self.head): self.head = self.head.next if(node == self.tail): self.tail = self.tail.prev self.removeNodeBindings(node) def removeNodeBindings(self,node): # O(1) T | O(1) S if node.prev is not None: node.prev.next=node.next if node.next is not None: node.next.prev = node.prev node.prev=None node.next=None def containsNodeWithValue(self, value): # O(N) T | O(1) S node = self.head while node is not None and node.value!=value: node=node.next return node is not None ================================================ FILE: Data-Structures/LinkedList/Doubly_Linked_List/README.md ================================================ ## This folder is empty. ================================================ FILE: Data-Structures/LinkedList/Doubly_Linked_List/double_linked_list.c ================================================ #include #include struct Node { struct Node *prev; int data; struct Node *next; }*first=NULL; void create(int A[],int n) { struct Node *t,*last; int i; first=(struct Node *)malloc(sizeof(struct Node)); first->data=A[0]; first->prev=first->next=NULL; last=first; for(i=1;idata=A[i]; t->next=last->next; t->prev=last; last->next=t; last=t; } } void Display(struct Node *p) { while(p) { printf("%d ",p->data); p=p->next; } printf("\n"); } int Length(struct Node *p) { int len=0; while(p) { len++; p=p->next; } return len; } void Insert(struct Node *p,int index,int x) { struct Node *t; int i; if(index < 0 || index > Length(p)) return; if(index==0) { t=(struct Node *)malloc(sizeof(struct Node)); t->data=x; t->prev=NULL; t->next=first; first->prev=t; first=t; } else { for(i=0;inext; t=(struct Node *)malloc(sizeof(struct Node)); t->data=x; { struct Node *temp; while(p!=NULL) { temp=p->next; p->next=p->prev; p->prev=temp; p=p->prev; if(p!=NULL && p->next==NULL) first=p; } } int main() { int A[]={10,20,30,40,50}; create(A,5); Reverse(first); Display(first); return 0; } ================================================ FILE: Data-Structures/LinkedList/Doubly_Linked_List/doubly.c ================================================ #include #include struct node{ int value; struct node *lptr,*rptr; }; void insert(struct node **LH,struct node **RH,int val){ struct node *NewNode,*temp; temp = *LH; NewNode = (struct node*)malloc(sizeof(struct node)); NewNode->value = val; if(*LH == NULL && *RH == NULL){ (*LH) = (*RH) = NewNode; NewNode->lptr = NewNode->rptr =NULL; }else{ printf("1) insert at first\n2) insert at last\n3) insert at order\nWhere u want to insert :"); int n; scanf("%d",&n); if(n==1){ // insert at front NewNode->rptr = *LH; NewNode->lptr = NULL; (*LH)->lptr = NewNode; *LH = NewNode; }else if(n==2){ NewNode->rptr = NULL; NewNode->lptr = *RH; (*RH)->rptr = NewNode; *RH = NewNode; }else if(n==3){ if(temp->lptr == NULL){ if(temp->value >= val){ NewNode->rptr = *LH; NewNode->lptr = NULL; (*LH)->lptr = NewNode; *LH = NewNode; } else{ NewNode->rptr = NULL; NewNode->lptr = *RH; (*RH)->rptr = NewNode; *RH = NewNode; } return; } if(temp->value >= val){ NewNode->rptr = *LH; NewNode->lptr = NULL; (*LH)->lptr = NewNode; *LH = NewNode; return; } while(temp->rptr->value <= val) temp = temp->rptr; if(temp->rptr == *RH){ NewNode->rptr = NULL; NewNode->lptr = *RH; (*RH)->rptr = NewNode; *RH = NewNode; }else{ NewNode->lptr = temp; NewNode->rptr = temp->rptr; temp->rptr->lptr = NewNode; temp->rptr = NewNode; } } else printf("\nsomething wrong"); } } void Display(struct node **LH,struct node ** RH){ struct node *temp; temp = *LH; while(temp != NULL){ printf(" %d ",temp->value); temp = temp->rptr; } printf("\n"); } void delete_Link(struct node **LH,struct node **RH){ struct node *NodetoBeDeleted,*temp; int n, val; temp = *LH; if(*LH == NULL ){ printf("\nsorry Link List is Empty\n"); return; } if(temp->lptr == NULL && temp->rptr == NULL){ NodetoBeDeleted = temp; free(NodetoBeDeleted); *LH= *RH= NULL; }else{ printf("1) Delete first Link\n2) Delete Last link\n3) Delete specific value \nwhich value u want to Delete"); scanf("%d",&n); if(n==3){ printf("Enter value :"); scanf("%d",&val); } if(n==1){ NodetoBeDeleted = *LH; (*LH) = (*LH)->rptr; free(NodetoBeDeleted); return; }else if(n==2){ NodetoBeDeleted = *RH; (*RH)->lptr->rptr = NULL; *RH = (*RH)->lptr; free(NodetoBeDeleted); return; }else if(n==3){ if((*RH)->value == val){ NodetoBeDeleted = *RH; *RH = (*RH)->lptr; free(NodetoBeDeleted); return; } if((*LH)->value == val){ NodetoBeDeleted = *LH; *LH = (*LH)->rptr; free(NodetoBeDeleted); return; }else{ while(temp->rptr->value != val) temp = temp->rptr; NodetoBeDeleted = temp->rptr; temp->rptr = temp->rptr->rptr; temp->rptr->lptr = temp; free(NodetoBeDeleted); } }else{ printf("sorry something wrong\n"); } } } int main(){ struct node *LH,*RH; LH = RH = NULL; int c,n; printf("1) Insert\n2) Delete\n3) Display\n4) Exit"); while(c!=4){ printf("\nEnter your choice :"); scanf("%d",&c); switch(c){ case 1: printf("Enter value :"); scanf("%d",&n); insert(&LH,&RH,n); break; case 2: delete_Link(&LH,&RH); break; case 3: Display(&LH,&RH); break; case 4: exit(0); break; default: printf("Please Enter Between 1 to 4"); break; } } return 0; } ================================================ FILE: Data-Structures/LinkedList/Doubly_Linked_List/doubly_ll.py ================================================ #this file has complete implementation of doubly linked list using python language and this class defined below has also reverse method which reverse given doubly linked list class Node(object): # Singly linked node def __init__(self, data=None, next=None, prev=None): self.data = data self.next = next self.prev = prev class doubly_linked_list(object): def __init__(self): self.head = None self.tail = None self.count = 0 def append_item(self, data): # Append an item new_item = Node(data, None, None) if self.head is None: self.head = new_item self.tail = self.head else: new_item.prev = self.tail self.tail.next = new_item self.tail = new_item self.count += 1 def iter(self): # Iterate the list current = self.head while current: item_val = current.data current = current.next yield item_val def print_foward(self): for node in self.iter(): print(node) def reverse(self): """ Reverse linked list. """ current = self.head while current: temp = current.next current.next = current.prev current.prev = temp current = current.prev temp = self.head self.head = self.tail self.tail = temp items = doubly_linked_list() items.append_item(4) items.append_item(6) items.append_item(8) items.append_item(9) items.append_item(2) items.append_item(1) print("Reversed doubly linked list ") items.reverse() items.print_foward() ================================================ FILE: Data-Structures/LinkedList/Doubly_Linked_List/simple linked list circular without header/LSLCSE.cbp ================================================ ================================================ FILE: Data-Structures/LinkedList/Doubly_Linked_List/simple linked list circular without header/LSLCSE.layout ================================================ ================================================ FILE: Data-Structures/LinkedList/Doubly_Linked_List/simple linked list circular without header/main.cpp ================================================ #include using namespace std; int main() { cout << "Hello world!" << endl; return 0; } ================================================ FILE: Data-Structures/LinkedList/Doubly_Linked_List/simple linked list circular without header/sllist.cpp ================================================ #include "sllist.h" void SLList::modifyClient(SLNode* p) { if(!isValidPos(p)) { throw ListException("Posicion invalida a la elminar"); } if(p==anchor) { anchor= anchor-> getNext(); } else { getPrevPos(p) -> setNext(p->getNext()); } delete p; } SLNode* SLList::getPrevPos( SLNode*& p) { if(isEmpty() or p==anchor) { return nullptr; } SLNode* aux = anchor; do { if(aux->getNext()==p) { return aux; } aux= aux->getNext() } while(aux != anchor); return nullptr; } void SLList::deleteData( SLNode* p) { if(!isValidPos(p)) { throw ListException("Posicion invalida al eliminar"); } if (p == anchor) { if(p->getNext()==p) { anchor =nullptr; } else { getLastPos()->getNext(anchor->getNext()); anchor = anchor->getNext(); } } else { getPrevPos(p)->setNext(p->next); } delete p; } SLNode* SLList::findData( Client& e) { if(isEmpty()) { return nullptr } SLNode* aux = anchor; do { if(aux->getData()==e) { return aux; } aux=aux->getNext(); } while(aux!=anchor) return nullptr; } void SLList::deleteAll() { SLNode* aux=anchor; SLNode* mark=anchor do { aux=anchor; anchor=anchor->getNext() delete aux; } while(anchor != mark); anchor=nullptr; } SLList::~SLList() { deleteAll(); } SLList::SLList() { anchor =nullptr; } bool SLList::isEmpty() { return anchor == nullptr; } void SLList::print() { if(isEmpty()) { return; } SLNode* aux = anchor; do { while(aux != nullptr) { aux->getData().toString() ; aux = aux->getNext(); } while(aux!=anchor); } } void SLList::insertData( SLNode* p, Client& e) { //insertar despus if(p != nullptr and !isValidPos(p)) { throw ListException("La posicion de insercion es invalida"); } SLNode* aux = new SLNode(e); if(aux == nullptr) { throw ListException("Memoria no disponible al insertar"); } if(p==nullptr) { //insercin al principio if(anchor==nullptr) { aux->getNext(aux); } else { //insercion en medio o al final de la lista getLastPos()->setNext(aux); } anchor=aux; else { //insercion en medio o al final de la lista getLastPos()->setNext(aux); } } bool SLList::isValidPos( SLNode*& p) { SLNode* aux = anchor; do { if(aux==p); { return true; } } while(aux != anchor) { } void SLList::insertOrdered( Client s) { SLNode* aux = anchor; SLNode* prev = nullptr; while(aux != nullptr and s > aux->getData()) { prev=aux; aux = aux->getNext(); } insertData(prev, s); } SLList::SLList( SLList*& l) : SLList() { SLNode* aux = l->anchor; while(aux != nullptr) { insertData(getLastPos(), aux->getData()); aux = aux->getNext(); } } SLNode* SLList::getFirsPos() { return anchor; } SLNode* SLList::getLastPos() { if(isEmpty()) { return nullptr; } SLNode* aux = anchor; while(aux->getNext() != anchor) { aux= aux->getNext(); } return aux; } SLNode* SLList::getNextPos( SLNode*& p) { //pendiente if(!isValidPos(p) or p->getNext()==anchor) { return nullptr; } return p->getNext(); } Client& SLList::retrieve( SLNode* p) { if(!isValidPos(p)) { throw ListException("Elemento inexistente al hacer retrieve"); } return p->getData(); } void SLList::writeToDisk (const std::string&fileName) { std::ofstream myFile; myFile.open(fileName, myFile.trunc); if(!myFile.is_open()) { throw ListException("No se pudo Abrir el Archivo"+ fileName + "Para escritura"); } if(!isEmpty()) { SLNode* aux = anchor; } while(aux!=nullptr) { myFile << aux->getData()<getNext(); } myFile.close(); } void SLList::readFromDisk(const std::string&fileName) { std::ifstream myFile; Client myClient; myFile.open(fileName); if(!myFile.is_open()) { throw ListException("No se pudo Abrir el Archivo"+ fileName + "Para lectura"); } deleteAll(); while(myFile>>myClient) { insertOrdered(myClient); } myFile.close(); } ================================================ FILE: Data-Structures/LinkedList/Doubly_Linked_List/simple linked list circular without header/sllist.h ================================================ #ifndef SLLIST_H_INCLUDED #define SLLIST_H_INCLUDED #include #include #include "listexception.h" #include "sllist.h" #include"slnode.h" class SLList { private: SLNode* anchor; bool isValidPos( SLNode*&); public: SLList(); SLList( SLList*&); ~SLList(); bool isEmpty(); void insertData( SLNode*, Client&); void insertOrdered( Client); void deleteData( SLNode*); void modifyClient(SLNode*); SLNode* getFirsPos(); SLNode* getLastPos(); SLNode* getPrevPos( SLNode*&); SLNode* getNextPos( SLNode*&); SLNode* findData(Client&); Client& retrieve(SLNode*); void print(); void deleteAll(); void writeToDisk(const std::string&); void readFromDisk(const std::string&); }; #endif // SLLIST_H_INCLUDED ================================================ FILE: Data-Structures/LinkedList/Doubly_Linked_List/simple linked list circular without header/slnode.cpp ================================================ #include"slnode.h" SLNode::SLNode() { next = nullptr; } SLNode::SLNode( Client&s): SLNode() { data = s; } Client& SLNode::getData() { return data; } SLNode* SLNode::getNext() { return next; } void SLNode::setData( Client&s) { data=s; } void SLNode::setNext(SLNode*p) { next=p; } ================================================ FILE: Data-Structures/LinkedList/Doubly_Linked_List/simple linked list circular without header/slnode.h ================================================ #ifndef SLNODE_H_INCLUDED #define SLNODE_H_INCLUDED #include "client.h" class SLNode { private: Client data; public: SLNode*next; SLNode(); SLNode( Client&); Client& getData(); SLNode* getNext(); void setData( Client&); void setNext( SLNode*); }; #endif // SLNODE_H_INCLUDED ================================================ FILE: Data-Structures/LinkedList/README.md ================================================ # This folder is empty. ================================================ FILE: Data-Structures/LinkedList/Singly_Linked_List/Delete_Kth_Node_From_End/Delete_Kth_Node_From_End.cpp ================================================ #include using namespace std; struct node { long long int data; struct node *next; }; typedef struct node *nodeptr; nodeptr getNode(long long int item) { nodeptr p = (nodeptr)malloc(sizeof(struct node)); p->data = item; p->next = NULL; return p; } nodeptr insertAtTheBeginning(long long int item, nodeptr start) { nodeptr p = getNode(item); if (start == NULL) start = p; else { p->next = start; start = p; } return start; } nodeptr insertAtTheEnd(long long int item, nodeptr start) { if (start == NULL) return insertAtTheBeginning(item, start); nodeptr p = getNode(item); nodeptr temp = start; while (temp->next != NULL) temp = temp->next; temp->next = p; return start; } nodeptr insertAtLocation(long long int item, nodeptr start, long long int location) { nodeptr p = getNode(item); long long int i; nodeptr temp = start; for (i = 1; i < location - 1; i++) temp = temp->next; if (i == 1) return insertAtTheBeginning(item, start); else { p->next = temp->next; temp->next = p; return start; } } nodeptr deleteFirst(nodeptr start) { nodeptr temp = start; start = start->next; free(temp); return start; } nodeptr deleteGivenNode(long long int item, nodeptr start) { if (item == start->data) return deleteFirst(start); else { nodeptr temp = start; while (temp != NULL && (temp->next)->data != item) temp = temp->next; nodeptr toBeDeleted = temp->next; temp->next = (temp->next)->next; free(toBeDeleted); return start; } } void display(nodeptr start) { nodeptr temp = start; while (temp != NULL) { cout << temp->data << " "; temp = temp->next; } cout << endl; } long long int countNodes(nodeptr start) { nodeptr temp = start; long long int counter = 1; if (start != NULL) { while (temp->next != NULL) { temp = temp->next; counter++; } } return counter; } nodeptr deleteNode(nodeptr start, long long int counter, long long int k) { if (start == NULL) { cout << "VOID DELETION" << endl; return NULL; } else { long long int it; nodeptr temp = start; for (it = 1; it <= counter - k; it++) temp = temp->next; cout << temp->data << " HAS BEEN DELETED" << endl; return deleteGivenNode(temp->data, start); } } int main() { nodeptr start = NULL; nodeptr list2 = NULL; nodeptr startSorted = NULL; long long int choice, item, location, i, counter = 0, k; for (i = 1; i; i++) { cout << "(1)INSERT AT BEGINNING\n(2)INSERT AT END\n(3)INSERT AT A LOCATION\n(4)DELETE NODE\n(5)DISPLAY\n(6)EXIT" << endl; cout << "ENTER CHOICE: "; cin >> choice; switch (choice) { case 1: cout << "ENTER ELEMENT TO BE INSERTED: "; cin >> item; start = insertAtTheBeginning(item, start); counter = countNodes(start); break; case 2: cout << "ENTER ELEMENT TO BE INSERTED: "; cin >> item; start = insertAtTheEnd(item, start); counter = countNodes(start); break; case 3: cout << "ENTER ELEMENT TO BE INSERTED: "; cin >> item; cout << "ENTER LOCATION: "; cin >> location; start = insertAtLocation(item, start, location); counter = countNodes(start); break; case 4: cout << "ENTER POSITION OF ELEMENT TO BE DELETED FROM END: "; cin >> k; if (k > counter || counter == 0) cout << "VOID DELETION" << endl; else { start = deleteNode(start, counter, k); counter = countNodes(start); } break; case 5: display(start); break; case 6: return 0; } } return 0; } ================================================ FILE: Data-Structures/LinkedList/Singly_Linked_List/Delete_Kth_Node_From_End/Delete_Kth_Node_From_End.java ================================================ import java.util.Scanner; class Delete_Kth_Node_From_End { static class Node { int data; Node next; }; static Node create(Node head, int x) { Node temp, ptr = head; temp = new Node(); temp.data = x; temp.next = null; if (head == null) head = temp; else { while (ptr.next != null) { ptr = ptr.next; } ptr.next = temp; } return head; } static Node removeNthFromEnd(Node head, int B) { int len = 0; Node tmp = head; while (tmp != null) { len++; tmp = tmp.next; } if (B > len) { System.out.print("Length of the linked list is " + len); System.out.print(" we can't remove "+ B + "th node from the"); System.out.print(" linked list\n"); return head; } else if (B == len) { return head.next; } else { int diff = len - B; Node prev= null; Node curr = head; for(int i = 0; i < diff; i++) { prev = curr; curr = curr.next; } prev.next = curr.next; return head; } } static void display(Node head) { Node temp = head; while (temp != null) { System.out.print(temp.data + " "); temp = temp.next; } System.out.println(); } public static void main(String[] args) { Node head = null; Scanner sc = new Scanner(System.in); System.out.print("Enter number of nodes to be inserted: "); int n = sc.nextInt(), p; for(int i=0;i 1): # Check if fibMm2 is a valid location i = min(offset + fibMMm2, n - 1) # If x is greater than the value at # index fibMm2, cut the subarray array # from offset to i if (arr[i] < x): fibM = fibMMm1 fibMMm1 = fibMMm2 fibMMm2 = fibM - fibMMm1 offset = i # If x is less than the value at # index fibMm2, cut the subarray # after i+1 elif (arr[i] > x): fibM = fibMMm2 fibMMm1 = fibMMm1 - fibMMm2 fibMMm2 = fibM - fibMMm1 # element found. return index else: return i # comparing the last element with x */ if (fibMMm1 and arr[offset + 1] == x): return offset + 1; # element not found. return -1 return -1 # Driver Code arr = [10, 22, 35, 40, 45, 50, 80, 82, 85, 90, 100] n = len(arr) x = 85 print("Found at index:", fibMonaccianSearch(arr, x, n)) ================================================ FILE: Data-Structures/LinkedList/Singly_Linked_List/Delete_Kth_Node_From_End/Delete_Kth_Node_From_End.rb ================================================ class Node attr_reader :value attr_accessor :next def initialize(value) @value = value @next = nil end end class SinglyLinkedList def initialize @head = nil @size = 0 end def insert(value) node = Node.new(value) current = @head while current && current.next do current = current.next end if current.nil? @head = node else current.next = node end @size += 1 end def delete_kth_from_end(k) return if (k > @size || @size <= 0) if k == @size @head = @head.next return end prev_node_pos_from_start = @size - k - 1 current = @head prev_node_pos_from_start.times do current = current.next end current.next = current.next.next @size -= 1 end def print_list current = @head loop do break if current.nil? print "#{current.value} " current = current.next end puts end end list = SinglyLinkedList.new list.insert(1) list.insert(2) list.insert(3) list.insert(4) list.insert(5) list.insert(6) list.print_list # 1 2 3 4 5 6 list.delete_kth_from_end(3) list.print_list # 1 2 3 5 6 list.delete_kth_from_end(1) list.print_list # 1 2 3 5 list.delete_kth_from_end(4) list.print_list # 2 3 5 ================================================ FILE: Data-Structures/LinkedList/Singly_Linked_List/Detect_Cycle/CycleDetection.c ================================================ #include #include #include #include #include #include #include typedef struct LinkedListNode LinkedListNode; // Node of a Linked List struct LinkedListNode { int val; LinkedListNode *next; }; LinkedListNode* _insert_node_into_singlylinkedlist(LinkedListNode *head, LinkedListNode *tail, int val) { if(head == NULL) { head = (LinkedListNode *) (malloc(sizeof(LinkedListNode))); head->val = val; head->next = NULL; tail = head; } else { LinkedListNode *node = (LinkedListNode *) (malloc(sizeof(LinkedListNode))); node->val = val; node->next = NULL; tail->next = node; tail = tail->next; } return tail; } //Function using Floyd Cycle detection algorithm bool hasCycle(LinkedListNode* head) { struct LinkedListNode* slow=head,*fast=head; while(slow && fast && fast->next) { slow=slow->next; fast=fast->next->next; if(slow==fast) { return true; } } return false; } // Main function int main() { FILE *f = stdout; char *output_path = getenv("OUTPUT_PATH"); if (output_path) { f = fopen(output_path, "w"); } bool res; int head_size = 0; LinkedListNode* head = NULL; LinkedListNode* head_tail = NULL; scanf("%d\n", &head_size); for(int i = 0; i < head_size; i++) { int head_item; scanf("%d", &head_item); head_tail = _insert_node_into_singlylinkedlist(head, head_tail, head_item); if(i == 0) { head = head_tail; } } int x; scanf("%d", &x); if (x > -1) { LinkedListNode* ptr = head; while (x--) ptr = ptr->next; head_tail->next = ptr; } res = hasCycle(head); fprintf(f, "%d\n", res); fclose(f); return 0; } ================================================ FILE: Data-Structures/LinkedList/Singly_Linked_List/Detect_Cycle/CycleDetection.java ================================================ //Detecting a cycle in singly linked list import java.util.*; class Node { //class describing structure of the node int data; Node next; Node(int value) { data = value; next = null; } } class Solution{ //creates a new linked list; public void create_list(Node head,int node_value){ Node newNode = new Node(node_value); if(head==null){ head = newNode; } else{ Node pointer = head; while(pointer.next!=null) pointer = pointer.next; pointer.next = newNode; } } //detects cycle in list public boolean hasCycle(Node head) { Node fast=head,slow=head; if(head==null || head.next==null) return false; while(fast!=null && fast.next!=null) { slow = slow.next; fast = fast.next.next; if(fast==slow) return true; } return false; } } //main class public class CycleDetection{ public static void main(String[] args){ Solution object = new Solution(); Node head = new Node(10); object.create_list(head,20); object.create_list(head,30); object.create_list(head,40); object.create_list(head,50); head.next.next.next = head; boolean answer = object.hasCycle(head); if(answer==true) System.out.println("Cycle is present"); else System.out.println("Cycle is not present"); } } ================================================ FILE: Data-Structures/LinkedList/Singly_Linked_List/Detect_Cycle/DetectCycle.cpp ================================================ #include using namespace std; class Node { public: int data; Node* next; }; void push(Node** head_ref, int new_data) { Node* new_node = new Node(); new_node->data = new_data; new_node->next = (*head_ref); (*head_ref) = new_node; } int detectLoop(Node* list) { Node *slow_p = list, *fast_p = list; while (slow_p && fast_p && fast_p->next) { slow_p = slow_p->next; fast_p = fast_p->next->next; if (slow_p == fast_p) { return 1; } } return 0; } int main() { Node* head = NULL; push(&head, 20); push(&head, 4); push(&head, 15); push(&head, 10); head->next->next->next->next = head; if (detectLoop(head)) cout << "Cycle found"; else cout << "No Cycle Found"; return 0; } ================================================ FILE: Data-Structures/LinkedList/Singly_Linked_List/Detect_Cycle/DetectCycle.py ================================================ # Node class class Node: # Constructor to initialize # the node object def __init__(self, data): self.data = data self.next = None class LinkedList: # Function to initialize head def __init__(self): self.head = None # Function to insert a new # node at the beginning def push(self, new_data): new_node = Node(new_data) new_node.next = self.head self.head = new_node # Utility function to print it # the linked LinkedList def printList(self): temp = self.head while(temp): print (temp.data, end =" ") temp = temp.next def detectCycle(self): s = set() temp = self.head while (temp): # If we have already has # this node in hashmap it # means their is a cycle # (Because you we encountering # the node second time). if (temp in s): return True # If we are seeing the node for # the first time, insert it in hash s.add(temp) temp = temp.next return False # Driver program for testing llist = LinkedList() llist.push(20) llist.push(4) llist.push(15) llist.push(10) # Create a loop for testing llist.head.next.next.next.next = llist.head; if( llist.detectCycle()): print ("Cycle found") else : print ("No Cycle found") ================================================ FILE: Data-Structures/LinkedList/Singly_Linked_List/Detect_Cycle/DetectCycle.ts ================================================ // Node class class ListNode { public data; public next: ListNode | null; // Constructor to initialize // the node object constructor(data: any) { this.data = data; this.next = null; } } class LinkedList { public head: ListNode | null; // Constructor to initialize LinkedList constructor() { this.head = null; } // Function to insert a new LinedListNode at the end of the list // with the given value append(data: any) { const newNode = new ListNode(data) if(!this.head) { this.head = newNode; } else { let pointer: ListNode | null = this.head; while (pointer.next) { pointer = pointer.next } pointer.next = newNode; } } // Function that detects if there is a cycle in the list // using Floyd's cycle-finding algorithm hasCycle() { // Floyd's Tortoise and Hare let slowPointer: ListNode | null = this.head; let fastPointer: ListNode | null = this.head; while(slowPointer && fastPointer && fastPointer.next) { slowPointer = slowPointer.next; fastPointer = fastPointer.next.next; if(slowPointer == fastPointer) { return true; } } return false; } } // Create a LinkedList instance and append values const linkedList = new LinkedList() linkedList.append(22) linkedList.append(4) linkedList.append(97) linkedList.append(1) // Create a loop // assigning the `next` of the last node to be the head of the LinkedList linkedList.head.next.next.next.next = linkedList.head; if(linkedList.hasCycle()) { console.log("Cycle is present"); } else { console.log("Cycle is not present"); } ================================================ FILE: Data-Structures/LinkedList/Singly_Linked_List/Detect_Cycle/Detect_Cycle.js ================================================ class ListNode { constructor(data) { this.data = data this.next = null } } class LinkedList { constructor(head = null) { this.head = head } add(element) { // creates a new node let node = new ListNode(element); // to store current node let current; // if list is Empty add the // element and make it head if (this.head == null) this.head = node; else { current = this.head; // iterate to the end of the // list while (current.next) { current = current.next; } // add node current.next = node; } } hasCycle (head) { if(!head) return false; let slow=head; let fast=head.next; while(slow!=fast) { if(!fast || !fast.next) return false; slow=slow.next; fast=fast.next.next; } return true; }; } const myList = new LinkedList(); myList.add(20); myList.add(30); myList.add(50); myList.head.next.next.next= myList.head; let ans=myList.hasCycle(myList.head); if(ans == true){ console.log(" The list contains cycle"); } else{ console.log(" The list does not contain cycle"); } ================================================ FILE: Data-Structures/LinkedList/Singly_Linked_List/Detect_Cycle/detect_cycle.cs ================================================ using System; namespace DSA { public class Node { public int Value { get; set; } public Node Next; public Node(int val) { this.Value = val; } } class ClosedLoop { public static bool DetectLoop(Node _head) { Node slow = _head, fast = _head.Next.Next; while (slow != null && fast != null && fast.Next != null) { if (slow == fast) { Console.WriteLine("Loop detected at: " + slow.Value); return true; } slow = slow.Next; //1 step increment fast = fast.Next.Next; //2 step increment } return false; } static void Main(string[] args) { Node tail = new Node(0); Node _actualHead = tail; Node intersection = null; //Creating linked list by adding nodes to the end of the list. for (int i = 1; i < 10; i++) { Node n = new Node(i); tail.Next = n; tail = n; //Taking the loop intersection. Comment below 'if' to avoid loop. if (i == 4) intersection = tail; } //Completing the loop tail.Next = intersection; if (!DetectLoop(_actualHead)) Console.WriteLine("No loop detected"); } } } ================================================ FILE: Data-Structures/LinkedList/Singly_Linked_List/Detect_Cycle/detect_cycle.go ================================================ package main import "fmt" type Node struct { Value int Next *Node } func NewNode(value int) *Node { return &Node{ Value: value, Next: nil, } } func DetectLoop(head *Node) bool { slow := head fast := head for slow != nil && fast != nil && fast.Next != nil{ slow = slow.Next fast = fast.Next.Next if slow == fast && slow != nil{ fmt.Println("Loop detected at ",slow.Value) return true } } return false } func main() { tail := NewNode(0) _actualHead := tail var intersection *Node // creating linked list for i := 1; i < 10; i++ { n := NewNode(i) tail.Next = n tail = n if i == 5 { intersection = tail // marking the loop node } } // completing the loop tail.Next = intersection if !DetectLoop(_actualHead) { fmt.Println("No loop detected") } } ================================================ FILE: Data-Structures/LinkedList/Singly_Linked_List/Java/PalindromeLinkedList.java ================================================ class ListNode { int val; ListNode next; ListNode() {} ListNode(int val) { this.val = val; } ListNode(int val, ListNode next) { this.val = val; this.next = next; } } class LinkedList { private ListNode head; public void addToTheLast(ListNode node) { if (head == null) { head = node; } else { ListNode temp = head; while (temp.next != null) temp = temp.next; temp.next = node; } } public boolean isPalindrome(ListNode head) { ListNode fast = head, slow = head; while (fast != null && fast.next != null) { fast = fast.next.next; slow = slow.next; } if (fast != null) { // odd nodes: let right half smaller slow = slow.next; } slow = reverse(slow); fast = head; while (slow != null) { if (fast.val != slow.val) { return false; } fast = fast.next; slow = slow.next; } return true; } public ListNode reverse(ListNode head) { ListNode prev = null; while (head != null) { ListNode next = head.next; head.next = prev; prev = head; head = next; } return prev; } } class PalindromLinkedList{ public static void main(String args[]){ LinkedList list = new LinkedList(); ListNode head=new ListNode(1); list.addToTheLast(head); list.addToTheLast(new ListNode(2)); list.addToTheLast(new ListNode(1)); list.addToTheLast(new ListNode(4)); list.addToTheLast(new ListNode(1)); if(list.isPalindrome(head)){ System.out.println("Linked List is Palindrome!"); }else{ System.out.println("Linked List is Not Palindrome!"); } } } ================================================ FILE: Data-Structures/LinkedList/Singly_Linked_List/LinkedList.cs ================================================ class LinkedList { private T value; private LinkedList next; public LinkedList(T value, LinkedList next) { SetValue(value); SetNext(next); } public LinkedList(T value) : this(value, null) {} public T GetValue() { return value; } public LinkedList GetNext() { return next; } public void SetValue(T value) { this.value = value; } public void SetNext(LinkedList next) { this.next = next; } } ================================================ FILE: Data-Structures/LinkedList/Singly_Linked_List/LinkedList.java ================================================ class LinkedList { private T value; private LinkedList next; public LinkedList(T value, LinkedList next) { SetValue(value); SetNext(next); } public LinkedList(T value) { this(value, null); } public T GetValue() { return value; } public LinkedList GetNext() { return next; } public void SetValue(T value) { this.value = value; } public void SetNext(LinkedList next) { this.next = next; } } ================================================ FILE: Data-Structures/LinkedList/Singly_Linked_List/LinkedList.py ================================================ class Node: def __init__(self, dataval=None): self.dataval = dataval self.nextval = None class SLinkedList: def __init__(self): self.headval = None list1 = SLinkedList() list1.headval = Node("Mon") a2 = Node("Tue") a3 = Node("Wed") # Link first Node to second node list1.headval.nextval = a2 # Link second Node to third node a2.nextval = a3 ================================================ FILE: Data-Structures/LinkedList/Singly_Linked_List/LinkedListAndOperations.cpp ================================================ #include using namespace std; struct list{ int data; list *link; }; list * head; void display_list(){ list *l=new list(); if(head==NULL){ cout<<"List is empty"; } else{ l=head; while(l!=NULL){ cout<data<<" "; l=l->link; } } } void insert_at_first(int z){ list *b=new list(); b->data=z; b->link=NULL; if(head==NULL){ head=b; } else { b->link=head; head=b; } } void insert_at_last(int n){ list *c=new list(); c->data=n; list *q=head; c->link=NULL; if(head==NULL){ head=c; } else { while(q->link!=NULL){ q=q->link; } q->link=c; } } void insert_at_mid(int a,int b){ list *d=new list(); list *q=head; d->data=b; while(q!=NULL){ if(q->data==a){ d->link=q->link; q->link=d; return; } q=q->link; } } void delete_first(){ list *p=head; p=p->link; head=p; } void delete_last(){ list *q=head; list*t; t=head; while(q->link!=0){ t=q; q=q->link; } if(t==head){ head=t->link; } else{ t->link=NULL; } } void delete_any(int a){ list *q=head; list *z=head; if(a==q->data){ head=q->link; } else{ while(q!=NULL){ if(a==q->data){ z->link=q->link; break; } z=q; q=q->link; } } } void count_list(){ int count=0; list *l=new list(); if(head==NULL){ cout<<"List is empty"; } else{ l=head; while(l!=NULL){ count++; l=l->link; } } cout<data; if(head==NULL){ cout<<0; } else{ while(q!=NULL){ if(maxdata){ max=q->data; } q=q->link; } } cout<< max; } void reverse_list(){ list *q=head; list*next=NULL; list*prev=NULL; while(q!=NULL){ next=q->link; q->link=prev; prev=q; q=next; } head =prev; } int main(){ int size,num1,num2; cout<<"Enter how many element you want to give to the list:-\t"; cin>>size; for(int i=0;i>num1; insert_at_first(num1); } cout<<"\n"; display_list(); cout<<"\nEnter the number you want to add at last :-\t"; cin>>num2; insert_at_last(num2); cout<<"\n"; display_list(); cout<<"\nEnter the number after which you want to add new element :-\t"; cin>>num1; cout<<"\nEnter the number which you want to add :-\t"; cin>>num2; insert_at_mid(num1,num2); cout<<"\n"; display_list(); cout<<"\nDelete 1st element"; delete_first(); cout<<"\n"; display_list(); cout<<"\nDelete last element"; delete_last(); cout<<"\n"; display_list(); cout<<"\nEnter the number you want to delete :-\t"; cin>>num1; delete_any(num1); cout<<"\n"; display_list(); cout<<"\n"; cout<<"Number of element left in list : "; count_list(); cout<<"\n"; cout<<"\nGiving maximum value: "; get_max_from_list(); cout<<"\nReversed the list : "; reverse_list(); cout<<"\n"; display_list(); return 0; } ================================================ FILE: Data-Structures/LinkedList/Singly_Linked_List/LoopDetection.cpp ================================================ #include using namespace std; //Templates start here #define pb push_back #define mp make_pair #define F first #define S second #define ll long long #define fo(i, j, k, in) for (int i = j; i < k; i += in) #define refo(i, j, k, in) for (int i = j; i >= k; i -= in) #define rep(i, j) fo(i, 0, j, 1) #define rerep(i, j) fo(i, j, 0, 1) #define all(cont) cont.begin(), cont.end() #define reall(cont) cont.end(), cont.begin() #define foreach(it, l) for (auto it = l.begin() l it != l.end(); it++) #define in(A, B, C) assert(B <= A && A <= C) #define MOD (int)1e9 #define MOD7 1000000007 #define PI 3.1415926535897932384626433832795 typedef pair PII; typedef pair PLL; typedef vector VI; typedef vector VL; typedef vector VS; typedef vector VII; typedef vector VLL; typedef vector VVI; typedef vector VVL; typedef map MPII; typedef map MPLL; typedef set SETI; typedef multiset MSETI; //Templates end here //I haven't used above templates for your better understanding but you are free to use it struct Node { int key; struct Node* next; }; Node* newNode(int key) { Node* temp = new Node; temp->key = key; temp->next = NULL; return temp; } void printList(Node* head) { while (head != NULL) { cout << head->key << " "; head = head->next; } cout << endl; } int distance(Node* first, Node* last) { int counter = 0; Node* curr; curr = first; while (curr != last) { counter += 1; curr = curr->next; } return counter + 1; } bool detectLoop(Node* head) { Node* temp = new Node; Node *first, *last; first = head; last = head; int current_length = 0; int prev_length = -1; while (current_length > prev_length && last != NULL) { prev_length = current_length; current_length = distance(first, last); last = last->next; } if (last == NULL) { return false; } else { return true; } } int main() { Node* head = newNode(1); head->next = newNode(2); head->next->next = newNode(3); head->next->next->next = newNode(4); head->next->next->next->next = newNode(5); head->next->next->next->next->next = head->next->next; bool found = detectLoop(head); if (found) cout << "Loop Found"; else cout << "No Loop Found"; return 0; } ================================================ FILE: Data-Structures/LinkedList/Singly_Linked_List/MiddleElementLL.cpp ================================================ #include using namespace std; struct Node{ int data; struct Node *next; }*head=NULL; int main() { struct Node *temp,*mid,*prev=NULL; int n,x,i,midval=0; cout<<"Enter the number of nodes:"; cin>>n; cout<<"\nEnter the elements\n"; for(i=0;i>x; temp=new Node; temp->data=x; temp->next=NULL; if(head==NULL) { head=temp; prev=head; mid=head; } else { prev->next=temp; prev=temp; if(i/2==midval) continue; else { mid=mid->next; midval++; } } } cout<<"Middle element is:"<data< { if (!node) return true; const reverse = traverse(node.next); const valChecker = front.value == node.value; front = front.next; return reverse && valChecker; } return traverse(head) }; } class LinkedListItem { value: any; next: LinkedListItem; constructor(val: number) { this.value = val; this.next = null; } } let head = new LinkedListItem(5); let linkedList = new LinkedList(head); linkedList.append(10); linkedList.append(2); linkedList.append(2); linkedList.append(10); linkedList.append(5); console.log(linkedList.showInArray()); console.log(linkedList.isPalindrome(head)); ================================================ FILE: Data-Structures/LinkedList/Singly_Linked_List/PalindromeLinkedList.cpp ================================================ #include using namespace std; class Node { public: int data; Node(int d) { data = d; } Node *ptr; }; bool isPalin(Node *head) { Node *slow = head; stack s; while (slow != NULL) { s.push(slow->data); // Move ahead slow = slow->ptr; } while (head != NULL) { int i = s.top(); s.pop(); if (head->data != i) { return false; } head = head->ptr; } return true; } // Driver Code int main() { // Creating a Linked List Node one = Node(1); Node two = Node(2); Node three = Node(3); Node four = Node(2); Node five = Node(1); // Initializing next pointers five.ptr = NULL; one.ptr = &two; two.ptr = &three; three.ptr = &four; four.ptr = &five; Node *temp = &one; int result = isPalin(&one); if (result == 1) cout << "isPalindrome is true\n"; else cout << "isPalindrome is true\n"; return 0; } ================================================ FILE: Data-Structures/LinkedList/Singly_Linked_List/PalindromeLinkedList.js ================================================ //classes to create the linklist class LinkedListNode { constructor(char, next) { this.value = char; this.next = next; } } class LinkedList { constructor(chars) { const len = chars.length; let currentNode = null; for (let i = len - 1; i >= 0; i--) { let node = new LinkedListNode(chars[i], currentNode); currentNode = node; } this.head = currentNode; } //function to check if the linked list iws a palindrome isPalindrome() { let center, slow, quick; center = slow = quick = this.head; if (slow.next == null) { return true; } while(quick.next != null) { slow = slow.next; slow.prev = center; center = slow quick = quick.next if (quick.next == null) { // even number center = slow.prev; } else { quick = quick.next; } } do { if(slow.value !== center.value) { return false; } slow = slow.next; center = center.prev; } while(slow != null) return true; } } var list=[],i,sizeofLinked=parseInt(prompt("enter the size of the linked list",0),10); for(i=0;i #include struct node { int num; struct node *next; }; void create(struct node **); void dup_delete(struct node **); void release(struct node **); void display(struct node *); int main() { struct node *p = NULL; struct node_occur *head = NULL; int n; printf("Enter data into the list\n"); create(&p); printf("Displaying the nodes in the list:\n"); display(p); printf("Deleting duplicate elements in the list...\n"); dup_delete(&p); printf("Displaying non-deleted nodes in the list:\n"); display(p); release(&p); return 0; } void dup_delete(struct node **head) { struct node *p, *q, *prev, *temp; p = q = prev = *head; q = q->next; while (p != NULL) { while (q != NULL && q->num != p->num) { prev = q; q = q->next; } if (q == NULL) { p = p->next; if (p != NULL) { q = p->next; } } else if (q->num == p->num) { prev->next = q->next; temp = q; q = q->next; free(temp); } } } void create(struct node **head) { int c, ch; struct node *temp, *rear; do { printf("Enter number: "); scanf("%d", &c); temp = (struct node *)malloc(sizeof(struct node)); temp->num = c; temp->next = NULL; if (*head == NULL) { *head = temp; } else { rear->next = temp; } rear = temp; printf("Do you wish to continue [1/0]: "); scanf("%d", &ch); } while (ch != 0); printf("\n"); } void display(struct node *p) { while (p != NULL) { printf("%d\t", p->num); p = p->next; } printf("\n"); } void release(struct node **head) { struct node *temp = *head; *head = (*head)->next; while ((*head) != NULL) { free(temp); temp = *head; (*head) = (*head)->next; } } ================================================ FILE: Data-Structures/LinkedList/Singly_Linked_List/Remove duplicates in a Linked List.cpp ================================================ #include using namespace std; class Node{ public: int data; Node *next; }*head = NULL; void create(int size){ int data, i; Node *temp; temp = head; cout << "Enter data: \n"; for(int i = 0; i < size; i++){ cin >> data; if(temp == NULL){ cout << "Couldn't allocate memory"; break; } if( i == 0 ){ head -> data = data; head -> next = NULL; } else{ Node *newNode = new Node(); newNode -> data = data; newNode -> next = NULL; temp -> next = newNode; temp = temp -> next; } } } void deleteNum(){ Node *ptr1, *ptr2, *prev; ptr1 = head; while(ptr1 != NULL){ ptr2 = ptr1 -> next; prev = ptr1; while(ptr2 != NULL){ if(ptr1 -> data == ptr2 -> data){ prev -> next = ptr2 -> next; } prev = ptr2; ptr2 = ptr2 -> next; } ptr1 = ptr1 -> next; } } void display(){ Node *temp = head; if(head == NULL){ cout << "Empty list"; } while(temp != NULL){ cout << temp -> data << "\t"; temp = temp -> next; } cout << endl; } int main() { int n, i; head = new Node(); cout << "Enter no.of nodes \n"; cin >> n; create(n); cout << "Original Linked List: \n"; display(); deleteNum(); cout << "After removin duplicates: \n"; display(); } ================================================ FILE: Data-Structures/LinkedList/Singly_Linked_List/Remove_Duplicates_in_LL.py ================================================ # Python3 program to remove duplicate # nodes from a sorted linked list # Node class class Node: # Constructor to initialize # the node object def __init__(self, data): self.data = data self.next = None class LinkedList: # Function to initialize head def __init__(self): self.head = None # Function to insert a new node # at the beginning def push(self, new_data): new_node = Node(new_data) new_node.next = self.head self.head = new_node # Given a reference to the head of a # list and a key, delete the first # occurence of key in linked list def deleteNode(self, key): # Store head node temp = self.head # If head node itself holds the # key to be deleted if (temp is not None): if (temp.data == key): self.head = temp.next temp = None return # Search for the key to be deleted, # keep track of the previous node as # we need to change 'prev.next' while(temp is not None): if temp.data == key: break prev = temp temp = temp.next # if key was not present in # linked list if(temp == None): return # Unlink the node from linked list prev.next = temp.next temp = None # Utility function to print the # linked LinkedList def printList(self): temp = self.head while(temp): print(temp.data , end = ' ') temp = temp.next # This function removes duplicates # from a sorted list def removeDuplicates(self): temp = self.head if temp is None: return while temp.next is not None: if temp.data == temp.next.data: new = temp.next.next temp.next = None temp.next = new else: temp = temp.next return self.head # Driver Code llist = LinkedList() print("Enter Number of Nodes in Linked List") N = int(input()) print("Enter Values For Linked List:") for _ in range(N): llist.push(int(input())) print ("Created Linked List: ") llist.printList() print() print("Linked List after removing duplicate elements:") llist.removeDuplicates() llist.printList() ================================================ FILE: Data-Structures/LinkedList/Singly_Linked_List/Reversed_Linked_List/ReversedLinkedList.js ================================================ class LinkedListNode { //Constructor to initialize a node constructor(value){ this.value = value; this.next = null; } } class LinkedList { //Constructor to initialize head constructor(){ this.head = null; } //Function to insert a new node at the start of list push(value){ const newNode=new LinkedListNode(value); newNode.next=this.head; this.head=newNode; } //Function to reverse a linked list reverse() { let node = this.head, previous, tmp; while (node) { //Save next before overwrite tmp = node.next; //Next equals previous; node.next = previous; //Move forward in the list previous = node node = tmp; } return previous; } } //Initialize list and push a few nodes const llist=new LinkedList() llist.push(5); llist.push(10); llist.push(15); llist.push(20); //Print out results console.log(llist.head) console.log(llist.reverse()) ================================================ FILE: Data-Structures/LinkedList/Singly_Linked_List/Reversed_Linked_List/reverseLinkedList.c ================================================ #include #include // structure of node typedef struct Node { struct Node *next; int data; } NODE; // insert a new node at the beginning of the linked list NODE *insert(NODE* head, int val) { NODE *p = (NODE *)malloc(sizeof(NODE)); p->data = val; p->next = (head == NULL) ? NULL : head; return head = p; } // reverse the linked list NODE *reverse(NODE *head) { NODE *p, *q, *r; p = NULL; q = head; while(q != NULL) { r = q->next; q->next = p; p = q; q = r; } return p; } // print the linked list void print_(NODE *head) { if(head == NULL) { printf("\n"); return; } printf("%d ", head->data); print_(head->next); } int main() { NODE *head = NULL; // inserting nodes in the linked list head = insert(head, 1); head = insert(head, 2); head = insert(head, 3); head = insert(head, 4); head = insert(head, 5); // printing the original linked list print_(head); // Output 5 4 3 2 1 // invoking the reverse head function NODE *revHead = reverse(head); // printing the reversed linked list print_(revHead); // Output 1 2 3 4 5 return 0; } ================================================ FILE: Data-Structures/LinkedList/Singly_Linked_List/Sublist_Search.rb ================================================ # simple linked list implementation class LinkedList attr_accessor :head # simple node implementation, constructor takes value and next ref class Node attr_accessor :value attr_accessor :next def initialize(val, nextNode) @value = val @next = nextNode end end # paramterized list constructor def initialize(val) @head = Node.new(val, nil) end # simple linked list insertion method def self.insert(node, val) # if given node is null, insert at given ref if not node then node = Node.new(val, nil) else # otherwise, iterate until end of list while node.next node = node.next end # then insert the new node node.next = Node.new(val, nil) end end # sublist search function implementation def self.search(listToFind, listBeingSearched) # declare result var res = false # base case - empty listToFind implies true [empty list always exists in a given list] if not listToFind then return true end # otherwise, see if lists match starting with first node of listToFind firstIteration = true while listBeingSearched do # update list2 to the corresponding node for this iteration if not firstIteration then # if list2 is eptied, return false if not listBeingSearched then return false end listBeingSearched = listBeingSearched.next end # make ref to head of each list for iter. purposes lookingFor = listToFind searchingIn = listBeingSearched # then try to match current form of list2 with list1 while lookingFor do # if list being searched is nil and list being searched for is not, fail if not searchingIn then return false # if a match fails, break and try from next list2 node elsif lookingFor.value != searchingIn.value then break end # otherwise, continue checking nodes lookingFor = lookingFor.next searchingIn = searchingIn.next end # if a match was found... if not lookingFor then return true end # o.w., continue firstIteration = false end end # simple print function for demonstration purposes def self.prettyPrint(node) while node print "#{node.value} -> " node = node.next end print "nil\n" end end # simple demonstration list setup via stdin puts "Please enter three values to put in the list that will be looked for:" list1 = LinkedList.new(gets.strip) for i in 1..2 LinkedList.insert(list1.head, gets.strip) end puts "Please enter five values to put in the list that will be searched:" list2 = LinkedList.new(gets.strip) for i in 1..4 LinkedList.insert(list2.head, gets.strip) end # pretty print the inputs puts "Seeking:" LinkedList.prettyPrint(list1.head) puts "Inside of:" LinkedList.prettyPrint(list2.head) # then demonstrate sublist search method puts "Result: " puts LinkedList.search(list1.head, list2.head) ================================================ FILE: Data-Structures/LinkedList/Singly_Linked_List/linked list.c ================================================ # include # include void create(); void display(); void insert_beg(); void count_node(); void delete(); struct node{ int data; struct node *next; }; struct node *start=NULL; void create(); void display(); void insert_beg(); void insert_end(); void insert_at_loc(); int main() { int c; create(); while(1){ printf("\n Available options:"); printf("1.DISPLAY\n 2.INSERT AT BEGINNING\n 3.INSERT AT END\n 4.INSERT AT LOCATION\n 5.COUNT\n 6.DELETE\n"); printf("\n Enter your choice"); scanf("%d",&c); switch(c){ case 1: display(); break; case 2: insert_beg(); break; case 3: insert_end(); break; case 4: insert_at_loc(); break; case 5: count_node(); break; case 6: delete(); break; } } return 0; } void create() { int n,item,i=1; printf("Enter the value of n"); scanf("%d",&n); struct node *p; p=(struct node*)malloc(sizeof(struct node)); start=p; printf("\n Enter the data for the node"); scanf("%d",&item); p->data=item; p->next=NULL; for(i=2;i<=n;i++) { printf("\n Enter the data for the node"); scanf("%d",&item); p->next = (struct node*)malloc(sizeof(struct node)); p=p->next; p->data=item; p->next=NULL; } } void display() { struct node *p=start; while(p!=NULL){ printf("%d->",p->data); p=p->next; } } void insert_beg() { int item; printf("\n Enter the data to be inserted"); scanf("%d",&item); struct node *temp; temp=(struct node*)malloc(sizeof(struct node)); temp->data= item; temp->next=start; start=temp; } void insert_end() { struct node *p=start,*temp; int item; printf("\n Enter the data to be inserted"); scanf("%d",&item); temp=(struct node*)malloc(sizeof(struct node)); temp->data=item; temp->next=NULL; while(p->next!=NULL) { p=p->next; } p->next=temp; } void insert_at_loc() { int i,item,loc; printf("Enter the data to be inserted\n"); scanf("%d",&item); printf("\n Enter the location"); scanf("%d",&loc); struct node *p=start,*temp; temp=(struct node*)malloc(sizeof(struct node)); temp->data=item; for(i=1;inext; } temp->next=p->next; p->next=temp; } void count_node() { int count=0; struct node *p=start; while(p!=NULL) { count=count+1; p=p->next; } printf("Node count : %d",count); } void delete() { int item; struct node *p=start,*old; printf("Enter the item to be deleted\n"); scanf("%d",&item); while(p!=NULL) { if(p->data ==item){ if(p==start){ start=p->next; free(p); return; } else{ old->next=p->next; free(p); return; } } else { old=p; p=p->next; } } } ================================================ FILE: Data-Structures/LinkedList/Singly_Linked_List/linked.cpp ================================================ #include #include #include using namespace std; struct Node { int info; Node* next; }*start,*newptr,*save,*ptr,*rear; Node* Create_New_Node(int); void Insert_End(Node*); void Display(Node*); void DelNode(); void Search(Node*); int main() { start=rear=NULL; int inf; char ch='y'; int choice; while(1) { cout<<"1:Insertion\n2:Display\n3:DelNode\n4:Search\n"; cout<<"ENTER YOUR CHOICE : "; cin>>choice; switch(choice) { case 1: { cout<<"\nEnter the Information for the new node..."; cin>>inf; newptr=Create_New_Node(inf); if(newptr!=NULL) { cout<<"\n"; } else { cout<<"\nCannot create new node!!!\n"; exit(1); } Insert_End(newptr); }break; case 2: cout<info=n; ptr->next=NULL; return ptr; } void Insert_End(Node*np) { if(start==NULL) { start=rear=np; }else { rear->next=np; rear=np; } } void Display(Node*np) { while(np!=NULL) { cout<info<<"->"; np=np->next; } cout<<"!!!\n"; } void DelNode() { if(start==NULL) { cout<<"UNDERFLOW!!!\n"; } else { ptr=start; start=start->next; delete ptr; } } void Search(Node*np) { int element; cout<<"Enter the Element to Search "; cin>>element; while(np!=NULL) { if(np->info==element) { cout<<"Search Successful \n"; break; } else cout<<"\n ELEMENT NOT FOUND "; np=np->next; } } ================================================ FILE: Data-Structures/LinkedList/Singly_Linked_List/linkedlist.cpp ================================================ #include #include #include using namespace std; /* * Node Declaration */ struct node { int info; struct node *next; }*start; /* * Class Declaration */ class single_llist { public: node* create_node(int); void insert_begin(); void insert_pos(); void insert_last(); void delete_pos(); void sort(); void search(); void update(); void reverse(); void display(); single_llist() { start = NULL; } }; /* * Main :contains menu */ main() { int choice, nodes, element, position, i; single_llist sl; start = NULL; while (1) { cout<>choice; switch(choice) { case 1: cout<<"Inserting Node at Beginning: "<info = value; temp->next = NULL; return temp; } } /* * Inserting element in beginning */ void single_llist::insert_begin() { int value; cout<<"Enter the value to be inserted: "; cin>>value; struct node *temp, *p; temp = create_node(value); if (start == NULL) { start = temp; start->next = NULL; } else { p = start; start = temp; start->next = p; } cout<<"Element Inserted at beginning"<>value; struct node *temp, *s; temp = create_node(value); s = start; while (s->next != NULL) { s = s->next; } temp->next = NULL; s->next = temp; cout<<"Element Inserted at last"<>value; struct node *temp, *s, *ptr; temp = create_node(value); cout<<"Enter the postion at which node to be inserted: "; cin>>pos; int i; s = start; while (s != NULL) { s = s->next; counter++; } if (pos == 1) { if (start == NULL) { start = temp; start->next = NULL; } else { ptr = start; start = temp; start->next = ptr; } } else if (pos > 1 && pos <= counter) { s = start; for (i = 1; i < pos; i++) { ptr = s; s = s->next; } ptr->next = temp; temp->next = s; } else { cout<<"Positon out of range"<next;s !=NULL;s = s->next) { if (ptr->info > s->info) { value = ptr->info; ptr->info = s->info; s->info = value; } } ptr = ptr->next; } } /* * Delete element at a given position */ void single_llist::delete_pos() { int pos, i, counter = 0; if (start == NULL) { cout<<"List is empty"<>pos; struct node *s, *ptr; s = start; if (pos == 1) { start = s->next; } else { while (s != NULL) { s = s->next; counter++; } if (pos > 0 && pos <= counter) { s = start; for (i = 1;i < pos;i++) { ptr = s; s = s->next; } ptr->next = s->next; } else { cout<<"Position out of range"<>pos; cout<<"Enter the new value: "; cin>>value; struct node *s, *ptr; s = start; if (pos == 1) { start->info = value; } else { for (i = 0;i < pos - 1;i++) { if (s == NULL) { cout<<"There are less than "<next; } s->info = value; } cout<<"Node Updated"<>value; struct node *s; s = start; while (s != NULL) { pos++; if (s->info == value) { flag = true; cout<<"Element "<next; } if (!flag) cout<<"Element "<next == NULL) { return; } ptr1 = start; ptr2 = ptr1->next; ptr3 = ptr2->next; ptr1->next = NULL; ptr2->next = ptr1; while (ptr3 != NULL) { ptr1 = ptr2; ptr2 = ptr3; ptr3 = ptr3->next; ptr2->next = ptr1; } start = ptr2; } /* * Display Elements of a link list */ void single_llist::display() { struct node *temp; if (start == NULL) { cout<<"The List is Empty"<info<<"->"; temp = temp->next; } cout<<"NULL"< #include #define SIZE(arr) (sizeof(arr) / sizeof(arr[0])) using namespace std; struct node { int data; struct node *next; }; node *createList(int *arr, int n){ node *head, *p; p = head = new node; head->data = arr[0]; head->next = NULL; for (int i = 1; i < n; ++i) { p->next = new node; p = p->next; p->data = arr[i]; p->next = NULL; } return head; } void displayList(node *head){ while (head != NULL) { cout << head->data << " "; head = head->next; } cout << endl; } node *mergeSortedLists(node *head1, node *head2){ node *result = NULL; if (head1 == NULL) { return head2; } if (head2 == NULL) { return head1; } if (head1->data < head2->data) { result = head1; result->next = mergeSortedLists(head1->next, head2); } else { result = head2; result->next = mergeSortedLists(head1, head2->next); } return result; } int main(){ int arr1[] = {10, 15, 17, 20}; int arr2[] = {5, 9, 13, 19}; node *head1, *head2, *result = NULL; head1 = createList(arr1, SIZE(arr1)); head2 = createList(arr2, SIZE(arr1)); cout << "First sorted list: " << endl; displayList(head1); cout << "Second sorted list: " << endl; displayList(head2); result = mergeSortedLists(head1, head2); cout << "Final sorted list: " << endl; displayList(result); return 0; } ================================================ FILE: Data-Structures/LinkedList/Singly_Linked_List/middle.ts ================================================ function main() { const input: string = window.prompt("Insert the values separated by commas. (I.e.: 1,2,3)"); const list = new SinglyLinkedList(); list.push(...input.split(',')); const middle: NodeCell = list.findMiddle(); console.log(`The middle of the list is ${middle.val}`); } class NodeCell { val: string; next: NodeCell; /** * Constructs a NodeCell. * @param {string} val - The value of the NodeCell. */ constructor(val: string){ this.val = val; this.next = null; } } class SinglyLinkedList { head: NodeCell; tail: NodeCell; /** * Constructs a SinglyLinkedList. */ constructor(){ this.head = null; this.tail = null; } /** * Push values into the SinglyLinkedList converting them into NodeCells. * @param {string[]} values - One or more values to be pushed into the List. */ push(...values: string[]){ for (const val of values) { const newNode = new NodeCell(val); if (!this.head) { this.head = newNode; this.tail = newNode; } else { this.tail.next = newNode; this.tail = newNode; } } } /** * Find the middle NodeCell of the SinglyLinkedList. * @returns {NodeCell} - The NodeCell currently in the middle of the List. */ findMiddle(): NodeCell{ let slowIterator: NodeCell = this.head; let fastIterator: NodeCell = this.head; while (fastIterator && fastIterator.next) { slowIterator = slowIterator.next; fastIterator = fastIterator.next.next; } return slowIterator; } } ================================================ FILE: Data-Structures/LinkedList/Singly_Linked_List/singly_linked_list.hs ================================================ module SinglyLinkedList where import Prelude hiding (tail, last) data List a = Cons a (List a) | Nil deriving (Show) size :: List a -> Int size Nil = 0 size (Cons _ tail) = 1 + size tail isEmpty :: List a -> Bool isEmpty Nil = True isEmpty _ = False first :: List a -> Maybe a first Nil = Nothing first (Cons x _) = Just x last :: List a -> Maybe a last Nil = Nothing last (Cons x Nil) = Just x last (Cons _ rest) = last rest addFirst :: a -> List a -> List a addFirst = Cons addLast :: a -> List a -> List a addLast x Nil = Cons x Nil addLast x (Cons el tail) = Cons el (addLast x tail) -- Convenience method. fromList :: [a] -> List a fromList = foldr Cons Nil ================================================ FILE: Data-Structures/LinkedList/detect_cycle.rb ================================================ # Definition for singly-linked list. class ListNode attr_accessor :val, :next def initialize(val) @val = val @next = nil end end # function to test if loop is there # @param {ListNode} head # @return {Boolean} def detect_cycle(head) slow = head fast = head while slow && fast && fast.next slow = slow.next fast = fast.next.next if slow && slow == fast return true end end false end # script to test the above tail = ListNode.new(5) head = tail loop_node = nil (2...9).each do |p| n = ListNode.new(5*p) tail.next = n tail = n if p == 7 loop_node = tail end end tail.next = loop_node puts("Loop detected ? = #{detect_cycle(head)}") ================================================ FILE: Data-Structures/LinkedList/sparce matrix/sparce addition.cpp ================================================ #include #include struct node { int r,c,v; struct node *next; }; void create(struct node **h) { struct node *cur,*ptr; *h=(struct node *)malloc(sizeof(struct node)); printf("Enter number of rows, coloumns and number of non zero elements"); scanf("%d%d%d",&(*h)->r,&(*h)->c,&(*h)->v); (*h)->next=NULL; ptr=*h; for(int i=0;i<(*h)->v;i++) { cur=(struct node *)malloc(sizeof(struct node)); printf("Enter row, coloumn and value of non zero elements"); scanf("%d%d%d",&cur->r,&cur->c,&cur->v); cur->next=NULL; ptr->next =cur; ptr=cur; } } void display1(struct node *h) { struct node *ptr; for(ptr=h;ptr!=NULL;ptr=ptr->next) { printf("%d\t%d\t%d",ptr->r,ptr->c,ptr->v); printf("\n"); } } void display2(struct node *h) { struct node *ptr; int c=0; for(int i=0;ir;i++) { for(int j=0;jc;j++) { for(ptr=h->next;ptr!=NULL;ptr=ptr->next) { if(ptr->r==i && ptr->c==j) { printf("%d\t",ptr->v); c=1; break; } else c=0; } if(c==0) printf("%d\t",0); } printf("\n"); } } void add(struct node *h1,struct node *h2,struct node **h3) { struct node *ptr,*cur,*p,*p2,*tmp; if(!(h1->r==h2->r && h1->c==h2->c)) return; *h3=(struct node *)malloc(sizeof(struct node)); (*h3)->r=h1->r; (*h3)->c=h1->c; (*h3)->v=h1->v+h2->v; ptr=*h3; for(p=h1->next;p!=NULL;p=p->next) { cur=(struct node *)malloc(sizeof(struct node)); cur->r=p->r; cur->c=p->c; cur->v=p->v; cur->next=NULL; ptr->next=cur; ptr=cur; } for(p=h2->next;p!=NULL;p=p->next) { cur=(struct node *)malloc(sizeof(struct node)); cur->r=p->r; cur->c=p->c; cur->v=p->v; cur->next=NULL; ptr->next=cur; ptr=cur; } for(p=(*h3)->next;p!=NULL;p=p->next) { tmp=p; p2=p->next; while(p2!=NULL) { if(p->r==p2->r && p->c==p2->c) { p->v=p->v+p2->v; tmp->next=p2->next; free(p2); p2=tmp; } tmp=p2; p2=p2->next; } } } int main() { struct node *h1,*h2,*h3; h1=h2=h3=NULL; create(&h1); create(&h2); display1(h1); printf("1st Matrix : \n"); display2(h1); printf("2nd Matrix : \n"); display2(h2); add(h1,h2,&h3); printf("Sum of Matrix is : \n"); display2(h3); return 0; } ================================================ FILE: Data-Structures/Queue/Circular-Queue/circular_queue.c ================================================ #include #include #define MAX_SIZE 100 struct queue { int info; struct queue *next; } *rear,*front,*temp;; int size = 0; void enqueue(int info); void dequeue(); void display(); void main(){ int choice,x; do{ printf("1-Insert\n2-Delete\n3-Display\n\nEnter a choice: "); scanf("%d",&choice); switch(choice){ case 1: printf("\nEnter the info to be inserted in the Queue : "); scanf("%d",&x); enqueue(x); display(); break; case 2: dequeue(); display(); break; case 3: display(); break; default:printf("Invalid choice, please try again.\n"); exit(0); } }while(choice!=4); } void enqueue(int x) { temp = (struct queue*) malloc(sizeof(struct queue)); temp -> info = x; if(front == NULL) front = temp; else { rear -> next = temp; rear = temp; } rear -> next = front; size++; } void dequeue() { int x; if (front == NULL) { printf("\nQueue is Empty"); } else if (front == rear) { x = front->info; free (front); front = rear = NULL; } else { temp = front; x = temp -> info; front = front -> next; rear -> next = front; free (temp); } size--; printf("\nThe deleted element is: %d",x); } void display() { if(front == NULL) printf("\nQueue is Empty!!!\n"); temp = front; while (temp->next!=NULL) { printf("%d\n", temp->info); temp = temp->next; } printf("%d\n", temp->info); } ================================================ FILE: Data-Structures/Queue/Circular-Queue/circular_queue.cs ================================================ using System; using System.Collections; namespace belphegorS.DataStructures { /// /// Summary description for CsCircularQueue. /// public class CircularQueue { private int nMaxSize; private int nFrontPosition; private int nRearPosition; private ArrayList alstQueueContent; public CircularQueue(int MaxSize) { nMaxSize = MaxSize; nFrontPosition = 0; nRearPosition= -1; alstQueueContent = new ArrayList(MaxSize); for(int i = 0;i 0) { nRearPosition = -1; } nRearPosition+=1; alstQueueContent[nRearPosition] = obj; if((nRearPosition-1) == nFrontPosition && alstQueueContent[nFrontPosition]==null) nFrontPosition = nFrontPosition+1; return true; } public object Dequeue() { object Output = "Empty" ; if(alstQueueContent[nFrontPosition] != null) { Output = alstQueueContent[nFrontPosition]; alstQueueContent[nFrontPosition]=null; if((nFrontPosition+1) #include struct node{ int data; struct node *next; }; struct queue{ struct node *front; struct node *rear; }; void enqueue(struct queue *q){ struct node *n=(struct node*)malloc(sizeof(struct node)); printf("\nEnter data for node\n"); scanf("%d",&n->data); if(q->front==NULL){ q->front=n; } else{ q->rear->next=n; } q->rear=n; q->rear->next=q->front; } void dequeue(struct queue *q){ if(q->front==NULL){ printf("\nQueue is empty\n"); } else if(q->front==q->rear){ printf("\nDeleted element=%d\n",q->front->data); q->front=NULL; q->rear=NULL; } else{ printf("\nDeleted element=%d\n",q->front->data); struct node *temp=q->front; q->front=q->front->next; q->rear->next=q->front; free(temp); } } void display(struct queue *q){ printf("\n"); struct node *temp=q->front; while(temp->next!=q->front){ printf("%d ",temp->data); temp=temp->next; } printf("%d ",temp->data); } int main(){ struct queue *p=(struct queue*)malloc(sizeof(struct queue)); p->front=NULL; p->rear=NULL; printf("\nEnter i->insertion, d->deletion, p->print and q->quit\n"); char ch; ch=getche(); while (ch!='q') { switch(ch){ case 'i': ; enqueue(p); break; case 'd': ; dequeue(p); break; case 'p': ; display(p); break; case 'q': ; break; default: printf("\n Wrong input\n"); break; } /* code */ printf("\n Enter i->insertion, d->deletion, p->print and q->quit\n"); ch=getche(); } return 0; } ================================================ FILE: Data-Structures/Queue/Circular-Queue/circular_queue_array_implementation.c ================================================ #include int front=-1; int rear=-1; int isFull(int size){ if((front==rear+1)||(front==0 && rear==size-1)) return 1; return 0; } int isEmpty(){ if(front==-1){ return 1; } return 0; } void display(int queue[],int size){ printf("\n"); int i; if(front>rear){ for(i=front;i0 && rear==size-1) rear=0; else rear++; queue[rear]=element; } } void dequeue(int queue[]){ if(isEmpty()){ printf("\nUnderflow\n"); } else{ if(front==rear){ printf("\nDeleted %d\n",queue[front]); front=-1; rear=-1; } else{ printf("\nDeleted %d\n",queue[front]); front++; } } } int main(){ int size; printf("Enter the size of the circular queue\n"); scanf("%d",&size); int queue[size]; printf("Enter the character from the following menu to perform the given operations\n"); printf("f->Display front element\nr->Display rear element\np->Display circular queue\ne->add an element from queue\nd->delete an element from queue\nq->quit"); char ch; while (1) { printf("\nEnter a character\n"); ch=getche(); if(ch=='q') break; else{ switch (ch) { case 'f': ; if(front!=-1) printf("\nFront element is %d\n",queue[front]); else printf("\nNo element present\n"); break; case 'r': ; if(rear!=-1) printf("\nRear element is %d\n",queue[rear]); else printf("\nNo element present\n"); break; case 'p': ; display(queue,size); break; case 'e': ; int tbe; printf("\nEnter the number to be inserted\n"); scanf("%d",&tbe); enqueue(queue,tbe,size); break; case 'd': ; dequeue(queue); break; default: printf("\nIllegal character\n"); break; } } } } ================================================ FILE: Data-Structures/Queue/Circular-Queue/cirqueue.cpp ================================================ #include #include #include using namespace std; void enqueue(int); void dequeue(); void display_CQ(); const int size = 5; int Cqueue[size],front=-1,rear=-1; int main() { int item,choice; cout<<("\n\n\t\t OPERATION MENU "); cout<<("\n\n\t\t 1.PUSH\n\t\t 2.POP\n\t\t 3.DISPLAY\n\t\t 4.EXIT"); do { cout<<("\n ENTER YOUR CHOICE : "); cin>>choice; switch(choice) { case 1: { cout<<"\n ENTER THE ITEM TO BE PUSHED : "; cin>>item; enqueue(item); break; } case 2: { dequeue(); break; } case 3: { display_CQ(); break; } case 4: exit(100); } }while(choice!=4); return 0; } void enqueue(int temp) { if((front==0 && rear==size-1) || (front==rear+1)) { cout<<"\n QUEUE OVERFLOW "; return ; } if(front==-1) { front=rear=0; } else { if(rear==size-1) { rear=0; } else rear++; } Cqueue[rear]=temp; } void dequeue() { if(front==-1) { cout<<"\n QUEUE UNDERFLOW "; return ; } cout<<"\n ELEMENT DELETED IS "< using namespace std; struct node { int value; node * next; node * prev; node(int x, node * pr, node * nx){ value = x; prev = pr; next = nx; } }; struct myDeque { private: node * head; node * tail; int cnt; void push(int x) { node * el = new node(x, NULL, NULL); head = el; tail = el; cnt++; } public: myDeque() { head = NULL; tail = NULL; cnt = 0; } void push_back(int x) { if(empty()){ push(x); return; } node * el = new node(x, tail, NULL); tail->next = el; tail = el; cnt++; } void push_front(int x) { if(empty()){ push(x); return; } node * el = new node(x, NULL, head); head->prev = el; head = el; cnt++; } void pop_back() { if(!empty()) { int res = tail->value; tail = tail->prev; cnt--; cout << res; } else { cout << "error"; } } void pop_front() { if(!empty()) { int res = head->value; head = head->next; cnt--; cout << res; } else { cout << "error"; } } void front() { if(!empty()) cout << head->value; else cout << "error"; } void back() { if(!empty()) cout << tail->value; else cout << "error"; } int size() { return cnt; } void clear() { head = NULL; tail = NULL; cnt = 0; } bool empty() { return cnt == 0; } }; int main() { string q; int x; myDeque md; do { cin >> q; if(q == "push_back"){ cin >> x; md.push_back(x); cout << "ok"; } if(q == "push_front"){ cin >> x; md.push_front(x); cout << "ok"; } if(q == "pop_back"){ md.pop_back(); } if(q == "pop_front"){ md.pop_front(); } if(q == "front"){ md.front(); } if(q == "back"){ md.back(); } if(q == "size"){ cout << md.size(); } if(q == "clear"){ md.clear(); cout << "ok"; } if(q == "exit"){ cout << "bye"; } cout << endl; } while(q != "exit"); return 0; } ================================================ FILE: Data-Structures/Queue/Deque/Deque.java ================================================ import java.util.ArrayList; import java.util.List; public class Deque{ private List deque = new ArrayList(); //add element at the beginning of the queue public void insertFront(int item){ System.out.println("element added at front: "+item); deque.add(0,item); System.out.println(deque); } //add element at the end of the queue public void insertRear(int item){ System.out.println("element added at rear: "+item); deque.add(item); System.out.println(deque); } //remove an item from the beginning of the queue public void removeFront(){ if(deque.isEmpty()){ System.out.println("Deque underflow, unable to remove."); return; } int rem = deque.remove(0); System.out.println("element removed from front: "+rem); System.out.println(deque); } //remove an item from the beginning of the queue public void removeRear(){ if(deque.isEmpty()){ System.out.println("Deque underflow, unable to remove."); return; } int rem = deque.remove(deque.size()-1); System.out.println("element removed from front: "+rem); System.out.println(deque); } //gets the element from the front without removing it public int peakFront(){ int item = deque.get(0); System.out.println("Element at first: "+item); return item; } //gets the element from the rear without removing it public int peakRear(){ int item = deque.get(deque.size()-1); System.out.println("Element at rear: "+item); return item; } public static void main(String a[]){ Deque deq = new Deque(); deq.insertFront(34); deq.insertRear(45); deq.removeFront(); deq.removeFront(); deq.removeFront(); deq.insertFront(21); deq.insertFront(98); deq.insertRear(5); deq.insertFront(43); deq.removeRear(); } } ================================================ FILE: Data-Structures/Queue/Deque/Deque.js ================================================ class Deque { constructor() { this.front = this.back = undefined; } // Adds a node to front of linked list addFront(value) { if (!this.front) this.front = this.back = { value }; else this.front = this.front.next = { value, prev: this.front }; } // Remove a node from the front of linked list removeFront() { let value = this.peekFront(); if (this.front === this.back) this.front = this.back = undefined; else (this.front = this.front.prev).next = undefined; return value; } // Get the value from the first node peekFront() { return this.front && this.front.value; } // Adds a node to end of linked list addBack(value) { if (!this.front) this.front = this.back = { value }; else this.back = this.back.prev = { value, next: this.back }; } // Removes a node from the back of linked list removeBack() { let value = this.peekBack(); if (this.front === this.back) this.front = this.back = undefined; else (this.back = this.back.next).back = undefined; return value; } // Get the value from the first node peekBack() { return this.back && this.back.value; } } // demo let deque = new Deque; console.log(deque.peekFront()); // undefined deque.addFront(1); console.log(deque.peekBack()); // 1 deque.addFront(2); console.log(deque.removeBack()); // 1 deque.addFront(3); deque.addFront(4); console.log(deque.peekBack()); // 2 deque.addBack(5); deque.addBack(6); console.log(deque.peekBack()); // 6 console.log(deque.removeFront()); // 4 console.log(deque.removeFront()); // 3 console.log(deque.removeFront()); // 2 console.log(deque.removeFront()); // 5 console.log(deque.removeFront()); // 6 console.log(deque.removeFront()); // undefined ================================================ FILE: Data-Structures/Queue/Deque/Deque.py ================================================ # Creating class deque class Deque(): # Initializing class def __init__(self, data=None): self.elements = [] if(data is not None): self.elements = list(data) # Appending an item def append(self, item): self.elements.append(item) # Appending an item to the left def appendleft(self, item): self.elements = [item] + self.elements # Popping an item def pop(self): return self.elements.pop() # Popping item from the left def popleft(self): return self.elements.pop(0) # Searching for item in range def index(self, item, start, stop): for i in range(start, min(stop, len(self.elements))): if(item == self.elements[i]): return i # Inserting item at index def insert(self,idx,item): self.elements = self.elements[:idx] + [item] + self.elements[idx:] # Removing item def remove(self, item): self.elements.remove(item) # Counting occurence of an item def count(self, item): counter = 0 for i in self.elements: if(i == item): counter+=1 return counter # Extending def extend(self, list_2): list_2 = list(list_2) self.elements += list_2 # Extending to the left def extendleft(self, list_2): list_2 = list(list_2) self.elements = list_2[::-1] + self.elements # Rotating deque def rotate(self,idx): self.elements = self.elements[-idx:] + self.elements[:-idx] # Clearing the deque def clear(self): self.elements.clear() # Creating a copy def copy(self): return Deque(self.elements) # Returning a string version def __str__(self): return str(self.elements) # Returning iterable def __iter__(self): for item in self.elements: yield item if __name__ == "__main__": x = Deque([2,3]) print("x:", x) x.appendleft(1) print("Appending 1 to the left:", x) x.append(4) print("Appending 4:", x) print("Popping element:\n", x.pop(), x) print("Popping first element:\n", x.popleft(), x) y = Deque([1,2,3,4,5,6,7,8,9]) print("y:", y) y.insert(0,0) print("Inserting 0 at position 0:", y) y.insert(10,10) print("Inserting 10 at position 10:", y) print("Index of 4:", y.index(4,0,100)) y.remove(10) print("After removing 10",y) y.extendleft(x) print("Extending x to the left:", y) y.extend([4,4,4]) print("Extending [4,4,4]:", y) y.rotate(2) print("Rotating by 2", y) y.rotate(-2) print("Rotating by -2", y) y.clear() print("Cleared y:",y) z = x.copy() print("Creating copy of x:",z) z.append(12345) print("After appending 12345 to z:", z) print("x:",x,"z:",z) ================================================ FILE: Data-Structures/Queue/Deque/Deque.ts ================================================ // Node class class DequeNode { public data; public prev: DequeNode | null; public next: DequeNode | null; // Constructor to initialize // the node object constructor(data: any) { this.data = data; this.prev = null; this.next = null; } } class Deque { public head: DequeNode | null; public tail: DequeNode | null; // Constructor to initialize LinkedList constructor() { this.head = null; this.tail = null; } // Utility function just to see the results at a certain time print() { let a = [] let pointer: DequeNode | null = this.head; while (pointer) { a.push(pointer.data) pointer = pointer.next } console.log(a) } // Function to see the beginning of the deque peekFront() { return this.head && this.head.data; } // Function to insert a new DequeNode at the beginning of the deque // with the given value appendFront(data: any) { const newNode = new DequeNode(data) if(!this.head) { this.head = newNode; this.tail = newNode; } else { this.head.prev = newNode; newNode.next = this.head; this.head = newNode; } } // Function to remove a beginning at the end of the deque removeFront() { const value = this.peekFront(); if(value) { if (this.head === this.tail) { this.head = null; this.tail = null; } else { this.head = this.head!.next; this.head!.prev = null; } } return value; } // Function to see the end the deque peekBack() { return this.tail && this.tail.data; } // Function to insert a new DequeNode at the beginning of the deque // with the given value appendBack(data: any) { const newNode = new DequeNode(data) if(!this.tail) { this.head = newNode; this.tail = newNode; } else { newNode.prev = this.tail; this.tail.next = newNode; this.tail = newNode; } } // Function to remove a node at the end of the deque removeBack() { const value = this.peekBack(); if(value) { if (this.head === this.tail) { this.head = null; this.tail = null; } else { this.tail = this.tail!.prev; this.tail!.next = null; } } return value; } } const deque = new Deque(); deque.appendFront(22); deque.appendBack(4); deque.appendBack(97); deque.appendFront(1); deque.appendBack(5); deque.print() deque.removeFront() deque.removeBack() deque.removeFront() deque.print() console.log('Current front:', deque.peekFront()); console.log('Current back:', deque.peekBack()); ================================================ FILE: Data-Structures/Queue/Deque/README.md ================================================ # This folder is empty. ================================================ FILE: Data-Structures/Queue/Priority-Queue/Priority-Queue.cpp ================================================ #include using namespace std; // Node Declaration struct node { int priority; int info; // info stands for the value or the item to be added struct node *link; }; // Class Priority Queue class Priority_Queue { private: node *front; //front node of queue public: Priority_Queue() { front = NULL; } // Insert into Priority Queue void insert(int item, int priority) { node *tmp, *q; tmp = new node; // make a temprory node tmp->info = item; //set the value tmp->priority = priority; //set the priority if (front == NULL || priority < front->priority) // if priority of current element less than front elemnt priority. { tmp->link = front; front = tmp; } //else if greater priority else { q = front; while (q->link != NULL && q->link->priority <= priority) q=q->link; tmp->link = q->link; q->link = tmp; } } // Delete from Priority Queue void del() { node *tmp; if(front == NULL) cout<<"Queue Underflow\n"; else { tmp = front; cout<<"Deleted item is: "<info<link; free(tmp); } } //Print Priority Queue void display() { node *ptr; ptr = front; if (front == NULL) cout<<"Queue is empty\n"; else { cout<<"Queue is :\n"; cout<<"Priority Item\n"; while(ptr != NULL) { cout<priority<<" "<info<link; } } } }; int main() { int choice, item, priority; Priority_Queue pq; do { cout<<"1.Insert\n"; cout<<"2.Delete\n"; cout<<"3.Display\n"; cout<<"4.Quit\n"; cout<<"Enter your choice : "; cin>>choice; switch(choice) { case 1: cout<<"Input the item value to be added in the queue : "; cin>>item; cout<<"Enter its priority : "; cin>>priority; pq.insert(item, priority); break; case 2: pq.del(); break; case 3: pq.display(); break; case 4: break; default : cout<<"Wrong choice\n"; } } while(choice != 4); return 0; } ================================================ FILE: Data-Structures/Queue/Priority-Queue/PriorityQueue.php ================================================ insert("p2",2); $obj->insert("p1",1); $obj->insert("p3",3); $obj->insert('p4',4); // Display the priority queue elements // var_dump($obj); echo"Object :"; print_r($obj); // Display the extracted element // from priority queue echo"Show extracted element according to priority :"; var_dump($obj->extract()); // Display the number of elements // in priority queue echo"Show the number of elements :"; var_dump($obj->count()); // Use isCorrupted() function to check // priority queue is in corrupted state // or not echo"Show priority queue is in corrupted state or not :"; var_dump($obj->isCorrupted()); // Use isEmpty() function to check // priority queue is empty or not echo"Show priority queue is empty or not :"; var_dump($obj->isEmpty()); ?> ================================================ FILE: Data-Structures/Queue/Priority-Queue/README.md ================================================ # This folder is empty. ================================================ FILE: Data-Structures/Queue/Priority-Queue/priorityQueue.js ================================================ class PriorityQueue { constructor() { this.queue = []; } // Insert an element into the queue enqueue(element, priority) { let node = [element, priority]; if(this.isEmpty()) { this.queue.push(node); return; } for(let i = 0; i < this.queue.length; i++) { if(node[1] > this.queue[i][1]) { this.queue.splice(i, 0, node); return; } } this.queue.push(node); } // Remove the element with the highest priority and return it dequeue() { return this.queue.shift(); } // Return the element with the highest priority peek() { return this.queue[0]; } // Check if the queue is empty isEmpty() { return this.queue.length == 0; } // Return the number of elements in the queue size() { return this.queue.length; } // For debugging purposes print() { this.queue.forEach(element => { console.log(element[0] + "\t" + element[1]); }); } } // Example queue = new PriorityQueue(); queue.enqueue(5, 5); queue.enqueue("Text", 7); queue.enqueue(true, 3); queue.print(); ================================================ FILE: Data-Structures/Queue/QueueUsingArray.c ================================================ #include void enqueue(int[],int); void dequeue(int[]); void display_Queue(int[]); int Queue[],size,front=-1,rear=-1; void main() { int item,choice; char ch; printf("\n ENETR THE SIZE OF QUEUE :"); scanf("%d",&size); printf("\n AFTER DEQUEUE OPERATION"); dequeue(Queue); printf("\n ENTER THE ITEM :"); scanf("%d",&item); enqueue(Queue,item); display_Queue(Queue); } void enqueue(int Queue[],int temp) { if(rear==size-1) printf("\n QUEUE OVERFLOW"); else if(rear==-1) { front=rear=0; Queue[rear]=temp; display_Queue(Queue); } else { rear++; Queue[rear]=temp; } } void dequeue(int Queue[]) { if(front==-1) printf("\n QUEUE UNDERFLOW"); else { printf("\n THE DELETED ITEM IS %d",Queue[front]); front++; display_Queue(Queue); if(front==rear) front=rear=-1; else front++; } } void display_Queue(int Queue[]) { if(front==-1) return ; for(int i=front;i<=rear;++i) printf(Queue[i]);printf("<-"); printf("%d",Queue[rear]); } ================================================ FILE: Data-Structures/Queue/QueueUsingArray.cpp ================================================ #include using namespace std; struct node { int data; struct node *next; }; struct node* front = NULL; struct node* rear = NULL; struct node* temp; void Insert() { int val; cout<<"Insert the element in queue : "<>val; if (rear == NULL) { rear = (struct node *)malloc(sizeof(struct node)); rear->next = NULL; rear->data = val; front = rear; } else { temp=(struct node *)malloc(sizeof(struct node)); rear->next = temp; temp->data = val; temp->next = NULL; rear = temp; } } void Delete() { temp = front; if (front == NULL) { cout<<"Underflow"<next != NULL) { temp = temp->next; cout<<"Element deleted from queue is : "<data<data<data<<" "; temp = temp->next; } cout<>ch; switch (ch) { case 1: Insert(); break; case 2: Delete(); break; case 3: Display(); break; case 4: cout<<"Exit"< { var array = [Element]() // ENQUEUE: Add an element at the end of the queue mutating func enqueue(_ element: Element) { array.append(element) } // DEQUEUE: Remove the element from the beginning of the queue mutating func dequeue() -> Element? { return isEmpty ? nil : array.removeFirst() } // PEEK: Returns the first element in the queue func peek() -> Element? { return array.first } // Is queue empty? var isEmpty: Bool { return array.isEmpty } // Number of elements in queue var count: Int { return array.count } } // Use case - any type var queue = Queue() queue.enqueue("Maria") queue.enqueue("Jim") queue.enqueue("Gloria") queue.peek() queue.count ================================================ FILE: Data-Structures/Queue/QueueUsingLL.c ================================================ #include #include struct qlist {int info; struct qlist *next; }; struct qlist *front=NULL,*rear=NULL; void enqueue(struct qlist **,struct qlist **,int ); int dequeue(struct qlist **,struct qlist**); int main() { int ch,item; while(1) { printf("\n 1. Enqueue \n2.Dequeue \n3.exit"); scanf("%d",&ch); switch(ch) { case 1:printf("\n Enter item"); scanf("%d",&item); enqueue(&front,&rear,item); break; case 2:item=dequeue(&front ,&rear); printf("\n %d deleted",item); break; case 3:exit(0); default:printf("\n invalid"); } } } void enqueue(struct qlist **pfront,struct qlist **prear,int item) { struct qlist *newnode; newnode=(struct qlist *)malloc(sizeof(struct qlist)); newnode->info=item; newnode->next=NULL; if(*pfront==NULL) *pfront=newnode; else (*prear)->next=newnode; *prear=newnode; } int dequeue(struct qlist **pfront,struct qlist**prear) { struct qlist *temp; int item; if(*pfront==NULL) { printf("\n underflow"); return(-9999); } temp=*pfront; item=(*pfront)->info; if(*pfront==*prear) { *pfront=NULL; *prear=NULL; } else *pfront=(*pfront)->next; temp->next=NULL; free(temp); return(item); } ================================================ FILE: Data-Structures/Queue/QueueUsingLL.cpp ================================================ // FIFO Mechanism #include using namespace std; struct node { int data; node *next; }; // Function to insert values in the end in the Queue node *add(node *rear, int val) { node *x; x = new node; x->data = val; x->next = NULL; if (rear != NULL) rear->next = x; rear = x; return rear; } // Function to delete values from the front in the Queue node *del(node *front, int &val) { if (front == NULL) { cout << "Queue is Empty..!" << endl; // Prints if the queue is empty val = -9999; } else { node *x; x = front; front = front->next; val = x->data; // Storing the deleted value in 'val' delete x; } return front; } // Function to print values in the Queue void showqueue(node *front) { node *ptr; ptr = front; if (ptr == NULL) { cout << "Queue is empty..!" << endl; // Prints if the queue is empty } else { cout << "Queue is " << endl; while (ptr != NULL) { cout << ptr->data << "\t"; ptr = ptr->next; } cout << endl; } } int main() { int choice, val; node *front, *rear; front = rear = NULL; // Menu Driven Program do { cout << "\nMain Menu\n" << "1. Insert\n" << "2. Delete\n" << "3. Show\n" << "4. Exit\n" << "Enter your choice: "; cin >> choice; switch (choice) { case 1: cout << "Enter value to be added: "; cin >> val; rear = add(rear, val); if (front == NULL) front = rear; break; case 2: front = del(front, val); if (val != -9999) cout << "The deleted value is: " << val << endl; if (front == NULL) rear = front; break; case 3: showqueue(front); break; default: break; } } while (choice != 4); // Program exits whenever the user enters no. 4 return 0; } // Author - Ankit Goel ================================================ FILE: Data-Structures/Queue/QueueUsingLL.cs ================================================ using System; using System.Collections; using System.Collections.Generic; namespace DataStructures { class SimpleQueue { private LinkedList queue = new LinkedList(); public void Enqueue(int val) { queue.AddLast(val); } public int Dequeue() { int ret = queue.First.Value; queue.RemoveFirst(); return ret; } public int Peek() { return queue.First.Value; } public int Size() { return queue.Count; } public bool IsEmpty() { return queue.Count == 0; } public void Print() { foreach (int i in queue) Console.Write(i + " "); } static void Main(string[] args) { SimpleQueue myQueue = new SimpleQueue(); myQueue.Enqueue(55); myQueue.Enqueue(33); myQueue.Enqueue(12); myQueue.Enqueue(77); myQueue.Enqueue(25); Console.WriteLine("Current queue: "); myQueue.Print(); Console.WriteLine(); int n = myQueue.Dequeue(); Console.WriteLine("The dequeued value: {0}", n); n = myQueue.Dequeue(); Console.WriteLine("The dequeued value: {0}", n); Console.WriteLine("Current queue: "); myQueue.Print(); Console.WriteLine(); } } } ================================================ FILE: Data-Structures/Queue/QueueUsingLL.php ================================================ front == null; } //Enqueue function public function enqueue($value){ $oldBack = $this->back; $this->back = new Node(); $this->back->value = $value; if($this->isEmpty()){ $this->front = $this->back; }else{ $oldBack->next = $this->back; } } // Dequeue Function public function dequeue(){ if($this->isEmpty()){ return null; } $removedValue = $this->front->value; $this->front = $this->front->next; return $removedValue; } // Show queue Function public function show(){ $current = $this->front; $print=""; while($current != NULL) { $print .=$current->value.","; $current = $current->next; } echo $print; } } //Create a New Queue $queue = new Queue(); //Inserting 1 , 2 , 3 , 4 $queue->enqueue(1); $queue->enqueue(2); $queue->enqueue(3); $queue->enqueue(4); $queue->show(); echo "
"; //DeQueue First Element $queue->dequeue()."\n"; //Show $queue->show(); ?> ================================================ FILE: Data-Structures/Queue/QueueUsingStacks.cpp ================================================ // Program to implement Queue using Stack in C. #include #define N 5 int stack1[5], stack2[5]; // declaration of two stacks // declaration of top variables. int top1=-1, top2=-1; int count=0; // inserting the elements in stack1. void push1(int data) { // Condition to check whether the stack1 is full or not. if(top1==N-1) { printf("\n Stack is overflow..."); } else { top1++; // Incrementing the value of top1 stack1[top1]=data; // pushing the data into stack1 } } // Removing the elements from the stack1. int pop1() { // Condition to check whether the stack1 is empty or not. if(top1==-1) { printf("\nStack is empty.."); } else { int a=stack1[top1]; // Assigning the topmost value of stack1 to 'a' variable. top1--; // decrementing the value of top1. return a; } } // pushing the data into the stack2. void push2(int x) { // Condition to check whether the stack2 is full or not if(top2==N-1) { printf("\nStack is full.."); } else { top2++; // incrementing the value of top2. stack2[top2]=x; // assigning the 'x' value to the Stack2 } } // Removing the elements from the Stack2 int pop2() { int element = stack2[top2]; // assigning the topmost value to element top2--; // decrement the value of top2 return element; } void enqueue(int x) { push1(x); count++; } void dequeue() { if((top1==-1) && (top2==-1)) { printf("\nQueue is empty"); } else { for(int i=0;i #include #include using namespace std; struct node { char data; node *next; }; struct eval_node { int data; eval_node *next; }; class stack { node *top; public: stack() { top=NULL; } void push(char a); char pop(); }; class eval_stack { eval_node *top; public: eval_stack() { top=NULL; } void push(int a); int pop(); }; void stack::push(char a) { node *newnode=new node; newnode->data=a; newnode->next=top; top=newnode; } char stack::pop() { if(top==NULL) { cout<<"\n UNDERFLOW!!"; return '%'; } char a=top->data; node *ptr=top; top=top->next; delete ptr; return a; } void eval_stack::push(int a) { eval_node *temp=new eval_node; temp->data=a; temp->next=top; top=temp; } int eval_stack::pop() { if(top==NULL) { cout<<"\n UNDERFLOW!!"; return '%'; } int a=top->data; eval_node *ptr=top; top=top->next; delete ptr; return a; } void disp(char b[]) { cout<<"["; for(int i=0;b[i]!='\0';i++) { cout<b2) { b[j]=a1; j++; s.push(a2); top++; } else { s.push(a1); top++; s.push(a2); top++; } } } i++; } else if(a[i]==')') { a1=s.pop(); top--; while(a1!='(') { b[j]=a1; j++; a1=s.pop(); top--; } i++; } } while(top!=-1) { a1=s.pop(); top--; b[j]=a1; j++; } b[j]='\0'; } void in_pre(char a[],char b[]) { int n=strlen(a); rev(a,n); in_pos(a,b); n=strlen(b); rev(b,n); } int eval_pos(char a[]) { eval_stack s; int op1,op2,top=-1,i=0,sol; while(a[i]!='\0') { if(isalnum(a[i])) { s.push(int(a[i])-48); top++; } else { op2=s.pop(); top--; op1=s.pop(); top--; sol=result(op1,op2,a[i]); s.push(sol); top++; } i++; } return sol; } int eval_pre(char a[]) { eval_stack s; int op1,op2,top=-1,sol; int i=strlen(a)-1; while(i>=0) { if(isalnum(a[i])) { s.push(int(a[i])-48); top++; } else { op1=s.pop(); top--; op2=s.pop(); top--; sol=result(op1,op2,a[i]); s.push(sol); top++; } i--; } return sol; } int main() { char ip[20],op[20]; int in,ch; cout<<"----MENU----\n"; cout<<"[1] INFIX TO POSTFIX\n"; cout<<"[2] INFIX TO PREFIX\n"; cout<<"[3] EVALUATION OF POSTFIX\n"; cout<<"[4] EVALUATION OF PREFIX\n\n"; do { cout<<"**** Enter your choice ****\n\n"; cin>>ch; if(ch==1) { cout<<"Enter Infix expression: \n"; cin>>ip; in_pos(ip,op); cout<<"Hence, Postfix Expression is: \n"; disp(op); } else if(ch==2) { cout<<"Enter Infix expression: \n"; cin>>ip; in_pre(ip,op); cout<<"Hence, Prefix Expression is: \n"; disp(op); } else if(ch==3) { cout<<"Enter Postfix expression: \n"; cin>>ip; int s1=eval_pos(ip); cout<<"Evaluating Postfix Expression, we get \n"; cout<>ip; int s2=eval_pre(ip); cout<<"Evaluating Prefix Expression, we get \n"; cout<>in; } while(in==1); { cout<<"\n----Operation Completed!! ThankYou----\n"; return 0; } } /* --------------------------------------------------------------------------------------------------------------------------- OUTPUT : ----MENU---- [1] INFIX TO POSTFIX [2] INFIX TO PREFIX [3] EVALUATION OF POSTFIX [4] EVALUATION OF PREFIX **** Enter your choice **** 1 Enter Infix expression: (a+(b*c))/(c-(d*b)) Hence, Postfix Expression is: [a b c * + c d b * - / ] ----Operation Completed!! ThankYou---- */ ================================================ FILE: Data-Structures/Stack/README.md ================================================ ## Stack In science of science, a pile is an ordered set of non-qualifying items that can be inserted and from which they can be disposed of at a single end - the top of the pile. Due to its form of operation, this data structure also has an alternative name - LIFO (Last-In, Fist-Out).The two changes that can be made to a stack are given special names. * When an item is added to a stack, it is "stacked" on top of the stack. * and when an item is removed, it is "unstacked". ================================================ FILE: Data-Structures/Stack/StackUsingArray.c ================================================ #include #define max 100 int st[100]; int top = -1; // This function will add an element in the top of the stack. void push() { int ele; top++; if(top >= max) { printf("Stack is overflow\n"); return; } printf("Enter any one element to push in stack: "); scanf("%d", &ele); st[top] = ele; printf("%d pushed successfully in stack.\n", ele); } // This function will remove an element from the top of the stack. void pop() { int ele; if(top < 0) { printf("Stack is underflow\n"); return; } ele = st[top]; top--; printf("%d has been deleted from the stack.\n", ele); } // This function will remove all the elements from stack. void clear() { top = -1; printf("Stack is cleared.\n"); } // This function will check if stack is empty or not. void isEmpty() { if(top < 0) { printf("Stack is empty.\n"); } else { printf("Stack is not empty.\n"); } } // This function will show the top element in the stack. void topmost() { if(top < 0) { printf("Stack is underflow\n"); return; } printf("Topmost element in stack is %d\n", st[top]); } // This function will show the occurence of any element in the stack. void seek() { int ele, count = 0; if(top < 0) { printf("Stack is underflow\n"); return; } printf("Enter any element to check the occurence in the stack: "); scanf("%d", &ele); for(int i = 0; i <= top; ++i) { if(st[i] == ele) { count++; } } printf("%d occurs %d times in the stack.\n", ele, count); } // This function will show all the elements in the stack. void display() { if(top < 0) { printf("Stack is underflow.\n"); return; } for(int i = 0; i <= top; ++i) { printf("%d ", st[i]); } printf("\n"); } void instructions() { printf("You can add upto 100 elements in this Stack.\n"); printf("Enter 1 to push the element.\n"); printf("Enter 2 to pop the element.\n"); printf("Enter 3 to display all the elements.\n"); printf("Enter 4 to see the topmost element in stack.\n"); printf("Enter 5 to search the occurence of any element in the stack.\n"); printf("Enter 6 to check if stack is empty or not.\n"); printf("Enter 7 to clear the stack.\n"); printf("Enter 8 to exit.\n"); } int main() { int choice; instructions(); do { printf("\nEnter your choice of operation: "); scanf("%d", &choice); switch(choice) { case 1: push(); break; case 2: pop(); break; case 3: display(); break; case 4: topmost(); break; case 5: seek(); break; case 6: isEmpty(); break; case 7: clear(); break; case 8: return 0; default: printf("Wrong input. Read instructions to use stack efficiently.\n\n"); instructions(); } } while(1); // Program will run until user choose 8. return 0; } ================================================ FILE: Data-Structures/Stack/StackUsingArray.cpp ================================================ #include using namespace std; class stack{ private: int top; int j; int arr[]; public: stack(){ // int j; top = -1; cout << "What stack size you want? " << endl; cin >> j; for (int i = 0; i < j; i++) { arr[i] = 0; } } bool isEmpty(){ if (top==-1) { return true; } else { return false; } } bool isFull(){ if (top==(j-1)) { return true; } else { return false; } } void push(int i){ if (isFull()) { cout<<"Stack is Overflown"<= 0; i--) { cout << i + 1 << ". " << arr[i]<> opt; switch (opt) { case 1: system("clear"); cout << "Enter the number to push to the stack" << endl; cin >> val; s1.push(val); cout << endl<< endl<< endl; break; case 2: system("clear"); cout << "Pop done!" << endl; cout<< s1.pop()<<" removed"<> pos; cout << s1.peek(pos) << " is at " << pos<< endl; cout << endl<< endl<< endl; break; case 6: system("clear"); cout << s1.count() <> pos; cout << "Enter the number " << endl; cin >> val; s1.change(val,pos) ; cout << endl<< endl<< endl; break; case 8: system("clear"); s1.display(); cout << endl<< endl<< endl; break; case 9: system("clear"); break; default: system("clear"); cout << "Please enter a valid number "< stack = new List(); int top; public Stack() { top = -1; } public void Push(int value) { stack.Add(value); top++; } public void Pop() { if (isEmpty()) { Console.WriteLine("Stack is empty!"); } int value = stack[top]; stack.RemoveAt(top); top--; Console.WriteLine($"The value {value} was removed of stack"); } public void Peek() { if (isEmpty()) { Console.WriteLine("Stack is empty!"); } Console.WriteLine($"The topmost element of stack is {stack[top]}"); } public bool isEmpty() { return top == -1; } } } ================================================ FILE: Data-Structures/Stack/StackUsingArray.go ================================================ package main import ( "fmt" ) type stack []int func (s stack) push(v int) stack { return append(s, v) } func (s stack) pop() (stack, int) { l := len(s) { return s[:l-1], s[l-1]} } func (s stack) size() int { return len(s) } func main(){ s := make(stack,0) s = s.push(101) s = s.push(203) s = s.push(399) s = s.push(501) s, p := s.pop() fmt.Println(p) fmt.Println( s.size()) } ================================================ FILE: Data-Structures/Stack/StackUsingArray.hs ================================================ module Stack where class Stack s where push :: a -> s a -> s a pop :: s a -> (Maybe a, s a) top :: s a -> Maybe a size :: s a -> Int isEmpty :: s a -> Bool empty :: s a newtype ListStack a = ListStack [a] deriving (Show) instance Stack ListStack where push x (ListStack st) = ListStack (x : st) pop (ListStack []) = (Nothing, empty) pop (ListStack (x:xs)) = (Just x, ListStack xs) top (ListStack []) = Nothing top (ListStack st) = Just (head st) size (ListStack st) = length st isEmpty (ListStack []) = True isEmpty _ = False empty = ListStack [] ================================================ FILE: Data-Structures/Stack/StackUsingArray.java ================================================ import java.util.Scanner; class Stack { int top; int maxsize = 10; int[] arr = new int[maxsize]; boolean isEmpty() { // If top is negative then stack is empty because stack was intialized with top=-1 return (top < 0); } Stack() { top = -1; } boolean push (Scanner sc) { if(top == maxsize-1) { // if top element index becomes equal to size of array -1 then it becomes overflow System.out.println("Overflow !!"); return false; } else { System.out.println("Enter Value"); int v = sc.nextInt(); top++; arr[top]=v; System.out.println("Item pushed"); return true; } } boolean pop () { if (top == -1) { // If top=-1 that means no element is present in the array System.out.println("Underflow !!"); return false; } else { top --; System.out.println("Element popped"); return true; } } void display () { System.out.println("Printing stack elements ....."); // Iterating over the array from top element to 0 index element because it is stack for(int i = top; i>=0;i--) { System.out.println(arr[i]); } } } public class Stack_Operations { public static void main(String[] args) { int ch=0; Scanner sc = new Scanner(System.in); Stack s = new Stack(); System.out.println("*********Stack using array*********\n"); while(ch != 4) { System.out.println("\nChose one from the below options...\n"); System.out.println("\n1.Push\n2.Pop\n3.Show\n4.Exit"); System.out.println("\n Enter your choice \n"); ch = sc.nextInt(); switch(ch) { case 1: { s.push(sc); break; } case 2: { s.pop(); break; } case 3: { s.display(); break; } case 4: { System.out.println("Exiting...."); System.exit(0); break; } default: { System.out.println("Please Enter valid choice "); } }; } } } ================================================ FILE: Data-Structures/Stack/StackUsingArray.js ================================================ class Stack { constructor() { this.stack = []; this.top = -1; } push(value) { this.top++; this.stack[this.top] = value; } pop() { if (this.top == -1) { return "Stack is empty"; } var ret_val = this.stack[this.top]; this.top--; return ret_val; } peek() { if (this.top == -1) { return "Stack is empty"; } var ret_val = this.stack[this.top]; return ret_val; } isEmpty() { return this.top == -1; } } stk = new Stack(); console.log(stk.isEmpty()); stk.push(1); stk.push(2); console.log(stk.peek()); console.log(stk.isEmpty()); stk.push(3); stk.push(4); console.log(stk.pop()); console.log(stk.pop()); console.log(stk.pop()); console.log(stk.pop()); console.log(stk.isEmpty()); ================================================ FILE: Data-Structures/Stack/StackUsingArray.php ================================================ stack = array(); //declare stack size $this->size = $size; } public function push($data) {//push element into stack if(count($this->stack) < $this->size) {//check if stack is overflow // array_unshift() prepends passed elements to the front of the array. array_unshift($this->stack, $data);//insert an element at the beginning } else { throw new RuntimeException("Stack overflow");//show error is stack overflow } } public function pop() {//pop element from stack if (empty($this->stack)) {//check if stack is empty throw new RuntimeException("Stack underflow");//throw error if empty } else { // array_shift() shifts the first value of the array off and returns it return array_shift($this->stack);//pop element } } } $stack = new Stack();//create obbject of class $stack->push(4);//add 4 to stack $stack->push(5);//add 5 to stack echo $stack->pop(); // Pop 5 and echo the element popped $stack->push(7);//add 7 to stack $stack->push(9);//add 9 to stack $stack->push(8);//add 8 to stack echo $stack->pop(); // Pop 8 and echo the element popped echo $stack->pop(); // Pop 9 and echo the element poppedv ?> ================================================ FILE: Data-Structures/Stack/StackUsingArray.rb ================================================ class DynamicStack def initialize @stack = [] end def is_empty? @stack.empty? end def push(value) @stack << value end def pop is_empty? ? nil : @stack.pop end def peek @stack.last end end class StaticStack # @param [Integer] capacity def initialize(capacity) @stack = Array.new(capacity) @top = -1 @capacity = capacity end def is_empty? @top == -1 end def push(value) raise "Stack full" if is_full? @top += 1 @stack[@top] = value end def pop return nil if is_empty? value = @stack[top] @top -= 1 value end def peek is_empty? ? nil : @stack[@top] end private def is_full? @top >= @capacity - 1 end end stack_kinds = [DynamicStack, StaticStack] params = [[], [4]] stack_kinds.zip(params).each do |klass, param| puts "Create new stack: #{klass}" stack = klass.new(*param) puts "Is stack empty? #{stack.is_empty?}" (1..5).each do |num| puts "Push to stack: #{num}" stack.push(num) end puts "Element at top is #{stack.peek}" loop do break if stack.is_empty? puts "Pop Element: #{stack.pop}" end end ================================================ FILE: Data-Structures/Stack/StackUsingArray.swift ================================================ import Foundation struct Stack { private var items: [T] = [] mutating func push(element: T) { items.append(element) } mutating func pop() -> T? { items.popLast() } func peek() -> T? { return items.last } var isEmpty: Bool { return items.isEmpty } } extension Stack: CustomStringConvertible { var description: String { return items.description } } var intStack = Stack() print(intStack.isEmpty) intStack.push(element: 1) intStack.push(element: 2) intStack.push(element: 3) print(intStack.description) print(intStack.isEmpty) intStack.pop() print(intStack.peek()) print(intStack.description) var stringStack = Stack() print(intStack.isEmpty) stringStack.push(element: "Hi") stringStack.push(element: "Person") print(intStack.isEmpty) print(stringStack.description) stringStack.pop() print(stringStack.peek()) print(stringStack.description) ================================================ FILE: Data-Structures/Stack/StackUsingLL.cpp ================================================ #include using namespace std; struct node { int value; node * prev; node(int x, node * pr){ value = x; prev = pr; } }; struct myStack { private: node * top; int cnt; public: myStack() { top = NULL; cnt = 0; } void push(int x) { node * el = new node(x, top); top = el; cnt++; } void pop() { if(!empty()) { int res = top->value; top = top->prev; cnt--; cout << res; } else { cout << "error"; } } void back() { if(!empty()) cout << top->value; else cout << "error"; } int size() { return cnt; } void clear() { top = NULL; cnt = 0; } bool empty() { return cnt == 0; } }; int main() { string q; int x; myStack st; do { cin >> q; if(q == "push"){ cin >> x; st.push(x); cout << "ok"; } if(q == "pop"){ st.pop(); } if(q == "back"){ st.back(); } if(q == "size"){ cout << st.size(); } if(q == "clear"){ st.clear(); cout << "ok"; } if(q == "exit"){ cout << "bye"; } cout << endl; } while(q != "exit"); return 0; } ================================================ FILE: Data-Structures/Stack/StackUsingLL.go ================================================ package main import ( "errors" "fmt" ) // Stack of String values type Stack []string func main() { var stack Stack stack.Push("First") stack.Push("Second") stack.Push("Third") for !stack.IsEmpty() { value, _ := stack.Peek() fmt.Printf("Peek - First item is: %s\n", value) value, _ = stack.Pop() fmt.Printf("Pop - popped item: %s\n", value) } } // IsEmpty returns true if there are no items in the Stack. func (s *Stack) IsEmpty() bool { return len(*s) == 0 } // Push appends a new value to the Stack. func (s *Stack) Push(value string) { *s = append(*s, value) } // Pop returns and removes the top value in the Stack. // Returns an error if trying to pop an empty Stack func (s *Stack) Pop() (string, error) { if s.IsEmpty() { return "", errors.New("stack is empty") } i := len(*s) - 1 value := (*s)[i] *s = (*s)[:i] return value, nil } // Peek returns first value in the Stack without removing // Returns an error if the Stack is empty func (s *Stack) Peek() (string, error) { if s.IsEmpty() { return "", errors.New("stack is empty") } i := len(*s) - 1 value := (*s)[i] return value, nil } ================================================ FILE: Data-Structures/Stack/StackUsingLL.java ================================================ import java.util.Scanner; public class StackUsingLL { Node head; class Node { int val; Node next; int min; public Node(int val, int min) { this.val = val; this.min = min; next = null; } } public void push(int x) { // O(1) if(head == null){ head = new Node(x, x); } else { Node node = new Node(x, Math.min(head.min,x)); node.next = head; head = node; } } public void pop() { if(head!=null){ head = head.next; } } public int peek() { if(head!=null) { return head.val; } return -1; } public int getMin() { if(head!=null){ return head.min; } return -1; } public void display() { // check for stack underflow if (head == null) { System.out.printf("\nStack Underflow"); } else { Node temp = head; while (temp != null) { System.out.print(temp.val+" "); temp = temp.next; } System.out.println(""); } } public static void operation(StackUsingLL stack) { System.out.println("Enter the operation"); System.out.println("1. "+"push"); System.out.println("2. pop"); System.out.println("3. peek"); System.out.println("4. display"); Scanner sc = new Scanner(System.in); int input = sc.nextInt(); switch(input) { // push into stack case 1: System.out.println("Enter the number of elements to be pushed"); int number = sc.nextInt(); System.out.println("Enter the elements"); while(number-->0) { int element = sc.nextInt(); stack.push(element); } stack.operation(stack); // Delete top element of Stack case 2: stack.pop(); stack.operation(stack); // print Top element of Stack case 3: System.out.printf("\nTop element is %d\n", stack.peek()); stack.operation(stack); //print Stack elements case 4: stack.display(); stack.operation(stack); case 5: System.out.println("EXIT"); System.exit(0); default: System.exit(0); } } public static void main(String[] args) { //object of class StackUsingLL stack = new StackUsingLL(); stack.operation(stack); } } ================================================ FILE: Data-Structures/Stack/StackUsingLL.js ================================================ class Node { constructor(data) { this.data = data; this.next = null; } } class Stack { constructor() { this.head = null; } isEmpty() { return this.head === null; } push(data) { if (this.head) { const newNode = new Node(data); newNode.next = this.head; this.head = newNode; } else { this.head = new Node(data); } } pop() { if (this.head) { const data = this.head.data; this.head = this.head.next; return data; } else { throw "Stack underflow"; } } peek() { if (this.head) { return this.head.data; } else { throw "Stack underflow"; } } } const stack = new Stack(); console.log(stack.isEmpty()); stack.push(5); stack.push(9); stack.push(6); console.log(stack.pop()); console.log(stack.peek()); stack.push(5); console.log(stack.isEmpty()); //OUTPUT(TEST CASE) //true //6 //9 //false ================================================ FILE: Data-Structures/Stack/StackUsingLL.py ================================================ class Node: def __init__(self,data): self.data = data self.next = None class Stack: def __init__(self): self.head = None def isempty(self): if self.head == None: return True else: return False def push(self,data): if self.head == None: self.head=Node(data) else: new_node = Node(data) new_node.next = self.head self.head = new_node def pop(self): if self.isempty(): print("Stack Underflow!") return None else: pop_node = self.head self.head = self.head.next pop_node.next = None return pop_node.data def peek(self): if self.isempty(): return None else: return self.head.data def display(self): iter_node = self.head if self.isempty(): print("Stack Underflow!") else: while(iter_node != None): print(iter_node.data,"->",end = " ") iter_node = iter_node.next return # Driver code MyStack = Stack() MyStack.push(1) MyStack.push(2) MyStack.push(3) MyStack.push(4) # Display stack elements MyStack.display() # Print top element of stack print("\nStack Top: ",MyStack.peek()) # Delete top elements of stack MyStack.pop() MyStack.pop() # Display stack elements MyStack.display() print("\nStack Top: ", MyStack.peek()) # Output: # 4 -> 3 -> 2 -> 1 -> # Stack Top: 4 # 2 -> 1 -> # Stack Top: 2 ================================================ FILE: Data-Structures/Stack/stackUsingLinkedList.c ================================================ #include #include struct node { int val; struct node *next; }; struct node *head; void push() { int val; struct node *ptr = (struct node *)malloc(sizeof(struct node)); if (ptr == NULL) printf("not able to push the element"); else { printf("Enter the value"); scanf("%d", &val); if (head == NULL) { ptr->val = val; ptr->next = NULL; head = ptr; } else { ptr->val = val; ptr->next = head; head = ptr; } printf("Item pushed"); } } void pop() { int item; struct node *ptr; if (head == NULL) printf("Underflow"); else { item = head->val; ptr = head; head = head->next; free(ptr); printf("Item popped"); } } void display() { int i; struct node *ptr; ptr = head; if (ptr == NULL) printf("Stack is empty\n"); else { printf("Printing Stack elements \n"); while (ptr != NULL) { printf("%d\n", ptr->val); ptr = ptr->next; } } } int main() { int choice = 0; while (choice != 4) { printf("\n\nChose one from the below options...\n"); printf("\n1.Push\n2.Pop\n3.Show\n4.Exit"); printf("\n Enter your choice \n"); scanf("%d", &choice); switch (choice) { case 1: { push(); break; } case 2: { pop(); break; } case 3: { display(); break; } case 4: { printf("Exiting...."); break; } default: printf("Please Enter valid choice "); }; } } ================================================ FILE: Data-Structures/Stack/stackusingLL.c ================================================ #include #include struct node{ int data; struct node *next; }; struct stack{ int top; struct node *list;//head of list }; struct node *newNode(){ struct node *newnode=(struct node*)malloc(sizeof(struct node)); printf("\nEnter the number to be inserted\n"); scanf("%d",&newnode->data); newnode->next=NULL; return newnode; } struct stack *create_stack(){ struct stack *st=(struct stack*)malloc(sizeof(struct stack)); st->list=NULL; st->top=-1; return st; } void push(struct node **head){ struct node *n=newNode(); if(*head==NULL){ *head=n; } else{ struct node *p=*head; n->next=p; *head=n; } } void pop(struct node **head){ if(*head==NULL){ printf("\nUNDERFLOW\n"); } else{ struct node *temp=*head; *head=temp->next; printf("\nDeleted %d\n",temp->data); free(temp); } } void top_element(struct node *head){ printf("\nTop element is %d\n",head->data); } void print_stack(struct node *head){ printf("\n"); struct node *p=head; while(p!=NULL){ printf("%d ",p->data); p=p->next; } printf("\n"); } int main(){ struct stack *st=create_stack(); char ch; printf("a->push\nd->pop\np->find top element\nk->print stack\nq->quit\n"); do{ printf("\nEnter a character from the given menu to perform the operations on stack\n"); ch=getche(); switch(ch){ case 'a': ; push(&st->list); break; case 'd': ; pop(&st->list); break; case 'p': ; top_element(st->list); break; case 'q': ; break; case 'k': ; print_stack(st->list); break; default: printf("\nIllegal Character entered\n"); break; } }while(ch!='q'); } ================================================ FILE: Data-Structures/Tree/23-Tree/23Tree.cpp ================================================ #include #include #define INT_MAX 2147483647 using namespace std; struct TreeNode{ //stores data - represents left, right, middle int keys[3]; // 4 pointers which refer to child, also stores parent node pointer struct TreeNode* p1, *p2, *p3, *p4, *parent; //maintains numbers of keys in keys array int keyCount; }; TreeNode* root = NULL; //prints inorder traversal of 2-3 tree void printInorder(TreeNode* root){ if(!root) return; printInorder(root->p1); cout<keys[0]<<" "; printInorder(root->p2); if(root->keyCount==2) cout<keys[1]<<" "; printInorder(root->p3); } //prints preorder traversal of 2-3 tree void printPreorder(TreeNode* root){ if(!root) return; cout<keys[0]<<" "; printPreorder(root->p1); if(root->keyCount==2) cout<keys[1]<<" "; printPreorder(root->p2); printPreorder(root->p3); } //prints postorder traversal of 2-3 tree void printPostorder(TreeNode* root){ if(!root) return; printPostorder(root->p1); printPostorder(root->p2); printPostorder(root->p3); if(root->keyCount==2) cout<keys[1]<<" "; cout<keys[0]<<" "; } //creates and initializes a new node TreeNode* newNode(int key){ TreeNode* node = new TreeNode; node->keys[0] = key; node->keys[1] = node->keys[2] = INT_MAX; node->p1 = node->p2 = node->p3 = node->p4 = node->parent = NULL; node->keyCount = 1; return node; } //searches the 2-3 tree and returns the node containing the key, returns NUlL when not found TreeNode* search(TreeNode* root, int key){ if(!root) return NULL; if(keykeys[0]) return search(root->p1, key); if(key>root->keys[0] && key < root->keys[1]) return search(root->p2, key); if(key > root->keys[1]) return search(root->p3, key); return root; } // checks if node is in overflow condition bool isOverflow(TreeNode* node){ return node && node->keyCount == 3; } // fixes the overflow condition, splits the overflowing node and shifts its middle to the parent void fixOverflow(TreeNode *node) { cout<<"Fix Overflow Start\n"; while (isOverflow(node)) { int median = node->keys[1]; TreeNode *temp = newNode(node->keys[2]); temp->p2 = node->p4; temp->p1 = node->p3; if (temp->p2) temp->p2->parent = temp; if (temp->p1) temp->p1->parent = temp; node->keys[1] = node->keys[2] = INT_MAX; node->p3 = node->p4 = NULL; node->keyCount = 1; TreeNode *p = node->parent; if (!p) { root = newNode(median); node->parent = temp->parent = root; root->p2 = temp; root->p1 = node; break; } else { temp->parent = p; if (node == p->p1) { p->keys[2] = p->keys[1]; p->keys[1] = p->keys[0]; p->keys[0] = median; p->keyCount++; p->p4 = p->p3; p->p3 = p->p2; p->p2 = temp; } else if (node == p->p2) { p->keys[2] = p->keys[1]; p->keys[1] = median; p->keyCount++; p->p4 = p->p3; p->p3 = temp; } else { p->keys[2] = median; p->keyCount++; p->p4 = temp; } node = p; } } cout<<"Fix Overflow End\n"; } // utility function to insert in a 2-3 tree, in case the overflow condition occur, fixOverflow is called void insert(int key) { cout<<"Insert Start\n"; TreeNode *node = NULL; TreeNode *temp = root; while(temp){ node = temp; if (key < temp->keys[0]) temp = temp->p1; else if (temp->keyCount == 1) temp = temp->p2; else temp = temp->p3; } if (!node){ cout<<"ok\n"; root = newNode(key); } else { if (key < node->keys[0]){ node->keys[2] = node->keys[1]; node->keys[1] = node->keys[0]; node->keys[0] = key; } else if (key > node->keys[0] && key < node->keys[1]){ node->keys[2] = node->keys[1]; node->keys[1] = key; } else node->keys[2] = key; node->keyCount++; if (isOverflow(node)) fixOverflow(node); } cout<<"Insert End\n"; } // checks underflow condition bool isUnderflow(TreeNode* node){ return node && node->keyCount<1; } // checks if a node can donate one of its keys bool canDonate(TreeNode* node){ return node && node->keyCount>1; } bool isEmpty(TreeNode* node){ return node->keyCount==0; } bool isRoot(TreeNode* node){ return node == root; } // fixes the underflow condition, redistribution and merging operations are done to overcome underflow void fixUnderflow(TreeNode *node) { while (isUnderflow(node)){ TreeNode *p = node->parent; TreeNode *x = NULL; TreeNode *z = NULL; if (node == p->p1){ z = p->p2; } else if (node == p->p2) { x = p->p1; z = p->p3; } else { x = p->p2; } if (canDonate(z)) { if(node == p->p1) { node->keys[0] = p->keys[0]; p->keys[0] = z->keys[0]; } else { node->keys[0] = p->keys[1]; p->keys[1] = z->keys[0]; } node->p2 = z->p1; if (node->p2) node->p2->parent = node; node->keyCount++; z->keys[0] = z->keys[1]; z->keys[1] = INT_MAX; z->p1 = z->p2; z->p2 = z->p3; z->p3 = NULL; z->keyCount--; } else if (canDonate(x)) { if(x == p->p1) { node->keys[0] = p->keys[0]; p->keys[0] = x->keys[1]; } else { node->keys[0] = p->keys[1]; p->keys[1] = x->keys[1]; } node->p1 = x->p3; if (node->p1) node->p1->parent = node; node->keyCount++; x->keys[1] = INT_MAX; x->p3 = NULL; x->keyCount--; } else { if (z){ if (node == p->p1) node->keys[0] = p->keys[0]; else node->keys[0] = p->keys[1]; node->keys[1] = z->keys[0]; node->p2 = z->p1; node->p3 = z->p2; if (node->p2) node->p2->parent = node; if (node->p3) node->p3->parent = node; node->keyCount += 2; if (node == p->p1) { p->p2 = p->p3; p->keys[0] = p->keys[1]; } p->p3 = NULL; p->keys[1] = INT_MAX; p->keyCount--; if (isEmpty(p) && isRoot(p)) { free(p); node->parent = p = NULL; root = node; } free(z); } else { if (x == p->p1) x->keys[1] = p->keys[0]; else x->keys[1] = p->keys[1]; x->p3 = node->p1; if (x->p3) x->p3->parent = x; x->keyCount++; if (x == p->p1) { p->p2 = p->p3; p->keys[0] = p->keys[1]; } p->p3 = NULL; p->keys[1] = INT_MAX; p->keyCount--; if (isEmpty(p) && isRoot(p)) { free(p); x->parent = p = NULL; root = x; } free(node); } } node = p; } } // gets the inorder successor to the given node TreeNode* getMin(TreeNode* root){ if(root->p1) getMin(root->p1); return root; } TreeNode* getMax(TreeNode* root){ if(root->p3) getMax(root->p3); if(root->p2) getMax(root->p2); return root; } bool isLeaf(TreeNode* node){ return !node->p1 && !node->p2; } // delete helper function, performs simple deletion and checks if there is underflow or not, if yes, then calls, fixUnderflow void deleteNode(int key) { TreeNode *node = search(root, key); if (isLeaf(node)) { if (key == node->keys[0]) { node->keys[0] = node->keys[1]; node->keys[1] = INT_MAX; } else node->keys[1] = INT_MAX; node->keyCount--; if (isUnderflow(node)) { if (isRoot(node)) { free(root); root = NULL; } else fixUnderflow(node); } } else { TreeNode *y = NULL; if (key == node->keys[0]) y = getMin(node->p2); else y = getMin(node->p3); if (key == node->keys[0]) node->keys[0] = y->keys[0]; else node->keys[1] = y->keys[0]; y->keys[0] = y->keys[1]; y->keys[1] = INT_MAX; y->keyCount--; if (isUnderflow(y)) fixUnderflow(y); } } int main(){ while(1){ cout<<"++++++++++++++++++++++++++++++++++\n"; cout<<"Select an Operation\n"; cout<<" 1. Insert\n 2. Delete \n 3. Search \n 4. Inorder Traverse\n 5. Preorder Traverse\n 6. Postorder Traverse\n 7. Exit \n"; cout<<"++++++++++++++++++++++++++++++++++\n"; int selection; cin>>selection; if(selection == 1){ cout<<"Enter Number to Insert\n"; int key; cin>>key; insert(key); } else if(selection==2){ cout<<"Enter Number to Delete\n"; int num; cin>>num; deleteNode(num); } else if(selection==3){ cout<<"Enter Number to Search\n"; int num; cin>>num; TreeNode* temp = search(root,num); if(temp) cout<<"Found\n"; else cout<<"Not Found\n"; } else if(selection==4){ printInorder(root); cout<<"\n"; } else if(selection==5){ printPreorder(root); cout<<"\n"; } else if(selection==6){ printPostorder(root); cout<<"\n"; } else if(selection==7){ break; } } } ================================================ FILE: Data-Structures/Tree/23-Tree/23Tree.py ================================================ class Node(object): path = [] def __init__(self, data, parent=None): self.childs = {} self.data = [data] self.parent = parent def insert(self, value): Node.path = [] insert_node = self.search(value) insert_node.add(value) def split(self): if self.parent is None and self.childs: branch = Node.path.pop() newNodeLeft = Node(self.data.pop(0), self) newNodeRight = Node(self.data.pop(1), self) if branch == "left": newNodeLeft.childs["left"] = self.childs["left"] newNodeLeft.childs["right"] = self.childs["overflow"] newNodeRight.childs["left"] = self.childs["mid"] newNodeRight.childs["right"] = self.childs["right"] elif branch == "mid": newNodeLeft.childs["left"] = self.childs["left"] newNodeLeft.childs["right"] = self.childs["mid"] newNodeRight.childs["left"] = self.childs["overflow"] newNodeRight.childs["right"] = self.childs["right"] elif branch == "right": newNodeLeft.childs["left"] = self.childs["left"] newNodeLeft.childs["right"] = self.childs["mid"] newNodeRight.childs["left"] = self.childs["right"] newNodeRight.childs["right"] = self.childs["overflow"] newNodeLeft.childs["left"].parent = newNodeLeft newNodeLeft.childs["right"].parent = newNodeLeft newNodeRight.childs["left"].parent = newNodeRight newNodeRight.childs["right"].parent = newNodeRight self.childs["left"] = newNodeLeft self.childs["right"] = newNodeRight del self.childs["mid"] elif self.parent is not None and self.childs: branch = Node.path.pop() newNode = Node(self.data.pop(), self.parent) self.parent.childs["overflow"] = newNode if branch == "left": newNode.childs["left"] = self.childs["mid"] newNode.childs["right"] = self.childs["right"] self.childs["right"] = self.childs["overflow"] elif branch == "mid": newNode.childs["left"] = self.childs["overflow"] newNode.childs["right"] = self.childs["right"] self.childs["right"] = self.childs["mid"] elif branch == "right": newNode.childs["left"] = self.childs["right"] newNode.childs["right"] = self.childs["overflow"] self.childs["right"] = self.childs["mid"] newNode.childs["left"].parent = newNode newNode.childs["right"].parent = newNode del self.childs["mid"] elif self.parent is None and not self.childs: self.childs["left"] = Node(self.data.pop(0), self) self.childs["right"] = Node(self.data.pop(1), self) elif self.parent is not None and not self.childs: self.parent.childs["overflow"] = Node(self.data.pop(), self.parent) def add(self, value): if value not in self.data: self.data.append(value) self.data.sort() if len(self.data) == 3: self.split() if self.parent is not None: self.parent.add(self.data.pop()) else: if "overflow" in self.childs: branch = Node.path.pop() if branch == "left": self.childs["mid"] = self.childs["overflow"] elif branch == "right": self.childs["mid"] = self.childs["right"] self.childs["right"] = self.childs["overflow"] del self.childs["overflow"] def search(self, value): if self.childs: boundLeft = min(self.data) boundRight = max(self.data) if value < boundLeft: Node.path.append("left") return self.childs["left"].search(value) elif value > boundRight: Node.path.append("right") return self.childs["right"].search(value) else: Node.path.append("mid") return self.childs["mid"].search(value) else: return self def element(self, value): if value in self.data: return True elif self.childs: boundLeft = min(self.data) boundRight = max(self.data) if value < boundLeft: return self.childs["left"].element(value) elif value > boundRight: return self.childs["right"].element(value) else: return self.childs["mid"].element(value) else: return False ================================================ FILE: Data-Structures/Tree/AVL-Tree/AVL_Tree.java ================================================ /* * Java Program to Implement AVL Tree */ import java.util.Scanner; /* Class AVLNode */ class AVLNode { AVLNode left, right; int data; int height; /* Constructor */ public AVLNode() { left = null; right = null; data = 0; height = 0; } /* Constructor */ public AVLNode(int n) { left = null; right = null; data = n; height = 0; } } /* Class AVLTree */ class AVLTree { private AVLNode root; /* Constructor */ public AVLTree() { root = null; } /* Function to check if tree is empty */ public boolean isEmpty() { return root == null; } /* Make the tree logically empty */ public void makeEmpty() { root = null; } /* Function to insert data */ public void insert(int data) { root = insert(data, root); } /* Function to get height of node */ private int height(AVLNode t ) { return t == null ? -1 : t.height; } /* Function to max of left/right node */ private int max(int lhs, int rhs) { return lhs > rhs ? lhs : rhs; } /* Function to insert data recursively */ private AVLNode insert(int x, AVLNode t) { if (t == null) t = new AVLNode(x); else if (x < t.data) { t.left = insert( x, t.left ); if( height( t.left ) - height( t.right ) == 2 ) if( x < t.left.data ) t = rotateWithLeftChild( t ); else t = doubleWithLeftChild( t ); } else if( x > t.data ) { t.right = insert( x, t.right ); if( height( t.right ) - height( t.left ) == 2 ) if( x > t.right.data) t = rotateWithRightChild( t ); else t = doubleWithRightChild( t ); } else ; // Duplicate; do nothing t.height = max( height( t.left ), height( t.right ) ) + 1; return t; } /* Rotate binary tree node with left child */ private AVLNode rotateWithLeftChild(AVLNode k2) { AVLNode k1 = k2.left; k2.left = k1.right; k1.right = k2; k2.height = max( height( k2.left ), height( k2.right ) ) + 1; k1.height = max( height( k1.left ), k2.height ) + 1; return k1; } /* Rotate binary tree node with right child */ private AVLNode rotateWithRightChild(AVLNode k1) { AVLNode k2 = k1.right; k1.right = k2.left; k2.left = k1; k1.height = max( height( k1.left ), height( k1.right ) ) + 1; k2.height = max( height( k2.right ), k1.height ) + 1; return k2; } /** * Double rotate binary tree node: first left child * with its right child; then node k3 with new left child */ private AVLNode doubleWithLeftChild(AVLNode k3) { k3.left = rotateWithRightChild( k3.left ); return rotateWithLeftChild( k3 ); } /** * Double rotate binary tree node: first right child * with its left child; then node k1 with new right child */ private AVLNode doubleWithRightChild(AVLNode k1) { k1.right = rotateWithLeftChild( k1.right ); return rotateWithRightChild( k1 ); } /* Functions to count number of nodes */ public int countNodes() { return countNodes(root); } private int countNodes(AVLNode r) { if (r == null) return 0; else { int l = 1; l += countNodes(r.left); l += countNodes(r.right); return l; } } /* Functions to search for an element */ public boolean search(int val) { return search(root, val); } private boolean search(AVLNode r, int val) { boolean found = false; while ((r != null) && !found) { int rval = r.data; if (val < rval) r = r.left; else if (val > rval) r = r.right; else { found = true; break; } found = search(r, val); } return found; } /* Function for inorder traversal */ public void inorder() { inorder(root); } private void inorder(AVLNode r) { if (r != null) { inorder(r.left); System.out.print(r.data +" "); inorder(r.right); } } /* Function for preorder traversal */ public void preorder() { preorder(root); } private void preorder(AVLNode r) { if (r != null) { System.out.print(r.data +" "); preorder(r.left); preorder(r.right); } } /* Function for postorder traversal */ public void postorder() { postorder(root); } private void postorder(AVLNode r) { if (r != null) { postorder(r.left); postorder(r.right); System.out.print(r.data +" "); } } } /* Class AVL Tree Test */ public class AVLTreeTest { public static void main(String[] args) { Scanner scan = new Scanner(System.in); /* Creating object of AVLTree */ AVLTree avlt = new AVLTree(); System.out.println("AVLTree Tree Test\n"); char ch; /* Perform tree operations */ do { System.out.println("\nAVLTree Operations\n"); System.out.println("1. insert "); System.out.println("2. search"); System.out.println("3. count nodes"); System.out.println("4. check empty"); System.out.println("5. clear tree"); int choice = scan.nextInt(); switch (choice) { case 1 : System.out.println("Enter integer element to insert"); avlt.insert( scan.nextInt() ); break; case 2 : System.out.println("Enter integer element to search"); System.out.println("Search result : "+ avlt.search( scan.nextInt() )); break; case 3 : System.out.println("Nodes = "+ avlt.countNodes()); break; case 4 : System.out.println("Empty status = "+ avlt.isEmpty()); break; case 5 : System.out.println("\nTree Cleared"); avlt.makeEmpty(); break; default : System.out.println("Wrong Entry \n "); break; } /* Display tree */ System.out.print("\nPost order : "); avlt.postorder(); System.out.print("\nPre order : "); avlt.preorder(); System.out.print("\nIn order : "); avlt.inorder(); System.out.println("\nDo you want to continue (Type y or n) \n"); ch = scan.next().charAt(0); } while (ch == 'Y'|| ch == 'y'); } } ================================================ FILE: Data-Structures/Tree/AVL-Tree/AVL_Tree.py ================================================ import sys class TreeNode(object): def __init__(self, key): self.key = key self.left = None self.right = None self.height = 1 class AVLTree(object): def insert_node(self, root, key): # Find the correct location and insert the node if not root: return TreeNode(key) elif key < root.key: root.left = self.insert_node(root.left, key) else: root.right = self.insert_node(root.right, key) root.height = 1 + max(self.getHeight(root.left), self.getHeight(root.right)) balanceFactor = self.getBalance(root) if balanceFactor > 1: if key < root.left.key: return self.rightRotate(root) else: root.left = self.leftRotate(root.left) return self.rightRotate(root) if balanceFactor < -1: if key > root.right.key: return self.leftRotate(root) else: root.right = self.rightRotate(root.right) return self.leftRotate(root) return root def delete_node(self, root, key): if not root: return root elif key < root.key: root.left = self.delete_node(root.left, key) elif key > root.key: root.right = self.delete_node(root.right, key) else: if root.left is None: temp = root.right root = None return temp elif root.right is None: temp = root.left root = None return temp temp = self.getMinValueNode(root.right) root.key = temp.key root.right = self.delete_node(root.right, temp.key) if root is None: return root root.height = 1 + max(self.getHeight(root.left), self.getHeight(root.right)) balanceFactor = self.getBalance(root) if balanceFactor > 1: if self.getBalance(root.left) >= 0: return self.rightRotate(root) else: root.left = self.leftRotate(root.left) return self.rightRotate(root) if balanceFactor < -1: if self.getBalance(root.right) <= 0: return self.leftRotate(root) else: root.right = self.rightRotate(root.right) return self.leftRotate(root) return root def leftRotate(self, z): y = z.right T2 = y.left y.left = z z.right = T2 z.height = 1 + max(self.getHeight(z.left), self.getHeight(z.right)) y.height = 1 + max(self.getHeight(y.left), self.getHeight(y.right)) return y def rightRotate(self, z): y = z.left T3 = y.right y.right = z z.left = T3 z.height = 1 + max(self.getHeight(z.left), self.getHeight(z.right)) y.height = 1 + max(self.getHeight(y.left), self.getHeight(y.right)) return y def getHeight(self, root): if not root: return 0 return root.height def getBalance(self, root): if not root: return 0 return self.getHeight(root.left) - self.getHeight(root.right) def getMinValueNode(self, root): if root is None or root.left is None: return root return self.getMinValueNode(root.left) def preOrder(self, root): if not root: return print("{0} ".format(root.key), end="") self.preOrder(root.left) self.preOrder(root.right) def printHelper(self, currPtr, indent, last): if currPtr != None: sys.stdout.write(indent) if last: sys.stdout.write("R----") indent += " " else: sys.stdout.write("L----") indent += "| " print(currPtr.key) self.printHelper(currPtr.left, indent, False) self.printHelper(currPtr.right, indent, True) myTree = AVLTree() root = None nums = [33, 13, 52, 9, 21, 61, 8, 11] for num in nums: root = myTree.insert_node(root, num) myTree.printHelper(root, "", True) key = 13 root = myTree.delete_node(root, key) print("After Deletion: ") myTree.printHelper(root, "", True) ================================================ FILE: Data-Structures/Tree/AVL-Tree/AVLtree.c ================================================ // AVL tree implementation in C #include #include // Create Node struct Node { int key; struct Node *left; struct Node *right; int height; }; int max(int a, int b); // Calculate height int height(struct Node *N) { if (N == NULL) return 0; return N->height; } int max(int a, int b) { return (a > b) ? a : b; } // Create a node struct Node *newNode(int key) { struct Node *node = (struct Node *) malloc(sizeof(struct Node)); node->key = key; node->left = NULL; node->right = NULL; node->height = 1; return (node); } // Right rotate struct Node *rightRotate(struct Node *y) { struct Node *x = y->left; struct Node *T2 = x->right; x->right = y; y->left = T2; y->height = max(height(y->left), height(y->right)) + 1; x->height = max(height(x->left), height(x->right)) + 1; return x; } // Left rotate struct Node *leftRotate(struct Node *x) { struct Node *y = x->right; struct Node *T2 = y->left; y->left = x; x->right = T2; x->height = max(height(x->left), height(x->right)) + 1; y->height = max(height(y->left), height(y->right)) + 1; return y; } // Get the balance factor int getBalance(struct Node *N) { if (N == NULL) return 0; return height(N->left) - height(N->right); } // Insert node struct Node *insertNode(struct Node *node, int key) { // Find the correct position to insertNode the node and insertNode it if (node == NULL) return (newNode(key)); if (key < node->key) node->left = insertNode(node->left, key); else if (key > node->key) node->right = insertNode(node->right, key); else return node; // Update the balance factor of each node and // Balance the tree node->height = 1 + max(height(node->left), height(node->right)); int balance = getBalance(node); if (balance > 1 && key < node->left->key) return rightRotate(node); if (balance < -1 && key > node->right->key) return leftRotate(node); if (balance > 1 && key > node->left->key) { node->left = leftRotate(node->left); return rightRotate(node); } if (balance < -1 && key < node->right->key) { node->right = rightRotate(node->right); return leftRotate(node); } return node; } struct Node *minValueNode(struct Node *node) { struct Node *current = node; while (current->left != NULL) current = current->left; return current; } // Delete a nodes struct Node *deleteNode(struct Node *root, int key) { // Find the node and delete it if (root == NULL) return root; if (key < root->key) root->left = deleteNode(root->left, key); else if (key > root->key) root->right = deleteNode(root->right, key); else { if ((root->left == NULL) || (root->right == NULL)) { struct Node *temp = root->left ? root->left : root->right; if (temp == NULL) { temp = root; root = NULL; } else *root = *temp; free(temp); } else { struct Node *temp = minValueNode(root->right); root->key = temp->key; root->right = deleteNode(root->right, temp->key); } } if (root == NULL) return root; // Update the balance factor of each node and // balance the tree root->height = 1 + max(height(root->left), height(root->right)); int balance = getBalance(root); if (balance > 1 && getBalance(root->left) >= 0) return rightRotate(root); if (balance > 1 && getBalance(root->left) < 0) { root->left = leftRotate(root->left); return rightRotate(root); } if (balance < -1 && getBalance(root->right) <= 0) return leftRotate(root); if (balance < -1 && getBalance(root->right) > 0) { root->right = rightRotate(root->right); return leftRotate(root); } return root; } // Print the Preorder tree void printPreOrder(struct Node *root) { if (root != NULL) { printf("%d ", root->key); printPreOrder(root->left); printPreOrder(root->right); } } // Print the Inorder tree void InOrder(struct Node *root) { if (root != NULL) { InOrder(root->left); printf("%d ", root->key); InOrder(root->right); } } // Print the Postorder tree void PostOrder(struct Node *root) { if (root != NULL) { PostOrder(root->left); PostOrder(root->right); printf("%d ", root->key); } } int main() { struct Node *root = NULL; root = insertNode(root, 2); root = insertNode(root, 1); root = insertNode(root, 7); root = insertNode(root, 4); root = insertNode(root, 5); root = insertNode(root, 3); root = insertNode(root, 8); printPreOrder(root); root = deleteNode(root, 3); printf("\nAfter deletion: "); printf("\nPreorder: "); printPreOrder(root); printf("\nInorder: "); InOrder(root); printf("\nPostorder: "); PostOrder(root); return 0; } /* Output: 4 2 1 3 7 5 8 After deletion: Preorder: 4 2 1 7 5 8 Inorder: 1 2 4 5 7 8 Postorder: 1 2 5 8 7 4 */ ================================================ FILE: Data-Structures/Tree/AVL-Tree/README.md ================================================ ## This folder is empty. ================================================ FILE: Data-Structures/Tree/AVL-Tree/avl_tree.py ================================================ ''' Python Code for AVL Tree @ Author - Sandip Dutta ------------------------------------------------------------------------ $ AVL Tree: AVL Tree is a special kind of Binary Search Tree. Each node in the tree, stores a variable called 'BalanceFactor'. Balance Factor is equal to the difference between the height of the left subtree and the right subtree of the node. BalanceFactor = (height(left_Subtree) - height(right_Subtree)) In AVL Trees, it is always maintained that the Balance Factor of each node is {-1, 0, 1}. This causes the tree to be balanced, that is not skewed in one direction or the other. $ Example of AVL Tree: 10 / \ 8 12 / / \ 2 11 15 If we calculate the balance factor for each node, it comes out to be {0, 1, -1}. $ Usefulness: AVL trees have common operations such as min, max, search all in O(log(n)) time complexity. $ How to maintain balance AVL achieve balance by using rotations. For more details, see Wikipedia. ''' class Node(object): '''Implement node of a tree.''' def __init__( self, value, left = None, right = None, height = 1): '''Implements the node of the tree. @ Args: > value - (int) Value of the node > left - (int, def - None) left node > right - (int, def - None) right node > height - (int, def - 1) height of the tree upto the node. Since we need to check height multiple times we store it ''' self.value = value self.left = left self.right = right self.height = height class AVL_Tree(object): '''Implements AVL Tree.''' # Helper/utility functions def getHeight(self, node): '''Returns the height of the node of AVL Tree. @ Args: > node - (Node) node of a tree. If empty tree, is None ''' if not node: return 0 return node.height def getBalanceFactor(self, node): '''Returns the balance factor of the AVL Tree. @ Args: > node - (Node) node of a tree. If empty tree, is None ''' if not node: return 0 return self.getHeight(node.left) - self.getHeight(node.right) def leftRotate(self, node): ''' Performs left rotation on subtree of a node rooted at @argument: node. @ Args: > node - (Node) node of AVL Tree. Empty == None @ Return: > finalNode - (Node) final Node after left rotation ''' finalNode = node.right # final parent node after rotation tempNode = finalNode.left # Rotate finalNode.left = node node.right = tempNode # update heights node.height = 1 + max( self.getHeight(node.left), self.getHeight(node.right) ) finalNode.height = 1 + max( self.getHeight(finalNode.left), self.getHeight(finalNode.right) ) # return finalNode so that parent of 'node' knows # what to point to return finalNode def rightRotate(self, node): ''' Performs right rotation on subtree of a node rooted at @argument: node. @ Args: > node - (Node) node of AVL Tree. Empty == None @ Return: > finalNode - (Node) final Node after right rotation ''' finalNode = node.left tempNode = finalNode.right # Rotate right finalNode.left = node node.right = tempNode # Update heights node.height = 1 + max( self.getHeight(node.left), self.getHeight(node.right) ) finalNode.height = 1 + max( self.getHeight(finalNode.left), self.getHeight(finalNode.right) ) # return finalNode so that parent of 'node' what to # point to return finalNode def insertNode(self, rootNode, value): '''Inserts node in AVL tree as per standard BST rules and performs necessary rotations to balance the tree. @ Args: > rootNode = (Node) The root node of the tree, Empty tree === None > value = (int) The value to be inserted @ Return: > rootNode = (Node) The root node of the tree with value in it's final position ''' if not rootNode: return Node(value) # Empty tree # Insert as per BST rules if value < rootNode.value: rootNode.left = self.insertNode(rootNode.left, value) else: rootNode.right = self.insertNode(rootNode.right, value) # Get balance factor balanceFactor = self.getBalanceFactor(rootNode) # Perform rotations after insertion if balanceFactor > 1: # if below condition is true, we know # as per BST rules, value is in left subtree # of left subtree of rootNode. # As insertion of value caused change in balance # We will adjust that subtree so that balance is # restored. if value < rootNode.left.value: return self.rightRotate(rootNode) else: # Left skewed tree after insertion # but value is greater than value of rootNode # Thus, value is the left node of the tree # After rotation, update parent node with # new left node. rootNode.left = self.leftRotate(root.left) return self.rightRotate(root) if balanceFactor < -1: if value > rootNode.right.value: # Adjust right sub tree return self.leftRotate(rootNode) else: # Update parent node rootNode.right = self.rightRotate(root.right) return self.leftRotate(rootNode) return rootNode ================================================ FILE: Data-Structures/Tree/Binary-Indexed-Tree/Binary-Indexed-Tree.c ================================================ /** Binary Index Tree or Fenwick Tree It is a data structure that can efficiently update elements and calculate prefix sums in a table of numbers. There are two types of query that the user can input in this program 1. Get sum upto ith position Format - 1 i Ex - 1 5 2. Update the element at ith position to k Format - 2 i k Ex - 1 5 2 SAMPLE INPUT :- 12 2 1 1 3 2 3 4 5 6 7 8 9 3 1 5 2 2 6 1 5 EXPECTED OUTPUT :- 9 14 */ #include //Create BIT in O(n) time void createBIT(int ftree[], int n) { for(int i=1; i<=n; i++) { int j = i + (i & (-1*i)); if(j <= n) ftree[j] += ftree[i]; } } //Update the value in the required nodes in Tree in O(log n) void update(int ftree[], int n, int val, int i) { while(i <= n) { ftree[i] += val; i += (i & (-1*i)); } } //Gives the sum of elements upto ith position in O(log n) int getSum(int ftree[], int n, int i) { int sum = 0; while(i != 0) { sum += ftree[i]; i -= (i & (-1*i)); } return sum; } int main() { int n, query; int val, i, type; printf("Enter size of Array: "); scanf("%d", &n); int ftree[n+1]; int arr[n+1]; ftree[0] = arr[0] = 0; printf("Enter %d elements in array: ", n); for(i=1; i<=n; i++) { scanf("%d", &arr[i]); ftree[i] = arr[i]; } printf("Enter no. of Queries: "); scanf("%d", &query); createBIT(ftree, n); while(query--) { printf("Enter Query: "); scanf("%d", &type); if(type == 1) { scanf("%d", &i); printf("Sum: %d\n", getSum(ftree, n, i)); } else { scanf("%d %d", &i, &val); update(ftree, n, val - arr[i], i); } } } ================================================ FILE: Data-Structures/Tree/Binary-Indexed-Tree/Binary-Indexed-Tree.go ================================================ package main import ( "bufio" "fmt" "os" "strconv" "strings" ) // BITree is a binary indexed tree, great for getting the sum from index 1 to n type BITree []int // NewBITree builds a BITree from an array func NewBITree(array []int) BITree { output := make(BITree, len(array)+1) for i := 1; i < len(output); i++ { output.Update(i, array[i-1]) } return output } // Update can be used to manually add values in the BITree func (b BITree) Update(i, val int) { for i < len(b) { b[i] += val // The line below makes i to move to the parent node i += i & (-i) } } // GetSum computes the sum from 1 to i in O(log n) time func (b BITree) GetSum(i int) (sum int) { for i > 0 { sum += b[i] // The line below makes i to move to the parent node i -= i & (-i) } return } func main() { // Get the array reader := bufio.NewReader(os.Stdin) fmt.Print("Values separated by commas: ") text, _ := reader.ReadString('\n') text = strings.ReplaceAll(text, " ", "") // Convert the text array to an actual []int a := make([]int, strings.Count(text, ",")+1) var err error for i, val := range strings.Split(text[:len(text)-2], ",") { a[i], err = strconv.Atoi(val) if err != nil { panic(err) } } BIT := NewBITree(a) fmt.Println("Binary Indexed Tree array:") fmt.Println(BIT) fmt.Println("Press Ctrl+c to exit the loop...") for { index := 0 fmt.Print("Get the sum from 1 to: ") fmt.Scan(&index) fmt.Println(BIT.GetSum(index)) } } ================================================ FILE: Data-Structures/Tree/Binary-Indexed-Tree/Binary-Indexed-Tree.java ================================================ /** Binary Index Tree or Fenwick Tree It is a data structure that can efficiently update elements and calculate prefix sums in a table of numbers. There are two types of query that the user can input in this program 1. Get sum upto ith position Format - 1 i Ex - 1 5 2. Update the element at ith position to k Format - 2 i k Ex - 1 5 2 SAMPLE INPUT :- 12 2 1 1 3 2 3 4 5 6 7 8 9 3 1 5 2 2 6 1 5 EXPECTED OUTPUT :- 9 14 */ import java.io.*; import java.util.StringTokenizer; class Binary_Index_Tree { static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); static StringTokenizer st; //Create BIT in O(n) time static void createBIT(int[] ftree, int n) { int i, j; for(i=1; i<=n; i++) { j = i + (i & (-1*i)); if(j <= n) ftree[j] += ftree[i]; } } //Update the value in the required nodes in Tree in O(log n) static void update(int[] ftree, int n, int val, int i) { while(i <= n) { ftree[i] += val; i += (i & (-1*i)); } } //Gives the sum of elements upto ith position in O(log n) static int getSum(int[] ftree, int n, int i) { int sum = 0; while(i != 0) { sum += ftree[i]; i -= (i & (-1*i)); } return sum; } public static void main(String[] args) throws IOException{ int n, query; int val, i, type; System.out.print("Enter size of Array: "); n = Integer.parseInt(br.readLine()); int[] ftree = new int[n+1]; int[] arr = new int[n+1]; ftree[0] = arr[0] = 0; System.out.print("Enter " + n + " elements in array: "); st = new StringTokenizer(br.readLine()); for(i=1; i<=n; i++) { ftree[i] = arr[i] = Integer.parseInt(st.nextToken()); } System.out.print("Enter no. of Queries: "); query = Integer.parseInt(br.readLine()); createBIT(ftree, n); while(query != 0) { System.out.print("Enter Query: "); st = new StringTokenizer(br.readLine()); type = Integer.parseInt(st.nextToken()); if(type == 1) { i = Integer.parseInt(st.nextToken()); System.out.println("Sum: " + getSum(ftree, n, i)); } else { i = Integer.parseInt(st.nextToken()); val = Integer.parseInt(st.nextToken()); update(ftree, n, val - arr[i], i); } query--; } } } ================================================ FILE: Data-Structures/Tree/Binary-Indexed-Tree/Binary-Indexed-Tree.py ================================================ # BUILD, UPDATE ,QUERY BINARY INDEXED TREE OR FENWICK TREE class BITree: # Construction of a Binary Indexed Tree def __init__(self, a: list): n = len(a) + 1 self.__BIT = [0] * n for i in range(1, n): self.update(i, a[i - 1]) def __getitem__(self, i): return self.__BIT[i] # Always pass by this method to update the BITree def update(self, i: int, val: int): while i < len(self.__BIT): self.__BIT[i] += val # The line below makes i to move to the parent node i += i & (-i) def getSum(self, i: int): total = 0 while i > 0: total += self.__BIT[i] i -= i & (-i) return total if __name__ == "__main__": a = [ int(i) for i in input("Values of separated by commas: ").replace(" ", "").split(",") ] BIT = BITree(a) print("Binary Indexed Tree array:") print(", ".join(str(i) for i in BIT)) print("Press Ctrl+c to exit the loop...") while True: index = int(input("Get the sum from 1 to : ")) print(BIT.getSum(index)) ================================================ FILE: Data-Structures/Tree/Binary-Search-Tree/BST.cs ================================================ using System; // http://csharpexamples.com/c-binary-search-tree-implementation/ class Node { public Node LeftNode { get; set; } public Node RightNode { get; set; } public int Data { get; set; } } class BinaryTree { public Node Root { get; set; } public bool Add(int value) { Node before = null, after = this.Root; while (after != null) { before = after; if (value < after.Data) //Is new node in left tree? after = after.LeftNode; else if (value > after.Data) //Is new node in right tree? after = after.RightNode; else { //Exist same value return false; } } Node newNode = new Node(); newNode.Data = value; if (this.Root == null)//Tree ise empty this.Root = newNode; else { if (value < before.Data) before.LeftNode = newNode; else before.RightNode = newNode; } return true; } public Node Find(int value) { return this.Find(value, this.Root); } public void Remove(int value) { this.Root = Remove(this.Root, value); } private Node Remove(Node parent, int key) { if (parent == null) return parent; if (key < parent.Data) parent.LeftNode = Remove(parent.LeftNode, key); else if (key > parent.Data) parent.RightNode = Remove(parent.RightNode, key); // if value is same as parent's value, then this is the node to be deleted else { // node with only one child or no child if (parent.LeftNode == null) return parent.RightNode; else if (parent.RightNode == null) return parent.LeftNode; // node with two children: Get the inorder successor (smallest in the right subtree) parent.Data = MinValue(parent.RightNode); // Delete the inorder successor parent.RightNode = Remove(parent.RightNode, parent.Data); } return parent; } private int MinValue(Node node) { int minv = node.Data; while (node.LeftNode != null) { minv = node.LeftNode.Data; node = node.LeftNode; } return minv; } private Node Find(int value, Node parent) { if (parent != null) { if (value == parent.Data) return parent; if (value < parent.Data) return Find(value, parent.LeftNode); else return Find(value, parent.RightNode); } return null; } public int GetTreeDepth() { return this.GetTreeDepth(this.Root); } private int GetTreeDepth(Node parent) { return parent == null ? 0 : Math.Max(GetTreeDepth(parent.LeftNode), GetTreeDepth(parent.RightNode)) + 1; } public void TraversePreOrder(Node parent) { if (parent != null) { Console.Write(parent.Data + " "); TraversePreOrder(parent.LeftNode); TraversePreOrder(parent.RightNode); } } public void TraverseInOrder(Node parent) { if (parent != null) { TraverseInOrder(parent.LeftNode); Console.Write(parent.Data + " "); TraverseInOrder(parent.RightNode); } } public void TraversePostOrder(Node parent) { if (parent != null) { TraversePostOrder(parent.LeftNode); TraversePostOrder(parent.RightNode); Console.Write(parent.Data + " "); } } static void Main(string[] args) { BinaryTree binaryTree = new BinaryTree(); binaryTree.Add(1); binaryTree.Add(2); binaryTree.Add(7); binaryTree.Add(3); binaryTree.Add(10); binaryTree.Add(5); binaryTree.Add(8); Node node = binaryTree.Find(5); int depth = binaryTree.GetTreeDepth(); Console.WriteLine("PreOrder Traversal:"); binaryTree.TraversePreOrder(binaryTree.Root); Console.WriteLine(); Console.WriteLine("InOrder Traversal:"); binaryTree.TraverseInOrder(binaryTree.Root); Console.WriteLine(); Console.WriteLine("PostOrder Traversal:"); binaryTree.TraversePostOrder(binaryTree.Root); Console.WriteLine(); binaryTree.Remove(7); binaryTree.Remove(8); Console.WriteLine("PreOrder Traversal After Removing Operation:"); binaryTree.TraversePreOrder(binaryTree.Root); Console.WriteLine(); } } ================================================ FILE: Data-Structures/Tree/Binary-Search-Tree/BST_balanced.cpp ================================================ #include #include using namespace std; int mx = -1e9-10, mn = 1e9+10, c = 0; struct node { int key; node * left; node * right; bool isBalancedNode; node(int k) { key = k; left = right = NULL; isBalancedNode = true; } }; struct BST { node * root; int cnt; BST() { cnt = 0; root = NULL; } node * add(node * root, int x) { if(root == NULL) { node * n = new node(x); root = n; cnt++; } else if(x < root->key) { root->left = add(root->left, x); } else if(x > root->key) { root->right = add(root->right, x); } return root; } void inorder(node * x) { if(x != NULL) { inorder(x->left); cout << x->key << ' ' << x->isBalancedNode << '\n'; inorder(x->right); } } int balance(node * root, int h) { if(root == NULL) return h; int l = balance(root->left, h+1); int r = balance(root->right, h+1); root->isBalancedNode = (abs(l - r) < 2); return max(l, r); } bool isBalanced(node * x) { if(x == NULL) return true; return x->isBalancedNode && isBalanced(x->right) && isBalanced(x->left); } }; int main() { BST myTree; int x, cnt=0; while(cin>>x && x!=0) { myTree.root = myTree.add(myTree.root, x); } myTree.balance(myTree.root, 0); cout <<(myTree.isBalanced(myTree.root) ? "YES" : "NO"); return 0; } ================================================ FILE: Data-Structures/Tree/Binary-Search-Tree/BinarySearchTree.go ================================================ package main import "fmt" type treeNode struct { value int leftNode *treeNode rightNode *treeNode } type tree struct { root *treeNode } func (binaryTree *tree) reset() { binaryTree.root = nil } func (binaryTree *tree) insert(value int) { binaryTree.insertRec(binaryTree.root, value) } func (binaryTree *tree) insertRec(node *treeNode, value int) *treeNode { if binaryTree.root == nil { binaryTree.root = &treeNode{ value: value, } return binaryTree.root } if node == nil { return &treeNode{value: value} } if value <= node.value { node.leftNode = binaryTree.insertRec(node.leftNode, value) } if value > node.value { node.rightNode = binaryTree.insertRec(node.rightNode, value) } return node } func (binaryTree *tree) find(value int) error { node := binaryTree.findRec(binaryTree.root, value) if node == nil { return fmt.Errorf("value: %d not present", value) } return nil } func (binaryTree *tree) findRec(node *treeNode, value int) *treeNode { if node == nil { return nil } if node.value == value { return binaryTree.root } if value < node.value { return binaryTree.findRec(node.leftNode, value) } return binaryTree.findRec(node.rightNode, value) } func (binaryTree *tree) inorder() { binaryTree.inorderRec(binaryTree.root) } func (binaryTree *tree) inorderRec(node *treeNode) { if node != nil { binaryTree.inorderRec(node.leftNode) fmt.Println(node.value) binaryTree.inorderRec(node.rightNode) } } func main() { binaryTree := &tree{} elements := []int{32, 48, 17, -8, 13, 21, 19} for _, val := range elements { binaryTree.insert(val) } fmt.Printf("Traversing the tree: Inorder:\n") binaryTree.inorder() binaryTree.reset() elements = []int{-13, -8, 15, 12, 0, 63, 21} for _, val := range elements { binaryTree.insert(val) } fmt.Printf("\nTraversing the tree: Inorder:\n") binaryTree.inorder() fmt.Printf("\nFinding Values:\n") toFind := 48 err := binaryTree.find(toFind) if err != nil { fmt.Printf("Value %d Not Found\n", toFind) } else { fmt.Printf("Value %d Found\n", toFind) } toFind = -33 err = binaryTree.find(toFind) if err != nil { fmt.Printf("Value %d Not Found\n", toFind) } else { fmt.Printf("Value %d Found\n", toFind) } toFind = 21 err = binaryTree.find(toFind) if err != nil { fmt.Printf("Value %d Not Found\n", toFind) } else { fmt.Printf("Value %d Found\n", toFind) } toFind = 0 err = binaryTree.find(toFind) if err != nil { fmt.Printf("Value %d Not Found\n", toFind) } else { fmt.Printf("Value %d Found\n", toFind) } } ================================================ FILE: Data-Structures/Tree/Binary-Search-Tree/BinarySearchTree.java ================================================ import java.util.LinkedList; import java.util.Queue; import java.util.Stack; public class BinarySearchTree { TreeNode root; public BinarySearchTree(){ this.root = null; } public boolean isEmpty(){ return root==null; } public void deleteByCopying(int deletevalue){ TreeNode p = this.root,prev=null; while(p!=null && p.info != deletevalue){ prev = p; if(deletevalue >= p.info){ p = p.right; } else{ p=p.left; } } TreeNode node = p; if(p!=null && p.info==deletevalue){ if(node.right == null){ node = node.left; } else if(node.left == null){ node = node.right; } else{ TreeNode tmp = node.left; TreeNode prev2 = node; while(tmp.right!=null){ prev2 = tmp; tmp = tmp.right; } node.info = tmp.info; if(prev2==node){ prev2.left = tmp.left; } else{ prev2.right = tmp.left; } } } } public void deleteByMerging(int deleteValue){ TreeNode p=this.root,prev=null; while(p!=null && p.info!=deleteValue){ // Search for delete node prev= p; if(deleteValue >= p.info){ p = p.right; } else{ p = p.left; } } TreeNode nodeForPrevToPointTo = p; if(p!=null && p.info == deleteValue){ if(p.right ==null){ nodeForPrevToPointTo = p.left; } else if(p.left == null){ nodeForPrevToPointTo = p.right; } else{ TreeNode temp = nodeForPrevToPointTo.left; while(temp.right!=null){ temp = temp.right; } temp.right = p.right; nodeForPrevToPointTo = p.left; if(p == root){ root = nodeForPrevToPointTo; } else if(prev.left == p){ prev.left = nodeForPrevToPointTo; } else{ prev.right = nodeForPrevToPointTo; } } } else if(root!=null){ System.out.println("Key " + deleteValue + "is not in the tree"); } else{ System.out.println("The tree is empty"); } } public void preorderTravelsal(){ TreeNode p = root; Stack stack = new Stack(); if(p!=null){ stack.push(p); while(!stack.isEmpty()){ p= (TreeNode)stack.pop(); System.out.print(p.info+" "); if(p.right!=null){ stack.push(p.right); } if(p.left!=null){ stack.push(p.left); } } } } public void breadthFirstTraversal(){ TreeNode p = root; Queue q = new LinkedList<>(); if(p!=null){ q.add(p); while(!q.isEmpty()){ p = q.remove(); System.out.print(p.info + " "); if(p.left !=null){ q.add(p.left); } if(p.right!=null){ q.add(p.right); } } } } public void inorderTraversalRecursion(TreeNode p){ if(p!=null){ inorderTraversalRecursion(p.left); System.out.print(p.info + " "); //visit node p inorderTraversalRecursion(p.right); } } public void preorderTraversalRecursion(TreeNode p){ if(p!=null){ System.out.print(p.info + " "); //visit node p preorderTraversalRecursion(p.left); preorderTraversalRecursion(p.right); } } public void postorderTraversalRecursion(TreeNode p){ if(p!=null){ postorderTraversalRecursion(p.left); postorderTraversalRecursion(p.right); System.out.print(p.info + " "); //visit node p } } public void insert(int newInfo){ if(isEmpty()){ this.root = new TreeNode(newInfo); } else{ TreeNode p = root; while(p!=null){ if(newInfo queue = new LinkedList(); if(p!=null){ queue.add(p); while(!queue.isEmpty()){ p = queue.poll(); System.out.print(p.info + " "); if(p.left !=null){ queue.add(p.left); } if(p.right!=null){ queue.add(p.right); } } } } public void preorder(TreeNode p){ if(p!=null){ System.out.print(p.info + " "); preorder(p.left); preorder(p.right); } } public void inorder(TreeNode p){ if(p!=null){ inorder(p.left); System.out.print(p.info + " "); inorder(p.right); } } public void postorder(TreeNode p){ if(p!=null){ postorder(p.left); postorder(p.right); System.out.print(p.info+ " "); } } public void iterativePreorder(){ TreeNode p = root; Stack travStack = new Stack(); if(p!=null){ travStack.push(p); while(!travStack.isEmpty()){ p= (TreeNode)travStack.pop(); System.out.print(p.info+" "); if(p.right!=null){ travStack.push(p.right); } if(p.left!=null){ travStack.push(p.left); } } } } public void iterativeInorder(){ TreeNode p = root; Stack travStack = new Stack(); while(p!=null){ while(p!=null){ if(p.right!=null){ travStack.push(p.right); } travStack.push(p); p = p.left; } p = (TreeNode) travStack.pop(); while(!travStack.isEmpty() && p.right == null){ System.out.print(p.info+" "); p = (TreeNode) travStack.pop(); } System.out.print(p.info+" "); if(!travStack.isEmpty()){ p= (TreeNode) travStack.pop(); } else{ p = null; } } } public void iterativeLastorder(){ TreeNode p = root,q=root; Stack travStack = new Stack(); while(p!=null){ for(;p.left!=null;p=p.left){ travStack.push(p); } while(p!=null && (p.right==null||p.right==q)){ System.out.print(p.info+" "); q = p; if(travStack.isEmpty())return; p = (TreeNode) travStack.pop(); } travStack.push(p); p=p.right; } } } class TreeNode { int info; TreeNode left,right; public TreeNode(int info){ this(info,null,null); } public TreeNode(int info,TreeNode left,TreeNode right){ this.info = info; this.left = left; this.right = right; } } ================================================ FILE: Data-Structures/Tree/Binary-Search-Tree/Binary_Search_Tree.cpp ================================================ // Author : Sachin19k // Topic: Binary Search Tree /* Problem Statement : Implement binary search tree and perform following operations: a) Insert (Handle insertion of duplicate entry) b) Delete c) Search d) Display tree Traversal (Recursive & Non-recursive) e) Display - Depth of tree f) Display - Mirror image g) Create a copy h) Display all parent nodes with their child nodes i) Display leaf nodes j) Display tree level wise */ #include #include #include using namespace std; // Structure of the node of Binary Search Tree struct dll { int data; dll *left; dll *right; }; dll *BSTinsert(dll *root,int x) //Inserting node in BST { dll *p, *prev, *r; r=new dll; r->data=x; r->left=NULL; r->right=NULL; if(root==NULL) { return r; } p=root; while(p!=NULL) { prev=p; if(x>p->data) p=p->right; else if(xdata) p=p->left; else { cout<<"DUPLICATE ELEMENTS ARRIVED :(\n"; //duplicate entry return (root); } } if(x>prev->data) prev->right=r; else prev->left=r; return (root); } void levelorder(dll *root) //Print the node in levelorder form { if(root==NULL) return; queue p; p.push(root); int count=1; while(!p.empty()) { if(count==0) { cout<<"\n"; count=p.size(); } dll *q = p.front(); cout<data<<"\t"; if(q->left!=NULL) p.push(q->left); if(q->right!=NULL) p.push(q->right); p.pop(); count--; } } void Rpreorder(dll *root) //Recursive Postorder { if(root!=NULL) { cout<data<<"\t"; Rpreorder(root->left); Rpreorder(root->right); } } void NRpreorder(dll *root) //Iterative Preorder { stack s; while(!s.empty() || root!=NULL) { while(root!=NULL) { cout<data<<"\t"; s.push(root); root=root->left; } root=s.top(); s.pop(); root=root->right; } } void Rinorder(dll *root) //Recursive Inorder { if(root!=NULL) { Rinorder(root->left); cout<data<<"\t"; Rinorder(root->right); } } void NRinorder(dll *root) //Iterative Inorder { stack s; while(!s.empty() || root!=NULL) { while(root!=NULL) { s.push(root); root=root->left; } root=s.top(); s.pop(); cout<data<<"\t"; root=root->right; } } void Rpostorder(dll *root) //Recursive Postorder { if(root==NULL) { return; } Rpostorder(root->left); Rpostorder(root->right); cout<data<<"\t"; } void NRpostorder(dll *root) //Iterative Postorder { stack s1; stack s2; while(root!=NULL) { s1.push(root); s2.push(0); root=root->left; } while(!s1.empty()) { root=s1.top(); if(s2.top()==1) { s1.pop(); s2.pop(); cout<data<<"\t"; } else { s2.top()=1; root=root->right; while(root!=NULL) { s1.push(root); s2.push(0); root=root->left; } } } } int BSTheight(dll *root) //Height of BST { if(root==NULL) return -1; queue p; p.push(root); int ht=-1,count; while(1) { count=p.size(); if(count==0) return ht; ht++; while(count--) { dll *q=p.front(); p.pop(); if(q->left!=NULL) p.push(q->left); if(q->right!=NULL) p.push(q->right); } } } dll* f_min(dll *root) //Find Minimum element from root { dll*p=root; while(p->left!=NULL) { p=p->left; } return (p); } dll *f_max(dll *root) //Find Maximum element from root { dll *p=root; while(p->right!=NULL) { p=p->right; } return (p); } bool search(dll *root,int x) //Search an element in BST { while(root!=NULL) { if(x==root->data) { cout<<"ELEMENT FOUND :)\n" ; return true; } else if(x>root->data) { root=root->right; } else { root=root->left; } } cout<<"ELEMENT NOT FOUND :( \n" ; return false; } dll *bstdelete(dll *root, int x) //Delete the node from BST { dll *m; if(root==NULL) { cout<<"NOT FOUND!!"; return root; } if(x < root->data) { root->left=bstdelete(root->left,x); return root; } if(x>root->data) { root->right=bstdelete(root->right,x); return root; } if(root->left==NULL && root->right==NULL) { m=root; delete m; return (NULL); } else if(root->left==NULL) { m=root; root=root->right; delete m; return (root); } else if(root->right==NULL) { m=root; root=root->left; delete m; return (root); } m=f_min(root->right); root->data=m->data; root->right=bstdelete(root->right, m->data); return (root); } dll *mirr(dll *root) //Mirror image of the BST { if(root==NULL) return NULL; dll *p=root; queue q; q.push(root); while(!q.empty()) { dll *curr=q.front(); q.pop(); swap(curr->left, curr->right); if(curr->left) q.push(curr->left); if(curr->right) q.push(curr->right); } return (p); } dll *nd_copy(dll *root) { if(root==NULL) { return root; } dll *p = new dll; p->data=root->data; p->left=nd_copy(root->left); p->right=nd_copy(root->right); return p; } void par_chld(dll *root) //Print all parents and their Children { if(root==NULL) return; queue p; p.push(root); int count=1,x; while(!p.empty()) { x=0; dll *q = p.front(); cout<data<<"\t"; if(q->left!=NULL) { x++; p.push(q->left); cout<<(q->left)->data<<"\t"; } if(q->right!=NULL) { x++; p.push(q->right); cout<<(q->right)->data<<"\t"; } if(x==0) { cout<<"\t\t(node has no child)"; } else if(x==1) { cout<<"\t(node has one child)"; } else if(x==2) { cout<<"(node has two children)"; } p.pop(); cout<<"\n"; } } void leaf_nd(dll *root) //Print all leafnode in BST { if (!root) return; if (root->left==NULL && root->right==NULL) { cout << root->data << "\t"; return; } if (root->left) leaf_nd(root->left); if (root->right) leaf_nd(root->right); } int main() //main function { dll *root=NULL,*z=NULL; bool b; int n,p,x; cout<<"[1] BST INSERT\n"; cout<<"[2] DELETE \n"; cout<<"[3] SEARCH AN ELEMENT'S PRESENCE \n"; cout<<"[4] RECURSIVE PREORDER\n"; cout<<"[5] NON RECURSIVE PREORDER\n"; cout<<"[6] RECURSIVE INORDER\n"; cout<<"[7] NON RECURSIVE INORDER\n"; cout<<"[8] RECURSIVE POSTORDER\n"; cout<<"[9] NON RECURSIVE POSTORDER\n"; cout<<"[10] HEIGHT OF TREE \n"; cout<<"[11] MIRROR IMAGE \n"; cout<<"[12] CREATE A COPY \n"; cout<<"[13] DISPLAY ALL PARENT NODES WITH CHILD NODES \n"; cout<<"[14] DISPLAY LEAF NODES \n"; cout<<"[15] LEVEL ORDER DISPLAY\n"; cout<<"[16] FIND MINIMUM \n"; cout<<"[17] FIND MAXIMUM \n"; do { cout<<"\nEnter your choice: "; cin>>n; switch(n) { case 1: do { cout<<"enter the data \n"; cin>>x; root = BSTinsert(root,x); cout<<"want to enter more?\n"; cin>>p; } while(p!=0); break; case 2: cout<<"enter the element to be deleted?\n"; cin>>x; if(search(root,x)) { root = bstdelete(root,x); levelorder(root); } else { cout<<"CAN'T DELETE!! \n"; } break; case 3: cout<<"ENTER THE ELEMENT TO BE SEARCHED??\n"; cin>>x; b = search(root,x); break; case 4: Rpreorder(root); break; case 5: NRpreorder(root); break; case 6: Rinorder(root); break; case 7: NRinorder(root); break; case 8: Rpostorder(root); break; case 9: NRpostorder(root); break; case 10: x = BSTheight(root); cout<data; break; case 17: z = f_max(root); cout<data; break; } } while(n<18); cout<<"\nOPERATION COMPLETED!! THANK YOU"; return 0; } /* ----------------------------------------------------------------------------------------------------------------------------- OUTPUT : [1] BST INSERT [2] DELETE [3] SEARCH AN ELEMENT'S PRESENCE [4] RECURSIVE PREORDER [5] NON RECURSIVE PREORDER [6] RECURSIVE INORDER [7] NON RECURSIVE INORDER [8] RECURSIVE POSTORDER [9] NON RECURSIVE POSTORDER [10] HEIGHT OF TREE [11] MIRROR IMAGE [12] CREATE A COPY [13] DISPLAY ALL PARENT NODES WITH CHILD NODES [14] DISPLAY LEAF NODES [15] LEVEL ORDER DISPLAY [16] FIND MINIMUM [17] FIND MAXIMUM Enter your choice: 1 enter the data 8 want to enter more? 1 enter the data 3 want to enter more? 1 enter the data 10 want to enter more? 1 enter the data 1 want to enter more? 1 enter the data 6 want to enter more? 1 enter the data 14 want to enter more? 1 enter the data 4 want to enter more? 1 enter the data 7 want to enter more? 1 enter the data 13 want to enter more? 0 Enter your choice: 3 ENTER THE ELEMENT TO BE SEARCHED?? 7 ELEMENT FOUND :) Enter your choice: 5 8 3 1 6 4 7 10 14 13 Enter your choice: 7 1 3 4 6 7 8 10 13 14 Enter your choice: 9 1 4 7 6 3 13 14 10 8 Enter your choice: 10 3 Enter your choice: 15 8 3 10 1 6 14 4 7 13 Enter your choice: 13 8 3 10 (node has two children) 3 1 6 (node has two children) 10 14 (node has one child) 1 (node has no child) 6 4 7 (node has two children) 14 13 (node has one child) 4 (node has no child) 7 (node has no child) 13 (node has no child) Enter your choice: 11 MIRROR IMAGE IS: 8 10 3 14 6 1 13 7 4 Enter your choice: 16 14 Enter your choice: 15 8 10 3 14 6 1 13 7 4 Enter your choice: 18 OPERATION COMPLETED!! THANK YOU ...Program finished with exit code 0 Press ENTER to exit console. */ ================================================ FILE: Data-Structures/Tree/Binary-Search-Tree/Binary_Search_Tree.py ================================================ # Binary Search Tree (BST) Implementation class BSTNode: def __init__(selfNode, nodeData): # Node Structure selfNode.nodeData = nodeData selfNode.left = None selfNode.right = None selfNode.parent = None # Insertion Operation def insert(selfNode, node): if selfNode.nodeData > node.nodeData: if selfNode.left is None: selfNode.left = node node.parent = selfNode else: selfNode.left.insert(node) elif selfNode.nodeData < node.nodeData: if selfNode.right is None: selfNode.right = node node.parent = selfNode else: selfNode.right.insert(node) # Removal Operation Functions def replace_node_of_parent(selfNode, new_node): if selfNode.parent is not None: if new_node is not None: new_node.parent = selfNode.parent if selfNode.parent.left == selfNode: selfNode.parent.left = new_node elif selfNode.parent.right == selfNode: selfNode.parent.right = new_node else: selfNode.nodeData = new_node.nodeData selfNode.left = new_node.left selfNode.right = new_node.right if new_node.left is not None: new_node.left.parent = selfNode if new_node.right is not None: new_node.right.parent = selfNode def find_min(selfNode): current = selfNode while current.left is not None: current = current.left return current def remove(selfNode): if (selfNode.left is not None and selfNode.right is not None): successor = selfNode.right.find_min() selfNode.nodeData = successor.nodeData successor.remove() elif selfNode.left is not None: selfNode.replace_node_of_parent(selfNode.left) elif selfNode.right is not None: selfNode.replace_node_of_parent(selfNode.right) else: selfNode.replace_node_of_parent(None) # Search required data within BST def search(selfNode, nodeData): if selfNode.nodeData > nodeData: if selfNode.left is not None: return selfNode.left.search(nodeData) else: return None elif selfNode.nodeData < nodeData: if selfNode.right is not None: return selfNode.right.search(nodeData) else: return None return selfNode # InOrder Traversal Operation def inorder(selfNode): if selfNode.left is not None: selfNode.left.inorder() print(selfNode.nodeData, end=' ') if selfNode.right is not None: selfNode.right.inorder() # PostOrder Traversal Operation def postorder(selfNode): if selfNode.left is not None: selfNode.left.inorder() if selfNode.right is not None: selfNode.right.inorder() print(selfNode.nodeData, end=' ') # PreOrder Traversal Operation def preorder(selfNode): print(selfNode.nodeData, end=' ') if selfNode.left is not None: selfNode.left.inorder() if selfNode.right is not None: selfNode.right.inorder() class BSTree: # Structure of Binary Search Tree def __init__(selfNode): selfNode.root = None def inorder(selfNode): if selfNode.root is not None: selfNode.root.inorder() def preorder(selfNode): if selfNode.root is not None: selfNode.root.preorder() def postorder(selfNode): if selfNode.root is not None: selfNode.root.postorder() def add(selfNode, nodeData): new_node = BSTNode(nodeData) if selfNode.root is None: selfNode.root = new_node else: selfNode.root.insert(new_node) def remove(selfNode, nodeData): to_remove = selfNode.search(nodeData) if (selfNode.root == to_remove and selfNode.root.left is None and selfNode.root.right is None): selfNode.root = None else: to_remove.remove() def search(selfNode, nodeData): if selfNode.root is not None: return selfNode.root.search(nodeData) bstree = BSTree() # Object of class BSTree # Menu of Operations on BST Tree print('BST Tree Operation Menu') print('Add ') print('Remove ') print('Inorder') print('Preorder') print('Postorder') print('Quit') while True: do = input('Enter your action => ').split() operation = do[0].strip().lower() if operation == 'add': nodeData = int(do[1]) bstree.add(nodeData) elif operation == 'remove': nodeData = int(do[1]) bstree.remove(nodeData) elif operation == 'inorder': print('Inorder Traversal: ', end='') bstree.inorder() print() elif operation == 'postorder': print('Postorder Traversal: ', end='') bstree.postorder() print() elif operation == 'preorder': print('Preorder Traversal: ', end='') bstree.preorder() print() elif operation == 'quit': print("BST Tree Implementation finished.") break ================================================ FILE: Data-Structures/Tree/Binary-Search-Tree/Binary_Search_Tree_operations.cpp ================================================ // Author : Sachin19k // Topic: Binary Search Tree /* Problem Statement : Implement binary search tree and perform following operations: a) Insert (Handle insertion of duplicate entry) b) Delete c) Search d) Display tree Traversal (Recursive & Non-recursive) e) Display - Depth of tree f) Display - Mirror image g) Create a copy h) Display all parent nodes with their child nodes i) Display leaf nodes j) Display tree level wise */ #include #include #include using namespace std; // Structure of the node of Binary Search Tree struct dll { int data; dll *left; dll *right; }; dll *BSTinsert(dll *root,int x) //Inserting node in BST { dll *p, *prev, *r; r=new dll; r->data=x; r->left=NULL; r->right=NULL; if(root==NULL) { return r; } p=root; while(p!=NULL) { prev=p; if(x>p->data) p=p->right; else if(xdata) p=p->left; else { cout<<"DUPLICATE ELEMENTS ARRIVED :(\n"; //duplicate entry return (root); } } if(x>prev->data) prev->right=r; else prev->left=r; return (root); } void levelorder(dll *root) //Print the node in levelorder form { if(root==NULL) return; queue p; p.push(root); int count=1; while(!p.empty()) { if(count==0) { cout<<"\n"; count=p.size(); } dll *q = p.front(); cout<data<<"\t"; if(q->left!=NULL) p.push(q->left); if(q->right!=NULL) p.push(q->right); p.pop(); count--; } } void Rpreorder(dll *root) //Recursive Postorder { if(root!=NULL) { cout<data<<"\t"; Rpreorder(root->left); Rpreorder(root->right); } } void NRpreorder(dll *root) //Iterative Preorder { stack s; while(!s.empty() || root!=NULL) { while(root!=NULL) { cout<data<<"\t"; s.push(root); root=root->left; } root=s.top(); s.pop(); root=root->right; } } void Rinorder(dll *root) //Recursive Inorder { if(root!=NULL) { Rinorder(root->left); cout<data<<"\t"; Rinorder(root->right); } } void NRinorder(dll *root) //Iterative Inorder { stack s; while(!s.empty() || root!=NULL) { while(root!=NULL) { s.push(root); root=root->left; } root=s.top(); s.pop(); cout<data<<"\t"; root=root->right; } } void Rpostorder(dll *root) //Recursive Postorder { if(root==NULL) { return; } Rpostorder(root->left); Rpostorder(root->right); cout<data<<"\t"; } void NRpostorder(dll *root) //Iterative Postorder { stack s1; stack s2; while(root!=NULL) { s1.push(root); s2.push(0); root=root->left; } while(!s1.empty()) { root=s1.top(); if(s2.top()==1) { s1.pop(); s2.pop(); cout<data<<"\t"; } else { s2.top()=1; root=root->right; while(root!=NULL) { s1.push(root); s2.push(0); root=root->left; } } } } int BSTheight(dll *root) //Height of BST { if(root==NULL) return -1; queue p; p.push(root); int ht=-1,count; while(1) { count=p.size(); if(count==0) return ht; ht++; while(count--) { dll *q=p.front(); p.pop(); if(q->left!=NULL) p.push(q->left); if(q->right!=NULL) p.push(q->right); } } } dll* f_min(dll *root) //Find Minimum element from root { dll*p=root; while(p->left!=NULL) { p=p->left; } return (p); } dll *f_max(dll *root) //Find Maximum element from root { dll *p=root; while(p->right!=NULL) { p=p->right; } return (p); } bool search(dll *root,int x) //Search an element in BST { while(root!=NULL) { if(x==root->data) { cout<<"ELEMENT FOUND :)\n" ; return true; } else if(x>root->data) { root=root->right; } else { root=root->left; } } cout<<"ELEMENT NOT FOUND :( \n" ; return false; } dll *bstdelete(dll *root, int x) //Delete the node from BST { dll *m; if(root==NULL) { cout<<"NOT FOUND!!"; return root; } if(x < root->data) { root->left=bstdelete(root->left,x); return root; } if(x>root->data) { root->right=bstdelete(root->right,x); return root; } if(root->left==NULL && root->right==NULL) { m=root; delete m; return (NULL); } else if(root->left==NULL) { m=root; root=root->right; delete m; return (root); } else if(root->right==NULL) { m=root; root=root->left; delete m; return (root); } m=f_min(root->right); root->data=m->data; root->right=bstdelete(root->right, m->data); return (root); } dll *mirr(dll *root) //Mirror image of the BST { if(root==NULL) return NULL; dll *p=root; queue q; q.push(root); while(!q.empty()) { dll *curr=q.front(); q.pop(); swap(curr->left, curr->right); if(curr->left) q.push(curr->left); if(curr->right) q.push(curr->right); } return (p); } dll *nd_copy(dll *root) { if(root==NULL) { return root; } dll *p = new dll; p->data=root->data; p->left=nd_copy(root->left); p->right=nd_copy(root->right); return p; } void par_chld(dll *root) //Print all parents and their Children { if(root==NULL) return; queue p; p.push(root); int count=1,x; while(!p.empty()) { x=0; dll *q = p.front(); cout<data<<"\t"; if(q->left!=NULL) { x++; p.push(q->left); cout<<(q->left)->data<<"\t"; } if(q->right!=NULL) { x++; p.push(q->right); cout<<(q->right)->data<<"\t"; } if(x==0) { cout<<"\t\t(node has no child)"; } else if(x==1) { cout<<"\t(node has one child)"; } else if(x==2) { cout<<"(node has two children)"; } p.pop(); cout<<"\n"; } } void leaf_nd(dll *root) //Print all leafnode in BST { if (!root) return; if (root->left==NULL && root->right==NULL) { cout << root->data << "\t"; return; } if (root->left) leaf_nd(root->left); if (root->right) leaf_nd(root->right); } int main() //main function { dll *root=NULL,*z=NULL; bool b; int n,p,x; cout<<"[1] BST INSERT\n"; cout<<"[2] DELETE \n"; cout<<"[3] SEARCH AN ELEMENT'S PRESENCE \n"; cout<<"[4] RECURSIVE PREORDER\n"; cout<<"[5] NON RECURSIVE PREORDER\n"; cout<<"[6] RECURSIVE INORDER\n"; cout<<"[7] NON RECURSIVE INORDER\n"; cout<<"[8] RECURSIVE POSTORDER\n"; cout<<"[9] NON RECURSIVE POSTORDER\n"; cout<<"[10] HEIGHT OF TREE \n"; cout<<"[11] MIRROR IMAGE \n"; cout<<"[12] CREATE A COPY \n"; cout<<"[13] DISPLAY ALL PARENT NODES WITH CHILD NODES \n"; cout<<"[14] DISPLAY LEAF NODES \n"; cout<<"[15] LEVEL ORDER DISPLAY\n"; cout<<"[16] FIND MINIMUM \n"; cout<<"[17] FIND MAXIMUM \n"; do { cout<<"\nEnter your choice: "; cin>>n; switch(n) { case 1: do { cout<<"enter the data \n"; cin>>x; root = BSTinsert(root,x); cout<<"want to enter more?\n"; cin>>p; } while(p!=0); break; case 2: cout<<"enter the element to be deleted?\n"; cin>>x; if(search(root,x)) { root = bstdelete(root,x); levelorder(root); } else { cout<<"CAN'T DELETE!! \n"; } break; case 3: cout<<"ENTER THE ELEMENT TO BE SEARCHED??\n"; cin>>x; b = search(root,x); break; case 4: Rpreorder(root); break; case 5: NRpreorder(root); break; case 6: Rinorder(root); break; case 7: NRinorder(root); break; case 8: Rpostorder(root); break; case 9: NRpostorder(root); break; case 10: x = BSTheight(root); cout<data; break; case 17: z = f_max(root); cout<data; break; } } while(n<18); cout<<"\nOPERATION COMPLETED!! THANK YOU"; return 0; } /* ----------------------------------------------------------------------------------------------------------------------------- OUTPUT : [1] BST INSERT [2] DELETE [3] SEARCH AN ELEMENT'S PRESENCE [4] RECURSIVE PREORDER [5] NON RECURSIVE PREORDER [6] RECURSIVE INORDER [7] NON RECURSIVE INORDER [8] RECURSIVE POSTORDER [9] NON RECURSIVE POSTORDER [10] HEIGHT OF TREE [11] MIRROR IMAGE [12] CREATE A COPY [13] DISPLAY ALL PARENT NODES WITH CHILD NODES [14] DISPLAY LEAF NODES [15] LEVEL ORDER DISPLAY [16] FIND MINIMUM [17] FIND MAXIMUM Enter your choice: 1 enter the data 8 want to enter more? 1 enter the data 3 want to enter more? 1 enter the data 10 want to enter more? 1 enter the data 1 want to enter more? 1 enter the data 6 want to enter more? 1 enter the data 14 want to enter more? 1 enter the data 4 want to enter more? 1 enter the data 7 want to enter more? 1 enter the data 13 want to enter more? 0 Enter your choice: 3 ENTER THE ELEMENT TO BE SEARCHED?? 7 ELEMENT FOUND :) Enter your choice: 5 8 3 1 6 4 7 10 14 13 Enter your choice: 7 1 3 4 6 7 8 10 13 14 Enter your choice: 9 1 4 7 6 3 13 14 10 8 Enter your choice: 10 3 Enter your choice: 15 8 3 10 1 6 14 4 7 13 Enter your choice: 13 8 3 10 (node has two children) 3 1 6 (node has two children) 10 14 (node has one child) 1 (node has no child) 6 4 7 (node has two children) 14 13 (node has one child) 4 (node has no child) 7 (node has no child) 13 (node has no child) Enter your choice: 11 MIRROR IMAGE IS: 8 10 3 14 6 1 13 7 4 Enter your choice: 16 14 Enter your choice: 15 8 10 3 14 6 1 13 7 4 Enter your choice: 18 OPERATION COMPLETED!! THANK YOU ...Program finished with exit code 0 Press ENTER to exit console. */ ================================================ FILE: Data-Structures/Tree/Binary-Search-Tree/LCA.py ================================================ #Code to get the inorder traversal and to find the lowest common ansester of two given node in binary search tree by user in python class new_node: def __init__(self,data): self.data=data self.left=None self.right=None def insert(root,data): if root==None: return new_node(data) else: if root.data==data: return root elif root.data>data: root.right=insert(root.right,data) elif data>root.data: root.left=insert(root.left,data) return root def inorder(root): if root: inorder(root.left) print(root.data,end=" ") inorder(root.right) def find_LCA(root,n1,n2): if root is None: return left_data=find_LCA(root.left,n1,n2) right_data=find_LCA(root.right,n1,n2) if root.data==n1 or root.data==n2: return root return left_data if left_data is not None else right_data if __name__=='__main__': n = int(input('Enter number of node u want in this BST: ')) x=int(input('Enter data you want to insert in root node: ')) root=new_node(x) for i in range(n-1): v=int(input('Data: ')) insert(root,v) choice=0 while(choice!=3): choice=int(input(''' 1. Inorder Traversal of BST 2. LCA of two node 3. Quit ''')) if choice==1: inorder(root) elif choice==2: print('Give two node whose LCA you want to find: ') m1,m2=map(int,input().split()) print(find_LCA(root,m1,m2).data) print('Have a nice day!') ================================================ FILE: Data-Structures/Tree/Binary-Search-Tree/README.md ================================================ ## This folder is empty. ================================================ FILE: Data-Structures/Tree/Binary-Search-Tree/Validate_BST.py ================================================ #!/usr/env/python class BSTNode: def __init__(self, data): # Node Structure self.data = data self.left = None self.right = None """ The data from the nodes should be ordered as left.data <= self.data <= right.data """ def isValid(self): return self is None or ( (self.left is None or (self.left.data <= self.data and self.left.isValid())) and (self.right is None or (self.data <= self.right.data and self.right.isValid()))) if __name__ == "__main__": bst = BSTNode(5) bst.left = BSTNode(3) bst.right = BSTNode(8) bst.left.left = BSTNode(1) bst.left.right = BSTNode(4) print(bst.isValid()) nonbst = BSTNode(5) nonbst.left = BSTNode(6) print(nonbst.isValid()) ================================================ FILE: Data-Structures/Tree/Binary-Search-Tree/Vertcal_order_traversal.py ================================================ #Code for inorder as well as vertical order traversal of BST in python class new_node: def __init__(self,data): self.data=data self.left=None self.right=None def insert(root,data): if root==None: return new_node(data) else: if root.data==data: return root elif root.data>data: root.right=insert(root.right,data) elif data>root.data: root.left=insert(root.left,data) return root def vertical_line(root,hd,m): if root is None: return try: m[hd].append(root.data) except: m[hd]=[root.data] vertical_line(root.left,hd-1,m) vertical_line(root.right,hd+1,m) def print_vertical_order(root): m=dict() h=0 vertical_line(root,h,m) for ind,val in enumerate(sorted(m)): for i in m[val]: print(i) print() def inorder(root): if root: inorder(root.left) print(root.data) inorder(root.right) if __name__=='__main__': n = int(input('Enter number of node u want in this BST: ')) x=int(input('Enter data you want to insert in root node: ')) root=new_node(x) for i in range(n-1): v=int(input('Data: ')) insert(root,v) choice=0 while(choice!=3): choice=int(input(''' 1. Inorder Traversal of BST 2. Vertical-order-traversal of BST 3. Quit ''')) if choice==1: inorder(root) elif choice==2: print_vertical_order(root) print('Have a nice day!') ================================================ FILE: Data-Structures/Tree/Binary-Search-Tree/inorder_transversal.c ================================================ #include #include struct node { int data; struct node* left; struct node* right; }; struct node* newNode(int data) { struct node* node = (struct node*) malloc(sizeof(struct node)); node->data = data; node->left = NULL; node->right = NULL; return(node); } void printInorder(struct node* node) { if (node == NULL) return; printInorder(node->left); printf("%d ", node->data); printInorder(node->right); } int main() { struct node *root = newNode(1); root->left = newNode(2); root->right= newNode(3); root->left->left= newNode(4); root->left->right = newNode(5); printf("\nInorder traversal of binary tree is \n"); printInorder(root); getchar(); return 0; } ================================================ FILE: Data-Structures/Tree/Binary-Search-Tree/operationBST.cpp ================================================ #include #include using namespace std; struct Node { int info; Node *left; Node *right; }; Node* FindMin(Node *node) { if(node==NULL) { return NULL; } if(node->left) return FindMin(node->left); else return node; } Node* FindMax(Node *node) { if(node==NULL) { return NULL; } if(node->right) return(FindMax(node->right)); else return node; } Node *Insert(Node *node,int info) { if(node==NULL) { Node *temp; temp=new Node; temp -> info = info; temp -> left = temp -> right = NULL; return temp; } if(info >(node->info)) { node->right = Insert(node->right,info); } else if(info < (node->info)) { node->left = Insert(node->left,info); } return node; } Node * Delet(Node *node, int info) { Node *temp; if(node==NULL) { cout<<"Element Not Found"; } else if(info < node->info) { node->left = Delet(node->left, info); } else if(info > node->info) { node->right = Delet(node->right, info); } else { if(node->right && node->left) { temp = FindMin(node->right); node -> info = temp->info; node -> right = Delet(node->right,temp->info); } else { temp = node; if(node->left == NULL) node = node->right; else if(node->right == NULL) node = node->left; free(temp); } } return node; } Node * Find(Node *node, int info) { if(node==NULL) { return NULL; } if(info > node->info) { return Find(node->right,info); } else if(info < node->info) { return Find(node->left,info); } else { return node; } } void Inorder(Node *node) { if(node==NULL) { return; } Inorder(node->left); cout<info<<" "; Inorder(node->right); } void Preorder(Node *node) { if(node==NULL) { return; } cout<info<<" "; Preorder(node->left); Preorder(node->right); } void Postorder(Node *node) { if(node==NULL) { return; } Postorder(node->left); Postorder(node->right); cout<info<<" "; } int n=1; int CountNodes(Node*root) { if(root==NULL) return 0; if(root->left!=NULL) { n=n+1; n=CountNodes(root->left); } if(root->right!=NULL) { n=n+1; n=CountNodes(root->right); } return n; } main() { Node *root = NULL,*temp; int ch; while(1) { cout<<"\n\t\t OPERATION MENU "; cout<<"\n\t 1.Insert\n\t 2.Delete\n\t 3.Inorder\n\t 4.Preorder\n\t 5.Postorder\n\t 6."; cout<<"FindMin\n\t 7.FindMax\n\t 8.Search\n\t 9.Count NO. of Nodes\n\t 10.Exit\n"; cout<<"Enter your choice:"; cin>>ch; switch(ch) { case 1: cout<<"\nEnter element to be insert:"; cin>>ch; root = Insert(root, ch); cout<<"\nElements in BST are:"; Inorder(root); break; case 2: cout<<"\nEnter element to be deleted:"; cin>>ch; root = Delet(root,ch); cout<<"\nAfter deletion elements in BST are:"; Inorder(root); break; case 3: cout<<"\nInorder Travesals is:"; Inorder(root); break; case 4: cout<<"\nPreorder Traversals is:"; Preorder(root); break; case 5: cout<<"\nPostorder Traversals is:"; Postorder(root); break; case 6: temp = FindMin(root); cout<<"\nMinimum element is :"<info; break; case 7: temp = FindMax(root); cout<<"\nMaximum element is :"<info; break; case 8: cout<<"\nEnter element to be searched:"; cin>>ch; temp = Find(root,ch); if(temp==NULL) { cout<<"Element is not found\n"; } else { cout<<"Element "<info<<" is Found\n"; } break; case 9: { cout<<"\n Total No. of Nodes is: "< #include struct node { int data; struct node* left; struct node* right; }; struct node* newNode(int data) { struct node* node = (struct node*) malloc(sizeof(struct node)); node->data = data; node->left = NULL; node->right = NULL; return(node); } void printPostorder(struct node* node) { if (node == NULL) return; printPostorder(node->left); printPostorder(node->right); printf("%d ", node->data); } int main() { struct node *root = newNode(1); root->left = newNode(2); root->right= newNode(3); root->left->left= newNode(4); root->left->right = newNode(5); printf("\nPostorder traversal of binary tree is \n"); printPostorder(root); getchar(); return 0; } ================================================ FILE: Data-Structures/Tree/Binary-Search-Tree/valid BST ================================================ #include using namespace std; struct Node { int data; struct Node* left, *right; Node(int data) { this->data = data; left = right = NULL; } }; bool isBSTUtil(struct Node* root, Node *&prev) { if (root) { if (!isBSTUtil(root->left, prev)) return false; if (prev != NULL && root->data <= prev->data) return false; prev = root; return isBSTUtil(root->right, prev); } return true; } bool isBST(Node *root) { Node *prev = NULL; return isBSTUtil(root, prev); } int main() { struct Node *root = new Node(3); root->left = new Node(2); root->right = new Node(5); root->left->left = new Node(1); root->left->right = new Node(4); if (isBST(root)) cout << "Is BST"; else cout << "Not a BST"; return 0; } ================================================ FILE: Data-Structures/Tree/Binary-Tree/BTree.cpp ================================================ #include #include using namespace std; //implementing BTree of Order 6 struct BTreeNode { //Array containing keys in a node int *vals; //Array containing pointer to children in a node BTreeNode **children; //Checks if node is a leaf node or not bool isLeaf; //Maintains number of keys present in vals array int numberOfKeys; }; // Pointer to root of tree and a temporary pointer BTreeNode* root = NULL, *x = NULL; //Creates a new empty node BTreeNode * newNode(){ BTreeNode* newptr = new BTreeNode; newptr->vals = new int[5]; newptr->children = new BTreeNode *[6]; newptr->isLeaf = true; newptr->numberOfKeys = 0; for (int i=0;i<6;i++){ newptr->children[i] = NULL; } return newptr; } //Performs DFS Traversal on the tree, inorder traversal to be precise void traverseBTree(BTreeNode* node){ int i; for(i=0; i< node->numberOfKeys; i++){ if(!node->isLeaf) traverseBTree(node->children[i]); cout<<" "<vals[i]; } if(!node->isLeaf){ traverseBTree(node->children[i]); } cout<<"\n"; } //Handles the splitting of child when the tree is full to prevent overflow int splitChild(BTreeNode *node, int index){ int mid; BTreeNode* temp1 = newNode(); temp1->isLeaf = true; if (index==-1){ mid = node->vals[2]; node->vals[2] = 0; node->numberOfKeys-=1; BTreeNode* temp = newNode(); temp->isLeaf = false; node->isLeaf = true; for(int i=3;i<5;i++){ temp1->vals[i-3] = node->vals[i]; temp1->children[i-3] = node->children[i]; temp1->numberOfKeys+=1; node->vals[i] = 0; node->numberOfKeys-=1; } for(int i=0;i<6;i++){ node->children[i] = NULL; } temp->vals[0] = mid; temp->children[temp->numberOfKeys] = node; temp->children[temp->numberOfKeys+1] = temp1; temp->numberOfKeys++; root = temp; } else { BTreeNode *temp2 = node->children[index]; mid = temp2->vals[2]; temp2->vals[2] = 0; temp2->numberOfKeys-=1; for(int i=3;i<5;i++) { temp1->vals[i-3] = temp2->vals[i]; temp1->numberOfKeys+=1; temp2->vals[i] = 0; temp2->numberOfKeys-=1; } x->children[index+1] = temp2; x->children[index+1] = temp1; } return mid; } //Handles the cases related to insertion of node in the tree and calls appropriate functions when needed void insertNode(int val){ int i, temp; x = root; if(!x){ root = newNode(); x = root; } else { if(x->isLeaf && x->numberOfKeys==5){ temp = splitChild(x, -1); x = root; for(i=0; i<(x->numberOfKeys);i++){ if((val>x->vals[i]) && (valvals[i + 1])){ i++; break; } else if (val < x->vals[0]){ break; } else { continue; } } x = x->children[i]; } else { while (!x->isLeaf){ for(i=0;i<(x->numberOfKeys);i++){ if((val>x->vals[i]) && (valvals[i + 1])){ i++; break; } else if (val < x->vals[0]){ break; } else { continue; } } if((x->children[i])->numberOfKeys==5){ temp = splitChild(x, i); x->vals[x->numberOfKeys] = temp; x->numberOfKeys+=1; continue; } else { x = x->children[i]; } } } } x->vals[x->numberOfKeys] = val; sort(x->vals, x->vals + x->numberOfKeys); x->numberOfKeys+=1; } //Implementing Deletion in a class as there is circular dependency between removeFromSubtree and removeFromGeneral //Such a case is very difficult to handle with sequential programming, hence using a class class Deletion{ public: //Returns the index of predecessor of the current node //Predecessor is the just smaller value, which means last element of the rightmost leaf to the left int getPredecessor(BTreeNode* node, int i){ BTreeNode* temp = node->children[i]; while(!temp->isLeaf) temp = temp->children[temp->numberOfKeys]; return temp->vals[temp->numberOfKeys-1]; } //Returns the index of successor of the current node //Successor is the just larger value, which means the first element of the leftmost leaf to the right int getSuccessor(BTreeNode* node, int i){ BTreeNode* temp = node->children[i+1]; while(!temp->isLeaf) temp = temp->children[0]; return temp->vals[0]; } //Borrows the value from the just previous child and copies it to the current one //Used when filling values in case there are less than 2 child void borrowFromPrevious(BTreeNode* node, int i){ BTreeNode* c = node->children[i]; BTreeNode* s = node->children[i-1]; for(int j = c->numberOfKeys-1;j>=0;j--) c->vals[i+1] = c->vals[i]; if(!c->isLeaf) for(int j = c->numberOfKeys;j>=0;j--) c->children[j+1] = c->children[j]; c->vals[0] = node->vals[i-1]; if(!c->isLeaf) c->children[0] = s->children[s->numberOfKeys]; node->vals[i-1] = s->vals[s->numberOfKeys-1]; c->numberOfKeys+=1; s->numberOfKeys-=1; } //Borrows the value from the just next child and copies it to the current one //Used when filling values in case of there are less than 2 child void borrowFromNext(BTreeNode* node, int i){ BTreeNode* c = node->children[i]; BTreeNode* s = node->children[i+1]; c->vals[c->numberOfKeys] = node->vals[i]; if(!c->isLeaf) c->children[c->numberOfKeys+1] = s->children[0]; node->vals[i] = s->vals[0]; for(int j=1;jnumberOfKeys;j++) s->vals[j-1] = s->vals[j]; if(!s->isLeaf) for(int j=1;j<=s->numberOfKeys;j++) s->children[j-1] = s->children[j]; c->numberOfKeys+=1; s->numberOfKeys-=1; } //Merges the current child with the next child and frees the memory of unused pointer void merge(BTreeNode* node, int i){ BTreeNode* c = node->children[i]; BTreeNode* s = node->children[i+1]; c->vals[2] = node->vals[i]; for(int j=0;jnumberOfKeys;j++) c->vals[j+3] = s->vals[j]; if(!c->isLeaf) for(int j=0;j<=s->numberOfKeys;j++) c->children[j+3] = s->children[j]; for(int j=i+1;jnumberOfKeys;j++) node->vals[j-1] = node->vals[j]; for(int j=i+2;j<=node->numberOfKeys;j++) node->children[j-1] = node->children[j]; c->numberOfKeys+=(s->numberOfKeys+1); node->numberOfKeys-=1; delete(s); } // Return the value the just >= the given key int findClosestKey(BTreeNode* node, int key){ int i=0; while(inumberOfKeys && node->vals[i]numberOfKeys;j++) node->vals[j-1] = node->vals[j]; node->numberOfKeys-=1; } //Removes the value from given non leaf node //Checks number of keys in children and calls appropriate function void removeFromGeneral(BTreeNode* node, int i){ int key = node->vals[i]; if(node->children[i]->numberOfKeys >= 3){ int pre = getPredecessor(node, i); node->vals[i] = pre; removeFromSubtree(node->children[i], pre); } else if(node->children[i+1]->numberOfKeys>=3){ int suc = getSuccessor(node, i); node->vals[i] = suc; removeFromSubtree(node->children[i+1], suc); } else { merge(node, i); removeFromSubtree(node, i); } } //Handles the node which has less than 2 keys and fill values accordingly void fill(BTreeNode* node, int i){ if(i!=0 && node->children[i-1]->numberOfKeys>=3) borrowFromPrevious(node,i); else if(i!=node->numberOfKeys && node->children[i+1]->numberOfKeys>=3) borrowFromNext(node,i); else{ if(i!=node->numberOfKeys) merge(node,i); else merge(node,i-1); } } //Removes values from the subtree rooted with given key void removeFromSubtree(BTreeNode* node, int key){ int i = findClosestKey(node,key); if(inumberOfKeys && node->vals[i]==key){ if(node->isLeaf) removeFromLeaf(node, i); else removeFromGeneral(node,i); } else { if(node->isLeaf){ cout<<"Key not found in tree\n"; return; } bool flag = (i==node->numberOfKeys) ? true : false; if(node->children[i]->numberOfKeys<3) fill(node, i); if(flag && i>node->numberOfKeys) removeFromSubtree(node->children[i-1], key); else removeFromSubtree(node->children[i], key); } } //The utility function to be called by main void deleteNode(BTreeNode* root, int val){ if(!root){ cout<<"Tree is Empty\n"; return; } removeFromSubtree(root, val); if(root->numberOfKeys==0){ BTreeNode* temp = root; if(root->isLeaf) root=NULL; else root = root->children[0]; delete(temp); } } }; // Searches the value in the given tree and returns a pointer to the node BTreeNode* search(BTreeNode* root, int val){ int i=0; while(inumberOfKeys && val>root->vals[i]) ++i; if(root->vals[i]==val) return root; if(root->isLeaf) return NULL; return search(root->children[i], val); } int main(){ while(1){ cout<<"++++++++++++++++++++++++++++++++++\n"; cout<<"Select an Operation\n"; cout<<" 1. Insert\n 2. Delete \n 3. Search \n 4.Traverse\n5. Exit \n"; cout<<"++++++++++++++++++++++++++++++++++\n"; int selection; cin>>selection; if(selection == 1){ cout<<"Enter Number to Insert\n"; int key; cin>>key; insertNode(key); } else if(selection == 2){ cout<<"Enter Number to Delete\n"; int num; cin>>num; BTreeNode* temp = search(root,num); Deletion d; if(temp) d.deleteNode(root,num); else cout<<"Value doesn't exist\n"; } else if(selection==3){ cout<<"Enter Number to Search\n"; int num; cin>>num; BTreeNode* temp = search(root,num); if(temp) cout<<"Found\n"; else cout<<"Not Found\n"; } else if(selection == 4){ cout<<"Traversal: "; traverseBTree(root); cout<<"\n"; } else if(selection == 5){ break; } } } ================================================ FILE: Data-Structures/Tree/Binary-Tree/Binary tree using C.c ================================================ #include #include struct bin_tree { int data; struct bin_tree * right, * left; }; typedef struct bin_tree node; void insert(node ** tree, int val) { node *temp = NULL; if(!(*tree)) { temp = (node *)malloc(sizeof(node)); temp->left = temp->right = NULL; temp->data = val; *tree = temp; return; } if(val < (*tree)->data) { insert(&(*tree)->left, val); } else if(val > (*tree)->data) { insert(&(*tree)->right, val); } } void print_preorder(node * tree) { if (tree) { printf("%d\n",tree->data); print_preorder(tree->left); print_preorder(tree->right); } } void print_inorder(node * tree) { if (tree) { print_inorder(tree->left); printf("%d\n",tree->data); print_inorder(tree->right); } } void print_postorder(node * tree) { if (tree) { print_postorder(tree->left); print_postorder(tree->right); printf("%d\n",tree->data); } } void deltree(node * tree) { if (tree) { deltree(tree->left); deltree(tree->right); free(tree); } } node* search(node ** tree, int val) { if(!(*tree)) { return NULL; } if(val < (*tree)->data) { search(&((*tree)->left), val); } else if(val > (*tree)->data) { search(&((*tree)->right), val); } else if(val == (*tree)->data) { return *tree; } } void main() { node *root; node *tmp; //int i; root = NULL; /* Inserting nodes into tree */ insert(&root, 9); insert(&root, 4); insert(&root, 15); insert(&root, 6); insert(&root, 12); insert(&root, 17); insert(&root, 2); /* Printing nodes of tree */ printf("Pre Order Display\n"); print_preorder(root); printf("In Order Display\n"); print_inorder(root); printf("Post Order Display\n"); print_postorder(root); /* Search node into tree */ tmp = search(&root, 4); if (tmp) { printf("Searched node=%d\n", tmp->data); } else { printf("Data Not found in tree.\n"); } /* Deleting all nodes of tree */ deltree(root); } ================================================ FILE: Data-Structures/Tree/Binary-Tree/Btree.java ================================================ /**************************************************** * Author - Ayush Sharma (belphegor-s) * File Name - B-Tree.java * * Short Note about B-Tree - * * B Tree is a specialized m-way tree that can * be widely used for disk access. * A B-Tree of order m can have at most m-1 keys * and m children. One of the main reason of using * B tree is its capability to store large number * of keys in a single node and large key values by * keeping the height of the tree relatively small. * ******************************************************/ // Java program to illustrate the sum of two numbers // A BTree class Btree { public BTreeNode root; // Pointer to root node public int t; // Minimum degree // Constructor (Initializes tree as empty) Btree(int t) { this.root = null; this.t = t; } // function to traverse the tree public void traverse() { if (this.root != null) this.root.traverse(); System.out.println(); } // function to search a key in this tree public BTreeNode search(int k) { if (this.root == null) return null; else return this.root.search(k); } } // A BTree node class BTreeNode { int[] keys; // An array of keys int t; // Minimum degree (defines the range for number of keys) BTreeNode[] C; // An array of child pointers int n; // Current number of keys boolean leaf; // Is true when node is leaf. Otherwise false // Constructor BTreeNode(int t, boolean leaf) { this.t = t; this.leaf = leaf; this.keys = new int[2 * t - 1]; this.C = new BTreeNode[2 * t]; this.n = 0; } // A function to traverse all nodes in a subtree rooted with this node public void traverse() { // There are n keys and n+1 children, travers through n keys // and first n children int i = 0; for (i = 0; i < this.n; i++) { // If this is not leaf, then before printing key[i], // traverse the subtree rooted with child C[i]. if (this.leaf == false) { C[i].traverse(); } System.out.print(keys[i] + " "); } // Print the subtree rooted with last child if (leaf == false) C[i].traverse(); } // A function to search a key in the subtree rooted with this node. BTreeNode search(int k) { // returns NULL if k is not present. // Find the first key greater than or equal to k int i = 0; while (i < n && k > keys[i]) i++; // If the found key is equal to k, return this node if (keys[i] == k) return this; // If the key is not found here and this is a leaf node if (leaf == true) return null; // Go to the appropriate child return C[i].search(k); } } ================================================ FILE: Data-Structures/Tree/Binary-Tree/Check_duplicates_in _BTree.java ================================================ import java.util.HashSet; public class CheckDuplicateValues { public static boolean checkDupUtil(Node root, HashSet s) { if (root == null) return false; if (s.contains(root.data)) return true; s.add(root.data); return checkDupUtil(root.left, s) || checkDupUtil(root.right, s); } public static boolean checkDup(Node root) { HashSet s=new HashSet<>(); return checkDupUtil(root, s); } public static void main(String args[]) { Node root = new Node(1); root.left = new Node(2); root.right = new Node(2); root.left.left = new Node(3); root.left.right = new Node(4); if (checkDup(root)) System.out.print("Yes This tree contains Duplicates value."); else System.out.print("No duplicates values exist"); } } class Node { int data; Node left; Node right; Node(int data) { this.data=data; } }; ================================================ FILE: Data-Structures/Tree/Binary-Tree/Density/DensityBtree.c ================================================ /* Density of Binary Tree = Size / Height */ #include //For standard input / output operations #include //For dynamic declaration of Node using malloc struct Node { //Struct for a Node in the tree int data; //Data stored in this node struct Node *left, *right; //Pointer to left and right child }; struct Node* newNode(int data) { //Function for defining a New Node struct Node* node = malloc(sizeof(struct Node)); node->data = data; node->left = node->right = NULL; //Initialize left and right child as 0 return node; } int heightAndSize(struct Node* node, int *size) { if (node==NULL) //Left node return 0; int left_child_height = heightAndSize(node->left, size); //Recursively calls of the function for its left child int right_child_height = heightAndSize(node->right, size); //Recursively calls of the function for its right child *size=*size+1; //Increments size by 1 on traversal of each node return (left_child_height > right_child_height) ? left_child_height + 1 : right_child_height + 1; //Returns the larger height among it's left and right child and adds 1 to account for itself } float density(struct Node* root){ //Function to calculate density by passing root of tree if (root == NULL) //Incase root is Null , tree will be empty and hence density is 0 return 0; int size, tree_height; size = 0; //Initialize size of the tree as 0 tree_height = heightAndSize(root, &size); //Calls function to find height and size of the tree (returns height and increments size by address of parameter) return (float)size/tree_height; } int main(){ struct Node* root = newNode(1); //Root of tree root->left = newNode(2); //Child Node root->right = newNode(3); //Child Node root->right->left = newNode(4); //Child Node // For current example, height = 3 and size = 4 hence density should be 1.3333 printf("Density of given binary tree is %f", density(root)); //Prints density return 0; } ================================================ FILE: Data-Structures/Tree/Binary-Tree/Density/DensityBtree.cpp ================================================ /*Density of Binary Tree = Size / Height */ #include struct Node { int data; Node *left, *right; }; Node* newNode(int data) { Node* node = new Node; node->data = data; node->left = node->right = NULL; return node; } int heighAndSize(Node* node, int &size) { if (node==NULL) return 0; int l = heighAndSize(node->left, size); int r = heighAndSize(node->right, size); size++; return (l > r) ? l + 1 : r + 1; } float density(Node* root) { if (root == NULL) return 0; int size = 0; // To store size int _height = heighAndSize(root, size); return (float)size/_height; } int main() { Node* root = newNode(1); root->left = newNode(2); root->right = newNode(3); printf("Density of given binary tree is %f", density(root)); return 0; } ================================================ FILE: Data-Structures/Tree/Binary-Tree/Deserialize/Deserialize.rb ================================================ # created : 13/10/2020 # author : baniksudipto class TreeNode attr_accessor :value, :left, :right def initialize(value = nil) @value = value @left = nil @right = nil end end class Codec def initialize(empty_leaf_marker, separator) @index = 0 @marker = empty_leaf_marker @separator = separator end def serialize(root) # Encodes a tree to a single string. if root [root.value , serialize(root.left), serialize(root.right)].join(@separator) else @marker.to_s end end def deserialize(data) # Decodes a string to a tree @index = 0 data = data.split(@separator) build_tree(data) end private def build_tree(data) value = data[@index] @index += 1 if value.nil? or value == @marker nil else node = TreeNode.new(value) node.left = build_tree(data) node.right = build_tree(data) node end end end # test serialized_string = "1,2,4,#,#,5,#,#,3,6,#,#,7,#,#" # 1 # 2 3 # 4 5 6 7 codec = Codec.new('#',',') raise "This is not working" unless codec.serialize(codec.deserialize(serialized_string)) == serialized_string ================================================ FILE: Data-Structures/Tree/Binary-Tree/Duplicate_values.cs ================================================ using System; using System.Collections; using System.Collections.Generic; class CheckDuplicateValues { //Function that used HashSet to // find presence of duplicate nodes public static Boolean checkDupUtil(Node root, HashSet s) { // If tree is empty, there are no // duplicates. if (root == null) return false; // If current node's data is already present. if (s.Contains(root.data)) return true; // Insert current node s.Add(root.data); // Recursively check in left and right // subtrees. return checkDupUtil(root.left, s) || checkDupUtil(root.right, s); } public static Boolean checkDup(Node root) { HashSet s = new HashSet(); return checkDupUtil(root, s); } public static void Main(String []args) { Node root = new Node(1); root.left = new Node(2); root.right = new Node(2); root.left.left = new Node(3); if (checkDup(root)) Console.Write("Yes"); else Console.Write("No"); } } public class Node { public int data; public Node left, right; public Node(int data) { this.data = data; } }; ================================================ FILE: Data-Structures/Tree/Binary-Tree/Invert_Binary_Tree/Invert_Binary_Tree.py ================================================ """Invert Binary Tree - Write a function that takes in a Binary Tree and inverts it. In other words, the function should swap every left node in the tree for its corresponding right node. Each Binary Tree node has an integer value, a left child node, and a right child node. Children nodes can either be Bina ry Tree nodes themselves or None / null. """ # ITERATIVE # O(N)T | O(N)S def invertBinaryTree(tree): queue = [tree] while len(queue) != 0: currNode = queue.pop(0) if currNode is None: continue swap(currNode) queue.append(currNode.left) queue.append(currNode.right) def swap(tree): tree.left, tree.right = tree.right, tree.left class BinaryTree: def __init__(self, value): self.value = value self.left = None self.right = None # RECURSIVE # O(N)T | O(d)S def invertBinaryTree(tree): if tree is not None: swap(tree) invertBinaryTree(tree.left) invertBinaryTree(tree.right) return def swap(tree): tree.left, tree.right = tree.right, tree.left # This is the class of the input binary tree. class BinaryTree: def __init__(self, value): self.value = value self.left = None self.right = None ================================================ FILE: Data-Structures/Tree/Binary-Tree/Invert_Binary_Tree/invertBinTree.rb ================================================ # simple bst implementation class BST attr_accessor :head # simple bst node implementation class Node attr_accessor :left attr_accessor :right attr_accessor :value def initialize(val) @value = val end end # bst constructor def initialize(val) @head = Node.new(val) end # method for inserting new values into a given bst def self.insert(val, tree) if not tree then return Node.new(val) else if val > tree.value then tree.right = insert(val, tree.right) else tree.left = insert(val, tree.left) end end tree end # tree inversion method def self.invert(tree) # base case, null leaf reached if not tree then return end # otherwise, recurse and swap left and right nodes of tree temp = tree.right tree.right = invert(tree.left) tree.left = invert(temp) # return inverted result tree end # simple bst print method for printing def self.printTree(tree, level = 0) if not tree then return else if level == 0 then puts tree.value elsif level == 1 then print tree.value else puts " #{tree.value}" end printTree(tree.left, 1) printTree(tree.right, 2) end end end # simple integer input example, takes three int inputs puts "Please input three integers for an example." b = BST.new((gets).to_i) BST.insert((gets).to_i, b.head) BST.insert((gets).to_i, b.head) puts "Example tree~" BST.printTree(b.head) # then inverts tree puts "Inverted result~" BST.invert(b.head) BST.printTree(b.head) ================================================ FILE: Data-Structures/Tree/Binary-Tree/Invert_Binary_Tree/invert_binary_tree.cpp ================================================ #include using namespace std; //Definition for binary tree- struct TreeNode { int val; TreeNode *left; TreeNode *right; }; //Utility function- struct TreeNode* newNode(int val) { struct TreeNode* node = (struct TreeNode*)malloc(sizeof(struct TreeNode)); node->val = val; node->left = NULL; node->right = NULL; return(node); } //Inverting Binary Tree using recursion- void invert(TreeNode* A){ if(A==NULL) return; invert(A->left); TreeNode* t1=A->left; invert(A->right); TreeNode* t2=A->right; A->left=t2; A->right=t1; } TreeNode* invertTree(TreeNode* root) { invert(root); return root; } int main() { struct TreeNode *root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); //Convert tree to its mirror- root = invertTree(root); return 0; } ================================================ FILE: Data-Structures/Tree/Binary-Tree/Invert_Binary_tree/invert_btree.swift ================================================ class TreeNode { var left: TreeNode? var right: TreeNode? var value: Int init(val: Int) { self.value = val } } class Tree{ var root: TreeNode init(val: TreeNode){ self.root = val } func invertTree(){ invert(node: self.root) } func invert(node: TreeNode){ if(node.left == nil&&node.right == nil){ return } let temp = node.left node.left = node.right node.right = temp if(node.left != nil ){ invert(node: node.left!) } if(node.right != nil){ invert(node: node.right!) } } } var root = TreeNode(val: 1) var o = TreeNode(val: 3) var b = TreeNode(val: 7) var h = TreeNode(val: 4) var g = TreeNode(val: 2) root.left = o root.right = b root.right?.right = h root.right?.left = g var myTree = Tree(val: root) myTree.invertTree() ================================================ FILE: Data-Structures/Tree/Binary-Tree/Right_View/RightViewBTree.java ================================================ class Node { int data; Node left, right; Node(int item) { data = item; left = right = null; } } class Max_level { int max_level; } class BinaryTree { Node root; Max_level max = new Max_level(); // Recursive function to print right view of a binary tree. void rightViewUtil(Node node, int level, Max_level max_level) { if (node == null) return; // If this is the last Node of its level if (max_level.max_level < level) { System.out.print(node.data + " "); max_level.max_level = level; } // Recur for right subtree first, then left subtree rightViewUtil(node.right, level + 1, max_level); rightViewUtil(node.left, level + 1, max_level); } void rightView() { rightView(root); } void rightView(Node node) { rightViewUtil(node, 1, max); } public static void main(String args[]) { BinaryTree tree = new BinaryTree(); tree.root = new Node(1); tree.root.left = new Node(2); tree.root.right = new Node(3); tree.root.left.left = new Node(4); tree.root.left.right = new Node(5); tree.root.right.left = new Node(6); tree.root.right.right = new Node(7); tree.root.right.left.right = new Node(8); tree.rightView(); } } ================================================ FILE: Data-Structures/Tree/Binary-Tree/Right_View/rightViewBinTree.rb ================================================ # simple bst implementation class BST attr_accessor :head # simple bst node implementation class Node attr_accessor :left attr_accessor :right attr_accessor :value def initialize(val) @value = val end end # bst constructor def initialize(val) @head = Node.new(val) end # method for inserting new values into a given bst def self.insert(val, tree) if not tree then return Node.new(val) else if val > tree.value then tree.right = insert(val, tree.right) else tree.left = insert(val, tree.left) end end tree end # right side view method def self.rightSideView(tree) rightView = [] while tree rightView << tree.value tree = tree.right end rightView end # simple bst print method for printing def self.printTree(tree, level = 0) if not tree then return else if level == 0 then puts tree.value elsif level == 1 then print tree.value else puts " #{tree.value}" end printTree(tree.left, 1) printTree(tree.right, 2) end end end # simple integer input example, takes three int inputs b = BST.new((gets).to_i) BST.insert((gets).to_i, b.head) BST.insert((gets).to_i, b.head) BST.printTree(b.head) puts BST.rightSideView(b.head).inspect ================================================ FILE: Data-Structures/Tree/Binary-Tree/Right_View/right_view.py ================================================ class Node: # A constructor to create a new Binary tree Node def __init__(self, item): self.data = item self.left = None self.right = None def rightViewUtil(root, level, max_level): # Base Case if root is None: return if (max_level[0] < level): print "%d " %(root.data), max_level[0] = level rightViewUtil(root.right, level+1, max_level) rightViewUtil(root.left, level+1, max_level) def rightView(root): max_level = [0] rightViewUtil(root, 1, max_level) # Driver program to test above function root = Node(1) root.left = Node(2) root.right = Node(3) root.left.left = Node(4) root.left.right = Node(5) root.right.left = Node(6) root.right.right = Node(7) root.right.left.right = Node(8) rightView(root) ================================================ FILE: Data-Structures/Tree/Binary-Tree/Right_View/right_view.swift ================================================ class TreeNode { var left: TreeNode? var right: TreeNode? var value: Int init(val: Int) { self.value = val } } class Tree{ var root: TreeNode init(val: TreeNode){ self.root = val } func rightView()-> [TreeNode]{ var rightView = [TreeNode]() var curretNode: TreeNode? curretNode = self.root while(curretNode?.right != nil){ rightView.append(curretNode!) curretNode = curretNode!.right } rightView.append(curretNode!) return rightView } } var root = TreeNode(val: 1) var o = TreeNode(val: 3) var b = TreeNode(val: 7) var h = TreeNode(val: 4) var g = TreeNode(val: 2) root.left = o root.right = b root.right?.right = h root.right?.left = g var myTree = Tree(val: root) for node in myTree.rightView() { print(node.value, " ") } ================================================ FILE: Data-Structures/Tree/Binary-Tree/Right_View/right_view_of_binary_tree.cpp ================================================ #include using namespace std; //Definition for binary tree struct TreeNode { int val; TreeNode *left; TreeNode *right; }; //Utility function to create Tree nodes TreeNode* newNode(int val) { TreeNode *temp = new TreeNode; temp->val = val; temp->left = temp->right = NULL; return temp; } //The task is equivalent to returning the last value in each level of the tree, ie. similar to Breadth First Traversal vector getRightView(TreeNode* root) { vectoranswer; queueQ; TreeNode* temp; Q.push(root); //NULL node is used to demarkate separate levels of the tree- Q.push(NULL); //BFS type approach using queue- while(!Q.empty()){ temp=Q.front(); Q.pop(); if(temp!=NULL){ if(temp->left!=NULL) Q.push(temp->left); if(temp->right!=NULL) Q.push(temp->right); if(Q.front()==NULL){ //we are at the end of the current level, ie. current node's value is required in the answer answer.push_back(temp->val); Q.pop(); Q.push(NULL); } } } return answer; } int main() { //constructing the tree- TreeNode* root = newNode(10); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(7); root->left->right = newNode(8); root->right->right = newNode(15); root->right->left = newNode(12); root->right->right->left = newNode(14); vector RightViewOfBTree = getRightView(root); //printing the vector containing right view of this tree- for(int i=0; i #define MARKER -1 struct Node { int key; struct Node* left, *right; }; Node* newNode(int key) { Node* temp = new Node; temp->key = key; temp->left = temp->right = NULL; return (temp); } void serialize(Node *root, FILE *fp) { if (root == NULL) { fprintf(fp, "%d ", MARKER); return; } fprintf(fp, "%d ", root->key); serialize(root->left, fp); serialize(root->right, fp); } int main() { struct Node *root = newNode(32); root->left = newNode(12); root->right = newNode(23); root->left->left = newNode(40); root->left->right = newNode(33); root->left->right->left = newNode(50); root->left->right->right = newNode(45); FILE *fp = fopen("tree.txt", "w"); if (fp == NULL) { puts("Error: Could not open file!"); return 0; } serialize(root, fp); fclose(fp); return 0; } ================================================ FILE: Data-Structures/Tree/Binary-Tree/Serialize/Serialize.py ================================================ class Node: def __init__(self, key, left=None, right=None): self.key = key self.left = left self.right = right def __repr__(self): left = f" left={self.left}" if self.left is not None else "" right = f" right={self.right}" if self.right is not None else "" return f"" def serialize(root): if root is None: return "-1" # for each branch, return the key, the left then the right node output = (str(root.key), serialize(root.left), serialize(root.right)) return " ".join(output) if __name__ == "__main__": # 1 # / \ # 2 3 # / \ / \ # 4 -1 6 7 root = Node(1, Node(2, Node(4)), Node(3, Node(6), Node(7))) print(root) with open("tree.txt", "w") as fp: fp.write(serialize(root)) ================================================ FILE: Data-Structures/Tree/Binary-Tree/Subtree_check/Subtree_check.cpp ================================================ #include #include using namespace std; #define MAX 100 // Structure of a tree node struct Node { char key; struct Node *left, *right; }; // A utility function to create a new BST node Node* newNode(char item) { Node* temp = new Node; temp->key = item; temp->left = temp->right = NULL; return temp; } // A utility function to store inorder traversal of tree rooted // with root in an array arr[]. Note that i is passed as reference void storeInorder(Node* root, char arr[], int& i) { if (root == NULL) { arr[i++] = '$'; return; } storeInorder(root->left, arr, i); arr[i++] = root->key; storeInorder(root->right, arr, i); } // A utility function to store preorder traversal of tree rooted // with root in an array arr[]. Note that i is passed as reference void storePreOrder(Node* root, char arr[], int& i) { if (root == NULL) { arr[i++] = '$'; return; } arr[i++] = root->key; storePreOrder(root->left, arr, i); storePreOrder(root->right, arr, i); } /* This function returns true if S is a subtree of T, otherwise false */ bool isSubtree(Node* T, Node* S) { /* base cases */ if (S == NULL) return true; if (T == NULL) return false; // Store Inorder traversals of T and S in inT[0..m-1] // and inS[0..n-1] respectively int m = 0, n = 0; char inT[MAX], inS[MAX]; storeInorder(T, inT, m); storeInorder(S, inS, n); inT[m] = '\0', inS[n] = '\0'; // If inS[] is not a substring of inT[], return false if (strstr(inT, inS) == NULL) return false; // Store Preorder traversals of T and S in preT[0..m-1] // and preS[0..n-1] respectively m = 0, n = 0; char preT[MAX], preS[MAX]; storePreOrder(T, preT, m); storePreOrder(S, preS, n); preT[m] = '\0', preS[n] = '\0'; // If preS[] is not a substring of preT[], return false // Else return true return (strstr(preT, preS) != NULL); } // Driver program to test above function int main() { Node* T = newNode('a'); T->left = newNode('b'); T->right = newNode('d'); T->left->left = newNode('c'); T->right->right = newNode('e'); Node* S = newNode('a'); S->left = newNode('b'); S->left->left = newNode('c'); S->right = newNode('d'); if (isSubtree(T, S)) cout << "Yes: S is a subtree of T"; else cout << "No: S is NOT a subtree of T"; return 0; } O ================================================ FILE: Data-Structures/Tree/Binary-Tree/SymmetricBTree.java ================================================ class Node { int key; Node left, right; Node(int item) { key = item; left = right = null; } } class BinaryTree { Node root; boolean isMirror(Node node1, Node node2) { if (node1 == null && node2 == null) return true; if (node1 != null && node2 != null && node1.key == node2.key) return (isMirror(node1.left, node2.right) && isMirror(node1.right, node2.left)); return false; } boolean isSymmetric(Node node) { return isMirror(root, root); } public static void main(String args[]) { BinaryTree tree = new BinaryTree(); tree.root = new Node(1); tree.root.left = new Node(2); tree.root.right = new Node(2); tree.root.left.left = new Node(3); tree.root.left.right = new Node(4); tree.root.right.left = new Node(4); tree.root.right.right = new Node(3); boolean output = tree.isSymmetric(tree.root); if (output == true) System.out.println("Tree is Symmetric "); else System.out.println("Tree is not Symmetric"); } } ================================================ FILE: Data-Structures/Tree/Binary-Tree/SymmetryBTree/SymmetryBTree.rb ================================================ # Question: # Given a binary tree, check whether it is a mirror of itself # # Solution: # # structure of TreeNode class TreeNode attr_accessor :val, :left, :right def initialize(val = 0, left = nil, right = nil) @val = val @left = left @right = right end end # method to check if Tree is symmetric def symmetric?(root) check_symmetry(root, root) end # utility method of symmetric? def check_symmetry(actual, mirror) return true if actual.nil? && mirror.nil? return false if actual.nil? || mirror.nil? (actual.val == mirror.val) && check_symmetry(actual.left, mirror.right) && check_symmetry(actual.right, mirror.left) end # =============== Test Cases ============ # sample tree 1 ==> symmetric? => true # 5 # 4 4 # 1 1 symmetric_tree = TreeNode.new(5) symmetric_tree.left = TreeNode.new(4) symmetric_tree.left.left = TreeNode.new(1) symmetric_tree.right = TreeNode.new(4) symmetric_tree.right.right = TreeNode.new(1) symmetric?(symmetric_tree) ? puts('working as expected') : puts('not working as expected') # sample tree 2 ==> symmetric? => false # 5 # 3 3 # 2 2 asymmetric_tree = TreeNode.new(5) asymmetric_tree.left = TreeNode.new(3) asymmetric_tree.right = TreeNode.new(3) asymmetric_tree.left.left = TreeNode.new(2) asymmetric_tree.right.left = TreeNode.new(2) !symmetric?(asymmetric_tree) ? puts('working as expected') : puts('not working as expected') # sample tree 3 ==> symmetric? => false # 5 # 3 4 # 2 1 asymmetric_tree = TreeNode.new(5) asymmetric_tree.left = TreeNode.new(3) asymmetric_tree.right = TreeNode.new(4) asymmetric_tree.left.left = TreeNode.new(2) asymmetric_tree.right.right = TreeNode.new(1) !symmetric?(asymmetric_tree) ? puts('working as expected') : puts('not working as expected') ================================================ FILE: Data-Structures/Tree/Binary-Tree/SymmetryBTree.cs ================================================ // C# program to check is binary // tree is symmetric or not using System; class Node { public int key; public Node left, right; public Node(int item) { key = item; left = right = null; } } class GFG { Node root; // returns true if trees with roots // as root1 and root2 are mirror Boolean isMirror(Node node1, Node node2) { // if both trees are empty, // then they are mirror image if (node1 == null && node2 == null) return true; // For two trees to be mirror images, // the following three conditions must be true // 1 - Their root node's key must be same // 2 - left subtree of left tree and right subtree // of right tree have to be mirror images // 3 - right subtree of left tree and left subtree // of right tree have to be mirror images if (node1 != null && node2 != null && node1.key == node2.key) return (isMirror(node1.left, node2.right) && isMirror(node1.right, node2.left)); // if neither of the above conditions // is true then root1 and root2 are // mirror images return false; } // returns true if the tree is symmetric // i.e mirror image of itself Boolean isSymmetric(Node node) { // check if tree is mirror of itself return isMirror(root, root); } // Driver Code static public void Main(String[] args) { GFG tree = new GFG(); tree.root = new Node(1); tree.root.left = new Node(2); tree.root.right = new Node(2); tree.root.left.left = new Node(3); tree.root.left.right = new Node(4); tree.root.right.left = new Node(4); tree.root.right.right = new Node(3); Boolean output = tree.isSymmetric(tree.root); if (output == true) Console.WriteLine("1"); else Console.WriteLine("0"); } } ================================================ FILE: Data-Structures/Tree/Binary-Tree/SymmetryBTree.py ================================================ # Node structure class TreeNode: def __init__(self, val=0, left=None, right=None): """" Creates a new tree node :param val: Value of the node :param left: Node on the left :param right: Node on the right """ self.val = val self.left = left self.right = right def isMirror(root1, root2): """" Returns True if trees with roots as root1 and root 2 are mirror :param root1: TreeNode :param root2: TreeNode """ # If both trees are empty, then they are mirror images if root1 is None and root2 is None: return True """ For two trees to be mirror images, the following three conditions must be true 1 - Their root node's key must be same 2 - left subtree of left tree and right subtree of the right tree have to be mirror images 3 - right subtree of left tree and left subtree of right tree have to be mirror images """ if (root1 is not None and root2 is not None): if root1.val == root2.val: return (isMirror(root1.left, root2.right)and isMirror(root1.right, root2.left)) # If neither of the above conditions is true then root1 # and root2 are not mirror images return False def isSymmetric(root: TreeNode): """ Checks if the tree is mirror of itself :param root: Tree Node """ # Check if tree is mirror of itself return isMirror(root, root) # Driver Program # Let's construct the tree show in the above figure root = TreeNode(1) root.left = TreeNode(2) root.right = TreeNode(2) root.left.left = TreeNode(3) root.left.right = TreeNode(4) root.right.left = TreeNode(4) root.right.right = TreeNode(3) print("1" if isSymmetric(root) == True else "0") # This code is contributed by Nikhil Kumar Singh(nickzuck_007) ================================================ FILE: Data-Structures/Tree/Binary-Tree/Two_level_Node/two_level_Node.cpp ================================================ #include using namespace std; /* A binary tree Node has key, pointer to left and right children */ struct Node { int key; struct Node* left, *right; }; /* Given a binary tree, print nodes from level number 'low' to level number 'high'*/ void printLevels(Node* root, int low, int high) { queue Q; Node *marker = new Node; // Marker node to indicate end of level int level = 1; // Initialize level number // Enqueue the only first level node and marker node for end of level Q.push(root); Q.push(marker); // Simple level order traversal loop while (Q.empty() == false) { // Remove the front item from queue Node *n = Q.front(); Q.pop(); // Check if end of level is reached if (n == marker) { // print a new line and increment level number cout << endl; level++; // Check if marker node was last node in queue or // level number is beyond the given upper limit if (Q.empty() == true || level > high) break; // Enqueue the marker for end of next level Q.push(marker); // If this is marker, then we don't need print it // and enqueue its children continue; } // If level is equal to or greater than given lower level, // print it if (level >= low) cout << n->key << " "; // Enqueue children of non-marker node if (n->left != NULL) Q.push(n->left); if (n->right != NULL) Q.push(n->right); } } /* Helper function that allocates a new Node with the given key and NULL left and right pointers. */ Node* newNode(int key) { Node* temp = new Node; temp->key = key; temp->left = temp->right = NULL; return (temp); } /* Driver program to test above functions*/ int main() { // Let us construct the BST shown in the above figure struct Node *root = newNode(20); root->left = newNode(8); root->right = newNode(22); root->left->left = newNode(4); root->left->right = newNode(12); root->left->right->left = newNode(10); root->left->right->right = newNode(14); cout << "Level Order traversal between given two levels is"; printLevels(root, 2, 3); return 0; } ================================================ FILE: Data-Structures/Tree/Binary-Tree/Two_level_Node.java ================================================ // Java program to print Nodes level by level between given two levels import java.util.LinkedList; import java.util.Queue; /* A binary tree Node has key, pointer to left and right children */ class Node { int data; Node left, right; public Node(int item) { data = item; left = right = null; } } class BinaryTree { Node root; /* Given a binary tree, print nodes from level number 'low' to level number 'high'*/ void printLevels(Node node, int low, int high) { Queue Q = new LinkedList<>(); Node marker = new Node(4); // Marker node to indicate end of level int level = 1; // Initialize level number // Enqueue the only first level node and marker node for end of level Q.add(node); Q.add(marker); // Simple level order traversal loop while (Q.isEmpty() == false) { // Remove the front item from queue Node n = Q.peek(); Q.remove(); // Check if end of level is reached if (n == marker) { // print a new line and increment level number System.out.println(""); level++; // Check if marker node was last node in queue or // level number is beyond the given upper limit if (Q.isEmpty() == true || level > high) break; // Enqueue the marker for end of next level Q.add(marker); // If this is marker, then we don't need print it // and enqueue its children continue; } // If level is equal to or greater than given lower level, // print it if (level >= low) System.out.print( n.data + " "); // Enqueue children of non-marker node if (n.left != null) Q.add(n.left); if (n.right != null) Q.add(n.right); } } // Driver program to test for above functions public static void main(String args[]) { BinaryTree tree = new BinaryTree(); tree.root = new Node(20); tree.root.left = new Node(8); tree.root.right = new Node(22); tree.root.left.left = new Node(4); tree.root.left.right = new Node(12); tree.root.left.right.left = new Node(10); tree.root.left.right.right = new Node(14); System.out.print("Level Order traversal between given two levels is "); tree.printLevels(tree.root, 2, 3); } } ================================================ FILE: Data-Structures/Tree/Binary-Tree/VerticalOrderTraversal.java ================================================ /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val = val; } * TreeNode(int val, TreeNode left, TreeNode right) { * this.val = val; * this.left = left; * this.right = right; * } * } */ class Solution { public List> verticalTraversal(TreeNode root) { TreeMap>> xCoord = new TreeMap(); view(root, 0, 0, xCoord); List> list = new ArrayList>(); for(Integer i: xCoord.keySet()){ TreeMap> yCoord = xCoord.get(i); List arr = new ArrayList(); for(Integer j: yCoord.keySet()){ TreeSet keys = yCoord.get(j); for(Integer k: keys) arr.add(k); } list.add(arr); } return list; } public void view(TreeNode root, int x, int y, TreeMap>> xCoord){ if(root==null) return; TreeMap> yCoord = xCoord.getOrDefault(x, new TreeMap>()); TreeSet keys = yCoord.getOrDefault(y, new TreeSet()); keys.add(root.val); yCoord.put(y, keys); xCoord.put(x, yCoord); view(root.left, x-1, y+1, xCoord); view(root.right, x+1, y+1, xCoord); } } ================================================ FILE: Data-Structures/Tree/Binary-Tree/VerticalOrderTraversal.py ================================================ # submission by liamm91 class TreeNode: def __init__(self, val=None, left=None, right=None): self._val = val self._left = left self._right = right # determining coords self._x = self._y = 0 def insertNode(self, node): if node.val: # if there is a value if self.val < node.val: # insert to the right if self.right: # node exists self.right.insertNode(node) else: # node doesn't exist self.right = node self.right.x = self.x + 1 self.right.y = self.y - 1 else: # insert to the left if self.left: # node exists self.left.insertNode(node) else: # node doesn't exist self.left = node self.left.x = self.x - 1 self.left.y = self.y - 1 # properties @property def y(self): return self._y @y.setter def y(self, new_y): self._y = new_y @property def x(self): return self._x @x.setter def x(self, new_x): self._x = new_x @property def left(self): return self._left @left.setter def left(self, left_node): self._left = left_node @property def right(self): return self._right @right.setter def right(self, right_node): self._right = right_node @property def val(self): return self._val @val.setter def val(self, new_val): self._val = new_val def traverse(self): if self.left: self.left.traverse() print(self) if self.right: self.right.traverse() def __str__(self): return "Node at x: %d, y: %d with value %d" % (self.x, self.y, self.val) class BinaryTree: def __init__(self, head: TreeNode=None): self.head = head self.vot = [self.head] def insertNode(self, node: TreeNode): if not self.head: # if head doesn't exist self.head = node self.head.x = self.head.y = 0 else: # head exists self.head.insertNode(node) def vertical_order_traverse(self): self.vot = [self.head] # reinitializing the list incase self.head is None def __group_nodes(arr_nodes): r = t = [] # init vars for node in arr_nodes: # looping thru the array if t: # if there are nodes in the temp list if t[0].x == node.x: # if the x pos of the node t.append(node) # add the node to the temp list else: # if the x pos between the node and list differ for n in t: t[t.index(n)] = n.val # converting nodes into their values r.append((t[0], t)[len(t) > 1]) # adding the temp list to the return array t = [node] # putting the temp list to the new node else: t = [node] # putting the temp list to thte new node if t: r.append(t[0].val) # if there are left over nodes, convert and add return r def __getsides(self, node): # recusive function to return all node in the tree l, r = node.left, node.right if l: self.vot.append(l) # appending node to the master list __getsides(self, l) if r: self.vot.append(r) # appending node to the master list __getsides(self, r) __getsides(self, self.head) # starting recursive function # sorting all the nodes self.vot.sort(key=lambda node: node.x) self.vot = __group_nodes(self.vot) # returning vertical traverse order return self.vot def main(): nums = [] print("Input numbers in to the array, the first number you put in will be the root of the tree. \nIf you input a non integer value, the Vertical Order Traversal will start.") while True: to_input = input(">: ") try: nums.append(float(to_input)) except Exception as e: print("Bad value") break tree = BinaryTree() for num in nums: tree.insertNode(TreeNode(num)) #tree.head.traverse() print(tree.vertical_order_traverse()) if __name__ == "__main__": main() ================================================ FILE: Data-Structures/Tree/Binary-Tree/Vertical_Sum/Verticle_sum_of_BinaryTree.java ================================================ import java.util.TreeMap; // Class for a tree node class TreeNode { // data members private int key; private TreeNode left; private TreeNode right; // Accessor methods public int key() { return key; } public TreeNode left() { return left; } public TreeNode right() { return right; } // Constructor public TreeNode(int key) { this.key = key; left = null; right = null; } // Methods to set left and right subtrees public void setLeft(TreeNode left) { this.left = left; } public void setRight(TreeNode right) { this.right = right; } } // Class for a Binary Tree class Tree { private TreeNode root; // Constructors public Tree() { root = null; } public Tree(TreeNode n) { root = n; } // Method to be called by the consumer classes // like Main class public void VerticalSumMain() { VerticalSum(root); } // A wrapper over VerticalSumUtil() private void VerticalSum(TreeNode root) { // base case if (root == null) { return; } // Creates an empty TreeMap hM TreeMap hM = new TreeMap(); // Calls the VerticalSumUtil() to store the // vertical sum values in hM VerticalSumUtil(root, 0, hM); // Prints the values stored by VerticalSumUtil() if (hM != null) { System.out.println(hM.entrySet()); } } // Traverses the tree in in-order form and builds // a hashMap hM that contains the vertical sum private void VerticalSumUtil(TreeNode root, int hD, TreeMap hM) { // base case if (root == null) { return; } // Store the values in hM for left subtree VerticalSumUtil(root.left(), hD - 1, hM); // Update vertical sum for hD of this node int prevSum = (hM.get(hD) == null) ? 0 : hM.get(hD); hM.put(hD, prevSum + root.key()); // Store the values in hM for right subtree VerticalSumUtil(root.right(), hD + 1, hM); } } // Driver class to test the verticalSum methods public class Main { public static void main(String[] args) { /* Create any Binary Tree for eg- 1 / \ 2 3 / \ / \ 4 5 6 7 */ TreeNode root = new TreeNode(1); root.setLeft(new TreeNode(2)); root.setRight(new TreeNode(3)); root.left().setLeft(new TreeNode(4)); root.left().setRight(new TreeNode(5)); root.right().setLeft(new TreeNode(6)); root.right().setRight(new TreeNode(7)); Tree t = new Tree(root); System.out.println("Following are the values of" + " vertical sums with the positions" + " of the columns with respect to root "); t.VerticalSumMain(); } } ================================================ FILE: Data-Structures/Tree/Binary-Tree/Vertical_Sum/Verticle_sum_of_Binary_Tree.cpp ================================================ #include using namespace std; struct TNode{ int key; struct TNode *left, *right; }; TNode* newTNode(int key) { TNode* temp = new TNode; temp->key = key; temp->left = temp->right = NULL; return temp; } struct LLNode{ int key; struct LLNode *prev, *next; }; LLNode* newLLNode(int key) { LLNode* temp = new LLNode; temp->key = key; temp->prev = temp->next = NULL; return temp; } void verticalSumDLLUtil(TNode *root, LLNode *sumNode) { sumNode->key = sumNode->key + root->key; if(root->left) { if(sumNode->prev == NULL) { sumNode->prev = newLLNode(0); sumNode->prev->next = sumNode; } verticalSumDLLUtil(root->left, sumNode->prev); } if(root->right) { if(sumNode->next == NULL) { sumNode->next = newLLNode(0); sumNode->next->prev = sumNode; } verticalSumDLLUtil(root->right, sumNode->next); } } void verticalSumDLL(TNode* root) { LLNode* sumNode = newLLNode(0); verticalSumDLLUtil(root, sumNode); while(sumNode->prev != NULL){ sumNode = sumNode->prev; } while(sumNode != NULL){ cout << sumNode->key <<" "; sumNode = sumNode->next; } } int main() { TNode *root = newTNode(1); root->left = newTNode(2); root->right = newTNode(3); root->left->left = newTNode(4); root->left->right = newTNode(5); root->right->left = newTNode(6); root->right->right = newTNode(7); cout << "Vertical Sums are\n"; verticalSumDLL(root); return 0; } ================================================ FILE: Data-Structures/Tree/Binary-Tree/b_tree.cpp ================================================ // Searching a key on a B-tree in C++ #include using namespace std; class TreeNode { int *keys; int t; TreeNode **C; int n; bool leaf; public: TreeNode(int temp, bool bool_leaf); void insertNonFull(int k); void splitChild(int i, TreeNode *y); void traverse(); TreeNode *search(int k); friend class BTree; }; class BTree { TreeNode *root; int t; public: BTree(int temp) { root = NULL; t = temp; } void traverse() { if (root != NULL) root->traverse(); } TreeNode *search(int k) { return (root == NULL) ? NULL : root->search(k); } void insert(int k); }; TreeNode::TreeNode(int t1, bool leaf1) { t = t1; leaf = leaf1; keys = new int[2 * t - 1]; C = new TreeNode *[2 * t]; n = 0; } void TreeNode::traverse() { int i; for (i = 0; i < n; i++) { if (leaf == false) C[i]->traverse(); cout << " " << keys[i]; } if (leaf == false) C[i]->traverse(); } TreeNode *TreeNode::search(int k) { int i = 0; while (i < n && k > keys[i]) i++; if (keys[i] == k) return this; if (leaf == true) return NULL; return C[i]->search(k); } void BTree::insert(int k) { if (root == NULL) { root = new TreeNode(t, true); root->keys[0] = k; root->n = 1; } else { if (root->n == 2 * t - 1) { TreeNode *s = new TreeNode(t, false); s->C[0] = root; s->splitChild(0, root); int i = 0; if (s->keys[0] < k) i++; s->C[i]->insertNonFull(k); root = s; } else root->insertNonFull(k); } } void TreeNode::insertNonFull(int k) { int i = n - 1; if (leaf == true) { while (i >= 0 && keys[i] > k) { keys[i + 1] = keys[i]; i--; } keys[i + 1] = k; n = n + 1; } else { while (i >= 0 && keys[i] > k) i--; if (C[i + 1]->n == 2 * t - 1) { splitChild(i + 1, C[i + 1]); if (keys[i + 1] < k) i++; } C[i + 1]->insertNonFull(k); } } void TreeNode::splitChild(int i, TreeNode *y) { TreeNode *z = new TreeNode(y->t, y->leaf); z->n = t - 1; for (int j = 0; j < t - 1; j++) z->keys[j] = y->keys[j + t]; if (y->leaf == false) { for (int j = 0; j < t; j++) z->C[j] = y->C[j + t]; } y->n = t - 1; for (int j = n; j >= i + 1; j--) C[j + 1] = C[j]; C[i + 1] = z; for (int j = n - 1; j >= i; j--) keys[j + 1] = keys[j]; keys[i] = y->keys[t - 1]; n = n + 1; } int main() { BTree t(3); t.insert(8); t.insert(9); t.insert(10); t.insert(11); t.insert(15); t.insert(16); t.insert(17); t.insert(18); t.insert(20); t.insert(23); cout << "The B-tree is: "; t.traverse(); int k = 10; (t.search(k) != NULL) ? cout << endl << k << " is found" : cout << endl << k << " is not Found"; k = 2; (t.search(k) != NULL) ? cout << endl << k << " is found" : cout << endl << k << " is not Found\n"; } ================================================ FILE: Data-Structures/Tree/Binary-Tree/b_tree.java ================================================ public class BTree { private int T; // Node creation public class Node { int n; int key[] = new int[2 * T - 1]; Node child[] = new Node[2 * T]; boolean leaf = true; public int Find(int k) { for (int i = 0; i < this.n; i++) { if (this.key[i] == k) { return i; } } return -1; }; } public BTree(int t) { T = t; root = new Node(); root.n = 0; root.leaf = true; } private Node root; // Search key private Node Search(Node x, int key) { int i = 0; if (x == null) return x; for (i = 0; i < x.n; i++) { if (key < x.key[i]) { break; } if (key == x.key[i]) { return x; } } if (x.leaf) { return null; } else { return Search(x.child[i], key); } } // Splitting the node private void Split(Node x, int pos, Node y) { Node z = new Node(); z.leaf = y.leaf; z.n = T - 1; for (int j = 0; j < T - 1; j++) { z.key[j] = y.key[j + T]; } if (!y.leaf) { for (int j = 0; j < T; j++) { z.child[j] = y.child[j + T]; } } y.n = T - 1; for (int j = x.n; j >= pos + 1; j--) { x.child[j + 1] = x.child[j]; } x.child[pos + 1] = z; for (int j = x.n - 1; j >= pos; j--) { x.key[j + 1] = x.key[j]; } x.key[pos] = y.key[T - 1]; x.n = x.n + 1; } // Inserting a value public void Insert(final int key) { Node r = root; if (r.n == 2 * T - 1) { Node s = new Node(); root = s; s.leaf = false; s.n = 0; s.child[0] = r; Split(s, 0, r); insertValue(s, key); } else { insertValue(r, key); } } // Insert the node final private void insertValue(Node x, int k) { if (x.leaf) { int i = 0; for (i = x.n - 1; i >= 0 && k < x.key[i]; i--) { x.key[i + 1] = x.key[i]; } x.key[i + 1] = k; x.n = x.n + 1; } else { int i = 0; for (i = x.n - 1; i >= 0 && k < x.key[i]; i--) { } ; i++; Node tmp = x.child[i]; if (tmp.n == 2 * T - 1) { Split(x, i, tmp); if (k > x.key[i]) { i++; } } insertValue(x.child[i], k); } } public void Show() { Show(root); } // Display private void Show(Node x) { assert (x == null); for (int i = 0; i < x.n; i++) { System.out.print(x.key[i] + " "); } if (!x.leaf) { for (int i = 0; i < x.n + 1; i++) { Show(x.child[i]); } } } // Check if present public boolean Contain(int k) { if (this.Search(root, k) != null) { return true; } else { return false; } } public static void main(String[] args) { BTree b = new BTree(3); b.Insert(8); b.Insert(9); b.Insert(10); b.Insert(11); b.Insert(15); b.Insert(20); b.Insert(17); b.Show(); if (b.Contain(12)) { System.out.println("\nfound"); } else { System.out.println("\nnot found"); } ; } } ================================================ FILE: Data-Structures/Tree/Binary-Tree/b_tree.js ================================================ 'use strict'; /* * JavaScript Implementation of a B tree, multi-way tree * m - order of tree ≈ max number of children * * nodes are split with left-bias, * - nodes that don't split evenly in two (after removing middle key) * - the left side will have one more key than the right side * * */ function btree(order) { let maxKeys = order-1; let root = null; return { root() { return root; }, setRoot(newRoot) { root = newRoot; return this }, maxKeys() { return maxKeys; }, isEmpty(){ return (root === null) }, exists(item, node = root){ if (root === null) return false; if (node.contains(item)) return true; if (node.isLeaf) return false; return (this.exists(item, node.child[node.subTree(item)])); }, find(item, node){ // return node that contains item or // the leaf node where item will be inserted if (root === null) return false; if ((node.isLeaf) || (node.contains(item))) { return node; } else { let pos = node.subTree(item); return this.find(item, node.child[pos]); } }, insert(item){ // insert item into tree if(this.root() === null) { this.setRoot(makeNode()); this.root().keys.push(item); } else { // get leaf to insert item into, unless already in tree let node = this.find(item, this.root()); if (!node.contains(item)) { node.leafInsert(item); // balance(tree, node); this.balance(node); } else { console.log(`${item} already in tree`); return false; } } return true; }, insertPoint(node, key) { let index = node.keys.findIndex((e) => e > key); let pos = (index === -1) ? node.keyCount() : index; return pos; }, merge(key, parent, left, right) { let pos = this.insertPoint(parent, key); parent.keys.splice(pos, 0, key); parent.child[pos] = left; parent.child.splice(pos+1, 0, right); right.parent = parent; return parent; }, split(node) { let [left, midKey, right] = this.getParts(node); let parent = left.parent; // did we split the root? if (parent === null) { parent = this.increaseHeight(left, right, midKey); } else { // merge midKey into parent node, update links parent = this.merge(midKey, parent, left, right); } return parent; }, getParts(node) { // newNode will hold right half of node let middle = node.midPoint(); let newNode = makeNode(); newNode.keys = node.keys.splice(middle+1); let midKey = node.keys.pop() if (!node.isLeaf) { newNode.isLeaf = false; newNode.child = node.child.splice(middle + 1); newNode.child.forEach((e) => { e.parent = newNode; }) } return [node, midKey, newNode]; }, balance (node) { if (node.keyCount() > this.maxKeys()) { this.balance(this.split(node)); } }, increaseHeight(left, right, key) { let newRoot = makeNode(); newRoot.parent === null; newRoot.isLeaf = false; this.setRoot(newRoot); newRoot.keys.push(key); newRoot.child[0] = left; newRoot.child[1] = right; // parent of the just split nodes ≈≈ new root left.parent = newRoot; right.parent = newRoot; return newRoot; }, // tree.traverse().inOrder().toArray(); traverse() { let items = []; let list = ''; let root = this.root(); return { inOrder : function(node = root){ if (node.isLeaf) { node.keys.forEach((k) => { items.push(k) } ); node.keys.forEach((k) => { list += k + ', ' } ); return this; } else { // visit left child, then root, then recurse for(let i = 0; i < node.keyCount(); i++) { this.inOrder(node.child[i]) items.push(node.keys[i]); list += node.keys[i] + ', '; } // print last right child this.inOrder(node.child[node.keyCount()]); } return this; }, toArray : function() { return items; }, toList : function() { // remove trailing whitespace & comma return list.trim().slice(0,-1); } } } } } function makeNode() { return { isLeaf: true, parent: null, keys: [], // max: m-1 child: [], // max: m keyCount() { return this.keys.length; }, midPoint() { return Math.floor(this.keys.length/2); }, contains(item) { return (this.keys.includes(item)) }, // returns index of child[] ≈≈ the subTree to search for item subTree(item){ if(item < this.keys[0]) { return 0; } else { let index = this.keys.findIndex((e) => e > item); return (index === -1) ? this.keyCount() : index; } }, // insert item into leaf node, then sort leafInsert(item) { this.keys.push(item); this.keys.sort((a,b) => ((ab) ? 1: 0))); }, } } // sample test /* const tree = btree(3); let a1 = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,20]; let a2 = [100,90,80,70,60,50,40,30,20,10,15,25,35,45,55,65,75,85,95]; let a3 = [4,2,7,1,5,3,8]; let a = a2; a.forEach((e) => { tree.insert(e); console.log(tree.traverse().inOrder().toList()); }); console.log(tree.traverse().inOrder().toArray()); */ // Interactive sample run const readline = require("readline"); const rl = readline.createInterface({ input: process.stdin, output: process.stdout }); console.log(); console.log("Enter order of tree on first line."); console.log("Enter numbers to insert, one per line."); console.log("^c to end input"); console.log(); let input = []; rl.on('line', function (line) { input.push(parseInt(line, 10)); }); rl.on('close', function (l) { let order = input.shift(); const tree = btree(order); input.forEach((e) => { tree.insert(e); }); console.log(`Tree order: ${order}`) console.log(`In order traversal:`) console.log(tree.traverse().inOrder().toList()); process.exit(0); }); module.exports.btree = btree; ================================================ FILE: Data-Structures/Tree/Binary-Tree/b_tree.py ================================================ class BTreeNode: def __init__(self, leaf=False): self.leaf = leaf self.keys = [] self.child = [] class BTree: def __init__(self, t): self.root = BTreeNode(True) self.t = t # Print the tree def print_tree(self, x, l=0): print("Level ", l, " ", len(x.keys), end=":") for i in x.keys: print(i, end=" ") print() l += 1 if len(x.child) > 0: for i in x.child: self.print_tree(i, l) # Search key def search_key(self, k, x=None): if x is not None: i = 0 while i < len(x.keys) and k > x.keys[i][0]: i += 1 if i < len(x.keys) and k == x.keys[i][0]: return (x, i) elif x.leaf: return None else: return self.search_key(k, x.child[i]) else: return self.search_key(k, self.root) # Insert the key def insert_key(self, k): root = self.root if len(root.keys) == (2 * self.t) - 1: temp = BTreeNode() self.root = temp temp.child.insert_key(0, root) self.split(temp, 0) self.insert_non_full(temp, k) else: self.insert_non_full(root, k) # Insert non full condition def insert_non_full(self, x, k): i = len(x.keys) - 1 if x.leaf: x.keys.append((None, None)) while i >= 0 and k[0] < x.keys[i][0]: x.keys[i + 1] = x.keys[i] i -= 1 x.keys[i + 1] = k else: while i >= 0 and k[0] < x.keys[i][0]: i -= 1 i += 1 if len(x.child[i].keys) == (2 * self.t) - 1: self.split(x, i) if k[0] > x.keys[i][0]: i += 1 self.insert_non_full(x.child[i], k) # Split def split(self, x, i): t = self.t y = x.child[i] z = BTreeNode(y.leaf) x.child.insert_key(i + 1, z) x.keys.insert_key(i, y.keys[t - 1]) z.keys = y.keys[t: (2 * t) - 1] y.keys = y.keys[0: t - 1] if not y.leaf: z.child = y.child[t: 2 * t] y.child = y.child[0: t - 1] def main(): B = BTree(3) for i in range(10): B.insert_key((i, 2 * i)) B.print_tree(B.root) if B.search_key(8) is not None: print("\nFound") else: print("\nNot found") if __name__ == '__main__': main() ================================================ FILE: Data-Structures/Tree/Binary-Tree/binary_tree_trans.cpp ================================================ #include using namespace std; struct Node { struct Node* left; struct Node* right; int data; Node(int data) { this->data = data; this->left = NULL; this->right = NULL; } }; int height(struct Node* root) { if (root == NULL) return 0; int lheight = height(root->left); int rheight = height(root->right); return max(1 + lheight, 1 + rheight); } void leftToRight(struct Node* root, int level) { if (root == NULL) return; if (level == 1) cout << root->data << " "; else if (level > 1) { leftToRight(root->left, level - 1); leftToRight(root->right, level - 1); } } void rightToLeft(struct Node* root, int level) { if (root == NULL) return; if (level == 1) cout << root->data << " "; else if (level > 1) { rightToLeft(root->right, level - 1); rightToLeft(root->left, level - 1); } } int main() { struct Node* root = new Node(1); root->left = new Node(2); root->right = new Node(3); root->left->left = new Node(4); root->right->left = new Node(5); root->right->right = new Node(7); root->left->left->left = new Node(10); root->left->left->right = new Node(11); root->right->right->left = new Node(8); int i = 1; int j = height(root); int flag = 0; while (i <= j) { if (flag == 0) { rightToLeft(root, i); flag = 1; i++; } else { leftToRight(root, j); flag = 0; j--; } } return 0; } ================================================ FILE: Data-Structures/Tree/Binary-Tree/duplicate_values.cpp ================================================ #include using namespace std; //Definition of Binary Tree node- struct TreeNode { int val; struct TreeNode* left; struct TreeNode* right; }; //Utility function- struct TreeNode* newNode(int val) { struct TreeNode* node = new TreeNode; node->val = val; node->left = node->right = NULL; return (node); } bool find(TreeNode* root, unordered_set &s) { // If tree is empty, there are no duplicates if (root == NULL) return false; // If current node's data is already present, ie. duplicate found- if (s.find(root->val) != s.end()) return true; // If not found, insert current node- s.insert(root->data); // Recursively check in left and right subtrees- return find(root->left, s)||find(root->right, s); } bool isDup(struct TreeNode* root) { unordered_set s; return find(root, s); } int main() { struct TreeNode* root = newNode(1); root->left = newNode(2); root->right = newNode(2); root->left->left = newNode(3); if (isDup(root)) return 1; return 0; } ================================================ FILE: Data-Structures/Tree/Binary-Tree/duplicate_values.py ================================================ class newNode: # Construct to create a new node def __init__(self, key): self.data = key self.left = None self.right = None def checkDupUtil( root, s) : # If tree is empty, there are no # duplicates. if (root == None) : return False # If current node's data is already present. if root.data in s: return True # Insert current node s.add(root.data) # Recursively check in left and right # subtrees. return checkDupUtil(root.left, s) or checkDupUtil(root.right, s) # To check if tree has duplicates def checkDup( root) : s=set() return checkDupUtil(root, s) # Driver Code if __name__ == '__main__': root = newNode(10) root.left = newNode(5) root.right = newNode(20) root.left.left = newNode(20) if (checkDup(root)): print("Yes") else: print("No") ================================================ FILE: Data-Structures/Tree/Binary-Tree/duplicate_values.rb ================================================ # simple bst implementation class BST attr_accessor :head # simple bst node implementation class Node attr_accessor :left attr_accessor :right attr_accessor :value def initialize(val) @value = val end end # bst constructor def initialize(val) @head = Node.new(val) end # method for inserting new values into a given bst def self.insert(val, tree) if not tree then return Node.new(val) else if val > tree.value then tree.right = insert(val, tree.right) else tree.left = insert(val, tree.left) end end tree end # method to check for duplicates def self.duplicates?(tree, prev_vals = []) # base case, if null leaf reached this path had no duplicates if not tree then return true # otherwise, check if current value is a duplicate elsif prev_vals.include? tree.value then return false end # if curr value is unique, add it to prev values tracker prev_vals << tree.value # then recurse duplicates?(tree.left) && duplicates?(tree.right) end # simple bst print method for printing (unbalanced trees may look odd) def self.printTree(tree, level = 0) if not tree then return else if level == 0 then puts tree.value elsif level == 1 then print "#{tree.value} " else puts " #{tree.value}" end printTree(tree.left, 1) printTree(tree.right, 2) end end end # simple integer input example, takes three int inputs puts "Please input three integers for an example." b = BST.new((gets).to_i) BST.insert((gets).to_i, b.head) BST.insert((gets).to_i, b.head) puts "Example tree~" BST.printTree(b.head) # then checks for duplicates puts "Duplicates? ~" puts BST.duplicates?(b.head) ================================================ FILE: Data-Structures/Tree/Binary-Tree/subtree_check.cpp ================================================ #include using namespace std; // Basic node structure of a binary tree class node { public: int data; node* left; node* right; }; // Helper function to grow the tree node* newNode(int data) { // allocate memory and assign data node* Node = new node(); Node->data = data; // point left and right Node pointers to NULL Node->left = NULL; Node->right = NULL; return(Node); } // Recursive Function to check whether trees // with roots as root1 and root2 // are identical or not bool areIdentical(node * root1, node *root2) { // if both trees are null then they are // identical trivially if (root1 == NULL && root2 == NULL) return true; // if either tree is identical then they // non identical if (root1 == NULL || root2 == NULL) return false; // check if data of both roots is same if (root1->data == root2->data) { // recursive definition to traverse through // both trees return (areIdentical(root1->left, root2->left) && areIdentical(root1->right, root2->right)); } // if data is not same then return false else { return false; } } // Recursive Main function which returns true if S // is a subtree of T, otherwise false bool isSubtree(node *T, node *S) { // base cases if (S == NULL) return true; if (T == NULL) return false; // Check the tree with root as current node if (areIdentical(T, S)) return true; // recursive definition to traverse through // the main tree to find identical subtree return isSubtree(T->left, S) || isSubtree(T->right, S); } int main() { // Driver code taken from GFG // TREE 1 /* Construct the following tree 26 / \ 10 3 / \ \ 4 6 3 \ 30 */ node *T = newNode(26); T->right = newNode(3); T->right->right = newNode(3); T->left = newNode(10); T->left->left = newNode(4); T->left->left->right = newNode(30); T->left->right = newNode(6); // TREE 2 /* Construct the following tree 10 / \ 4 6 \ 30 */ node *S = newNode(10); S->right = newNode(6); S->left = newNode(4); S->left->right = newNode(30); if (isSubtree(T, S)) cout << "Tree 2 is subtree of Tree 1"; else cout << "Tree 2 is not a subtree of Tree 1"; return 0; } ================================================ FILE: Data-Structures/Tree/Binary-Tree/symmetry_bTree.cpp ================================================ //Definition for binary tree- struct TreeNode { int val; TreeNode *left; TreeNode *right; }; //Utility function- TreeNode *newNode(int val) { TreeNode *temp = new Node; temp->val = val; temp->left = temp->right = NULL; return (temp); } int check(TreeNode* A, TreeNode* B){ if(A==NULL && B==NULL) return 1; //one is NULL, other is not, ie. Asymmetric- if(A==NULL || B==NULL) return 0; //unequal values, ie. Asymmetric- if(A->val != B->val) return 0; //checking all subtrees using recursion- if(check(A->left, B->right) && check(A->right, B->left)) return 1; //Asymmetric- return 0; } int isSymmetric(TreeNode* A) { //null tree is considered symmetric- if(A==NULL) return 1; return check(A->left, A->right); } int main() { TreeNode *root = newNode(1); root->left = newNode(2); root->right = newNode(2); root->left->left = newNode(3); root->left->right = newNode(4); root->right->left = newNode(4); root->right->right = newNode(3); return isSymmetric(root); } ================================================ FILE: Data-Structures/Tree/Binary-Tree/two_level_node.py ================================================ class Node: # Constructor tor create a new node def __init__(self, key): self.key = key self.left = None self.right = None def printLevels(root, low, high): Q = [] marker = Node(11114) # Marker node to indicate end of level level = 1 # Initialize level number # Enqueue the only first level node and marker node for # end of level Q.append(root) Q.append(marker) #print Q # Simple level order traversal loop while(len(Q) >0): # Remove the front item from queue n = Q[0] Q.pop(0) #print Q # Check if end of level is reached if n == marker: # print a new line and increment level number print level += 1 # Check if marker node was last node in queue # or level nubmer is beyond the given upper limit if len(Q) == 0 or level > high: break # Enqueue the marker for end of next level Q.append(marker) # If this is marker, then we don't need print it # and enqueue its children continue if level >= low: print n.key, # Enqueue children of non-marker node if n.left is not None: Q.append(n.left) Q.append(n.right) # Driver program to test the above function root = Node(20) root.left = Node(8) root.right = Node(22) root.left.left = Node(4) root.left.right = Node(12) root.left.right.left = Node(10) root.left.right.right = Node(14) print "Level Order Traversal between given two levels is", printLevels(root,2,3) ================================================ FILE: Data-Structures/Tree/Expression Tree/Expression_Tree.cpp ================================================ /* Author: adi1212 */ /*Problem Statement : Construct an Expression Tree from postfix and prefix expression. Perform recursive and nonrecursive In-order, pre-order and post-order traversals. */ #include using namespace std; struct dll { char data; dll *left; dll *right; }; void levelorder(dll *root) { if(root==NULL) return; queue p; p.push(root); int count=1; while(!p.empty()) { if(count==0) { cout<<"\n"; count=p.size(); } dll *q = p.front(); cout<data<<"\t"; if(q->left!=NULL) p.push(q->left); if(q->right!=NULL) p.push(q->right); p.pop(); count--; } } void Rpreorder(dll *root) //Recursive preorder { if(root!=NULL) { cout<data<<"\t"; Rpreorder(root->left); Rpreorder(root->right); } } void NRpreorder(dll *root) //non-Recursive preorder { stack s; while(!s.empty() || root!=NULL) { while(root!=NULL) { cout<data<<"\t"; s.push(root); root=root->left; } root=s.top(); s.pop(); root=root->right; } } void Rinorder(dll *root) //Recursive inorder { if(root!=NULL) { Rinorder(root->left); cout<data<<"\t"; Rinorder(root->right); } } void NRinorder(dll *root) //non-Recursive inorder { stack s; while(!s.empty() || root!=NULL) { while(root!=NULL) { s.push(root); root=root->left; } root=s.top(); s.pop(); cout<data<<"\t"; root=root->right; } } void Rpostorder(dll *root) //Recursive postorder { if(root==NULL) { return; } Rpostorder(root->left); Rpostorder(root->right); cout<data<<"\t"; } void NRpostorder(dll *root) //non-Recursive postorder { stack s1; stack s2; while(root!=NULL) { s1.push(root); s2.push(0); root=root->left; } while(!s1.empty()) { root=s1.top(); if(s2.top()==1) { s1.pop(); s2.pop(); cout<data<<"\t"; } else { s2.top()=1; root=root->right; while(root!=NULL) { s1.push(root); s2.push(0); root=root->left; } } } } bool isOperator(char c) //checking whether operator { if (c == '+' || c == '-' || c == '*' || c == '/' || c == '^') { return true; } return false; } void trav(dll *root) //tree traversal { int ch; cout<<"\n[1] RECURSIVE PREORDER\n"; cout<<"[2] NON RECURSIVE PREORDER\n"; cout<<"[3] RECURSIVE INORDER\n"; cout<<"[4] NON RECURSIVE INORDER\n"; cout<<"[5] RECURSIVE POSTORDER\n"; cout<<"[6] NON RECURSIVE POSTORDER\n"; do { cout<<"\nEnter your choice: (enter -1 to exit)"; cin>>ch; switch(ch) { case 1: Rpreorder(root); break; case 2: NRpreorder(root); break; case 3: Rinorder(root); break; case 4: NRinorder(root); break; case 5: Rpostorder(root); break; case 6: NRpostorder(root); break; } } while(ch!=-1); } void call1(char s[]) //postfix expression { stack s1; dll *p,*op1,*op2; int i=0; int n=strlen(s); char c; while(idata=s[i]; if(isOperator(s[i])) { op1=s1.top(); s1.pop(); op2=s1.top(); s1.pop(); p->left=op2; p->right=op1; s1.push(p); } else { p->left=NULL; p->right=NULL; s1.push(p); } i++; } p=s1.top(); s1.pop(); cout<<"\nwant to see level order? (TYPE Y if YES)\n"; cin>>c; if(c=='Y' || c=='y') { levelorder(p); } trav(p); } void call2(char s[]) //prefix expression { int i=strlen(s)-1; stack s1; dll *p,*op1,*op2; char c; while(i>=0) { p=new dll; p->data=s[i]; if(isOperator(s[i])) { op2=s1.top(); s1.pop(); op1=s1.top(); s1.pop(); p->left=op2; p->right=op1; s1.push(p); } else { p->left=NULL; p->right=NULL; s1.push(p); } i--; } p=s1.top(); s1.pop(); cout<<"\nwant to see level order? (TYPE Y if YES)\n"; cin>>c; if(c=='Y' || c=='y') { levelorder(p); } trav(p); } int main() { dll *root=NULL; char s[20],n; int ch; do { cout<<"Construct a EXPRESSION TREE from?\n"; cout<<"[1] POSTFIX EXPRESSION\n"; cout<<"[2] PREFIX EXPRESSION\n"; cout<<"\nEnter your choice: (enter 0 to exit)"; cin>>n; if(n=='1') { cout<<"Enter postfix expression: \n"; cin>>s; call1(s); } else if(n=='2') { cout<<"Enter prefix expression: \n"; cin>>s; call2(s); } } while(n!='0'); cout<<"\nOPERATION COMPLETED!! THANK YOU"; return 0; } /* --------------------------------------------------------------------------------------------------------------------------- OUTPUT : Construct a EXPRESSION TREE from? [1] POSTFIX EXPRESSION [2] PREFIX EXPRESSION Enter your choice: (enter 0 to exit)1 Enter postfix expression: AB*CD*+ want to see level order? (TYPE Y if YES) y + * * A B C D [1] RECURSIVE PREORDER [2] NON RECURSIVE PREORDER [3] RECURSIVE INORDER [4] NON RECURSIVE INORDER [5] RECURSIVE POSTORDER [6] NON RECURSIVE POSTORDER Enter your choice: (enter -1 to exit)3 A * B + C * D Enter your choice: (enter -1 to exit)-1 Construct a EXPRESSION TREE from? [1] POSTFIX EXPRESSION [2] PREFIX EXPRESSION Enter your choice: (enter 0 to exit)0 OPERATION COMPLETED!! THANK YOU ...Program finished with exit code 0 Press ENTER to exit console. */ ================================================ FILE: Data-Structures/Tree/Fibonacci-Heap/Fibonacci-Heap.c ================================================ // Operations on a Fibonacci heap in C #include #include #include #include typedef struct _NODE { int key; int degree; struct _NODE *left_sibling; struct _NODE *right_sibling; struct _NODE *parent; struct _NODE *child; bool mark; bool visited; } NODE; typedef struct fibanocci_heap { int n; NODE *min; int phi; int degree; } FIB_HEAP; FIB_HEAP *make_fib_heap(); void insertion(FIB_HEAP *H, NODE *new, int val); NODE *extract_min(FIB_HEAP *H); void consolidate(FIB_HEAP *H); void fib_heap_link(FIB_HEAP *H, NODE *y, NODE *x); NODE *find_min_node(FIB_HEAP *H); void decrease_key(FIB_HEAP *H, NODE *node, int key); void cut(FIB_HEAP *H, NODE *node_to_be_decrease, NODE *parent_node); void cascading_cut(FIB_HEAP *H, NODE *parent_node); void Delete_Node(FIB_HEAP *H, int dec_key); FIB_HEAP *make_fib_heap() { FIB_HEAP *H; H = (FIB_HEAP *)malloc(sizeof(FIB_HEAP)); H->n = 0; H->min = NULL; H->phi = 0; H->degree = 0; return H; } // Printing the heap void print_heap(NODE *n) { NODE *x; for (x = n;; x = x->right_sibling) { if (x->child == NULL) { printf("node with no child (%d) \n", x->key); } else { printf("NODE(%d) with child (%d)\n", x->key, x->child->key); print_heap(x->child); } if (x->right_sibling == n) { break; } } } // Inserting nodes void insertion(FIB_HEAP *H, NODE *new, int val) { new = (NODE *)malloc(sizeof(NODE)); new->key = val; new->degree = 0; new->mark = false; new->parent = NULL; new->child = NULL; new->visited = false; new->left_sibling = new; new->right_sibling = new; if (H->min == NULL) { H->min = new; } else { H->min->left_sibling->right_sibling = new; new->right_sibling = H->min; new->left_sibling = H->min->left_sibling; H->min->left_sibling = new; if (new->key < H->min->key) { H->min = new; } } (H->n)++; } // Find min node NODE *find_min_node(FIB_HEAP *H) { if (H == NULL) { printf(" \n Fibonacci heap not yet created \n"); return NULL; } else return H->min; } // Union operation FIB_HEAP *unionHeap(FIB_HEAP *H1, FIB_HEAP *H2) { FIB_HEAP *Hnew; Hnew = make_fib_heap(); Hnew->min = H1->min; NODE *temp1, *temp2; temp1 = Hnew->min->right_sibling; temp2 = H2->min->left_sibling; Hnew->min->right_sibling->left_sibling = H2->min->left_sibling; Hnew->min->right_sibling = H2->min; H2->min->left_sibling = Hnew->min; temp2->right_sibling = temp1; if ((H1->min == NULL) || (H2->min != NULL && H2->min->key < H1->min->key)) Hnew->min = H2->min; Hnew->n = H1->n + H2->n; return Hnew; } // Calculate the degree int cal_degree(int n) { int count = 0; while (n > 0) { n = n / 2; count++; } return count; } // Consolidate function void consolidate(FIB_HEAP *H) { int degree, i, d; degree = cal_degree(H->n); NODE *A[degree], *x, *y, *z; for (i = 0; i <= degree; i++) { A[i] = NULL; } x = H->min; do { d = x->degree; while (A[d] != NULL) { y = A[d]; if (x->key > y->key) { NODE *exchange_help; exchange_help = x; x = y; y = exchange_help; } if (y == H->min) H->min = x; fib_heap_link(H, y, x); if (y->right_sibling == x) H->min = x; A[d] = NULL; d++; } A[d] = x; x = x->right_sibling; } while (x != H->min); H->min = NULL; for (i = 0; i < degree; i++) { if (A[i] != NULL) { A[i]->left_sibling = A[i]; A[i]->right_sibling = A[i]; if (H->min == NULL) { H->min = A[i]; } else { H->min->left_sibling->right_sibling = A[i]; A[i]->right_sibling = H->min; A[i]->left_sibling = H->min->left_sibling; H->min->left_sibling = A[i]; if (A[i]->key < H->min->key) { H->min = A[i]; } } if (H->min == NULL) { H->min = A[i]; } else if (A[i]->key < H->min->key) { H->min = A[i]; } } } } // Linking void fib_heap_link(FIB_HEAP *H, NODE *y, NODE *x) { y->right_sibling->left_sibling = y->left_sibling; y->left_sibling->right_sibling = y->right_sibling; if (x->right_sibling == x) H->min = x; y->left_sibling = y; y->right_sibling = y; y->parent = x; if (x->child == NULL) { x->child = y; } y->right_sibling = x->child; y->left_sibling = x->child->left_sibling; x->child->left_sibling->right_sibling = y; x->child->left_sibling = y; if ((y->key) < (x->child->key)) x->child = y; (x->degree)++; } // Extract min NODE *extract_min(FIB_HEAP *H) { if (H->min == NULL) printf("\n The heap is empty"); else { NODE *temp = H->min; NODE *pntr; pntr = temp; NODE *x = NULL; if (temp->child != NULL) { x = temp->child; do { pntr = x->right_sibling; (H->min->left_sibling)->right_sibling = x; x->right_sibling = H->min; x->left_sibling = H->min->left_sibling; H->min->left_sibling = x; if (x->key < H->min->key) H->min = x; x->parent = NULL; x = pntr; } while (pntr != temp->child); } (temp->left_sibling)->right_sibling = temp->right_sibling; (temp->right_sibling)->left_sibling = temp->left_sibling; H->min = temp->right_sibling; if (temp == temp->right_sibling && temp->child == NULL) H->min = NULL; else { H->min = temp->right_sibling; consolidate(H); } H->n = H->n - 1; return temp; } return H->min; } void cut(FIB_HEAP *H, NODE *node_to_be_decrease, NODE *parent_node) { NODE *temp_parent_check; if (node_to_be_decrease == node_to_be_decrease->right_sibling) parent_node->child = NULL; node_to_be_decrease->left_sibling->right_sibling = node_to_be_decrease->right_sibling; node_to_be_decrease->right_sibling->left_sibling = node_to_be_decrease->left_sibling; if (node_to_be_decrease == parent_node->child) parent_node->child = node_to_be_decrease->right_sibling; (parent_node->degree)--; node_to_be_decrease->left_sibling = node_to_be_decrease; node_to_be_decrease->right_sibling = node_to_be_decrease; H->min->left_sibling->right_sibling = node_to_be_decrease; node_to_be_decrease->right_sibling = H->min; node_to_be_decrease->left_sibling = H->min->left_sibling; H->min->left_sibling = node_to_be_decrease; node_to_be_decrease->parent = NULL; node_to_be_decrease->mark = false; } void cascading_cut(FIB_HEAP *H, NODE *parent_node) { NODE *aux; aux = parent_node->parent; if (aux != NULL) { if (parent_node->mark == false) { parent_node->mark = true; } else { cut(H, parent_node, aux); cascading_cut(H, aux); } } } void decrease_key(FIB_HEAP *H, NODE *node_to_be_decrease, int new_key) { NODE *parent_node; if (H == NULL) { printf("\n FIbonacci heap not created "); return; } if (node_to_be_decrease == NULL) { printf("Node is not in the heap"); } else { if (node_to_be_decrease->key < new_key) { printf("\n Invalid new key for decrease key operation \n "); } else { node_to_be_decrease->key = new_key; parent_node = node_to_be_decrease->parent; if ((parent_node != NULL) && (node_to_be_decrease->key < parent_node->key)) { printf("\n cut called"); cut(H, node_to_be_decrease, parent_node); printf("\n cascading cut called"); cascading_cut(H, parent_node); } if (node_to_be_decrease->key < H->min->key) { H->min = node_to_be_decrease; } } } } void *find_node(FIB_HEAP *H, NODE *n, int key, int new_key) { NODE *find_use = n; NODE *f = NULL; find_use->visited = true; if (find_use->key == key) { find_use->visited = false; f = find_use; decrease_key(H, f, new_key); } if (find_use->child != NULL) { find_node(H, find_use->child, key, new_key); } if ((find_use->right_sibling->visited != true)) { find_node(H, find_use->right_sibling, key, new_key); } find_use->visited = false; } FIB_HEAP *insertion_procedure() { FIB_HEAP *temp; int no_of_nodes, ele, i; NODE *new_node; temp = (FIB_HEAP *)malloc(sizeof(FIB_HEAP)); temp = NULL; if (temp == NULL) { temp = make_fib_heap(); } printf(" \n enter number of nodes to be insert = "); scanf("%d", &no_of_nodes); for (i = 1; i <= no_of_nodes; i++) { printf("\n node %d and its key value = ", i); scanf("%d", &ele); insertion(temp, new_node, ele); } return temp; } void Delete_Node(FIB_HEAP *H, int dec_key) { NODE *p = NULL; find_node(H, H->min, dec_key, -5000); p = extract_min(H); if (p != NULL) printf("\n Node deleted"); else printf("\n Node not deleted:some error"); } int main(int argc, char **argv) { NODE *new_node, *min_node, *extracted_min, *node_to_be_decrease, *find_use; FIB_HEAP *heap, *h1, *h2; int operation_no, new_key, dec_key, ele, i, no_of_nodes; heap = (FIB_HEAP *)malloc(sizeof(FIB_HEAP)); heap = NULL; while (1) { printf(" \n Operations \n 1. Create Fibonacci heap \n 2. Insert nodes into fibonacci heap \n 3. Find min \n 4. Union \n 5. Extract min \n 6. Decrease key \n 7.Delete node \n 8. print heap \n 9. exit \n enter operation_no = "); scanf("%d", &operation_no); switch (operation_no) { case 1: heap = make_fib_heap(); break; case 2: if (heap == NULL) { heap = make_fib_heap(); } printf(" enter number of nodes to be insert = "); scanf("%d", &no_of_nodes); for (i = 1; i <= no_of_nodes; i++) { printf("\n node %d and its key value = ", i); scanf("%d", &ele); insertion(heap, new_node, ele); } break; case 3: min_node = find_min_node(heap); if (min_node == NULL) printf("No minimum value"); else printf("\n min value = %d", min_node->key); break; case 4: if (heap == NULL) { printf("\n no FIbonacci heap created \n "); break; } h1 = insertion_procedure(); heap = unionHeap(heap, h1); printf("Unified Heap:\n"); print_heap(heap->min); break; case 5: if (heap == NULL) printf("Empty Fibonacci heap"); else { extracted_min = extract_min(heap); printf("\n min value = %d", extracted_min->key); printf("\n Updated heap: \n"); print_heap(heap->min); } break; case 6: if (heap == NULL) printf("Fibonacci heap is empty"); else { printf(" \n node to be decreased = "); scanf("%d", &dec_key); printf(" \n enter the new key = "); scanf("%d", &new_key); find_use = heap->min; find_node(heap, find_use, dec_key, new_key); printf("\n Key decreased- Corresponding heap:\n"); print_heap(heap->min); } break; case 7: if (heap == NULL) printf("Fibonacci heap is empty"); else { printf(" \n Enter node key to be deleted = "); scanf("%d", &dec_key); Delete_Node(heap, dec_key); printf("\n Node Deleted- Corresponding heap:\n"); print_heap(heap->min); break; } case 8: print_heap(heap->min); break; case 9: free(new_node); free(heap); exit(0); default: printf("Invalid choice "); } } } ================================================ FILE: Data-Structures/Tree/Generic Tree/GenericTree.cpp ================================================ #include #include #include #include using namespace std; #define INF 1e18 struct Node { int key; vector children;//reference to child nodes Node(int x) { key=x; } }; int main() { ios_base::sync_with_stdio(0); cin.tie(0); //for fast IO Node *root = new Node(10); int n; //enter n numbers that will be children of root cin>>n; for(int i=0;i>x; root->children.push_back(new Node(x)); } //enter x1 numbers that will children of first child int x1; cin>>x1; for(int i=0;i>x; Node* k=new Node(x); root->children[0]->children.push_back(k); } int x2; cin>>x2; //enter x2 numbers that will children of first child for(int i=0;i>x; root->children[1]->children.push_back(new Node(x)); } // dynamically we can more children cout<children[1]->key; } ================================================ FILE: Data-Structures/Tree/README.md ================================================ # This folder is empty. ================================================ FILE: Data-Structures/Tree/Red-Black-Tree/Red-Black-Tree.c ================================================ #include #include enum nodeColor { RED, BLACK }; struct rbNode { int data, color; struct rbNode *link[2]; }; struct rbNode *root = NULL; // Create a red-black tree struct rbNode *createNode(int data) { struct rbNode *newnode; newnode = (struct rbNode *)malloc(sizeof(struct rbNode)); newnode->data = data; newnode->color = RED; newnode->link[0] = newnode->link[1] = NULL; return newnode; } // Insert an node void insertion(int data) { struct rbNode *stack[98], *ptr, *newnode, *xPtr, *yPtr; int dir[98], ht = 0, index; ptr = root; if (!root) { root = createNode(data); return; } stack[ht] = root; dir[ht++] = 0; while (ptr != NULL) { if (ptr->data == data) { printf("Duplicates Not Allowed!!\n"); return; } index = (data - ptr->data) > 0 ? 1 : 0; stack[ht] = ptr; ptr = ptr->link[index]; dir[ht++] = index; } stack[ht - 1]->link[index] = newnode = createNode(data); while ((ht >= 3) && (stack[ht - 1]->color == RED)) { if (dir[ht - 2] == 0) { yPtr = stack[ht - 2]->link[1]; if (yPtr != NULL && yPtr->color == RED) { stack[ht - 2]->color = RED; stack[ht - 1]->color = yPtr->color = BLACK; ht = ht - 2; } else { if (dir[ht - 1] == 0) { yPtr = stack[ht - 1]; } else { xPtr = stack[ht - 1]; yPtr = xPtr->link[1]; xPtr->link[1] = yPtr->link[0]; yPtr->link[0] = xPtr; stack[ht - 2]->link[0] = yPtr; } xPtr = stack[ht - 2]; xPtr->color = RED; yPtr->color = BLACK; xPtr->link[0] = yPtr->link[1]; yPtr->link[1] = xPtr; if (xPtr == root) { root = yPtr; } else { stack[ht - 3]->link[dir[ht - 3]] = yPtr; } break; } } else { yPtr = stack[ht - 2]->link[0]; if ((yPtr != NULL) && (yPtr->color == RED)) { stack[ht - 2]->color = RED; stack[ht - 1]->color = yPtr->color = BLACK; ht = ht - 2; } else { if (dir[ht - 1] == 1) { yPtr = stack[ht - 1]; } else { xPtr = stack[ht - 1]; yPtr = xPtr->link[0]; xPtr->link[0] = yPtr->link[1]; yPtr->link[1] = xPtr; stack[ht - 2]->link[1] = yPtr; } xPtr = stack[ht - 2]; yPtr->color = BLACK; xPtr->color = RED; xPtr->link[1] = yPtr->link[0]; yPtr->link[0] = xPtr; if (xPtr == root) { root = yPtr; } else { stack[ht - 3]->link[dir[ht - 3]] = yPtr; } break; } } } root->color = BLACK; } // Delete a node void deletion(int data) { struct rbNode *stack[98], *ptr, *xPtr, *yPtr; struct rbNode *pPtr, *qPtr, *rPtr; int dir[98], ht = 0, diff, i; enum nodeColor color; if (!root) { printf("Tree not available\n"); return; } ptr = root; while (ptr != NULL) { if ((data - ptr->data) == 0) break; diff = (data - ptr->data) > 0 ? 1 : 0; stack[ht] = ptr; dir[ht++] = diff; ptr = ptr->link[diff]; } if (ptr->link[1] == NULL) { if ((ptr == root) && (ptr->link[0] == NULL)) { free(ptr); root = NULL; } else if (ptr == root) { root = ptr->link[0]; free(ptr); } else { stack[ht - 1]->link[dir[ht - 1]] = ptr->link[0]; } } else { xPtr = ptr->link[1]; if (xPtr->link[0] == NULL) { xPtr->link[0] = ptr->link[0]; color = xPtr->color; xPtr->color = ptr->color; ptr->color = color; if (ptr == root) { root = xPtr; } else { stack[ht - 1]->link[dir[ht - 1]] = xPtr; } dir[ht] = 1; stack[ht++] = xPtr; } else { i = ht++; while (1) { dir[ht] = 0; stack[ht++] = xPtr; yPtr = xPtr->link[0]; if (!yPtr->link[0]) break; xPtr = yPtr; } dir[i] = 1; stack[i] = yPtr; if (i > 0) stack[i - 1]->link[dir[i - 1]] = yPtr; yPtr->link[0] = ptr->link[0]; xPtr->link[0] = yPtr->link[1]; yPtr->link[1] = ptr->link[1]; if (ptr == root) { root = yPtr; } color = yPtr->color; yPtr->color = ptr->color; ptr->color = color; } } if (ht < 1) return; if (ptr->color == BLACK) { while (1) { pPtr = stack[ht - 1]->link[dir[ht - 1]]; if (pPtr && pPtr->color == RED) { pPtr->color = BLACK; break; } if (ht < 2) break; if (dir[ht - 2] == 0) { rPtr = stack[ht - 1]->link[1]; if (!rPtr) break; if (rPtr->color == RED) { stack[ht - 1]->color = RED; rPtr->color = BLACK; stack[ht - 1]->link[1] = rPtr->link[0]; rPtr->link[0] = stack[ht - 1]; if (stack[ht - 1] == root) { root = rPtr; } else { stack[ht - 2]->link[dir[ht - 2]] = rPtr; } dir[ht] = 0; stack[ht] = stack[ht - 1]; stack[ht - 1] = rPtr; ht++; rPtr = stack[ht - 1]->link[1]; } if ((!rPtr->link[0] || rPtr->link[0]->color == BLACK) && (!rPtr->link[1] || rPtr->link[1]->color == BLACK)) { rPtr->color = RED; } else { if (!rPtr->link[1] || rPtr->link[1]->color == BLACK) { qPtr = rPtr->link[0]; rPtr->color = RED; qPtr->color = BLACK; rPtr->link[0] = qPtr->link[1]; qPtr->link[1] = rPtr; rPtr = stack[ht - 1]->link[1] = qPtr; } rPtr->color = stack[ht - 1]->color; stack[ht - 1]->color = BLACK; rPtr->link[1]->color = BLACK; stack[ht - 1]->link[1] = rPtr->link[0]; rPtr->link[0] = stack[ht - 1]; if (stack[ht - 1] == root) { root = rPtr; } else { stack[ht - 2]->link[dir[ht - 2]] = rPtr; } break; } } else { rPtr = stack[ht - 1]->link[0]; if (!rPtr) break; if (rPtr->color == RED) { stack[ht - 1]->color = RED; rPtr->color = BLACK; stack[ht - 1]->link[0] = rPtr->link[1]; rPtr->link[1] = stack[ht - 1]; if (stack[ht - 1] == root) { root = rPtr; } else { stack[ht - 2]->link[dir[ht - 2]] = rPtr; } dir[ht] = 1; stack[ht] = stack[ht - 1]; stack[ht - 1] = rPtr; ht++; rPtr = stack[ht - 1]->link[0]; } if ((!rPtr->link[0] || rPtr->link[0]->color == BLACK) && (!rPtr->link[1] || rPtr->link[1]->color == BLACK)) { rPtr->color = RED; } else { if (!rPtr->link[0] || rPtr->link[0]->color == BLACK) { qPtr = rPtr->link[1]; rPtr->color = RED; qPtr->color = BLACK; rPtr->link[1] = qPtr->link[0]; qPtr->link[0] = rPtr; rPtr = stack[ht - 1]->link[0] = qPtr; } rPtr->color = stack[ht - 1]->color; stack[ht - 1]->color = BLACK; rPtr->link[0]->color = BLACK; stack[ht - 1]->link[0] = rPtr->link[1]; rPtr->link[1] = stack[ht - 1]; if (stack[ht - 1] == root) { root = rPtr; } else { stack[ht - 2]->link[dir[ht - 2]] = rPtr; } break; } } ht--; } } } // Print the inorder traversal of the tree void inorderTraversal(struct rbNode *node) { if (node) { inorderTraversal(node->link[0]); printf("%d ", node->data); inorderTraversal(node->link[1]); } return; } // Driver code int main() { int ch, data; while (1) { printf("1. Insertion\t2. Deletion\n"); printf("3. Traverse\t4. Exit"); printf("\nEnter your choice:"); scanf("%d", &ch); switch (ch) { case 1: printf("Enter the element to insert:"); scanf("%d", &data); insertion(data); break; case 2: printf("Enter the element to delete:"); scanf("%d", &data); deletion(data); break; case 3: inorderTraversal(root); printf("\n"); break; case 4: exit(0); default: printf("Not available\n"); break; } printf("\n"); } return 0; } ================================================ FILE: Data-Structures/Tree/Red-Black-Tree/Red-Black-Tree.cpp ================================================ #include using namespace std; struct Node { int data; Node *parent; Node *left; Node *right; int color; }; typedef Node *NodePtr; class RedBlackTree { private: NodePtr root; NodePtr TNULL; void initializeNULLNode(NodePtr node, NodePtr parent) { node->data = 0; node->parent = parent; node->left = nullptr; node->right = nullptr; node->color = 0; } // Preorder void preOrderHelper(NodePtr node) { if (node != TNULL) { cout << node->data << " "; preOrderHelper(node->left); preOrderHelper(node->right); } } // Inorder void inOrderHelper(NodePtr node) { if (node != TNULL) { inOrderHelper(node->left); cout << node->data << " "; inOrderHelper(node->right); } } // Post order void postOrderHelper(NodePtr node) { if (node != TNULL) { postOrderHelper(node->left); postOrderHelper(node->right); cout << node->data << " "; } } NodePtr searchTreeHelper(NodePtr node, int key) { if (node == TNULL || key == node->data) { return node; } if (key < node->data) { return searchTreeHelper(node->left, key); } return searchTreeHelper(node->right, key); } // For balancing the tree after deletion void deleteFix(NodePtr x) { NodePtr s; while (x != root && x->color == 0) { if (x == x->parent->left) { s = x->parent->right; if (s->color == 1) { s->color = 0; x->parent->color = 1; leftRotate(x->parent); s = x->parent->right; } if (s->left->color == 0 && s->right->color == 0) { s->color = 1; x = x->parent; } else { if (s->right->color == 0) { s->left->color = 0; s->color = 1; rightRotate(s); s = x->parent->right; } s->color = x->parent->color; x->parent->color = 0; s->right->color = 0; leftRotate(x->parent); x = root; } } else { s = x->parent->left; if (s->color == 1) { s->color = 0; x->parent->color = 1; rightRotate(x->parent); s = x->parent->left; } if (s->right->color == 0 && s->right->color == 0) { s->color = 1; x = x->parent; } else { if (s->left->color == 0) { s->right->color = 0; s->color = 1; leftRotate(s); s = x->parent->left; } s->color = x->parent->color; x->parent->color = 0; s->left->color = 0; rightRotate(x->parent); x = root; } } } x->color = 0; } void rbTransplant(NodePtr u, NodePtr v) { if (u->parent == nullptr) { root = v; } else if (u == u->parent->left) { u->parent->left = v; } else { u->parent->right = v; } v->parent = u->parent; } void deleteNodeHelper(NodePtr node, int key) { NodePtr z = TNULL; NodePtr x, y; while (node != TNULL) { if (node->data == key) { z = node; } if (node->data <= key) { node = node->right; } else { node = node->left; } } if (z == TNULL) { cout << "Key not found in the tree" << endl; return; } y = z; int y_original_color = y->color; if (z->left == TNULL) { x = z->right; rbTransplant(z, z->right); } else if (z->right == TNULL) { x = z->left; rbTransplant(z, z->left); } else { y = minimum(z->right); y_original_color = y->color; x = y->right; if (y->parent == z) { x->parent = y; } else { rbTransplant(y, y->right); y->right = z->right; y->right->parent = y; } rbTransplant(z, y); y->left = z->left; y->left->parent = y; y->color = z->color; } delete z; if (y_original_color == 0) { deleteFix(x); } } // For balancing the tree after insertion void insertFix(NodePtr k) { NodePtr u; while (k->parent->color == 1) { if (k->parent == k->parent->parent->right) { u = k->parent->parent->left; if (u->color == 1) { u->color = 0; k->parent->color = 0; k->parent->parent->color = 1; k = k->parent->parent; } else { if (k == k->parent->left) { k = k->parent; rightRotate(k); } k->parent->color = 0; k->parent->parent->color = 1; leftRotate(k->parent->parent); } } else { u = k->parent->parent->right; if (u->color == 1) { u->color = 0; k->parent->color = 0; k->parent->parent->color = 1; k = k->parent->parent; } else { if (k == k->parent->right) { k = k->parent; leftRotate(k); } k->parent->color = 0; k->parent->parent->color = 1; rightRotate(k->parent->parent); } } if (k == root) { break; } } root->color = 0; } void printHelper(NodePtr root, string indent, bool last) { if (root != TNULL) { cout << indent; if (last) { cout << "R----"; indent += " "; } else { cout << "L----"; indent += "| "; } string sColor = root->color ? "RED" : "BLACK"; cout << root->data << "(" << sColor << ")" << endl; printHelper(root->left, indent, false); printHelper(root->right, indent, true); } } public: RedBlackTree() { TNULL = new Node; TNULL->color = 0; TNULL->left = nullptr; TNULL->right = nullptr; root = TNULL; } void preorder() { preOrderHelper(this->root); } void inorder() { inOrderHelper(this->root); } void postorder() { postOrderHelper(this->root); } NodePtr searchTree(int k) { return searchTreeHelper(this->root, k); } NodePtr minimum(NodePtr node) { while (node->left != TNULL) { node = node->left; } return node; } NodePtr maximum(NodePtr node) { while (node->right != TNULL) { node = node->right; } return node; } NodePtr successor(NodePtr x) { if (x->right != TNULL) { return minimum(x->right); } NodePtr y = x->parent; while (y != TNULL && x == y->right) { x = y; y = y->parent; } return y; } NodePtr predecessor(NodePtr x) { if (x->left != TNULL) { return maximum(x->left); } NodePtr y = x->parent; while (y != TNULL && x == y->left) { x = y; y = y->parent; } return y; } void leftRotate(NodePtr x) { NodePtr y = x->right; x->right = y->left; if (y->left != TNULL) { y->left->parent = x; } y->parent = x->parent; if (x->parent == nullptr) { this->root = y; } else if (x == x->parent->left) { x->parent->left = y; } else { x->parent->right = y; } y->left = x; x->parent = y; } void rightRotate(NodePtr x) { NodePtr y = x->left; x->left = y->right; if (y->right != TNULL) { y->right->parent = x; } y->parent = x->parent; if (x->parent == nullptr) { this->root = y; } else if (x == x->parent->right) { x->parent->right = y; } else { x->parent->left = y; } y->right = x; x->parent = y; } // Inserting a node void insert(int key) { NodePtr node = new Node; node->parent = nullptr; node->data = key; node->left = TNULL; node->right = TNULL; node->color = 1; NodePtr y = nullptr; NodePtr x = this->root; while (x != TNULL) { y = x; if (node->data < x->data) { x = x->left; } else { x = x->right; } } node->parent = y; if (y == nullptr) { root = node; } else if (node->data < y->data) { y->left = node; } else { y->right = node; } if (node->parent == nullptr) { node->color = 0; return; } if (node->parent->parent == nullptr) { return; } insertFix(node); } NodePtr getRoot() { return this->root; } void deleteNode(int data) { deleteNodeHelper(this->root, data); } void printTree() { if (root) { printHelper(this->root, "", true); } } }; int main() { RedBlackTree bst; bst.insert(55); bst.insert(40); bst.insert(65); bst.insert(60); bst.insert(75); bst.insert(57); bst.printTree(); cout << endl << "After deleting" << endl; bst.deleteNode(40); bst.printTree(); } ================================================ FILE: Data-Structures/Tree/Red-Black-Tree/Red-Black-Tree.java ================================================ class Node { int data; Node parent; Node left; Node right; int color; } public class RedBlackTree { private Node root; private Node TNULL; // Preorder private void preOrderHelper(Node node) { if (node != TNULL) { System.out.print(node.data + " "); preOrderHelper(node.left); preOrderHelper(node.right); } } // Inorder private void inOrderHelper(Node node) { if (node != TNULL) { inOrderHelper(node.left); System.out.print(node.data + " "); inOrderHelper(node.right); } } // Post order private void postOrderHelper(Node node) { if (node != TNULL) { postOrderHelper(node.left); postOrderHelper(node.right); System.out.print(node.data + " "); } } // Search the tree private Node searchTreeHelper(Node node, int key) { if (node == TNULL || key == node.data) { return node; } if (key < node.data) { return searchTreeHelper(node.left, key); } return searchTreeHelper(node.right, key); } // Balance the tree after deletion of a node private void fixDelete(Node x) { Node s; while (x != root && x.color == 0) { if (x == x.parent.left) { s = x.parent.right; if (s.color == 1) { s.color = 0; x.parent.color = 1; leftRotate(x.parent); s = x.parent.right; } if (s.left.color == 0 && s.right.color == 0) { s.color = 1; x = x.parent; } else { if (s.right.color == 0) { s.left.color = 0; s.color = 1; rightRotate(s); s = x.parent.right; } s.color = x.parent.color; x.parent.color = 0; s.right.color = 0; leftRotate(x.parent); x = root; } } else { s = x.parent.left; if (s.color == 1) { s.color = 0; x.parent.color = 1; rightRotate(x.parent); s = x.parent.left; } if (s.right.color == 0 && s.right.color == 0) { s.color = 1; x = x.parent; } else { if (s.left.color == 0) { s.right.color = 0; s.color = 1; leftRotate(s); s = x.parent.left; } s.color = x.parent.color; x.parent.color = 0; s.left.color = 0; rightRotate(x.parent); x = root; } } } x.color = 0; } private void rbTransplant(Node u, Node v) { if (u.parent == null) { root = v; } else if (u == u.parent.left) { u.parent.left = v; } else { u.parent.right = v; } v.parent = u.parent; } private void deleteNodeHelper(Node node, int key) { Node z = TNULL; Node x, y; while (node != TNULL) { if (node.data == key) { z = node; } if (node.data <= key) { node = node.right; } else { node = node.left; } } if (z == TNULL) { System.out.println("Couldn't find key in the tree"); return; } y = z; int yOriginalColor = y.color; if (z.left == TNULL) { x = z.right; rbTransplant(z, z.right); } else if (z.right == TNULL) { x = z.left; rbTransplant(z, z.left); } else { y = minimum(z.right); yOriginalColor = y.color; x = y.right; if (y.parent == z) { x.parent = y; } else { rbTransplant(y, y.right); y.right = z.right; y.right.parent = y; } rbTransplant(z, y); y.left = z.left; y.left.parent = y; y.color = z.color; } if (yOriginalColor == 0) { fixDelete(x); } } // Balance the node after insertion private void fixInsert(Node k) { Node u; while (k.parent.color == 1) { if (k.parent == k.parent.parent.right) { u = k.parent.parent.left; if (u.color == 1) { u.color = 0; k.parent.color = 0; k.parent.parent.color = 1; k = k.parent.parent; } else { if (k == k.parent.left) { k = k.parent; rightRotate(k); } k.parent.color = 0; k.parent.parent.color = 1; leftRotate(k.parent.parent); } } else { u = k.parent.parent.right; if (u.color == 1) { u.color = 0; k.parent.color = 0; k.parent.parent.color = 1; k = k.parent.parent; } else { if (k == k.parent.right) { k = k.parent; leftRotate(k); } k.parent.color = 0; k.parent.parent.color = 1; rightRotate(k.parent.parent); } } if (k == root) { break; } } root.color = 0; } private void printHelper(Node root, String indent, boolean last) { if (root != TNULL) { System.out.print(indent); if (last) { System.out.print("R----"); indent += " "; } else { System.out.print("L----"); indent += "| "; } String sColor = root.color == 1 ? "RED" : "BLACK"; System.out.println(root.data + "(" + sColor + ")"); printHelper(root.left, indent, false); printHelper(root.right, indent, true); } } public RedBlackTree() { TNULL = new Node(); TNULL.color = 0; TNULL.left = null; TNULL.right = null; root = TNULL; } public void preorder() { preOrderHelper(this.root); } public void inorder() { inOrderHelper(this.root); } public void postorder() { postOrderHelper(this.root); } public Node searchTree(int k) { return searchTreeHelper(this.root, k); } public Node minimum(Node node) { while (node.left != TNULL) { node = node.left; } return node; } public Node maximum(Node node) { while (node.right != TNULL) { node = node.right; } return node; } public Node successor(Node x) { if (x.right != TNULL) { return minimum(x.right); } Node y = x.parent; while (y != TNULL && x == y.right) { x = y; y = y.parent; } return y; } public Node predecessor(Node x) { if (x.left != TNULL) { return maximum(x.left); } Node y = x.parent; while (y != TNULL && x == y.left) { x = y; y = y.parent; } return y; } public void leftRotate(Node x) { Node y = x.right; x.right = y.left; if (y.left != TNULL) { y.left.parent = x; } y.parent = x.parent; if (x.parent == null) { this.root = y; } else if (x == x.parent.left) { x.parent.left = y; } else { x.parent.right = y; } y.left = x; x.parent = y; } public void rightRotate(Node x) { Node y = x.left; x.left = y.right; if (y.right != TNULL) { y.right.parent = x; } y.parent = x.parent; if (x.parent == null) { this.root = y; } else if (x == x.parent.right) { x.parent.right = y; } else { x.parent.left = y; } y.right = x; x.parent = y; } public void insert(int key) { Node node = new Node(); node.parent = null; node.data = key; node.left = TNULL; node.right = TNULL; node.color = 1; Node y = null; Node x = this.root; while (x != TNULL) { y = x; if (node.data < x.data) { x = x.left; } else { x = x.right; } } node.parent = y; if (y == null) { root = node; } else if (node.data < y.data) { y.left = node; } else { y.right = node; } if (node.parent == null) { node.color = 0; return; } if (node.parent.parent == null) { return; } fixInsert(node); } public Node getRoot() { return this.root; } public void deleteNode(int data) { deleteNodeHelper(this.root, data); } public void printTree() { printHelper(this.root, "", true); } public static void main(String[] args) { RedBlackTree bst = new RedBlackTree(); bst.insert(55); bst.insert(40); bst.insert(65); bst.insert(60); bst.insert(75); bst.insert(57); bst.printTree(); System.out.println("\nAfter deleting:"); bst.deleteNode(40); bst.printTree(); } } ================================================ FILE: Data-Structures/Tree/Red-Black-Tree/Red-Black-Tree.py ================================================ import sys # Node creation class Node(): def __init__(self, item): self.item = item self.parent = None self.left = None self.right = None self.color = 1 class RedBlackTree(): def __init__(self): self.TNULL = Node(0) self.TNULL.color = 0 self.TNULL.left = None self.TNULL.right = None self.root = self.TNULL # Preorder def pre_order_helper(self, node): if node != TNULL: sys.stdout.write(node.item + " ") self.pre_order_helper(node.left) self.pre_order_helper(node.right) # Inorder def in_order_helper(self, node): if node != TNULL: self.in_order_helper(node.left) sys.stdout.write(node.item + " ") self.in_order_helper(node.right) # Postorder def post_order_helper(self, node): if node != TNULL: self.post_order_helper(node.left) self.post_order_helper(node.right) sys.stdout.write(node.item + " ") # Search the tree def search_tree_helper(self, node, key): if node == TNULL or key == node.item: return node if key < node.item: return self.search_tree_helper(node.left, key) return self.search_tree_helper(node.right, key) # Balancing the tree after deletion def delete_fix(self, x): while x != self.root and x.color == 0: if x == x.parent.left: s = x.parent.right if s.color == 1: s.color = 0 x.parent.color = 1 self.left_rotate(x.parent) s = x.parent.right if s.left.color == 0 and s.right.color == 0: s.color = 1 x = x.parent else: if s.right.color == 0: s.left.color = 0 s.color = 1 self.right_rotate(s) s = x.parent.right s.color = x.parent.color x.parent.color = 0 s.right.color = 0 self.left_rotate(x.parent) x = self.root else: s = x.parent.left if s.color == 1: s.color = 0 x.parent.color = 1 self.right_rotate(x.parent) s = x.parent.left if s.right.color == 0 and s.right.color == 0: s.color = 1 x = x.parent else: if s.left.color == 0: s.right.color = 0 s.color = 1 self.left_rotate(s) s = x.parent.left s.color = x.parent.color x.parent.color = 0 s.left.color = 0 self.right_rotate(x.parent) x = self.root x.color = 0 def __rb_transplant(self, u, v): if u.parent == None: self.root = v elif u == u.parent.left: u.parent.left = v else: u.parent.right = v v.parent = u.parent # Node deletion def delete_node_helper(self, node, key): z = self.TNULL while node != self.TNULL: if node.item == key: z = node if node.item <= key: node = node.right else: node = node.left if z == self.TNULL: print("Cannot find key in the tree") return y = z y_original_color = y.color if z.left == self.TNULL: x = z.right self.__rb_transplant(z, z.right) elif (z.right == self.TNULL): x = z.left self.__rb_transplant(z, z.left) else: y = self.minimum(z.right) y_original_color = y.color x = y.right if y.parent == z: x.parent = y else: self.__rb_transplant(y, y.right) y.right = z.right y.right.parent = y self.__rb_transplant(z, y) y.left = z.left y.left.parent = y y.color = z.color if y_original_color == 0: self.delete_fix(x) # Balance the tree after insertion def fix_insert(self, k): while k.parent.color == 1: if k.parent == k.parent.parent.right: u = k.parent.parent.left if u.color == 1: u.color = 0 k.parent.color = 0 k.parent.parent.color = 1 k = k.parent.parent else: if k == k.parent.left: k = k.parent self.right_rotate(k) k.parent.color = 0 k.parent.parent.color = 1 self.left_rotate(k.parent.parent) else: u = k.parent.parent.right if u.color == 1: u.color = 0 k.parent.color = 0 k.parent.parent.color = 1 k = k.parent.parent else: if k == k.parent.right: k = k.parent self.left_rotate(k) k.parent.color = 0 k.parent.parent.color = 1 self.right_rotate(k.parent.parent) if k == self.root: break self.root.color = 0 # Printing the tree def __print_helper(self, node, indent, last): if node != self.TNULL: sys.stdout.write(indent) if last: sys.stdout.write("R----") indent += " " else: sys.stdout.write("L----") indent += "| " s_color = "RED" if node.color == 1 else "BLACK" print(str(node.item) + "(" + s_color + ")") self.__print_helper(node.left, indent, False) self.__print_helper(node.right, indent, True) def preorder(self): self.pre_order_helper(self.root) def inorder(self): self.in_order_helper(self.root) def postorder(self): self.post_order_helper(self.root) def searchTree(self, k): return self.search_tree_helper(self.root, k) def minimum(self, node): while node.left != self.TNULL: node = node.left return node def maximum(self, node): while node.right != self.TNULL: node = node.right return node def successor(self, x): if x.right != self.TNULL: return self.minimum(x.right) y = x.parent while y != self.TNULL and x == y.right: x = y y = y.parent return y def predecessor(self, x): if (x.left != self.TNULL): return self.maximum(x.left) y = x.parent while y != self.TNULL and x == y.left: x = y y = y.parent return y def left_rotate(self, x): y = x.right x.right = y.left if y.left != self.TNULL: y.left.parent = x y.parent = x.parent if x.parent == None: self.root = y elif x == x.parent.left: x.parent.left = y else: x.parent.right = y y.left = x x.parent = y def right_rotate(self, x): y = x.left x.left = y.right if y.right != self.TNULL: y.right.parent = x y.parent = x.parent if x.parent == None: self.root = y elif x == x.parent.right: x.parent.right = y else: x.parent.left = y y.right = x x.parent = y def insert(self, key): node = Node(key) node.parent = None node.item = key node.left = self.TNULL node.right = self.TNULL node.color = 1 y = None x = self.root while x != self.TNULL: y = x if node.item < x.item: x = x.left else: x = x.right node.parent = y if y == None: self.root = node elif node.item < y.item: y.left = node else: y.right = node if node.parent == None: node.color = 0 return if node.parent.parent == None: return self.fix_insert(node) def get_root(self): return self.root def delete_node(self, item): self.delete_node_helper(self.root, item) def print_tree(self): self.__print_helper(self.root, "", True) if __name__ == "__main__": bst = RedBlackTree() bst.insert(55) bst.insert(40) bst.insert(65) bst.insert(60) bst.insert(75) bst.insert(57) bst.print_tree() print("\nAfter deleting an element") bst.delete_node(40) bst.print_tree() ================================================ FILE: Data-Structures/Tree/Segment-Tree/Segment-Tree.c ================================================ /** * Segment Tree, or Segment Tree, is one of the most used data structures in competitive programming * due to its efficiency and versatility in operations of consultation in intervals and updating of elements in the array. * It consists of breaking the array into several intervals (segments). * Then, based on these intervals, we build a tree where each node stores the sum of the elements in the interval. * Complexity: construction - O (n); query & update - O (log n). * * @author Ytalo Ramon */ #include "stdio.h" #include "stdlib.h" #include "string.h" #define MAX 10 #define CALMIDDLE(a, b)((a + b) / 2) int build(int *listV, int *listSegment, int startInterv, int endInterv, int posi); int update(int newValue, int indexUpdate, int *listSegment, int startInterv, int endInterv, int posi); int getSum(int *listSegment, int findStartIndex, int findEndIndex, int startInterv, int endInterv, int posi); void show(char *title, int *l, int length); int main(int argc, char const *argv[]){ // Allocation variable and defined values int listValues[MAX] = {15, 2, 6, 9, 10, 1, 156, 7, 88, 65}, listSegmTree[MAX * 4]; // Set 0 the segment tree in all position memset(listSegmTree, 0, sizeof(int) * MAX * 4); // Constructor segment tree build(listValues, listSegmTree, 0, MAX, 0); show("Array", listValues, MAX); show("SegTree", listSegmTree, MAX * 3 + 10); printf("Update: idx=0; new_value=4\n"); listValues[0] = 4; update(4, 0, listSegmTree, 0, MAX, 0); show("Array", listValues, MAX); show("SegTree", listSegmTree, MAX * 3 + 10); printf("SUM: start=0; end=4 => %d\n", getSum(listSegmTree, 0, 4, 0, MAX, 0)); show("Array", listValues, MAX); printf("SUM: start=5; end=9 => %d\n", getSum(listSegmTree, 5, 9, 0, MAX, 0)); show("Array", listValues, MAX); printf("Update: idx=6; new_value=899\n"); listValues[6] = 899; update(899, 6, listSegmTree, 0, MAX, 0); show("Array", listValues, MAX); show("SegTree", listSegmTree, MAX * 3 + 10); printf("SUM: start=0; end=9 => %d\n", getSum(listSegmTree, 0, 9, 0, MAX, 0)); show("Array", listValues, MAX); printf("SUM: start=3; end=7 => %d\n", getSum(listSegmTree, 3, 7, 0, MAX, 0)); show("Array", listValues, MAX); return 0; } int build(int *listV, int *listSegment, int startInterv, int endInterv, int posi){ if (startInterv == endInterv - 1) return listSegment[posi] = listV[startInterv]; const int middle = CALMIDDLE(startInterv, endInterv), sumInterv = build(listV, listSegment, startInterv, middle, posi * 2 + 1) + build(listV, listSegment, middle, endInterv, posi * 2 + 2); return listSegment[posi] = sumInterv; } int update(int newValue, int indexUpdate, int *listSegment, int startInterv, int endInterv, int posi){ if (startInterv == endInterv - 1) return listSegment[posi] = newValue; const int middle = CALMIDDLE(startInterv, endInterv), sumInterv = indexUpdate < middle ? update(newValue, indexUpdate, listSegment, startInterv, middle, posi * 2 + 1) + listSegment[posi * 2 + 2]: update(newValue, indexUpdate, listSegment, middle, endInterv, posi * 2 + 2) + listSegment[posi * 2 + 1]; return listSegment[posi] = sumInterv; } int getSum(int *listSegment, int findStartIndex, int findEndIndex, int startInterv, int endInterv, int posi){ if (findStartIndex >= endInterv || findEndIndex < startInterv) return 0; if (findStartIndex <= startInterv && endInterv <= findEndIndex + 1) return listSegment[posi]; const int middle = CALMIDDLE(startInterv, endInterv); return getSum(listSegment, findStartIndex, findEndIndex, startInterv, middle, posi * 2 + 1) + getSum(listSegment, findStartIndex, findEndIndex, middle, endInterv, posi * 2 + 2); } void show(char *title, int *l, int length){ printf("%s\n", title); for (int i = 0; i < length; i++) printf("%d ", l[i]); printf("\n-----------------\n\n"); } ================================================ FILE: Data-Structures/Tree/Splay-Tree/Splay-Tree.c ================================================ #include #include #include using namespace std; struct s//node declaration { int k; s* lch; s* rch; }; class SplayTree { public: s* RR_Rotate(s* k2) { s* k1 = k2->lch; k2->lch = k1->rch; k1->rch = k2; return k1; } s* LL_Rotate(s* k2) { s* k1 = k2->rch; k2->rch = k1->lch; k1->lch = k2; return k1; } s* Splay(int key, s* root) { if (!root) return NULL; s header; header.lch= header.rch = NULL; s* LeftTreeMax = &header; s* RightTreeMin = &header; while (1) { if (key < root->k) { if (!root->lch) break; if (key< root->lch->k) { root = RR_Rotate(root); if (!root->lch) break; } RightTreeMin->lch= root; RightTreeMin = RightTreeMin->lch; root = root->lch; RightTreeMin->lch = NULL; } else if (key> root->k) { if (!root->rch) break; if (key > root->rch->k) { root = LL_Rotate(root); if (!root->rch) break; } LeftTreeMax->rch= root; LeftTreeMax = LeftTreeMax->rch; root = root->rch; LeftTreeMax->rch = NULL; } else break; } LeftTreeMax→rch = root->lch; RightTreeMin→lch = root->rch; root->lch = header.rch; root->rch = header.lch; return root; } s* New_Node(int key) { s* p_node = new s; if (!p_node) { fprintf(stderr, "Out of memory!\n"); exit(1); } p_node->k = key; p_node->lch = p_node->rch = NULL; return p_node; } s* Insert(int key, s* root) { static s* p_node = NULL; if (!p_node) p_node = New_Node(key); else p_node->k = key; if (!root) { root = p_node; p_node = NULL; return root; } root = Splay(key, root); if (key < root->k) { p_node->lch= root->lch; p_node->rch = root; root->lch = NULL; root = p_node; } else if (key > root->k) { p_node->rch = root->rch; p_node->lch = root; root->rch = NULL; root = p_node; } else return root; p_node = NULL; return root; } s* Delete(int key, s* root)//delete node { s* temp; if (!root)//if tree is empty return NULL; root = Splay(key, root); if (key != root->k)//if tree has one item return root; else { if (!root->lch) { temp = root; root = root->rch; } else { temp = root; root = Splay(key, root->lch); root->rch = temp->rch; } free(temp); return root; } } s* Search(int key, s* root)//seraching { return Splay(key, root); } void InOrder(s* root)//inorder traversal { if (root) { InOrder(root->lch); cout<< "key: " <k; if(root->lch) cout<< " | left child: "<< root->lch->k; if(root->rch) cout << " | right child: " << root->rch->k; cout<< "\n"; InOrder(root->rch); } } }; int main() { SplayTree st; s *root; root = NULL; st.InOrder(root); int i, c; while(1) { cout<<"1. Insert "<>c; switch©//perform switch operation { case 1: cout<<"Enter value to be inserted: "; cin>>i; root = st.Insert(i, root); cout<<"\nAfter Insert: "<>i; root = st.Delete(i, root); cout<<"\nAfter Delete: "<>i; root = st.Search(i, root); cout<<"\nAfter Search "< using namespace std; //Structure of the Threaded Binary Tree struct TBT_nd { int data; TBT_nd *left; TBT_nd *right; int th_left; int th_right; } *head; TBT_nd *insert(TBT_nd *root, TBT_nd *temp) //Inserting node in Threaded Binary Tree { if(head->left==head && head->right==head) { temp->left=head; temp->right=head; head->left=temp; head->th_left=1; root=temp; return root; } TBT_nd *curr=root; if(temp->data < curr->data) { if(curr->th_left==0) { temp->left=curr->left; curr->left=temp; temp->right=curr; curr->th_left=1; } else { insert(curr->left,temp); } } else if(temp->data > curr->data) { if(curr->th_right==0) { temp->right=curr->right; curr->right=temp; temp->left=curr; curr->th_right=1; } else { insert(curr->right,temp); } } return root; } TBT_nd *new_nd() { TBT_nd *temp=new TBT_nd; cout<<"ENTER DATA : "; cin>>temp->data; temp->left=NULL; temp->right=NULL; temp->th_left=0; temp->th_right=0; return temp; } TBT_nd *create(TBT_nd *root) //Create the node in Threaded Binary Tree { int ch; TBT_nd *temp; if(root==NULL) { head=new TBT_nd; head->data=9999; head->left=head; head->right=head; head->th_right=1; head->th_left=0; root=head; } do { temp=new_nd(); if(root!=NULL) { root=insert(root,temp); } cout<<"do you want to insert more nodes?? (enter 1 to continue)\n"; cin>>ch; } while(ch==1); return root; } TBT_nd *pre_suc(TBT_nd *t) //Predecessor of the node { if(t->th_left==1) return(t->left); while(t->th_right==0) t=t->right; return(t->right); } void TBTpreoder(TBT_nd *root) //Preoder Traversal in Threaded BT { TBT_nd *p=root; while(p!=head) { cout<data<<"\t"; p=pre_suc(p); } } TBT_nd *in_suc(TBT_nd *t) //Successor of the node { if(t->th_right==0) return (t->right); t=t->right; while(t->th_left==1) t=t->left; return(t); } void TBTinoder(TBT_nd *root) //Inoder Traversal in Threaded BT { TBT_nd *p=root; while(p->th_left==1) { p=p->left; } while(p!=head) { cout<data<<"\t"; p=in_suc(p); } } int main() //Main function { TBT_nd *root=NULL; int n; cout<<"INORDER THREADED BINARY TREE !"; do { cout<<"\n[1] CREATE (Or insert node in existing tree)?\n"; cout<<"[2] INORDER TRAVERSE?\n"; cout<<"[3] PREORDER TRAVERSE?\n"; cout<<"\nEnter your choice: (enter 0 to exit)"; cin>>n; if(n==1) { root=create(root); } else if(n==2) { cout<<"INORDER TRAVERSAL: \n"; TBTinoder(root); } else if(n==3) { cout<<"PREORDER TRAVERSAL: \n"; TBTpreoder(root); } } while(n!=0); cout<<"\nOPERATION COMPLETED!! THANK YOU"; return 0; } /* ----------------------------------------------------------------------------------------------------------------------------- OUTPUT : INORDER THREADED BINARY TREE ! [1] CREATE (Or insert node in existing tree)? [2] INORDER TRAVERSE? [3] PREORDER TRAVERSE? Enter your choice: (enter 0 to exit)1 ENTER DATA : 10 do you want to insert more nodes?? (enter 1 to continue) 1 ENTER DATA : 6 do you want to insert more nodes?? (enter 1 to continue) 1 ENTER DATA : 13 do you want to insert more nodes?? (enter 1 to continue) 1 ENTER DATA : 15 do you want to insert more nodes?? (enter 1 to continue) 1 ENTER DATA : 7 do you want to insert more nodes?? (enter 1 to continue) 1 ENTER DATA : 20 do you want to insert more nodes?? (enter 1 to continue) 1 ENTER DATA : 2 do you want to insert more nodes?? (enter 1 to continue) 1 ENTER DATA : 3 do you want to insert more nodes?? (enter 1 to continue) 0 [1] CREATE (Or insert node in existing tree)? [2] INORDER TRAVERSE? [3] PREORDER TRAVERSE? Enter your choice: (enter 0 to exit)2 INORDER TRAVERSAL: 2 3 6 7 10 13 15 20 [1] CREATE (Or insert node in existing tree)? [2] INORDER TRAVERSE? [3] PREORDER TRAVERSE? Enter your choice: (enter 0 to exit)3 PREORDER TRAVERSAL: 10 6 2 3 7 13 15 20 [1] CREATE (Or insert node in existing tree)? [2] INORDER TRAVERSE? [3] PREORDER TRAVERSE? Enter your choice: (enter 0 to exit)0 OPERATION COMPLETED!! THANK YOU ...Program finished with exit code 0 Press ENTER to exit console. */ ================================================ FILE: Data-Structures/Tree/Trie/README.md ================================================ # This folder is empty. ================================================ FILE: Data-Structures/Tree/Trie/Trie.c ================================================ #include #include #include #include #define ARRAY_SIZE(a) sizeof(a)/sizeof(a[0]) #define ALPHABET_SIZE (26) #define CHAR_TO_INDEX(c) ((int)c - (int)'a') // trie node struct TrieNode { struct TrieNode *children[ALPHABET_SIZE]; bool isEndOfWord; }; struct TrieNode *getNode(void) { struct TrieNode *pNode = NULL; pNode = (struct TrieNode *)malloc(sizeof(struct TrieNode)); if (pNode) { int i; pNode->isEndOfWord = false; for (i = 0; i < ALPHABET_SIZE; i++) pNode->children[i] = NULL; } return pNode; } void insert(struct TrieNode *root, const char *key) { int level; int length = strlen(key); int index; struct TrieNode *pCrawl = root; for (level = 0; level < length; level++) { index = CHAR_TO_INDEX(key[level]); if (!pCrawl->children[index]) pCrawl->children[index] = getNode(); pCrawl = pCrawl->children[index]; } pCrawl->isEndOfWord = true; } bool search(struct TrieNode *root, const char *key) { int level; int length = strlen(key); int index; struct TrieNode *pCrawl = root; for (level = 0; level < length; level++) { index = CHAR_TO_INDEX(key[level]); if (!pCrawl->children[index]) return false; pCrawl = pCrawl->children[index]; } return (pCrawl != NULL && pCrawl->isEndOfWord); } int main() { char keys[][8] = {"the", "a", "there", "answer", "any", "by", "bye", "their"}; char output[][32] = {"Not present in trie", "Present in trie"}; struct TrieNode *root = getNode(); // Construct trie int i; for (i = 0; i < ARRAY_SIZE(keys); i++) insert(root, keys[i]); printf("%s --- %s\n", "the", output[search(root, "the")] ); printf("%s --- %s\n", "these", output[search(root, "these")] ); printf("%s --- %s\n", "their", output[search(root, "their")] ); printf("%s --- %s\n", "thaw", output[search(root, "thaw")] ); return 0; } ================================================ FILE: Data-Structures/Tree/Trie/trie.cpp ================================================ #include using namespace std; struct TrieNode { unordered_map branches; bool isEnd; }; // creates new node and initialises isEnd to false TrieNode* createNode(void) { TrieNode* node = new TrieNode; node->isEnd = false; return node; } void insert(TrieNode*& node, const string &str, int index = 0) { // inserts a character node to existing trie structure if (node == NULL) // creates a new root if there is none { node = createNode(); cout<<"Creating ROOT"<= str.length()) // check if we have reached end of the word { temp->isEnd = true; return; } // assigns letter on i'th position of string to key char key = str[index]; if (temp->branches.find(key) == temp->branches.end()) { temp->branches[key] = createNode(); } // recursive definition to insert into trie return insert(temp->branches[key], str, index+1); } string search(TrieNode* root, const string &str, int index = 0) { // function which returns word if found else error message if (root == NULL) // return not found if no words added { return "Word not found."; } TrieNode* temp = root; if (index >= str.length()) // return found if end of word encountered { return "Word found."; } char key = str[index]; // recursive definition to iterate through trie return search(temp->branches[key], str, index+1); } int main() { TrieNode* root = NULL; // Build the dictionary insert(root, "trie"); insert(root, "is"); insert(root, "an"); insert(root, "efficient"); insert(root, "retrieval"); insert(root, "structure"); // search for "book" in our trie string str; cout<<"Enter Word to search:"; cin>>str; cout << search(root, str); return 0; } ================================================ FILE: Data-Structures/Tree/Trie/trie.py ================================================ class TrieNode: def __init__(self): self.children = [None]*26 self.isEndOfWord = False class Trie: def __init__(self): self.root = self.getNode() def getNode(self): # Returns new trie node (initialized to NULLs) return TrieNode() def _charToIndex(self,ch): return ord(ch)-ord('a') def insert(self,key): pCrawl = self.root length = len(key) for level in range(length): index = self._charToIndex(key[level]) # if current character is not present if not pCrawl.children[index]: pCrawl.children[index] = self.getNode() pCrawl = pCrawl.children[index] pCrawl.isEndOfWord = True def search(self, key): pCrawl = self.root length = len(key) for level in range(length): index = self._charToIndex(key[level]) if not pCrawl.children[index]: return False pCrawl = pCrawl.children[index] return pCrawl != None and pCrawl.isEndOfWord # driver function def main(): print("Input keys (use only 'a' through 'z' and lower case") keys=[] n=input("Enter number of arguments") for i in range(n): keys.append(input()) output = ["Not present in trie", "Present in trie"] # Trie object t = Trie() # Construct trie for key in keys: t.insert(key) print("{} ---- {}".format("the",output[t.search("the")])) print("{} ---- {}".format("these",output[t.search("these")])) print("{} ---- {}".format("their",output[t.search("their")])) print("{} ---- {}".format("thaw",output[t.search("thaw")])) if __name__ == '__main__': main() ================================================ FILE: LICENSE ================================================ MIT License Copyright (c) 2021 Priyanshu Tiwari Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ================================================ FILE: Maths/Algebra/Babylionian/Babylionian.cs ================================================ // C# Porgram for Babylonian // method of square root // Contributed By - Ayush Sharma (belphegor-s) using System; class SQRT { // Returns the square root of n. // Note that the function static float squareRoot(float n) { // We are using n itself as // initial approximation This // can definitely be improved float x = n; float y = 1; // e decides the // accuracy level double e = 0.000001; while (x - y > e) { x = (x + y) / 2; y = n / x; } return x; } public static void Main() { int n = Console.ReadLine(); Console.Write("Square root of " + n + " is " + squareRoot(n)); } } ================================================ FILE: Maths/Algebra/Babylionian/Babylionian.go ================================================ package main import ( "fmt" "strconv" ) func main() { fmt.Println("Enter the number for which square root is to be found :") var n string fmt.Scan(&n) var a float64 = 1 var e float64 = 0.000001 value, err := strconv.ParseFloat(n, 64) var temp float64 = value if err != nil { fmt.Printf("%s is not a valid number ", n) return } for temp-a > e { temp = (temp + a) / 2 a = value / temp } fmt.Printf("Square rooot of %f is %.02f \n", value, temp) } ================================================ FILE: Maths/Algebra/Babylionian/Babylonian.java ================================================ class Babylonian { /*Returns the square root of n. Note that the function */ static float squareRoot(float n) { /*We are using n itself as initial approximation This can definitely be improved */ float x = n; float y = 1; // e decides the accuracy level double e = 0.000001; while (x - y > e) { x = (x + y) / 2; y = n / x; } return x; } /* Driver program to test above function*/ public static void main(String[] args) { System.out.print("Please enter a number: "); Scanner myObj = new Scanner(System.in); try { Float n = myObj.nextFloat(); System.out.printf("Square root of " + n + " is " + squareRoot(n)); } catch (InputMismatchException e) { String msg = e.getMessage(); System.out.println("That is not a number, please try again."); } } } ================================================ FILE: Maths/Algebra/Babylonian/Babylonian.js ================================================ function babylonianSqrt(n) { // Checks for valid number input if (!(typeof n === 'number' && n >= 0 && !isNaN(n))) { return NaN; } else if (n === 0) { return 0; } else if (n === Infinity) { return Infinity; } var value = n; while (true) { var last = value; // Calculate value value = (value + n / value) * 0.5; // Check if true if (Math.abs(value - last) < 1e-9) { break; } } return value; } // Test let userInput = parseInt(prompt("Enter a number to find the Babylonian square root:")) babylonianSqrt(userInput); ================================================ FILE: Maths/Algebra/Babylonian/babylonian_square_root.c ================================================ /* Babylonian is used to find the square root of a number. It is a very old method. */ #include /* squareRoot function @param:num the number whose square root is to find. return square root of the number in float. */ float squareRoot( int num ){ float x = num, y = 1.0, diff = 0.000001; while( x - y > diff ){ x = ( x + y ) / 2 ; y = num / x ; } return x; } //main function int main(){ int num = 0; float result = 0.0; printf( "Enter a number to find Square Root :" ); scanf( "%d", &num ); result = squareRoot( num ); if( num < 0 ){ printf( "Square Root is not real for negative numbers. \n"); return 0; } printf( "The Square Root of %d : %f\n", num, result ); return 0; } // Contributed by Vishwaroop Shah ================================================ FILE: Maths/Algebra/Derivative_Of_Polynomial/Matrix_Multiplication.c ================================================ #include #define MAX 100 int main() { int arow,acolumn,brow,bcolumn,i,j,k; int a[MAX][MAX],b[MAX][MAX],product[MAX][MAX]; int sum=0; printf("Enter the number of row and column of matrix A:"); scanf("%d%d",&arow,&acolumn); printf("Enter the elements of matric A:"); for(i=0;i unsigned int factorial(unsigned int n) { int fact = 1, i; for (i = 2; i <= n; i++) fact *= i; return fact; } int main() { int num; printf("Enter a non-negative number: "); scanf("%d",&num); if(num<0){ printf("Factorial of a negative integer cannot be found"); } else{ printf("Factorial of %d is %d", num, factorial(num)); } return 0; } ================================================ FILE: Maths/Algebra/Factorial/factorial.cpp ================================================ #include using namespace std; int factorial(int n); int main() { int n; cout << "Enter a positive integer: "; cin >> n; cout << "Factorial of " << n << " = " << factorial(n); return 0; } int factorial(int n) { if(n > 1) return n * factorial(n - 1); else return 1; } ================================================ FILE: Maths/Algebra/Factorial/factorial.cs ================================================ using System; public class FactorialExample { public static void Main(string[] args) { int i,fact=1,number; Console.Write("Enter a non-negative Number: "); number= int.Parse(Console.ReadLine()); for(i=1;i<=number;i++){ fact=fact*i; } Console.Write("Factorial of " +number+" is: "+fact); } } ================================================ FILE: Maths/Algebra/Factorial/factorial.go ================================================ package main import ( "fmt" ) func IterativeFactorial(number int) uint64 { var result uint64 = 1 if number < 0 { } else { for i := 1; i <= number; i++ { result *= uint64(i) } } return result } func main() { var number int fmt.Print("Enter Number:") fmt.Scanln(&number) fmt.Printf("Factorial of %d = %d", number, IterativeFactorial(number)) } ================================================ FILE: Maths/Algebra/Factorial/factorial.js ================================================ let number = parseInt(prompt("Enter a positive integer: ")); if (number < 0) { console.log("Factorial for negative number does not exist."); } else if (number === 0) { console.log(`The factorial of ${number} is 1.`); } else { let fact = 1; for (let i = 1; i <= number; i++) { fact *= i; } console.log(`The factorial of ${number} is ${fact}.`); } ================================================ FILE: Maths/Algebra/Factorial/factorial.php ================================================ Factorial Program using loop in PHP
Enter the Number:

"; echo fact($number) . "
"; } ?> ================================================ FILE: Maths/Algebra/Factorial/factorial.py ================================================ # recursive function to calculate factorial of a number def fact(num): # if the number is greater than 0 # make a recursive call to the function if num > 0: factorial = num * fact(num-1) else: factorial = 1 # return the factorial return factorial # taking an integer input n = int(input("Enter the number: ")) # print the factorial of the number print(fact(n)) ================================================ FILE: Maths/Algebra/Factorial/factorial.rb ================================================ puts "Enter a non-negative number:" num= gets.to_i fact=1 if (num<0) puts "Factorial of a non-negative number doesn't exists" else i=1 while(i<=num) fact=fact*i i+=1 end puts "factorial of #{num} is #{fact}" end ================================================ FILE: Maths/Algebra/Factorial/factorial.sh ================================================ #!/bin/bash # Usage: factorial [n] factorial=1 if [ $# -eq 1 ]; then n=$1 while [ $n -gt 0 ]; do factorial=$(( $n * $factorial )) n=$(( $n - 1 )) done echo $factorial else echo "Usage: $0 [n]" fi ================================================ FILE: Maths/Algebra/Factorial/factorial.swift ================================================ import UIKit let num=readline() var a=Int(num!) func factorial(a: Int) -> Int { let n = a if(n == 1){ return 1 }else{ return n*factorial(n-1) } } factorial(a: a) ================================================ FILE: Maths/Algebra/Factorial/factorial.ts ================================================ // tail recyrsion not work in js, but not the worst decision const factorial = (n: number): number => rFactorial(n, 1); const rFactorial = (n:number, acc:number): number => (n <= 0) ? acc : rFactorial(n-1, n*acc); factorial(11) ================================================ FILE: Maths/Algebra/Factorial_of_Large_Number/Factorial_of_Large_Number.cs ================================================ using System; using System.Collections.Generic; public class Factorial_of_Large_Number { private static List resultDigits; public static void Main(string[] args) { resultDigits = null; Console.Write("Enter a number to find its factorial: "); int number = Convert.ToInt32(Console.ReadLine()); FindFactorial(number); Console.WriteLine("The factorial value is: "); DisplayDigits(); resultDigits = null; } // initializes resultDigits list with one element, 1 // multiplies factors 2, 3, ..., n-1, n static void FindFactorial(int n) { resultDigits = new List(); resultDigits.Add(1); for (int factor = 2; factor <= n; ++factor) { DigitWiseMultiply(factor); } } // multiplies factor to list treating each element as digit // this accounts for carry as well static void DigitWiseMultiply(int factor) { int carry = 0; for (int i = resultDigits.Count - 1; i >= 0; --i) { int temp = resultDigits[i] * factor + carry; resultDigits[i] = temp % 10; carry = temp / 10; } // inserts leftover carry to the start of list while (carry > 0) { resultDigits.Insert(0, carry % 10); carry /= 10; } } // loops through resultDigits and prints it static void DisplayDigits() { for (int i = 0; i < resultDigits.Count; ++i) { Console.Write(resultDigits[i]); } } } ================================================ FILE: Maths/Algebra/Factorial_of_Large_Number/Factorial_of_Large_Number.hs ================================================ module Factorial_of_Large_Number (fact) where fact x = foldr (*) [1..x] ================================================ FILE: Maths/Algebra/Factorial_of_Large_Number/Factorial_of_Large_Number.js ================================================ /* Factorial simply tells us to multiply any natural number by all the natural numbers that are smaller than it. Example : If we're asked to evaluate 5!, I simply have to do 5 * 4 * 3 * 2 * 1, and I get 120. */ // Recursive function to calculate factorial of a large number const largeNumberFactorial = (num) => { if (num === 0n) return 1n; return num * largeNumberFactorial(num - 1n); }; const number = 50; // Calling Function const factorial = String(largeNumberFactorial(BigInt(number))); console.log(`Factorial of ${number} is ${factorial}`); /* Output : Factorial of 50 is 30414093201713378043612608166064768844377641568960512000000000000 */ ================================================ FILE: Maths/Algebra/Factorial_of_Large_Number/Factorial_of_Large_Number.php ================================================ = 0; $i--) { $currentResult = $digitArray[$i] * $number + $carry; $digitArray[$i] = (int) ($currentResult % 10); $carry = (int) ($currentResult / 10); } while($carry > 0) { array_unshift($digitArray, (int) ($carry % 10)); $carry = (int) ($carry / 10); } } // Test $number = 70; echo "Factorial of {$number} is: " . factorial($number); //Output => Factorial of 70 is: 11978571669969891796072783721689098736458938142546425857555362864628009582789845319680000000000000000 ================================================ FILE: Maths/Algebra/Factorial_of_Large_Number/Factorial_of_large_number.c ================================================ #include unsigned int factorial(unsigned int n) { int fact = 1, i; for (i = 2; i <= n; i++) fact *= i; return fact; } int main() { int num; printf("Enter a non-negative number: "); scanf("%d",&num); if(num<0){ printf("Factorial of a negative integer cannot be found"); } else{ printf("Factorial of %d is %d", num , factorial(num)); } return 0; } ================================================ FILE: Maths/Algebra/Factorial_of_Large_Number/README.md ================================================ ## This folder is empty. ================================================ FILE: Maths/Algebra/Factorial_of_Large_Number/bigfactorial.cpp ================================================ #include using namespace std; #define MAX 500 int multiply(int x, int res[], int res_size); void factorial(int n) { int res[MAX]; res[0] = 1; int res_size = 1; for (int x=2; x<=n; x++) res_size = multiply(x, res, res_size); cout << "Factorial of given number is \n"; for (int i=res_size-1; i>=0; i--) cout << res[i]; } int multiply(int x, int res[], int res_size) { int carry = 0; // Initialize carry for (int i=0; i Int { var bigger = max(input1, input2) var smaller = min(input1, input2) while smaller > 0 { let rem = bigger % smaller bigger = smaller; smaller = rem } return bigger } var number1 = Int(readLine()!)! var number2 = Int(readLine()!)! let res = getGCD(input1: number1, input2: number2) print("GCD of \(number1) and \(number2) is \(res)") ================================================ FILE: Maths/Algebra/GCD/Euclidean_gcd.py ================================================ def euclideanGCD(x, y): while(y): x, y = y, x % y return x a = 10 b= 35 print ("The gcd of 10 and 35 is : ",end="") print (euclideanGCD(10,35)) ================================================ FILE: Maths/Algebra/GCD/EuclidianGCD.py ================================================ def gcd(a, b): if a == 0 : return b return gcd(b%a, a) a,b=map(int,input().split()) print(gcd(a,b)) ================================================ FILE: Maths/Algebra/GCD/GCD.cpp ================================================ // Implementing Euclid algorithm to find GCD #include using namespace std; // Finding GCD using Euclid algorithm by recursion int gcd(int a, int b) { if (a == 0) { return b; } return gcd(b % a, a); } //main function int main() { // taking input the required two numbers // whose gcd is to be calculated int a, b; cin >> a >> b; cout << gcd(a, b); return 0; } ================================================ FILE: Maths/Algebra/GCD/GCD.cs ================================================ using System; public class Program { static int GCD(int num1, int num2) { int Remainder; while (num2 != 0) { Remainder = num1 % num2; num1 = num2; num2 = Remainder; } return num1; } static int Main(string[] args) { int x, y; Console.Write("Enter the First Number : "); x = int.Parse(Console.ReadLine()); Console.Write("Enter the Second Number : "); y = int.Parse(Console.ReadLine()); Console.Write("\nThe Greatest Common Divisor of "); Console.WriteLine("{0} and {1} is {2}", x, y, GCD(x, y)); Console.ReadLine(); return 0; } } ================================================ FILE: Maths/Algebra/GCD/GCD.js ================================================ function gcd_two_numbers(x, y) { // Check if number is numerial or not if ((typeof x !== 'number') || (typeof y !== 'number')) return false; // Taking absolute values x = Math.abs(x); y = Math.abs(y); // Calculating GCD while (y) { var t = y; y = x % y; x = t; } return x; } // Test Cases console.log(gcd_two_numbers(12, 13)); console.log(gcd_two_numbers(9, 3)); // Output : > // 1 // 3 ================================================ FILE: Maths/Algebra/GCD/GCD.php ================================================ Here's my solution for getting the GCD of several numbers. ================================================ FILE: Maths/Algebra/GCD/GCD.py ================================================ # function def euclid_gcd(a, b): if b == 0: print(a) return a c = a%b euclid_gcd(b, c) # input 2 numbers with a space between them a, b = map(int, input().split()) euclid_gcd(min(a, b),max(a,b)) ================================================ FILE: Maths/Algebra/GCD/GCD.rb ================================================ #!/usr/bin/env ruby -w def gcd(num1, num2) return num1 if num2 == 0 gcd(num2, num1 % num2) end num1 = gets.chomp.to_i num2 = gets.chomp.to_i puts gcd(num1, num2) ================================================ FILE: Maths/Algebra/GCD/GCD.sh ================================================ #!/bin/bash echo "Enter two numbers to find their GCD" read a b x=$((a)) y=$((b)) while [ $a -ne $b ] do if [ $a -gt $b ] then let "a-=b" else let "b-=a" fi done echo "The GCD of "$((x))" and "$((y))" is = "$((a)) exit ================================================ FILE: Maths/Algebra/GCD/README.md ================================================ ## This folder is empty. ================================================ FILE: Maths/Algebra/GCD/gcd.java ================================================ import java.util.Scanner; public class GCD { public static void main(String args[]) { Scanner sc = new Scanner(System.in); System.out.println("Please enter first number to find GCD"); int n1 = sc.nextInt(); System.out.println("Please enter second number to find GCD"); int n2 = sc.nextInt(); System.out.println("GCD of two numbers " + n1 +" and " + n2 +" is :" + findGCD(n1,n2)); } /* * Java method to find GCD of two number using Euclid's method * @return GDC of two numbers in Java */ private static int findGCD(int number1, int number2) { //base case if(number2 == 0) { return number1; } return findGCD(number2, number1%number2); } } ================================================ FILE: Maths/Algebra/Inverse_of_a_Matrix/README.md ================================================ ## This folder is empty. ================================================ FILE: Maths/Algebra/LCM/LCM.c ================================================ #include int main() { int n1, n2, max; printf("Enter two positive integers: "); scanf("%d %d", &n1, &n2); // maximum number between n1 and n2 is stored in min max = (n1 > n2) ? n1 : n2; while (1) { if (max % n1 == 0 && max % n2 == 0) { printf("The LCM of %d and %d is %d.", n1, n2, max); break; } ++max; } return 0; } ================================================ FILE: Maths/Algebra/LCM/LCM.cpp ================================================ #include namespace algo_ds { /* * The implementation are kinda cryptic. I will try my best to explain what all the template stuff means * First off, both lcm and gcd are function templates, taking `a` of type T and `b` of type U * * If both T and U are the same, the return type is gonna be just that, otherwise, std::common_type_t comes in. * std::common_type_t does some hackery, and gives us a type both T and U are convertible to. If such a type * doesn't exist... there's gonna be some template errors (although on clang 10.1 at least, they are pretty good) * * the noexcept basically means, that if T and U are primitives, i.e. [int, long, unsigned, char] etc., it is guaranteed * the "functions" won't throw an exception */ //implementation for a gcd function template in C++ 14 template [[nodiscard]] constexpr std::common_type_t gcd(const T& a, const U& b) noexcept(std::is_integral::value && std::is_integral::value) { if (a == 0) { return b; } return gcd(b % a, a); } //implementation for a lcm function template in C++ 14 template [[nodiscard]] constexpr std::common_type_t lcm(const T& a, const U& b) noexcept(std::is_integral::value && std::is_integral::value) { return (a / gcd(a, b)) * b; } } /** * Prints a nice table, the output should look like this: Table of the least common multiples for the pairs in the range 1-9: 1 | 2 3 4 5 6 7 8 9 ______________________________________________________ 2 | 2 6 4 10 6 14 8 18 3 | 6 3 12 15 6 21 24 9 4 | 4 12 4 20 12 28 8 36 5 | 10 15 20 5 30 35 40 45 6 | 6 6 12 30 6 42 24 18 7 | 14 21 28 35 42 7 56 63 8 | 8 24 8 40 24 56 8 72 9 | 18 9 36 45 18 63 72 9 */ #include #include int main() { std::cout << "Table of the least common multiples for the pairs in the range 1-9:\n\n"; for(auto i = 1; i < 10; i++) { //Make the table look pretty by giving it a border if(i == 2) { for(auto j = 0; j < 6*9; j++) { std::cout << '_'; } std::cout << '\n'; } for(auto j = 1; j < 10; j++) { //setw() to align the numbers in the table std::cout << std::setw(5) << algo_ds::lcm(i, j) << ' '; if(j == 1) //again, making a border { std::cout << '|'; } } std::cout << '\n'; } } ================================================ FILE: Maths/Algebra/LCM/LCM.java ================================================ // Java program to find LCM of two numbers. class Test { static int gcd(int a, int b) { if (a == 0) return b; return gcd(b % a, a); } static int lcm(int a, int b) { return (a / gcd(a, b)) * b; } public static void main(String[] args) { int a = 15, b = 20; System.out.println("LCM of " + a + " and " + b + " is " + lcm(a, b)); } } ================================================ FILE: Maths/Algebra/LCM/LCM.js ================================================ let lcm = (n1, n2) => { //Find the smallest and biggest number from both the numbers let lar = Math.max(n1, n2); let small = Math.min(n1, n2); //Loop till you find a number by adding the largest number which is divisble by the smallest number let i = lar; while (i % small !== 0) { i += lar; } //return the number return i; }; console.log(lcm(12, 13)); console.log(lcm(9, 3)); ================================================ FILE: Maths/Algebra/LCM/LCM.py ================================================ def lcm(x:int, y:int) -> int: ''' Input: 2 integers x and y Output: The smallest integer which is divisible by both x and y ''' greater = max(x,y) lesser = min(x,y) multiple = 1 while ((greater * multiple) % lesser != 0): # I use instead of because greater steps through the number line faster multiple += 1 return greater * multiple def main(): num1 = int(input()) num2 = int(input()) print(f"LCM({num1}, {num2}) = {lcm(num1,num2)}") if __name__ == "__main__": main() ================================================ FILE: Maths/Algebra/LCM/LCM.sh ================================================ echo "Enter any two numbers to find their LCM : " read a b x=$((a)) y=$((b)) while [ $a -ne $b ] do if [ $a -gt $b ] then let "a-=b" else let "b-=a" fi done lcm=$(((x*y)/a)) echo "LCM of "$x" and "$y" is = "$lcm ================================================ FILE: Maths/Algebra/LCM/LCM_GCD.c ================================================ #include int main() { int x,y,gcd,lcm; printf("Enter any two number to find LCM AND GCD:"); scanf("%d%d",&x,&y); if(x>y) z=x; else { z=y; } for(gcd=z;gcd>=1;gcd--) { if(x%gcd==0 && y%gcd==0) break; } printf("The Gcd of %d,%d = %d",x,y,gcd); lcm=(x*y)/gcd; printf("The Lcm of %d, %d = %d",x,y,lcm); return 0; } ================================================ FILE: Maths/Algebra/LCM/LCM_python.py ================================================ def compute_gcd(x, y): while(y): x, y = y, x % y return x def compute_lcm(x, y): lcm = (x*y)//compute_gcd(x,y) return lcm num1 = 54 num2 = 24 print("The L.C.M. is", compute_lcm(num1, num2)) ================================================ FILE: Maths/Algebra/LCM/README.md ================================================ ## This folder is empty. ================================================ FILE: Maths/Algebra/Markov_Matrix/MarkovMatrix.java ================================================ import java.util.Scanner; public class MarkovMatrix{ public static void main(String []args){ Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int m = sc.nextInt(); double[][] markovMatrix = new double[n][m]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { markovMatrix[i][j] = sc.nextDouble(); } } double rowSum = 0; for (int i = 0; i < n; i++) { rowSum = 0; for (int j = 0; j < m; j++) { rowSum += markovMatrix[i][j]; } if (rowSum != 1) throw new RuntimeException("Row sum != 1"); } System.out.print ("Input matrix is a Markov matrix"); } } /* 2 2 0.4 0.6 0.5 0.5 = Markov matrix 2 2 0.1 0.1 1 1 = not a Markov matrix, results in error */ ================================================ FILE: Maths/Algebra/Markov_Matrix/Markov_Matrix.c++ ================================================ #include using namespace std; int main() { int i ,j ,n,m; cout << "Enter Number of Rows and Columns :- " << "\n"; cin >> n >> m; double Matrix[n][m]; cout << "Enter Matrix Elements :- " << "\n"; for (i = 0; i < n; i++) { for(j = 0 ; j < m;j++) cin >> Matrix[i][j]; } int flag = -1; for(i = 0; i ().Any(element => element > 1 || element < 0); } private static bool IsLeftStochastic(decimal[,] matrix) { //a left stochastic matrix has a sum of 1 for each column //to check this, we iterate through each column and check the sum of it's elements var columnCount = matrix.GetLength(1); for (var i = 0; i < columnCount; i++) { if (GetColumn(matrix, i).Sum() != 1) return false; } return true; } private static bool IsRightStochastic(decimal[,] matrix) { //a right stochastic matrix has a sum of 1 for each row //to check this, we iterate through each row and check the sum of it's elements var rowCount = matrix.GetLength(0); for (var i = 0; i < rowCount; i++) { if (GetRow(matrix, i).Sum() != 1) return false; } return true; } private static IEnumerable GetRow(decimal[,] matrix, int rowIndex) { //Get a certain row inside the matrix: iterate through all columns with fixed row index var columnCount = matrix.GetLength(1); for (var i = 0; i < columnCount; i++) { yield return matrix[rowIndex, i]; } } private static IEnumerable GetColumn(decimal[,] matrix, int columnIndex) { //Get a certain column inside the matrix: iterate through all rows with fixed column index var rowCount = matrix.GetLength(0); for (var i = 0; i < rowCount; i++) { yield return matrix[i, columnIndex]; } } } public enum MatrixType { NotAMarkovMatrix = 0, RightStochasticMatrix = 1, LeftStochasticMatrix = 2, DoublyStochasticMatrix = 3 } //use dotnet-script to run this code Console.WriteLine("Enter Matrix to check, line by line"); Console.WriteLine("Columns are separated by single space character"); Console.WriteLine("Empty string ends input and starts validation"); var input = Console.ReadLine(); var numbersList = input.Split(' ').Select(i => decimal.Parse(i)).ToList(); var columns = numbersList.Count(); var rows = 1; input = Console.ReadLine(); while (!string.IsNullOrWhiteSpace(input)) { var row = input.Split(' ').Select(i => decimal.Parse(i)).ToList(); if (row.Count == columns) { numbersList.AddRange(row); rows++; } else { Console.WriteLine("All rows must have the same amount of columns"); } input = Console.ReadLine(); }; var matrix = ConvertToSquareArray(rows, columns, numbersList); Console.WriteLine(MarkovMatrix.Validate(matrix)); private static decimal[,] ConvertToSquareArray(int rows, int columns, List numbers) { var index = 0; var rowIndex = 0; var colIndex = 0; var matrix = new decimal[rows, columns]; foreach (var number in numbers) { matrix.SetValue(number, rowIndex, colIndex); index++; rowIndex += 1; rowIndex %= rows; colIndex += 1; colIndex %= columns; } return matrix; } ================================================ FILE: Maths/Algebra/Markov_Matrix/Markov_Matrix.js ================================================ function isMarkovMatrix(matrix) { let isRight = isRightMarkov(matrix) let isLeft = isLeftMarkov(matrix) if (isRight && isLeft) { //If the matrix is a right and left Markov algorithm -> doubly markov matrix return 3 } else if (isLeft) { //If the matrix is a left markov algorithm return 2 } else if (isRight) { //If the matrix is a right markov algorithm return 1 } else { //If every test fails, then its not a Markov matrix return 0 } } function isRightMarkov(matrix) { //Each row summing to 1 if ( matrix .map(val => { //Get each row of the matrix and transform it to the //sum of all the elements in each row return val.reduce((prev, curr) => prev + curr) }) .every(row => row == 1) //Check if every sum equals to 1 ) { return true //If check is true } return false //If check is false } function isLeftMarkov(matrix) { //Each collumn summing to 1 let rot_matrix = matrix.map((val, index) => matrix.map(row => row[index])) //Rotates the matrix 90° //When rotated, collumns become rows, so we can reuse the isRightMarkov function return isRightMarkov(rot_matrix) //See if its a right markov matrix } //EXAMPLE INPUT let example_matrix = [ [0.9, 0.1], //Right markov matrix example [0.5, 0.5], /* [0.9, 0.5], //left markov matrix example [0.1, 0.5], [1, 0, 0,], //not markov matrix example [0, 0, 2], [0, 0, 1] [1, 0, 0,], //doubly markov matrix example [0, 1, 0], [0, 0, 1] */ ] //EXAMPLE OUTPUT switch (isMarkovMatrix(example_matrix)) { case 3: console.log("doubly markov matrix") break case 2: console.log("left markov matrix") break case 1: console.log("right markov matrix") break case 0: console.log("its not a markov matrix") break } ================================================ FILE: Maths/Algebra/Matrix_Multipication/MatMul.cpp ================================================ #include #include #include #include #include #include template class Matrix { std::vector> data; public: Matrix(std::vector> dataArray) { data = dataArray; } Matrix(size_t row, size_t col) { data = std::vector> (row, std::vector(col, 0)); ; } T& operator[](std::array index) { size_t row = index[0]; size_t column = index[1]; return data[row][column]; } size_t rowCount() { return data.size(); } size_t columnCount() { return data[0].size(); } std::string toString() { std::string r = "{"; for (size_t y = 0; y < rowCount(); y++) { r += '{'; for (size_t x = 0; x < columnCount(); x++) { r += std::to_string((*this)[{y, x}]); if (x != columnCount() - 1)r += ','; } r+='}'; if (y != rowCount() - 1)r += ','; } r += '}'; return r; } }; template Matrix operator*(Matrix &a, Matrix &b) { if (a.columnCount() != b.rowCount()) throw std::invalid_argument("Must be multiplication between matrixes MxN and NxP"); Matrix r(a.rowCount(), b.columnCount()); int sharedVal = a.columnCount(); for (size_t i = 0; i < r.rowCount(); i++) for (size_t j = 0; j < r.columnCount(); j++) for (size_t n = 0; n < sharedVal; n++) { r[{i, j}] += a[{i, n}] * b[{n, j}]; } return r; } int main() { int m, n, p; std::cout << "insert m, n, and p: "; std::cout.flush(); std::cin >> m; std::cin >> n; std::cin >> p; Matrix a(m, n); for (size_t y = 0; y < m; y++) { for (size_t x = 0; x < n; x++) { std::cout << "a(" << y << ',' << x << "): "; std::cout.flush(); std::cin >> a[{y, x}]; } } Matrix b(n, p); for (size_t y = 0; y < n; y++) { for (size_t x = 0; x < p; x++) { std::cout << "b(" << y << ',' << x << "): "; std::cout.flush(); std::cin >> b[{y, x}]; } } Matrix r = a*b; std::cout << "a: " << a.toString() << std::endl; std::cout << "b: " << b.toString() << std::endl; std::cout << "r: " << r.toString() << std::endl; } ================================================ FILE: Maths/Algebra/Matrix_Multipication/MatrixMultipication.py ================================================ def matrixMultiplication(matrixA, matrixB): resultMatrix = [] sizeOfMatrixA = len(matrixA) sizeOfMatrixB = len(matrixB) for rowIndex in range(sizeOfMatrixA): tempList = [] for columnIndex in range(sizeOfMatrixB): sum = 0 for columnIndexMatrixA in range(len(matrixA[0])): sum += matrixA[rowIndex][columnIndexMatrixA] * matrixB[columnIndexMatrixA][columnIndex] tempList.append(sum) resultMatrix.append(tempList) return resultMatrix A = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] B = [[9, 8, 7], [6, 5, 4], [3, 2, 1]] print(matrixMultiplication(A, B)) ================================================ FILE: Maths/Algebra/Matrix_Multipication/MatrixMultiply.java ================================================ import java.util.*; public class MatrixMultiply { private static Scanner sc = new Scanner(System.in); public static void main(String[] args) { System.out.println("Enter the number of rows of 1st matrix"); int m = sc.nextInt(); System.out.println("Enter the number of columns of 1st matrix"); int n = sc.nextInt(); System.out.println("Enter the number of rows of 2nd matirx"); int p = sc.nextInt(); System.out.println("Enter the number of columns of 2nd matrix"); int q = sc.nextInt(); if(n!=p) { System.out.println("Sorry the matrix cannot be multiplied"); }else { int first[][] = new int[m][n]; int second[][] = new int[p][q]; System.out.println("Enter the elements of the 1st matrix"); for(int i=0;i #include int main(){ int a[10][10],b[10][10],mul[10][10],r,c,i,j,k; system("cls"); printf("enter the number of row="); scanf("%d",&r); printf("enter the number of column="); scanf("%d",&c); printf("enter the first matrix element=\n"); for(i=0;i using namespace std; int main() { int a[10][10],b[10][10],mul[10][10],r,c,i,j,k; cout<<"enter the number of row="; cin>>r; cout<<"enter the number of column="; cin>>c; cout<<"enter the first matrix element=\n"; for(i=0;i>a[i][j]; } } cout<<"enter the second matrix element=\n"; for(i=0;i>b[i][j]; } } cout<<"multiply of the matrix=\n"; for(i=0;i ================================================ FILE: Maths/Algebra/Matrix_Multipication/multiply.py ================================================ matB = [] matA = [] rows,columns = map(int,input("Enter rows and columns for matrices").split()) for i in range(rows): matA.append([]) for j in range(columns): matA[i].append(int(input(f"Enter a no. for matrixA[{i}][{j}] : "))) for i in range(rows): matB.append([]) for j in range(columns): matB[i].append(int(input(f"Enter a no. for matrixB[{i}][{j}] : "))) print("------------------------------\n Matrix A is : ") for i in matA: print(i) print("------------------------------\n Matrix B is : ") for i in matB: print(i) matM = [] for i in range(rows): matM.append([]) for j in range(columns): sum_of_column = 0 for k in range(rows): sum_of_column += matA[i][k]*matB[k][i] matM[i].append(sum_of_column) print("------------------------------\nMultiplication of the Matrix A and B is : ") for i in matM: print(i) # OUTPUT #Enter rows and columns for matrices2 2 #Enter a no. for matrixA[0][0] : 1 #Enter a no. for matrixA[0][1] : 2 #Enter a no. for matrixA[1][0] : 3 #Enter a no. for matrixA[1][1] : 4 #Enter a no. for matrixB[0][0] : 1 #Enter a no. for matrixB[0][1] : 1 #Enter a no. for matrixB[1][0] : 1 #Enter a no. for matrixB[1][1] : 1 #------------------------------ # Matrix A is : #[1, 2] #[3, 4] #------------------------------ # Matrix B is : #[1, 1] #[1, 1] #------------------------------ #Multiplication of the Matrix A and B is : #[3, 3] #[7, 7] ================================================ FILE: Maths/Algebra/Permutation_And_Combination/Permutations_Combinations.ipynb ================================================ { "nbformat": 4, "nbformat_minor": 0, "metadata": { "colab": { "name": "Untitled3.ipynb", "provenance": [] }, "kernelspec": { "name": "python3", "display_name": "Python 3" } }, "cells": [ { "cell_type": "code", "metadata": { "id": "UPeL109N3trH", "outputId": "d0555f7e-a5be-4fac-e437-57534267f35b", "colab": { "base_uri": "https://localhost:8080/", "height": 187 } }, "source": [ "#finding permutations of elements in a list\n", "from itertools import permutations\n", "n=int(input('enter no of elements'))\n", "list=[]\n", "for i in range (0,n):\n", " a=int(input('enter number'))\n", " list.append(a)\n", "seq=permutations(list)\n", "for p in seq:\n", " print(p)" ], "execution_count": 4, "outputs": [ { "output_type": "stream", "text": [ "enter no of elements3\n", "enter number1\n", "enter number2\n", "enter number3\n", "(1, 2, 3)\n", "(1, 3, 2)\n", "(2, 1, 3)\n", "(2, 3, 1)\n", "(3, 1, 2)\n", "(3, 2, 1)\n" ], "name": "stdout" } ] }, { "cell_type": "code", "metadata": { "id": "gDYpPS7I5Reo", "outputId": "2707482d-92dc-472f-f8be-29a515d95bb1", "colab": { "base_uri": "https://localhost:8080/", "height": 119 } }, "source": [ "#Find the permutation by defining the length of the permutation.\n", "seq = permutations(list, 2)\n", "for p in seq:\n", " print(p)" ], "execution_count": 5, "outputs": [ { "output_type": "stream", "text": [ "(1, 2)\n", "(1, 3)\n", "(2, 1)\n", "(2, 3)\n", "(3, 1)\n", "(3, 2)\n" ], "name": "stdout" } ] }, { "cell_type": "code", "metadata": { "id": "V3wJrRPC5ujs", "outputId": "4101b4de-0bfc-4da3-c8cf-b14e45820a4e", "colab": { "base_uri": "https://localhost:8080/", "height": 68 } }, "source": [ "from itertools import combinations\n", "#Getting all combination of a particular length.\n", "combi = combinations(list, 2)\n", "\n", "#Print the list of combinations\n", "\n", "for c in combi:\n", " print(c)" ], "execution_count": 7, "outputs": [ { "output_type": "stream", "text": [ "(1, 2)\n", "(1, 3)\n", "(2, 3)\n" ], "name": "stdout" } ] } ] } ================================================ FILE: Maths/Algebra/Permutation_And_Combination/README.md ================================================ ## This folder is empty. ================================================ FILE: Maths/Algebra/Permutation_And_Combination/permutation_combination.cpp ================================================ #include using namespace std; long long factorial( long long num ){ if( ( num == 0 ) || ( num == 1 )){ return num; } long long fact = 1; while( num > 0 ){ fact = fact * num; num = num - 1; } return fact; } long long permutation( long long n , long long r ){ return ( factorial( n ) / factorial( n - r ) ); } long long combination( long long n , long long r ){ return ( factorial ( n ) / ( factorial ( r ) * factorial ( n - r ) ) ); } int main(){ long long selection = 0, n = 0 , r = 0; cout<<"Press 1 for Permutaion or Press 2 for Combination :"; cin >> selection; if( (selection != 1 ) && ( selection != 2 ) ){ cout <<""<<"\n"; return 1; } cout<<"Enter the value of the places [n] and the number of objects [r] :"; cin >> n >> r; if( n < r ){ cout<<"\n"; return 1; } if( selection == 1 ){ cout <<"Permutation :"< [option 1] [option 2] [option 3] // example "node permutation_combination.js c 100 40" /// this is a self-invoked function (function run(){ /// check if the input size is right node [option 1] [option 2] [option 3] let inputSize = process.argv.length === 5 ; /// validate first option to be

or let validateFirstInput = (process.argv[2]).toLowerCase() ==='p' || (process.argv[2]).toLowerCase() ==='c'; /// validate that options 3 and 4 are not a not a number (this is a double negation lol :'D ) let validateSecondAndThirdInput = !isNaN( process.argv[3]) && !isNaN( process.argv[4]); const permutationOrCombination = process.argv[2].toLowerCase(); const N = parseInt( process.argv[3]); const R = parseInt( process.argv[4]); let nGreaterthanR = N > R; let greaterThanZero = N>0 && R > 0 /// the input must meet all above constraints anded together so if not we output the menu then return if(!(inputSize && validateFirstInput && validateSecondAndThirdInput && nGreaterthanR && greaterThanZero)){ promoptForInput(); return ; } if(permutationOrCombination ==='p'){ console.log(`permutation ${N}P${R} =` , permutation(N,R)); } else { console.log(`Combination ${N}C${R} =` , permutation(N,R)); } })(); /// this is the simplest implementation for nPr and nCr /// but not the most efficient one /// this is the first release so I will improve it in future if I have time function permutation(N , R){ return Factorial(N)/Factorial(N-R); } function permutation(N , R){ return Factorial(N)/Factorial(N-R); } function combination(N, R){ return Factorial(N)/(Factorial(N-R) * Factorial(R)); } function Factorial(N){ if(N<=1) return 1 ; return N* Factorial(N-1); } /// this function is a guide for input style function promoptForInput(){ console.log('this is a node js script to calcualate permuatations (nPr) and combinations (nCr)'); console.log('please provide options like this from '); console.log('node [option 1] [option2] [option3]'); console.log('where\n\t[option 1] is P or C where P is for permutation and C is for Combination '); console.log('\t[option 2] is ( N ) where N is for nCr or nPr '); console.log('\t[option 3] is ( R ) where R is for nCr or nPr '); console.log('Conditions :'); console.log('\t N must be larger than R and both are larger than Zero'); console.log('Examples :'); console.log('\tnode permutation_combination.js c 10 4'); console.log('\tnode permutation_combination.js p 10 4'); } ================================================ FILE: Maths/Algebra/Prime_Factorization/PrimeFactorisation.cpp ================================================ // Calculating Prime factors of a given number #include using namespace std; // Function to find prime factors of a number num void PrimeFactorisation(int num) { // first checking for 2 while (num % 2 == 0) { cout << 2 << " "; num = num / 2; } // now finding rest of prime factors for (int i = 3; i <= sqrt(num); i += 2) { while (num % i == 0) { cout << i << " "; num = num / i; } } // If num != 1 then it itself is a prime number if (num > 2) cout << num << " "; } // main function int main() { // taking input int num; cin >> num; PrimeFactorisation(num); return 0; } ================================================ FILE: Maths/Algebra/Prime_Factorization/Prime_Factor.c ================================================ /* C Program to Find Prime Factors of a Number*/ #include int main() { int i, j, Number, isPrime; printf("\n Please Enter any number to Find Factors : "); scanf("%d", &Number); for (i = 2; i <= Number; i++) { if(Number % i == 0) { isPrime = 1; for (j = 2; j <= i/2; j++) { if(i % j == 0) { isPrime = 0; break; } } if(isPrime == 1) { printf("\n %d is a Prime Factor ", i); } } } return 0; } ================================================ FILE: Maths/Algebra/Prime_Factorization/Prime_Factorisation.cpp ================================================ #include using namespace std; void primeFactors(int n) { // Print the number of 2s that divide n while (n % 2 == 0) { cout << 2 << " "; n = n/2; } for (int i = 3; i <= sqrt(n); i = i + 2) { // While i divides n, print i and divide n while (n % i == 0) { cout << i << " "; n = n/i; } } if (n > 2) cout << n << " "; } int main() { int n = 315; primeFactors(n); return 0; } ================================================ FILE: Maths/Algebra/Prime_Factorization/Prime_Factorization.cs ================================================ using System; using System.Collections.Generic; using System.Text; namespace SoftwareAndFinance { class Math { const int MAX_SIZE = 15000; static bool IsPrimeNumber(int num) { bool bPrime = true; int factor = num / 2; int i = 0; for (i = 2; i <= factor; i++) { if ((num % i) == 0) bPrime = false; } return bPrime; } static public int GetPrimeFactors(int num, out int [] arrResult) { int count = 0; int [] arr = new int[MAX_SIZE]; arrResult = new int[MAX_SIZE]; int i = 0; int idx = 0; for(i = 2; i <= num; i++) { if(IsPrimeNumber(i) == true) arr[count++] = i; } while(true) { if(IsPrimeNumber(num) == true) { arrResult[idx++] = num; break; } for(i = count - 1; i >= 0; i--) { if( (num % arr[i]) == 0) { arrResult[idx++] = arr[i]; num = num / arr[i]; break; } } } return idx; } static void Main(string[] args) { int [] arrResult; Console.Write("Enter a number to find prime factor: "); int n = Convert.ToInt32(Console.ReadLine()); int count = GetPrimeFactors(n, out arrResult); for (int i = 0; i < count; i++) { Console.Write("{0,4:n}", arrResult[i]); if (i != count - 1) Console.Write(" * "); } Console.WriteLine(); } } } ================================================ FILE: Maths/Algebra/Prime_Factorization/README.md ================================================ ## This folder is empty. ================================================ FILE: Maths/Algebra/Prime_Factorization/prime-factorisation.js ================================================ /*Explanation=> The following code is to calculate all the prime factors of a desired number "num" Steps followed :- 1. Took input num; 2. Made a for loop to traverse through 2 to num and check the number completely divisible by num using (num%i ==0) 3.Made another loop to see if the number is prime or not 4.If prime then push it into the array and print out */ let findPrimeFactors = (num) => { let arr = []; for ( var i = 2; i < num; i++) { let isPrime if (num % i === 0) { isPrime = true; for (var j = 2; j <= i; j++) { if ( i % j === 0) { isPrime == false; } } }if (isPrime == true) { arr.push(i)} }console.log(arr) } findPrimeFactors(num); ================================================ FILE: Maths/Algebra/Prime_Factorization/prime.cpp ================================================ #include #include using namespace std; void PF(int n) { // Print the number of 2s that divide n while (n % 2 == 0) { cout << 2 << " "; n = n/2; } // n must be odd at this point. So we can skip // one element (Note i = i +2) for (int i = 3; i <= sqrt(n); i = i + 2) { // While i divides n, print i and divide n while (n % i == 0) { cout << i << " "; n = n/i; } } // This condition is to handle the case when n // is a prime number greater than 2 if (n > 2) cout << n << " "; } /* Driver code */ int main() { int n; cout<<"Enter a number"; cin>>n; PF(n); return 0; } ================================================ FILE: Maths/Algebra/Prime_Factorization/prime_factorization.cpp ================================================ using namespace std; long fac(long i) { if (i==0) { return (1); } else {return (i*fac(i-1));} } int main() { int z; cout<<“enter number”; cin>>z; cout< 60 = 2x2x3x5 sample input 2: 297 sample output 2: Prime Factorization of 297 -> 297 = 3x3x3x11 sample input 3: 1024 sample output 3: Prime Factorization of 1024 -> 1024 = 2x2x2x2x2x2x2x2x2x2 sample input 4: 547 sample output 4: Prime Factorization of 547 -> 547 = 547 */ class prime_factorization{ // method for factorization. private static void factorize(int n){ System.out.println("Prime Factorization of "+n+" -> "); System.out.print("\t "+n+" = "); // any number can have atmost 1 prime factor greater than sqrt(n). for(int i=2;i<=(int)Math.sqrt(n);i++){ // if n=1 exit the loop if(n<2){ break; } // until n is divisible by i print i and divide n while(n%i==0){ System.out.print(i); n/=i; if(n>=2){ System.out.print("x"); } } } if(n>2){ // prints the only prime factor that is greater than sqrt(n) System.out.print(n); } } public static void main(String[] args){ Scanner input = new Scanner(System.in); int n; // input variable for which prime factors are to be generated try{ n = input.nextInt(); // scanning for input if(n>2){ factorize(n); // passing parameter to 'factorize' method. } else{ System.out.println(n+" cannot have any prime factors"); // negative and numbers lesser than 2 are excluded } }catch(Exception e){ System.out.println("error: invalid input\nValid input: Integers only"); // handling execption for invalid or large input }finally{ input.close(); } } } ================================================ FILE: Maths/Algebra/Prime_Factorization/prime_factorization.py ================================================ # Python program to print prime factors import math def primeFactors(n): while n % 2 == 0: print("2 ") n = n / 2 for i in range(3,int(math.sqrt(n))+1,2): while n % i== 0: print(i, " ") n = n / i if n > 2: print(n," ") n = int(input()) primeFactors(n) ================================================ FILE: Maths/Algebra/Prime_Factorization/prime_factorization.ts ================================================ let findPrimeFactors = (num: number) => { const arr: number[] = []; for (let i: number = 2; i <= num; i++) { while ((num % i) === 0) { arr.push(i); num /= i; } } return arr; } findPrimeFactors(777) ================================================ FILE: Maths/Algebra/Quadratic_Formula/Quadratic_Formula.cpp ================================================ #include #include using namespace std; int main() { float a, b, c, x1, x2, discriminant, realPart, imaginaryPart; cout << "Enter coefficients a, b and c: "; cin >> a >> b >> c; discriminant = b*b - 4*a*c; if (discriminant > 0) { x1 = (-b + sqrt(discriminant)) / (2*a); x2 = (-b - sqrt(discriminant)) / (2*a); cout << "Roots are real and different." << endl; cout << "x1 = " << x1 << endl; cout << "x2 = " << x2 << endl; } else if (discriminant == 0) { cout << "Roots are real and same." << endl; x1 = (-b + sqrt(discriminant)) / (2*a); cout << "x1 = x2 =" << x1 << endl; } else { realPart = -b/(2*a); imaginaryPart =sqrt(-discriminant)/(2*a); cout << "Roots are complex and different." << endl; cout << "x1 = " << realPart << "+" << imaginaryPart << "i" << endl; cout << "x2 = " << realPart << "-" << imaginaryPart << "i" << endl; } return 0; } ================================================ FILE: Maths/Algebra/Quadratic_Formula/Quadratic_Formula.hs ================================================ module Quadratic_Formula (csqrt, quadratic) where import Data.Complex csqrt z@(a :+ b) = let (mag, ph) = polar z in mkPolar (sqrt mag) (ph/2) quadratic a b c = ( quad (conjugate a) (conjugate b) (conjugate c) (+), quad (conjugate a) (conjugate b) (conjugate c) (-) ) where quad a b c op = (-b `op` csqrt ( b^2 - 4 * a * c))/(2 * a) ================================================ FILE: Maths/Algebra/Quadratic_Formula/Quadratic_Formula.sh ================================================ #!/bin/bash echo "Enter coefficients of a, b and c : " read a b c d=$((b*b - (4*a*c))) if [ $d -gt 0 ] then disc=$(bc <<< "scale=4;sqrt($d)") x1=$(bc<<<"scale=4;((((-$b + $disc)/(2*$a))))") x2=$(bc<<<"scale=4;((((-$b - $disc)/(2*$a))))") echo "Roots are real and different" echo " x1 = " $x1 echo " x2 = " $x2 elif [ $d -eq 0 ] then disc=$(bc <<< "scale=4;sqrt($d)") x1=$(bc<<<"scale=4;(((((-$b + $disc)/(2*$a))))") echo "Roots are real and equal" echo " x1=x2= "$x1 elif [ $d -lt 0 ] then let "d=-d" disc=$(bc<<<"scale=4;sqrt($d)") real=$(bc<<<"scale=4;((-$b/(2*$a)))") imag=$(bc<<<"scale=4;(($disc/(2*$a)))") echo " x1 = "$real " + "$imag " i" echo " x2 = "$real " - "$imag " i" fi ================================================ FILE: Maths/Algebra/Quadratic_Formula/README.md ================================================ ## This folder is empty. ================================================ FILE: Maths/Algebra/Quadratic_Formula/quadraticformula.py ================================================ # -*- coding: utf-8 -*- """ Created on Sat Oct 3 03:34:46 2020 @author: Erik Quadratic formula """ import math as m a = int(input("constant 'a' for x^2: ")) b = int(input("constant 'b' for x^1: ")) c = int(input("free constant 'c': ")) print("the function is ", a, "x^2 + ", b, "x + ", c) #f = a*x^2 + b*x + c root = (b**2) - (4*a*c) x1 = (-b + m.sqrt(root))/(2*a) x2 = (-b - m.sqrt(root))/(2*a) print("x1 = ", x1, ". and x2 = ", x2) ================================================ FILE: Maths/Algebra/README.md ================================================ # This folder is empty. ================================================ FILE: Maths/Algebra/Sieve of Eratosthenes/SieveOfEratosthenes.cpp ================================================ #include using namespace std; #define mp make_pair #define pb push_back #define f first #define s second void Sieve(int n) { bool prime[n+1]; memset(prime, true, sizeof(prime)); for (int p=2; p*p<=n; p++) { if (prime[p] == true) { for (int i=p*p; i<=n; i += p) prime[i] = false; } } int c = 0; for (int p=2; p<=n; p++) { if (prime[p]) c++; } cout << "Prime Numbers <= n:- " << c << endl; } int main() { int N; cout << "Enter N :-" << endl; cin >> N; Sieve(N); return 0; } ================================================ FILE: Maths/Algebra/Sieve of Eratosthenes/SieveOfEratosthenes.py ================================================ import timeit def Sieve(n): prime = [True for i in range(n+1)] p = 2 while (p * p <= n): if (prime[p] == True): for i in range(p*2,n+1,p): prime[i] = False p += 1 c = 0 for p in range(2,n): if prime[p]: print(p) c += 1 return c t0 = timeit.default_timer() c = Sieve(100000) print("Total prime numbers in range: ", c) t1 = timeit.default_timer() print("Time required: ", t1-t0 ) ================================================ FILE: Maths/Algebra/Sieve of Eratosthenes/SieveOfEratosthens.c ================================================ /*C program to print all prime number less than or equal to n using Sieve of Eratosthenes*/ #include #include void SieveOfEratosthenes(int num) { /*Boolean array to mark a number is prime or not*/ bool prime[num+1]; int i,j; /*Initialisation(Mark all number as prime)*/ for(i=0;i<=num;i++) prime[i]=true; /*Zero is not prime*/ prime[0]=false; /*One is not prime*/ prime[1]=false; /*Mark all non prime number as false*/ for(i=2;i<=num;i++){ if(prime[i]==true){ for(j=i*i;j<=num;j+=i) prime[j]=false; } } /*Print all the prime numbers*/ for(i=2;i<=num;i++){ if(prime[i]==true) printf("%d ",i); } printf("\n"); } int main() { int num; /*Take input from the user*/ scanf("%d",&num); /*Prime number generation using Sieve of Eratosthenes*/ SieveOfEratosthenes(num); return 0; } ================================================ FILE: Maths/Algebra/Sieve of Eratosthenes/SieveofEratosthenes.java ================================================ /* This is a Java program to find prime numbers up to a limit using the Sieve of Eratosthenes approach. Time complexity: O(nlog(log n)) Space complexity: O(n) */ import java.util.*; public class SieveofEratosthenes { public static void main (String[] args) { Scanner scanner = new Scanner(System.in); System.out.println("Enter a number:"); int limit = scanner.nextInt(); if(limit < 2) { System.out.println(String.format("There are no prime numbers up to %d", limit)); return; } SieveofEratosthenes Sieve = new SieveofEratosthenes(); System.out.println(String.format("Prime numbers up to %d are:", limit)); boolean[] isPrime = Sieve.getPrimes(limit); Sieve.printPrimes(isPrime); } // Function to get the prime numbers up to the limit. public boolean[] getPrimes(int limit) { boolean[] isPrime = new boolean[limit + 1]; // Set all the values from 2 to max as primes. for(int i = 2; i <= limit; i++) { isPrime[i] = true; } for(int i = 2; i*i <= limit; i++) { // If a value is already set as prime, // mark its multiples as non-primes (composites). if(isPrime[i]) { for(int j = i*2; j <= limit; j += i) { isPrime[j] = false; } } } return isPrime; } // Function to print the obtained prime numbers. public void printPrimes(boolean[] isPrime) { for(int i = 2; i < isPrime.length; i++) { if(isPrime[i]) { System.out.println(i); } } } } ================================================ FILE: Maths/Algebra/Strassens_Algorithm/README.md ================================================ ## This folder is empty. ================================================ FILE: Maths/Algebra/Strassens_Algorithm/Strassen.java ================================================ import java.util.Scanner; class Strassen { public int[][] multiply(int[][] A, int[][] B) { int n = A.length; int[][] R = new int[n][n]; if (n == 1) R[0][0] = A[0][0] * B[0][0]; else { int[][] A11 = new int[n/2][n/2]; int[][] A12 = new int[n/2][n/2]; int[][] A21 = new int[n/2][n/2]; int[][] A22 = new int[n/2][n/2]; int[][] B11 = new int[n/2][n/2]; int[][] B12 = new int[n/2][n/2]; int[][] B21 = new int[n/2][n/2]; int[][] B22 = new int[n/2][n/2]; split(A, A11, 0 , 0); split(A, A12, 0 , n/2); split(A, A21, n/2, 0); split(A, A22, n/2, n/2); split(B, B11, 0 , 0); split(B, B12, 0 , n/2); split(B, B21, n/2, 0); split(B, B22, n/2, n/2); /** M1 = (A11 + A22)(B11 + B22) M2 = (A21 + A22) B11 M3 = A11 (B12 - B22) M4 = A22 (B21 - B11) M5 = (A11 + A12) B22 M6 = (A21 - A11) (B11 + B12) M7 = (A12 - A22) (B21 + B22) **/ int [][] M1 = multiply(add(A11, A22), add(B11, B22)); int [][] M2 = multiply(add(A21, A22), B11); int [][] M3 = multiply(A11, sub(B12, B22)); int [][] M4 = multiply(A22, sub(B21, B11)); int [][] M5 = multiply(add(A11, A12), B22); int [][] M6 = multiply(sub(A21, A11), add(B11, B12)); int [][] M7 = multiply(sub(A12, A22), add(B21, B22)); C11 = M1 + M4 - M5 + M7 C12 = M3 + M5 C21 = M2 + M4 C22 = M1 - M2 + M3 + M6 int [][] C11 = add(sub(add(M1, M4), M5), M7); int [][] C12 = add(M3, M5); int [][] C21 = add(M2, M4); int [][] C22 = add(sub(add(M1, M3), M2), M6); join(C11, R, 0 , 0); join(C12, R, 0 , n/2); join(C21, R, n/2, 0); join(C22, R, n/2, n/2); } return R; } public int[][] sub(int[][] A, int[][] B) { int n = A.length; int[][] C = new int[n][n]; for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) C[i][j] = A[i][j] - B[i][j]; return C; } public int[][] add(int[][] A, int[][] B) { int n = A.length; int[][] C = new int[n][n]; for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) C[i][j] = A[i][j] + B[i][j]; return C; } public void split(int[][] P, int[][] C, int iB, int jB) { for(int i1 = 0, i2 = iB; i1 < C.length; i1++, i2++) for(int j1 = 0, j2 = jB; j1 < C.length; j1++, j2++) C[i1][j1] = P[i2][j2]; } public void join(int[][] C, int[][] P, int iB, int jB) { for(int i1 = 0, i2 = iB; i1 < C.length; i1++, i2++) for(int j1 = 0, j2 = jB; j1 < C.length; j1++, j2++) P[i2][j2] = C[i1][j1]; } public static void main (String[] args) { Scanner scan = new Scanner(System.in); System.out.println("Strassen Multiplication Algorithm Test\n"); Strassen s = new Strassen(); System.out.println("Enter order n :"); int N = scan.nextInt(); System.out.println("Enter N order matrix 1\n"); int[][] A = new int[N][N]; for (int i = 0; i < N; i++) for (int j = 0; j < N; j++) A[i][j] = scan.nextInt(); System.out.println("Enter N order matrix 2\n"); int[][] B = new int[N][N]; for (int i = 0; i < N; i++) for (int j = 0; j < N; j++) B[i][j] = scan.nextInt(); int[][] C = s.multiply(A, B); System.out.println("\nProduct of matrices A and B : "); for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) System.out.print(C[i][j] +" "); System.out.println(); } } } ================================================ FILE: Maths/Algebra/Strassens_Algorithm/Strassens_Algorithm.c++ ================================================ #include using namespace std; int** initializeMatrix(int n) { int** temp = new int*[n]; for(int i=0; i> M[i][j]; cout << endl; } void printMatrix(int** M, int n) { for(int i=0; i> n; int** A = initializeMatrix(n); int** B = initializeMatrix(n); input(A, n); cout << "Matrix A:" << endl; printMatrix(A,n); input(B, n); cout << "Matrix B:" << endl; printMatrix(B, n); int** C = initializeMatrix(n); C = strassenMultiply(A, B, n); cout << "Multipliction result:" << endl; printMatrix(C, n); for(int i=0; i #include float fun(float x, float y) { float f; f = x + y; return f; } int main() { //input x0, y0, h, t //basic formula implementation is required. float a, b, x, y, h, t, k; printf("\nEnter x0, y0, h, xn: "); scanf("%f%f%f%f", &a, &b, &h, &t); printf("\n"); x = a; y = b; printf("\nX and Y respectively are: \n"); //basic formula implementation while (x <= t) { k = h * fun(x, y); y = y + k; x = x + h; printf("%0.3f, %0.3f\n", x, y); } } ================================================ FILE: Maths/Calculus/Euler_Approximation/Euler_Approximation.cpp ================================================ /* CPP Program to find approximation of a ordinary differential equation using euler method.*/ #include using namespace std; // Consider a differential equation // dy/dx=(x + y + xy) float func(float x, float y) { return (x + y + x * y); } // Function for Euler formula void euler(float x0, float y, float h, float x) { float temp = -0; // Iterating till the point at which we // need approximation while (x0 < x) { temp = y; y = y + h * func(x0, y); x0 = x0 + h; } // Printing approximation cout << "Approximate solution at x = " << x << " is " << y << endl; } // Driver program int main() { // Initial Values float x0; float y0; float h; cin>>x0>>y0>>h; // Value of x at which we need approximation float x ; cin>>x; euler(x0, y0, h, x); return 0; } ================================================ FILE: Maths/Calculus/Euler_Approximation/Euler_Approximation.java ================================================ public class Euler_Approximation { /** * Represents dy/dx. Change this function to your desired differential equation * @return dy/dx evaluated at the coordinate (x, y) */ public static double function(double x, double y) { return (x + y); } /** * Uses Euler's method to approximate a point. * @param xInitial initial coniditon for the X value * @param yInitial initial coniditon for the Y value * @param xApprox value to approximate * @param steps number of steps to use for the appromixation. Used to determine step size. * @return approximation of f(xApprox) * @see #function(double, double) */ public static double approximate(final double xInitial, final double yInitial, double xApprox, int steps) { // find step size // (b - a) / n final double stepSize = (xApprox - xInitial) / (double)steps; // check track of the X and Y coordinates double prevX = xInitial; double prevY = yInitial; // iterate until we meet our end coordinate for(int i = 0; i < steps; i++) { // apply Euler's method // f(x) = f(prevY) + stepSize * dy/dx(prevX, prevY) prevY = prevY + stepSize * function(prevX, prevY); prevX += stepSize; } return prevY; } public static void main(String[] args) { // approximates f(2) given dy/dx = x + y; y(-1) = 1 // using 6 equal subdivisions System.out.println(approximate(-1, 1, 2, 6)); } } ================================================ FILE: Maths/Calculus/Euler_Approximation/Euler_Approximation.py ================================================ # Python Code to find approximation # of a ordinary differential equation # using euler method. # Consider a differential equation # dy / dx =(2x + 3y + 4xy) def func( x, y ): return (2 * x + 3 * y + 4 * x * y) def euler( x0, y, h, x ): # Iterating till the point at which we # need approximation while x0 < x: temp = y y = y + h * func(x0, y) x0 = x0 + h print("Approximate solution at x = ", x, " is ", "%.6f"% y) # Initial Values x0 = float(input("Enter value of x0:- ")) y0 = float(input("Enter value oy y0:- ")) h = float(input("Enter step size:- ")) # Value of x at which we need approximation x = float(input("Enter value of x at which you want to approximate:- ")) euler(x0, y0, h, x) ================================================ FILE: Maths/Calculus/Euler_Approximation/README.md ================================================ ## This folder is empty. ================================================ FILE: Maths/Calculus/Leibniz_formula/LeibnizFormula.py ================================================ from sympy import * from math import comb ''' requirements - pip install sympy ''' def leibniz_formula(u, v, n: int): ''' Compute the nth order derivative of the product of two functions u and v Parameters ---------- u : function function with one variable - x v : function function with one variable - x n : integer the order of the derivative to be computed Returns ------- function nth order derivative of the product of u and v computed using leibniz formula ''' x = symbols('x') f = 0 for i in range(n+1): f += comb(n, i) * diff(u, x, n-i) * diff(v, x, i) return simplify(f) x = symbols('x') # examples # 1 u = exp(x) v = sin(x) n = 4 f = leibniz_formula(u, v, n) print(f"The {n}th order derivative of {u}*{v} is : {f}") # 2 u = x v = log(x) n = 10 f = leibniz_formula(u, v, n) print(f"The {n}th order derivative of {u}*{v} is : {f}") ================================================ FILE: Maths/Calculus/Leibniz_formula/Leibniz_Formula.java ================================================ public class Leibniz_formula { public static void main(String[] args) { int count = 999999999; double pi = 0; double denominator = 1; for (int x = 0; x < count; x++) { if (x % 2 == 0) { pi = pi + (1 / denominator); } else { pi = pi - (1 / denominator); } denominator = denominator + 2; } pi = pi * 4; System.out.println(pi); } } ================================================ FILE: Maths/Calculus/Leibniz_formula/Leibniz_formula.cpp ================================================ #include #include using namespace std; int main() { int n; double sum = 0; cout.precision(12); cout << "Enter an n number of iterations: " << endl; cin >> n; cout << "Pi estimated at " << n << " iterations is: " << endl; int i = 0; while (i < n) { cout << i << " "; i++; sum = sum + 4 * (pow(-1.0, i) / ((2.0 * i) + 1)); cout << sum << endl; cout << endl; } cout.precision(12); cout << sum << endl; cout << "The value of pi to " << n << " iterations is " << sum << endl; cout << "cmath library estimates Pi at " << M_PI << endl; return 0; ================================================ FILE: Maths/Calculus/Leibniz_formula/README.md ================================================ ## This folder is empty. ================================================ FILE: Maths/Calculus/Probability_Density_Functions/README.md ================================================ ## This folder is empty. ================================================ FILE: Maths/Calculus/README.md ================================================ # This folder is empty. ================================================ FILE: Maths/Calculus/Riemann_Sum/README.md ================================================ ## This folder is empty. ================================================ FILE: Maths/Calculus/Riemann_Sum/Riemann.py ================================================ from math import sin, pi def Rsum(a,b): for i in range(1001): s = 0.0 delx = float(b-a)/1000.0 g = i*delx h = (i+1.0)*delx y_i = float(sin(a+g)) y_ii = float(sin(a+h)) s += 1.0/2.0 * (y_i + y_ii) * delx #s += 1/2 * (sin(a+i*delx) + sin(a+(i+1)*delx)) * delx return s print Rsum(0,pi) ================================================ FILE: Maths/Calculus/Riemann_Sum/Riemann_Sum.cpp ================================================ #include #include double F1(double x,double a){ double f1=0.0; f1=(sqrt(a-pow(x,2))); return f1; } int main(){ double a=0.0,p=0.0,q=0.0,h=0.0,x=0.0,err=0; int func=3,n=2; double power=0.0,T=0.0; double sum=0.0,last=0.0,difference=1.0; scanf("%d",&func); while(func!=0){ n=2; scanf("%lf%lf%lf%lf",&a,&p,&q,&err); power=pow(10.0,-err); h=(q-p)/n; if(func==1){ difference=1.0; while(difference>=power){ h=(q-p)/n; sum=0.0; for(x=p+h;x<=q-h;x++){ sum+=(2*F1(x,a)); } T=(h/2)*(F1(p,a)+F1(q,a)+sum); if(difference==1.0){ difference=T; }else{ difference=last-T; } last=T; n++; } } printf("%.5lf\n",T); scanf("%d",&func); } return 0; } ================================================ FILE: Maths/Calculus/Riemann_Sum/Riemann_Sum.cs ================================================ using System; internal interface IFunction { float CalculateFx(float x); } internal class XPowerN : IFunction { private float n = 0; public XPowerN(float n) { this.n = n; } public float CalculateFx(float x) { return MathF.Pow(x, n); } public override string ToString() { return $"y = x^{n}"; } } internal class AsinNX : IFunction { private float a = 0; private float n = 0; public AsinNX(float a, float n) { this.a = a; this.n = n; } public float CalculateFx(float x) { return a * MathF.Sin(n * x); } public override string ToString() { return $"y = {a} * sin {n}x"; } } internal class AcosNX : IFunction { private float a = 0; private float n = 0; public AcosNX(float a, float n) { this.a = a; this.n = n; } public float CalculateFx(float x) { return a * MathF.Cos(n * x); } public override string ToString() { return $"y = {a} * cos {n}x"; } } internal class AtanNX : IFunction { private float a = 0; private float n = 0; public AtanNX(float a, float n) { this.a = a; this.n = n; } public float CalculateFx(float x) { return a * MathF.Tan(n * x); } public override string ToString() { return $"y = {a} * tan {n}x"; } } public class Riemann_Sum { public static void Main(string[] args) { do { IFunction function; Console.Clear(); Console.WriteLine("Select the desired function: "); Console.WriteLine("1. y = x^n"); Console.WriteLine("2. y = A * sin nx"); Console.WriteLine("3. y = A * cos nx"); Console.WriteLine("4. y = A * tan nx"); Console.Write("\nPick a function: "); float tempA; switch (Convert.ToInt32(Console.ReadLine())) { // TODO: finish case 1: Console.Write("Enter a value for n: "); function = new XPowerN(Convert.ToSingle(Console.ReadLine())); break; case 2: Console.Write("Enter a value for A: "); tempA = Convert.ToInt32(Console.ReadLine()); Console.Write("Enter a value for n: "); function = new AsinNX(tempA, Convert.ToSingle(Console.ReadLine())); break; case 3: Console.Write("Enter a value for A: "); tempA = Convert.ToInt32(Console.ReadLine()); Console.Write("Enter a value for n: "); function = new AcosNX(tempA, Convert.ToSingle(Console.ReadLine())); break; case 4: Console.Write("Enter a value for A: "); tempA = Convert.ToInt32(Console.ReadLine()); Console.Write("Enter a value for n: "); function = new AtanNX(tempA, Convert.ToSingle(Console.ReadLine())); break; default: continue; } // Enter bounds of the evaluation. Note that lower must be less than upper Console.Write("Enter the lower limit of the evaluation: "); float lower = Convert.ToSingle(Console.ReadLine()); Console.Write("Enter the upper limit of the evaluation: "); float upper = Convert.ToSingle(Console.ReadLine()); // must be non-zero Console.Write("Enter the resolution of the Riemann approximation: "); uint resolution = Convert.ToUInt32(Console.ReadLine()); Console.WriteLine(); EvaluateRiemannSumLeft(function, lower, upper, resolution); EvaluateRiemannSumRight(function, lower, upper, resolution); EvaluateRiemannSumTrapezoid(function, lower, upper, resolution); break; } while (true); } private static void EvaluateRiemannSumLeft( IFunction function, in float lowerLimit, in float upperLimit, in uint resolution) { float riemannSum = 0f; float xIncrement = (upperLimit - lowerLimit) / resolution; for (int i = 0; i < resolution; ++i) { float x = lowerLimit + xIncrement * i; float height = function.CalculateFx(x); riemannSum += xIncrement * height; } Console.WriteLine($"The Left Riemann sum of {function} between {lowerLimit} and {upperLimit} is {riemannSum}."); } private static void EvaluateRiemannSumRight( IFunction function, in float lowerLimit, in float upperLimit, in uint resolution) { float riemannSum = 0f; float xIncrement = (upperLimit - lowerLimit) / resolution; for (int i = 1; i <= resolution; ++i) { float x = lowerLimit + xIncrement * i; float height = function.CalculateFx(x); riemannSum += xIncrement * height; } Console.WriteLine($"The Right Riemann sum of {function} between {lowerLimit} and {upperLimit} is {riemannSum}."); } private static void EvaluateRiemannSumTrapezoid( IFunction function, in float lowerLimit, in float upperLimit, in uint resolution) { float riemannSum = 0f; float xIncrement = (upperLimit - lowerLimit) / resolution; for (int i = 0; i < resolution; ++i) { float x = lowerLimit + xIncrement * i; float leftValue = function.CalculateFx(x); float rightValue = function.CalculateFx(x + xIncrement); if (leftValue < rightValue) // leftValue is lower, section is increasing { // adding area of smallest rect riemannSum += xIncrement * leftValue; // adding triangle area riemannSum += 0.5f * xIncrement * (rightValue - leftValue); } else // rightValue is lower, section is decreasing { // adding area of smallest rect riemannSum += xIncrement * rightValue; // adding triangle area riemannSum += xIncrement * (leftValue - rightValue); } } Console.WriteLine($"The Trapezoid Riemann sum of {function} between {lowerLimit} and {upperLimit} is {riemannSum}."); } } ================================================ FILE: Maths/Calculus/Riemann_Sum/riemann_sum.py ================================================ import numpy as np def riemann_sum(f, a, b, N: int, method='midpoint'): ''' Compute the Riemann sum of f(x) over the interval [a,b]. Parameters ---------- f : function Vectorized function of one variable a , b : numbers Endpoints of the interval [a,b] N : integer Number of subintervals of equal length in the partition of [a,b] method : string Determines the kind of Riemann sum: right : Riemann sum using right endpoints left : Riemann sum using left endpoints midpoint (default) : Riemann sum using midpoints Returns ------- float Approximation of the integral given by the Riemann sum. ''' dx = (b - a)/N x = np.linspace(a, b, N+1) # left riemann sum if method == 'left': x_left = x[:-1] return np.sum(f(x_left)*dx) # right reimann sum elif method == 'right': x_right = x[1:] return np.sum(f(x_right)*dx) # midpoint reimann sum elif method == 'midpoint': x_mid = (x[:-1] + x[1:])/2 return np.sum(f(x_mid)*dx) else: raise ValueError("Method must be 'left', 'right' or 'midpoint'.") # example problems # 1 f = np.sin r_sum = riemann_sum(f, 0, np.pi/2, 100) right_r_sum = riemann_sum(f, 0, np.pi/2, 100, 'right') left_r_sum = riemann_sum(f, 0, np.pi/2, 100, 'left') print(f"""Sin(x) in the interval [0,pi/2] partition with 100 sub-intervals Left Riemann Sum: {left_r_sum} Midpoint Riemann Sum: {r_sum} Right Riemann Sum: {right_r_sum}""") # 2 f = lambda x : 1 / (1 + x**2) r_sum = riemann_sum(f, 0, 5, 10) right_r_sum = riemann_sum(f, 0, 5, 10, 'right') left_r_sum = riemann_sum(f, 0, 5, 10, 'left') print(f""" 1/(1+x^2) in the interval [0,5] partition with 10 sub-intervals Left Riemann Sum: {left_r_sum} Midpoint Riemann Sum: {r_sum} Right Riemann Sum: {right_r_sum}""") ================================================ FILE: Maths/Calculus/Runge–Kutta_Method/Range-Kutta.c ================================================ #include int compare_float(float x, float y) { float val=0.0001f; if(fabs(x - y) < val) return 1; //they are same return 0; //they are not same } // for the equation 2xy +e^x/x^2+x*e^x float equation(float x,float y) { float val=0; val=(2*x*y+pow(2.71828,x))/(pow(x,2)+x*pow(2.71828,x)); return(val); } float next(float x,float y,float h) { float k[4]; k[0]=h*equation(x,y); k[1]=h*equation(x+0.5*h,y+0.5*k[0]); k[2]=h*equation(x+0.5*h,y+0.5*k[1]); k[3]=h*equation(x+h,y+k[2]); k[0]=(k[0]+2*k[1]+2*k[2]+k[3])/6; y=y+k[0]; return(y); } int main() { float xg,yg,yf,xgf,h; printf("Enter the given X value: "); scanf("%f",&xg); printf("Enter corresponding Y value: "); scanf("%f",&yg); printf("Enter the X value which value have to be find: "); scanf("%f",&xgf); printf("Enter the h value : "); scanf("%f",&h); while(1) { yg=next(xg,yg,h); xg=xg+h; if(compare_float(xg,xgf)) { break; } } printf("The value of y(%f) is : %f",xgf,yg); } ================================================ FILE: Maths/Calculus/Runge–Kutta_Method/Runge-Kutta.cpp ================================================ #include #include #include using namespace std; /*======================================================================*/ /*===================== Runge-Kutta Method for ODE =====================*/ /*======================================================================*/ //getting dx/dt static double dx_dt(double t, double x) { return tan(x) + 1; } //Formula used : //Yn+1 = Yn + 1/6 *(k1+2*k2+2*k3+k4) :: let interval = h //where k1=dx/dt(Xn,Yn) ,k2=dx/dt((Xn+ h/2 ,Yn+k1/2 ),k3=dx/dt((Xn+ h/2 ,Yn+k2/2 ) and k4=dx/dt((Xn+ h ,Yn+k3 ) //Instead of dx/dt we can also use other differential function void calculate_Y(double &initial_X, double final_X,double interval ,double &y ){ int n = static_cast((final_X - initial_X) /interval); for (int i = 0; i < n; i++) { double k1 = dx_dt(initial_X, y); double k2 = dx_dt(initial_X + interval / 2.0, y + interval*k1 / 2.0); double k3 = dx_dt(initial_X + interval/ 2.0, y + interval*k2 / 2.0); double k4 = dx_dt(initial_X + interval, y + interval*k3); y += (k1 + 2 * k2 + 2 * k3 + k4) * interval / 6.0; //cout << initial_X << ": " << y << endl; initial_X += interval; } } int main(int argc, const char * argv[]) { cout<<"Press 1 for giving Your own input and 2 for default example"<>option; cout << setprecision(16); double initial_X = 1.0; double final_X = 1.1; double y = 1.0; double h = 0.025; if(option == 1){ cout<<" Enter Initial value of X i.e X0 "<>initial_X; cout<<" Final Value of X "<>final_X; cout<<" Enter Initial value of Y i.e Y0 "<>y; cout<<" Enter Interval "<>h; calculate_Y(initial_X,final_X,h,y); }else if(option ==2){ cout<<" For the example The values taken are :"< int ackermann_peter(int m, int n) { if (m == 0){ return n+1; } else if((m > 0) && (n == 0)){ return ackermann_peter(m-1, 1); } else if((m > 0) && (n > 0)){ return ackermann_peter(m-1, ackermann_peter(m, n-1)); } } int main(){ //accept values int ackermann_result, num1, num2; scanf("%d %d", &num1, &num2); //compute the result and print it ackermann_result = ackermann_peter(num1, num2); printf("%d", ackermann_result); return 0; } ================================================ FILE: Maths/Discrete/Ackermann_Peter/Ackermann_Peter.cpp ================================================ #include using namespace std; int A(int, int); int main() { int m=NULL, n=0, count=0; while(count<=7) { cout<= 0, 'm is unacceptable' assert isinstance(n, int) and n >= 0, 'n is unacceptable' stack = [] while True: if not m: if not stack: return n + 1 m, n = stack.pop(), n + 1 elif not n: m, n = m - 1, 1 else: stack.append(m - 1) n -= 1 ================================================ FILE: Maths/Discrete/Ackermann_Peter/Python/ackermann.py ================================================ def ackermann(m,n): if m == 0: return (n + 1) elif n == 0: return ackermann(m - 1, 1) else: return ackermann(m - 1, ackermann(m, n - 1)) #Example # ackermann(2, 1) --> 5 # ackermann(2, 2) --> 7 ================================================ FILE: Maths/Discrete/Ackermann_Peter/README.md ================================================ ## DISCRETE MATHEMATICS Discrete mathematics is a branch of mathematics wherein we study about discrete or disconnected objects. The tools and techniques of DM make you fall in love with beauty of mathematics and computer science. ## Topics coming under Discrete Mathematics 1. Number Theory and Cryptography 2. Induction and Recursion 3. Counting 4. Discrete Probability 5. Advanced counting techniques 6. Relations 7. Graphs 8. Trees 9. Boolean Algebra 10. Modeling Computation ## Books Recommended Discrete Mathematics and Its Applications by Kenneth H. Rosen You can easily find on the internet. All the best!! ================================================ FILE: Maths/Discrete/README.md ================================================ ## DISCRETE MATHEMATICS Discrete mathematics is a branch of mathematics wherein we study about discrete or disconnected objects. The tools and techniques of DM make you fall in love with beauty of mathematics and computer science. ## Topics coming under Discrete Mathematics 1. Number Theory and Cryptography 2. Induction and Recursion 3. Counting 4. Discrete Probability 5. Advanced counting techniques 6. Relations 7. Graphs 8. Trees 9. Boolean Algebra 10. Modeling Computation ## Books Recommended Discrete Mathematics and Its Applications by Kenneth H. Rosen You can easily find on the internet. All the best!! ================================================ FILE: Maths/Geometry/Clock_Angle/ClockAngle.cs ================================================ using System; namespace clock_angle { class ClockAngle { static void Main(string[] args) { Console.WriteLine("Enter hours:"); int hours = Convert.ToInt32(Console.ReadLine()); Console.WriteLine("Enter minutes:"); int minutes = Convert.ToInt32(Console.ReadLine()); double angle = findAngleBetweenHourAndMinuteHand(hours, minutes); Console.WriteLine(angle); } private static double findAngleBetweenHourAndMinuteHand(int hours, int minutes) { if(hours<0||minutes<0||hours>12||minutes>59) { Console.WriteLine("Invalid input"); return 0; } double angleHoursHandMoved = 0.5*((hours*60)+minutes); double angleMinutesHandMoved = 6*minutes; return Math.Abs(angleHoursHandMoved-angleMinutesHandMoved); } } } ================================================ FILE: Maths/Geometry/Clock_Angle/Clock_Angle.c ================================================ #include int main(){ int hour,minute; float hourAngle,minAngle,angle; printf("Enter Hour (12 hour format) -> "); scanf("%d",&hour); printf("Enter Minute -> "); scanf("%d",&minute); minAngle = 6 * minute; hourAngle = (30 * hour) + (0.5 * minute); if(hourAngle>minAngle){ angle = hourAngle - minAngle; }else{ angle = minAngle - hourAngle; } if(angle>180){ angle = 360 - angle; } printf("Smallest Angle between hour and minute hand for the entered time is -> %0.1f",angle); return 0; } ================================================ FILE: Maths/Geometry/Clock_Angle/Clock_Angle.cpp ================================================ CODE: #include using namespace std; int findAngle(int hour, int min) { int h = (hour * 360) / 12 + (min * 360) / (12 * 60); int m = (min * 360) / (60); int angle = abs(h - m); if (angle > 180) angle = 360 - angle; return angle; } int main() { int hour; int min; cin>>hour>>min; cout << findAngle(hour, min); return 0; } INPUT:hour=5, min=30 OUTPUT:15 ================================================ FILE: Maths/Geometry/Clock_Angle/Clock_Angle.hs ================================================ module Clock_Angle (clock_angle) where clock_angle hour minute = if (hour `elem` [1..12]) && (minute `elem` [0..59]) then let { hour' = if hour == 12 then 0 else hour; minute_angle = minute * 6; hour_angle = hour' * 30 + minute * 0.5; } in Just (abs (hour_angle - minute_angle)) else Nothing ================================================ FILE: Maths/Geometry/Clock_Angle/Clock_Angle.java ================================================ public class Clock_Angle { public static int findAngle(int hour, int minute){ if (hour <0 || minute < 0 || hour >12 || minute > 59){ System.out.println("Wrong input"); return -1; } if(hour == 12){ hour = 0; } if(hour >12){ hour = hour-12; } int hour_angle = (int)(0.5 * (hour*60 + minute)); int minute_angle = (int)(6*minute); int angle = Math.abs(hour_angle - minute_angle); return angle; } public static void main(String[] args){ System.out.println(findAngle(10,12)); } } //Maths_And_Stats => Geometry => Clock_Angle => Clock_Angle.java ================================================ FILE: Maths/Geometry/Clock_Angle/Clock_Angle.js ================================================ var hour = prompt("Enter Hour (12 hour format) -> "); var minute = prompt("Enter Minute -> "); var hourAngle,minAngle,angle; minAngle = 6 * minute; hrAngle = (30 * hour) + (0.5 * minute); if(hrAngle>minAngle){ angle = hrAngle - minAngle; }else{ angle = minAngle - hrAngle; } if(angle>180){ angle = 360 - angle; } alert("Smallest Angle between hour and minute hand for the entered time is -> " + angle); ================================================ FILE: Maths/Geometry/Clock_Angle/README.md ================================================ ## This folder is empty. ================================================ FILE: Maths/Geometry/Clock_Angle/clock_angle.go ================================================ package main import ( "fmt" "math" ) // use consts instead of "magic numbers" const minutesPerHour = 60 const hourHandDegreePerMinute = 0.5 const minuteHandDegreePerMinute = 6 // Calculate clock angle between hour hand and minute hand in degrees // Where: // hours in range 0 - 12 // minutes in range 0 -59 func clockAngle(hours uint, minutes uint) (float64, error) { // Check user input if hours < 0 || minutes < 0 || hours > 12 || minutes > 59 { return 0, fmt.Errorf("Invalid input:\n0 < hour < 12 and 0 < minute < 59") } hourAngle := hourHandDegreePerMinute * float64((hours * minutesPerHour + minutes)) minuteAngle := float64(minuteHandDegreePerMinute * minutes) angle := math.Abs(hourAngle - minuteAngle) return angle, nil } func main() { var ( hours uint minutes uint ) // Get user input fmt.Printf("Please enter hours and minutes separated by a space where h(0-12) m(0, 59): ") _, err := fmt.Scanf("%d%d", &hours, &minutes) if err != nil { fmt.Println("Invalid input type, decimal values required !") return } // Calculate and display the clock angle based on a 12 hour clock angle, err := clockAngle(hours, minutes) if err != nil { fmt.Println(err) return } fmt.Printf("The angle between hour hand and minute hand is %.2f (deg)", angle) } ================================================ FILE: Maths/Geometry/Clock_Angle/clock_angle.py ================================================ """ author- Ose Oaiya (esoiya) Submission Description: Clock angle problems relate two different measurements: angles and time. The angle is typically measured in degrees from the mark of number 12 clockwise. The time is usually based on a 12-hour clock. The hour hand of a normal 12-hour analogue clock turns 360° in 12 hours (720 minutes) or 0.5° per minute. """ def clock_angle(hour, minute): """ Calculate Clock Angle between hour hand and minute hand param hour: hour type: int param minute: number of minutes pas the hour type: int return: the smallest angle of the two possible angles """ if (hour < 0 or minute < 0 or hour > 12 or minute > 59): raise ValueError("Invalid Input: Time is based on a 12-hour clock") if hour == 12: hour = 0 # calculate the angle moved by the hour and minute hands # with reference to 12:00 hour_angle = 0.5 * (hour * 60 + minute) minute_angle = 6 * minute # Find the difference between the two angles angle = abs(minute_angle - hour_angle) return angle ================================================ FILE: Maths/Geometry/Distance_Formula/Distance_Formula.c ================================================ #include #include int main() { int x1,x2,y1,y2; int x,y; //temporary variables float distance; printf("Enter X and Y coordinates of first point: "); scanf("%d %d",&x1,&y1); printf("Enter X and Y coordinates of Second point: "); scanf("%d %d",&x2,&y2); x=x2-x1; y=y2-y1; distance=sqrt((x*x)+(y*y)); printf("Distance: %.2f",distance); return 0; } ================================================ FILE: Maths/Geometry/Distance_Formula/Distance_Formula.cpp ================================================ #include #include using namespace std; int main() { double point_1[2]; double point_2[2]; cout << "Enter the co-ordinates of point 1: \n"; cout << "x1: "; cin >> point_1[0]; cout << "y1: "; cin >> point_1[1]; cout << "Enter the co-ordinates of point 2: \n"; cout << "x2: "; cin >> point_2[0]; cout << "y2: "; cin >> point_2[1]; double a_square; double b_square; a_square = pow((point_2[0] - point_1[0]), 2); b_square = pow((point_2[1] - point_1[1]), 2); cout << "The distance between both points is " << sqrt(a_square+b_square) << " units.\n"; } ================================================ FILE: Maths/Geometry/Distance_Formula/Distance_Formula.cs ================================================ using System; internal struct Point { public float x; public float y; public Point(float x, float y) { this.x = x; this.y = y; } public override string ToString() { return $"({x},{y})"; } } public class Distance_Formula { public static void Main(string[] args) { string[] input = new string[2]; // Get coordinates of point A from stdin Console.WriteLine("Enter coordinates of point A: "); Console.Write("x: "); input[0] = Console.ReadLine(); Console.Write("y: "); input[1] = Console.ReadLine(); Point pointA = new Point( x: Convert.ToSingle(input[0]), y: Convert.ToSingle(input[1]) ); // Get coordinates of point B from stdin Console.WriteLine("Enter coordinates of point B: "); Console.Write("x: "); input[0] = Console.ReadLine(); Console.Write("y: "); input[1] = Console.ReadLine(); Point pointB = new Point( x: Convert.ToSingle(input[0]), y: Convert.ToSingle(input[1]) ); // calculate distance double distance = Math.Sqrt( (pointB.x - pointA.x) * (pointB.x - pointA.x) + (pointB.y - pointA.y) * (pointB.y - pointA.y)); // output to stdout Console.WriteLine($"The distance between {pointA} and {pointB} is {distance}"); } } ================================================ FILE: Maths/Geometry/Distance_Formula/Distance_Formula.go ================================================ package main import "fmt" import "strconv" import "math" func main() { //Getting input of user for x1,x2,y1 and y2 coordinates then converting them to float types if numeric values are not entered then program stops. fmt.Println("Enter X1 coordinate: ") var x1 string fmt.Scanln(&x1) convX1,err:= strconv.ParseFloat(x1,64) if err!=nil{ fmt.Println("Bad Input please enter numeric values only for X1.") return } fmt.Println("Enter Y1 coordinate: ") var y1 string fmt.Scanln(&y1) convY1,err:= strconv.ParseFloat(y1,64) if err!=nil{ fmt.Println("Bad Input please enter numeric values only for Y1.") return } fmt.Println("Enter X2 coordinate: ") var x2 string fmt.Scanln(&x2) convX2,err:= strconv.ParseFloat(x2,64) if err!=nil{ fmt.Println("Bad Input please enter numeric values only for X2.") return } fmt.Println("Enter Y2 coordinate: ") var y2 string fmt.Scanln(&y2) convY2,err:= strconv.ParseFloat(y2,64) if err!=nil{ fmt.Println("Bad Input please enter numeric values only for Y2:",) return } //calculating difference between x1,x2 and y1,y2 coordinates diffXC:= math.Abs(convX2-convX1) diffYC:= math.Abs(convY2-convY1) //Calculating squares of the differences obtained above. squX:=diffXC*diffXC squY:=diffYC*diffYC //Calculating the final distance after adding and finding the square root. totalDistance:=math.Sqrt(squX+squY) fmt.Printf("The distance between the two points (x1=%0.2F,y1=%0.2F) and (x2=%0.2F,y2=%0.2F) is %0.2F\n",convX1,convY1,convX2,convY2,totalDistance) } ================================================ FILE: Maths/Geometry/Distance_Formula/Distance_Formula.hs ================================================ module Distance_Formula (distance_formula) where distance_formula [a,b] [c,d] = sqrt $ (a-c)^2 + (b-d)^2 ================================================ FILE: Maths/Geometry/Distance_Formula/Distance_Formula.java ================================================ public class Distance_Formula { public static double findDistance(double x1, double y1 , double x2, double y2){ double length = x2 - x1; double height = y2 - y1; return Math.sqrt(length*length + height*height); } } ================================================ FILE: Maths/Geometry/Distance_Formula/Distance_Formula.js ================================================ // function to calculate distance between two points const distanceFormula = (x1, y1, x2, y2) => { const x_diff = x2 - x1; const y_diff = y2 - y1; return Math.sqrt(x_diff * x_diff + y_diff * y_diff); }; // Take two points as input let x1 = prompt("Enter x value of first point: "); let y1 = prompt("Enter y value of first point: "); let x2 = prompt("Enter x value of second point: "); let y2 = prompt("Enter x value of second point: "); // output console.log(distanceFormula(x1, y1, x2, y2)); ================================================ FILE: Maths/Geometry/Distance_Formula/Distance_Formula.php ================================================ "; distance($x1,$x2,$y1,$y2); function distance($x1,$x2,$y1,$y2){ $d = sqrt(pow($x2-$x1,2)+pow($y2-$y1,2)); echo "Distance = ".$d; } ?> ================================================ FILE: Maths/Geometry/Distance_Formula/Distance_Formula.py ================================================ """ LANGUAGE: PYTHON """ from math import sqrt def Distance_Formula(x, y): return sqrt((y[0]-x[0])**2+(y[1]-x[1])**2) ================================================ FILE: Maths/Geometry/Distance_Formula/README.md ================================================ ## This folder is empty. ================================================ FILE: Maths/Geometry/Manhattan_Distance/ManhattanDistance.java ================================================ // Java Program to implement Manhattan Distance in JAVA import java.util.*; public class ManhattanDistance { // Driver Program public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int x1 = scanner.nextInt(); int y1 = scanner.nextInt(); int x2 = scanner.nextInt(); int y2 = scanner.nextInt(); int manhattanDistance = Math.abs(x1 - x2) + Math.abs(y1 - y2); System.out.println("MANHATTAN DISTANCE IS : " + manhattanDistance); } } ================================================ FILE: Maths/Geometry/Manhattan_Distance/ManhattanDistance.js ================================================ const manhattanDistance = (x1, y1, x2, y2) => { return Math.abs(x2 - x1) + Math.abs(y2 - y1); }; // Test Cases: // Horizontal Direction // Vertical Direction // Diagonal Direction // No Movement // Non-(0, 0) Origin // Negative and Positive Values Mixed const startXPositions = [0, 0, 0, 0, 1, -3]; const startYPositions = [0, 0, 0, 0, 1, 4]; const endXPositions = [5, 0, 5, 0, 6, 2]; const endYPositions = [0, 5, 5, 0, 6, -8]; for (var i = 0; i < startXPositions.length; i++) { const startXPos = startXPositions[i]; const startYPos = startYPositions[i]; const endXPos = endXPositions[i]; const endYPos = endYPositions[i]; console.log(`The manhattan distance between (${startXPos}, ${startYPos}) and (${endXPos}, ${endYPos}) is ${manhattanDistance(startXPos, startYPos, endXPos, endYPos)}!`); }; ================================================ FILE: Maths/Geometry/Manhattan_Distance/Manhattan_Distance.c ================================================ // Nothing Special #include #include #include int manhattan_dist(int a1 , int a2 , int b1 , int b2) { return (abs(a1 - a2) + abs(b1 - b2)); } int main() { int x1, x2, y1, y2, dist=0; printf("Enter points of A: "); scanf("%d %d" , &x1 , &x2); printf("Enter points of B: "); scanf("%d %d" , &x2 , &y2); dist = manhattan_dist(x1 , x2 , y1 , y2); printf("The Manhattan distance is: %d\n" , dist); return 0; } ================================================ FILE: Maths/Geometry/Manhattan_Distance/Manhattan_Distance.hs ================================================ {-- Calculates Manhattan distance between points in any dimension. - - Syntax: - > manhattan_distance [1,2,3] [7,7,8] - 16 -} module Manhattan_Distance (manhattan_distance) where manhattan_distance xs ys = sum $ map (\(x, y) -> abs (x-y)) (zip xs ys) ================================================ FILE: Maths/Geometry/Manhattan_Distance/README.md ================================================ ## This folder is empty. ================================================ FILE: Maths/Geometry/Manhattan_Distance/manhattan_dist.cpp ================================================ #include using namespace std; int manhattan_dist(int, int, int, int); int main() { int x1, x2, y1, y2, dist=0; cout << "Enter points of A: "; cin >> x1 >> y1; cout << "Enter points of B: "; cin >> x2 >> y2; dist = manhattan_dist(x1, x2, y1, y2); cout << "The Manhattan distance is: " << dist << endl; return 0; } int manhattan_dist(int a1, int a2, int b1, int b2) { return (abs(a1-a2)+abs(b1-b2)); } ================================================ FILE: Maths/Geometry/Manhattan_Distance/manhattan_dist.go ================================================ package main import ( "fmt" "math" ) func calcManhattanDist(x1, y1, x2, y2 int) { dist := math.Abs(float64(x1 - x2)) + math.Abs(float64(y1 - y2)) fmt.Println(dist) } func main() { calcManhattanDist(2, 5, 10, 14) } ================================================ FILE: Maths/Geometry/Manhattan_Distance/manhattan_dist.py ================================================ def calcManhattanDist(x1, y1, x2, y2) -> float: return abs(x1 - x2) + abs(y1 - y2) def main(): print(calcManhattanDist(2, 5, 10, 14)) if __name__ == "__main__": main() ================================================ FILE: Maths/Geometry/Manhattan_Distance/manhattan_distance.py ================================================ # function to calculate Manhattan Distance between two points def manhattan_dist(x1, y1, x2, y2): return abs(x1-x2) + abs(y1-y2) x1, y1 = (list(map(int, input("Enter the first point (x,y): ").split(",")))) x2, y2 = (list(map(int, input("Enter the second point (x,y): ").split(",")))) print("Manhattan Distance: ", manhattan_dist(x1, y1, x2, y2)) ================================================ FILE: Maths/Geometry/N_Dimensional_Distance/N_Dimensional_Distance.c ================================================ #include #include #include /** * This function calculates the euclidian (or L2) distance of two points. * @param point1 coordinates of first point stored in an array * @param point2 coordinates of second point stored in an array * @param dimension the number of coordinates each point is expected to have * * @return The euclidian distance between the points */ float n_dimensional_distance(double const *point1, double const * point2, const size_t dimension) { double result = 0; for (size_t index = 0; index < dimension; ++index) { double difference = point1[index] - point2[index]; result += difference*difference; } return sqrt(result); } int main(void) { const size_t N = 3; const double point1[] = {1,1,1}; const double point2[] = {3,4,7}; double distance = n_dimensional_distance(point1, point2, N); printf("The %zu-dimensional distance between the points point1 and point2 is %f", N, distance); return EXIT_SUCCESS; } ================================================ FILE: Maths/Geometry/Polar_Cartesian_Conversion/Polar_Cartesian_Conversion.go ================================================ /* This code takes input r and θ in Polar Coordinates and converts them into cartesian coordinates. Language : Golang Author : Pulkit Sapra */ package main //Package fmt implements formatted I/O with functions analogous to C's printf and scanf. import ( "fmt" "math" ) func convert_to_cartesian(r float64, theta float64){ var x,y float64 //convert degree to radians theta = theta*math.Pi/180 //Conversion of polar coord. to Cartesian x = r * math.Cos(theta) y = r * math.Sin(theta) fmt.Printf("x = %0.3f, y = %0.3f\n", x , y) } // Main Function func main() { fmt.Print("Please enter radius(r) and theta(in degree) : ") // Declaring variables and their types. var r,theta float64 // Taking input for r adn theta fmt.Scan(&r) fmt.Scan(&theta) //Function call convert_to_cartesian(r,theta) } ================================================ FILE: Maths/Geometry/Polar_Cartesian_Conversion/Polar_Cartesian_Conversion.hs ================================================ module Polar_Cartesian_Conversion (polar_to_cartesian) where polar_to_cartesian [mod, arg] = [mod * cos(arg), mod * sin(arg)] ================================================ FILE: Maths/Geometry/Polar_Cartesian_Conversion/Polar_Cartesian_Conversion.java ================================================ import java.util.Scanner; public class PolarCartesian { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print("Input radius: "); double radius = sc.nextDouble(); System.out.print("Input theta in degrees: "); double theta = sc.nextDouble(); // converting theta from degrees to radians theta = theta * Math.PI / 180f; double x = radius * Math.cos(theta); double y = radius * Math.sin(theta); System.out.printf("Cartesian coordinates: (%5.3f, %5.3f)", x, y); } } ================================================ FILE: Maths/Geometry/Polar_Cartesian_Conversion/Polar_Cartesian_Conversion.py ================================================ import math def polarToCart(r, theta): theta = theta*math.pi/180.0 x = r*math.cos(theta) y = r*math.sin(theta) return (x, y) ================================================ FILE: Maths/Geometry/Pythagorean_theorem/PythagoreanTheorem.cs ================================================ using System; using System.Collections; using System.Collections.Generic; using System.Linq; class PythagoreanTheorem { // Derived from the Pythagorean Theorem // a^2 + b^2 = c^2 in reference to a right triangle's sides a, b, and hypotenuse c // c = sqrt(a^2 + b^2) private static double GetHypotenuse(float a, float b) { return Math.Sqrt(a * a + b * b); } // a = sqrt(c^2 - b^2) private static double GetSideA(float b, float c) { return Math.Sqrt(c * c - b * b); } // b = sqrt(c^2 - a^2) private static double GetSideB(float a, float c) { return Math.Sqrt(c * c - a * a); } private static bool IsRightAngled(float a, float b, float c) { return GetHypotenuse(a, b) == c; } static void Main(string[] args) { Console.WriteLine(GetHypotenuse(3, 4)); Console.WriteLine(GetSideA(4, 5)); Console.WriteLine(GetSideB(3, 5)); Console.WriteLine(IsRightAngled(3, 4, 5)); Console.WriteLine(IsRightAngled(3.5f, 4, 5)); Console.ReadLine(); } } ================================================ FILE: Maths/Geometry/Pythagorean_theorem/Pythagorean_theorem.cpp ================================================ #include using namespace std; int main() { double sides[3]; cout << "Enter the sides of triangle: "; cin >> sides[0] >> sides[1] >> sides[2]; sort(sides, sides + 3); if((sides[0] * sides[0]) + (sides[1] * sides[1]) == sides[2] * sides[2]) { cout << "True, it is a right angled triangle as it follows Pythagorean Theorem (a^2 + b^2 = c^2)" << endl; } else { cout << "False, it is not a right angled triangle as it does not follow the Pythagorean Theorem" << endl; } return 0; } ================================================ FILE: Maths/Geometry/Pythagorean_theorem/Pythagorean_theorem.hs ================================================ main = do { putStrLn "Enter sides of the triangle"; sides <- getLine; putStrLn ( let { [x,y,z] = map (\x -> read x :: Int) (words sides); hyp = maxx x y z; legs = filter (< hyp) [x,y,z]; } in ( if isRectTriangle [x,y,z] then "Hypotenuse: " ++ show hyp ++ ", legs: " ++ show legs else "The sides don't follow Pythagoras' theorem." ) ) } isRectTriangle [a,b,c] = or [ a^2 + b^2 == c^2, b^2 + c^2 == a^2, c^2 + a^2 == b^2] maxx a b c = max a (max b c) ================================================ FILE: Maths/Geometry/Pythagorean_theorem/Pythagorean_theorem.js ================================================ //This function checks the 3 numbers. If they form a pythagorean triplet, it finds out hypotenuse and legs // else it return null const checkPythagoreanTriplet = (a, b, c) => { if (!a || !b || !c) { return null; } if (a * a + b * b === c * c) { return { hypotenuse: c, legs: [a, b] } } else if (a * a + c * c === b * b) { return { hypotenuse: b, legs: [a, c] } } else if (c * c + b * b === a * a) { return { hypotenuse: a, legs: [c, b] } } return null; } console.log(checkPythagoreanTriplet(3, 4, 5), checkPythagoreanTriplet(13, 12, 5), checkPythagoreanTriplet(3, 4, 6)) ================================================ FILE: Maths/Geometry/Pythagorean_theorem/Pythagorean_theorem.py ================================================ def CheckPythagoreanTriplet(a, b, c): if not a or not b or not c: return elif a ** 2 == b ** 2 + c ** 2: return a elif b ** 2 == a ** 2 + c ** 2: return b elif c ** 2 == a ** 2 + b ** 2: return c return print("Enter the sides of right angled triangle: ") x = int(input()) y = int(input()) z = int(input()) hypotenuse = CheckPythagoreanTriplet(x, y, z) if hypotenuse == x: print("{0}, {1}, {2} are the sides of a right angled triangle with {0} as hypotenuse and {1}, {2} as legs" .format(x, y, z)) elif hypotenuse == y: print("{1}, {0}, {2} are the sides of a right angled triangle with {0} as hypotenuse and {1}, {2} as legs" .format(y, x, z)) elif hypotenuse == z: print("{1}, {2}, {0} are the sides of a right angled triangle with {0} as hypotenuse and {1}, {2} as legs" .format(z, x, y)) else: print("{}, {}, {} are not the sides of a right angled triangle".format(x, y, z)) ================================================ FILE: Maths/Geometry/Pythagorean_theorem/Pythagorean_theorem.rb ================================================ #!/usr/bin/env ruby puts "Enter the sides of the triangle:" sides = gets.chomp(" ") .split(" ") .map(&:to_f) .sort if sides.length != 3 raise ArgumentError, "Please enter the lengths of the three sides of a triangle" end if sides[0]**2 + sides[1]**2 == sides[2]**2 puts "According to Pythagorean Theorem, a^2 + b^2 = c^2, you have a right triangle" else puts "According to Pythagorean Theorem, you do not have a right triangle" end ================================================ FILE: Maths/Geometry/Pythagorean_theorem/Pythagorean_theorem.swift ================================================ import Foundation func isPythagorean(_ sideA: Float64, _ sideB: Float64, _ sideC: Float64) -> Bool { let sideA_squared = sideA * sideA let sideB_squared = sideB * sideB let sideC_squared = sideC * sideC return (sideA_squared == sideB_squared + sideC_squared) || (sideB_squared == sideA_squared + sideC_squared) || (sideC_squared == sideA_squared + sideB_squared) } print("Enter side A:") let sideAinString = readLine(strippingNewline: true) print("Enter side B:") let sideBinString = readLine(strippingNewline: true) print("Enter side C:") let sideCinString = readLine(strippingNewline: true) if let sideA = Double(sideAinString!), let sideB = Double(sideBinString!), let sideC = Double(sideCinString!) { print(isPythagorean(sideA, sideB, sideC)) } else { print("Input value cannot be converted to a number") } ================================================ FILE: Maths/Geometry/Pythagorean_theorem/README.md ================================================ ## This folder is empty. ================================================ FILE: Maths/Geometry/Pythagorean_theorem/pythogoras_theorem.java ================================================ import java.util.*; import java.lang.*; class pythogoras_theorem{ public static void main(String args[]){ Scanner sc= new Scanner(System.in); double arr[] = new int[3]; System.out.println("Enter the length of the sides of the triangle"); for(int i = 0;i<3;i++){ arr[i] = sc.nextDouble(); } // The user may enter sides length in any order Arrays.sort(arr); if(Math.pow(arr[0],2) + Math.pow(arr[1],2) == Math.pow(arr[2],2)){ System.out.println("The sides of the triangle follow pythogorean theorem."); } else{ System.out.println("The sides of the triangle does not follow pythogorean theorem."); } } } ================================================ FILE: Maths/Geometry/README.md ================================================ # This folder is empty. ================================================ FILE: Maths/Geometry/Radians_Degrees_Conversion/README.md ================================================ ## This folder is empty. ================================================ FILE: Maths/Geometry/Radians_Degrees_Conversion/Radians_Degree_Conversion.c ================================================ // Nothing Special #include #include // Function for conversion double Convert(double degree) { double pi = 3.14159265359; return (degree * (pi / 180)); } // Driver code int main() { double degree; printf("Enter a value:\n"); scanf("%lf" , °ree); double radian = Convert(degree); printf("%lf\n" , radian); return 0; } ================================================ FILE: Maths/Geometry/Radians_Degrees_Conversion/Radians_Degrees_Conversion.c ================================================ #include #define M_PI 3.14159265358979323846 float convert(float *n, int _case); int main() { int _case = 0; //to indicate direction of the conversion float value; printf("What do you want to do?\n"); while(_case != 1 && _case != 2) { printf("\n\t1) Convert degrees to radians.\n\t2) Convert radians to degrees.\n"); scanf("%d", &_case); //get direction of conversion switch(_case) { case 1: printf("Enter your value in degrees: "); break; case 2: printf("Enter your value in radians: "); break; default: printf("\nInvalid choice! Please choose one of the options below..."); break; } } scanf("%f", &value); printf("Value of %f ", value); printf("%s in %s is: %f", ((_case==1) ? "degrees" : "radians"), ((_case==1) ? "radians" : "degrees"), convert(&value, _case)); if(_case == 1) printf(" rad or %.3fPi rad", value/M_PI); else printf(" deg"); char c; scanf("%c", &c); //wait for user input return 0; } float convert(float *n, int _case) { switch(_case) { case 1: //convert from degrees to radians *n=(*n*M_PI)/180; return(*n); break; case 2: //convert from radians to degrees *n=(*n*180)/M_PI; return(*n); break; } } ================================================ FILE: Maths/Geometry/Radians_Degrees_Conversion/Radians_Degrees_Conversion.cpp ================================================ #include #include using namespace std; // Function for conversion double Convert(double degree) { double pi = 3.14159265359; return (degree * (pi / 180)); } // Driver code int main() { double degree; cout<<"Enter a value: <>degree; double radian = Convert(degree); cout << radian; return 0; } ================================================ FILE: Maths/Geometry/Radians_Degrees_Conversion/Radians_Degrees_Conversion.hs ================================================ module Radians_Degrees_Conversion (radToDeg) where radToDeg deg = deg * pi / 180 ================================================ FILE: Maths/Geometry/Radians_Degrees_Conversion/Radians_Degrees_Conversion.java ================================================ class Conversion { private static double radiansToDegrees(double radians) { return round(radians * (180 / Math.PI)); } private static double degreesToRadians(double degrees) { return round(degrees * (Math.PI / 180)); } private static double round(double value) { return (double) Math.round(value * 100) / 100; } public static void main(String[] args) { final double radians = 1; final double degrees = 57.30; assert radiansToDegrees(radians) == degrees; assert degreesToRadians(degrees) == radians; } } ================================================ FILE: Maths/Geometry/Radians_Degrees_Conversion/Radians_Degrees_Conversion.js ================================================ const pi = 3.1415926535; // function to convert degrees to radians const degreesToRadians = (degrees) => { return degrees * (pi / 180); }; // function to convert radians to degrees const radiansToDegrees = (radians) => { return radians * (180 / pi); }; //driver code const degreeInput = prompt("Enter a number to convert from degree to radian: "); let radianOutput = degreesToRadians(degreeInput); console.log(`${degreeInput}° = ${radianOutput} rad`); const radianInput = prompt("Enter a number to convert from radian to degree: "); let degreeOutput = radiansToDegrees(radianInput); console.log(`${radianInput} rad = ${degreeOutput}°`); ================================================ FILE: Maths/Geometry/Radians_Degrees_Conversion/Radians_Degrees_Conversion.py ================================================ def convert(degree): pi = 3.14159265359 return degree * (pi/180) degree = float(input("Enter degrees:")) print("In radians:", convert(degree)) ================================================ FILE: Maths/Geometry/Scalar_Product/README.md ================================================ ## This folder is empty. ================================================ FILE: Maths/Geometry/Scalar_Product/Scalar_Product.c ================================================ // Nothing Special #include int main() { int a1,b1,c1,a2,b2,c2; printf("Enter the 1st Vector\n\n"); printf("A1 = "); scanf("%d" , &a1); printf("B1 = "); scanf("%d" , &b1); printf("C1 = "); scanf("%d" , &c1); printf("Enter the 2nd Vector\n\n"); printf("A2 = "); scanf("%d" , &a2); printf("B2 = "); scanf("%d" , &b2); printf("C2 = "); scanf("%d" , &c2); puts(""); printf("Scalar Product of both vectors is %d\n" , a1 * a2 + b1 * b2 + c1 * c2); return 0; } ================================================ FILE: Maths/Geometry/Scalar_Product/Scalar_Product.hs ================================================ module Scalar_Product (scalar) where [] `scalar` [] = 0 (x:xs) `scalar` (y:ys) = x * y + xs `scalar` ys ================================================ FILE: Maths/Geometry/Scalar_Product/Scalar_Product.java ================================================ import java.io.*; class ScalarProduct { static int n = 3; static int dotProduct(int vect_A[], int vect_B[]) { int product = 0; for (int i = 0; i < n; i++) product = product + vect_A[i] * vect_B[i]; return product; } public static void main(String[] args) { int vect_A[] = {1, 2, 6}; int vect_B[] = {-5, 3, 4}; int cross_P[] = new int[n]; System.out.print("Dot product:"); System.out.println(dotProduct(vect_A, vect_B)); } } ================================================ FILE: Maths/Geometry/Scalar_Product/Scalar_Product.js ================================================ /** * @description given two equal-length vectors, returns a single scalar number. * @param {Number[]} vectorA * @param {Number[]} vectorB * @returns {Number} scalar number */ export function scalarProduct(vectorA, vectorB) { if (vectorA.length != vectorB.length) { throw ("The dimension of the vectors must be the same.") } return vectorA.reduce((accumulator, _, i) => accumulator += (vectorA[i] * vectorB[i]), 0) } ================================================ FILE: Maths/Geometry/Scalar_Product/Scalar_Product.py ================================================ """ LANGUAGE: PYTHON AUTHOR: Diadochokinetic GITHUB: https://github.com/Diadochokinetic """ from operator import mul def Scalar_Product(x, y): return sum(map(mul, x, y)) def float_input(string_input): return [float(element) for element in string_input.split()] if __name__ == '__main__': a = float_input(input("Please enter a vector containing n elements, e.g. 1 2 3: ")) b = float_input(input("Please enter another vector containing n elements, e.g. 4 5 6: ")) print(f'The scalar product for {a} and {b} is: {Scalar_Product(a, b)}') ================================================ FILE: Maths/Geometry/Scalar_Product/scalar_product.cpp ================================================ #include using namespace std; void scalar_prod(int [], int [], int); int main() { int n, a[100], b[100]; cout << "Enter size: "; cin >> n; cout << "Enter data of a: "; for(int i=0; i> a[i]; cout << "Enter data of b: "; for(int i=0; i> b[i]; scalar_prod(a, b, n); return 0; } void scalar_prod(int x[], int y[], int num) { int prod=0; for(int j=0; j " vector_a = gets.chomp.split(",").map(&:to_f) print "Second vector => " vector_b = gets.chomp.split(",").map(&:to_f) puts "Scalar product: #{scalar_product(vector_a, vector_b)}" ================================================ FILE: Maths/Geometry/Vector_Product/README.md ================================================ ## This folder is empty. ================================================ FILE: Maths/Geometry/Vector_Product/Vector_Product.c ================================================ // Nothing Special #include int main() { int a1,b1,c1,a2,b2,c2; printf("Enter the 1st Vector\n\n"); printf("A1 = "); scanf("%d" , &a1); printf("B1 = "); scanf("%d" , &b1); printf("C1 = "); scanf("%d" , &c1); printf("Enter the 2nd Vector\n\n"); printf("A2 = "); scanf("%d" , &a2); printf("B2 = "); scanf("%d" , &b2); printf("C2 = "); scanf("%d" , &c2); puts(""); printf("Vector Product of both vectors is %d %d %d\n" , (b1 * c2) - (b2 * c1) , (a1 * c2) - (a2 * c1) , (a1 * b2) - (a2 * b1)); return 0; } ================================================ FILE: Maths/Geometry/Vector_Product/Vector_Product.cpp ================================================ #include using namespace std; vector vector_product (vector a, vector b){ if (a.size()!=3 || b.size()!=3){ cout<<"Invalid INPUT"<<"\n"; return {}; } vector ans(3); ans[0] = a[1]*b[2] - a[2]*b[1]; ans[1] = a[2]*b[0] - a[0]*b[2]; ans[2] = a[0]*b[1] - a[1]*b[0]; return ans; } int main(){ vector a (3); vector b (3); cout<<"Enter the coordinartes of First Vector"<>a[0]>>a[1]>>a[2]; cout<<"Enter the coordinartes of First Vector"<>b[0]>>b[1]>>b[2]; cout<<"Output is :" for (auto x:vector_product(a,b)) cout< using namespace std; // Query range struct Query { int L, R; }; // Prints sum of all query ranges (m is the number of queries, n is the size of the array) void printQuerySums(int a[], int n, Query q[], int m) { // One by one compute sum of all queries for (int i = 0; i < m; i++) { // Left and right boundaries of current range int L = q[i].L, R = q[i].R; // Compute sum of current query range int sum = 0; for (int j = L; j <= R; j++) sum += a[j]; // Print sum of current query range cout << "Sum of [" << L << ", " << R << "] is " << sum << endl; } } int main() { int a[] = {1, 1, 2, 1, 3, 4, 5, 2, 8}; int n = sizeof(a) / sizeof(a[0]); Query q[] = {{0, 4}, {1, 3}, {2, 4}}; int m = sizeof(q) / sizeof(q[0]); printQuerySums(a, n, q, m); return 0; } ================================================ FILE: Maths/MOs-Algorithm/Mos_Algorithm.cpp ================================================ // Mos Algorithm.cpp : This file contains the 'main' function. Program execution begins and ends there. // // User: kcirym10 // Mos Algorithm is widely used for decreasing complexity in query base problems #include #include #include using namespace std; //This variable represents the block size and is global in order to be used insede of the compare function int block; //Structure that represents a query range struct Query { int L, R; }; bool compare(Query x, Query y) { if (x.L / block != y.L / block) return x.L / block < y.L / block; return x.R < y.R; } void queryResults(vector a, const int n, vector q, const int m) { //Set the block size block = (int)sqrt(n); //Sort all queries using the compare function so that //all queries belonging to the same block are grouped together sort(q.begin(), q.end(), compare); //Initialize the current L, current R and the current sum int currentL = 0, currentR = 0, currentSum = 0; for (int i = 0; i < m; i++) { //Get the L and R values of the current range int L = q[i].L, R = q[i].R; //Remove the extra elements of the previous range while (currentL < L) { currentSum -= a[currentL]; currentL++; } //Add elements from the current range while (currentL > L) { currentSum += a[currentL - 1]; currentL--; } while (currentR <= R) { currentSum += a[currentR]; currentR++; } //Remove the elements from the previous range while (currentR > R + 1) { currentSum -= a[currentR - 1]; currentR--; } // Print sum of current range cout << "Sum of [" << L << ", " << R << "] is " << currentSum << endl; } } int main() { //Default values in order to run the code but a vector can be implemented in order to /*int a[] = { 1, 1, 2, 1, 3, 4, 5, 2, 8 }; int n = sizeof(a) / sizeof(a[0]); Query q[] = { {0, 4}, {1, 3}, {2, 4} }; int m = sizeof(q) / sizeof(q[0]);*/ vector a; vector q; int n; int m; Query temp; int iTemp; cout << "Enter the number of elements: "; cin >> n; cout << "Enter all n elements\n"; for (int i = 0; i < n; i++) { cin >> iTemp; a.push_back(iTemp); } cout << "Enter the number of query calls: "; cin >> m; cout << "Enter the pair of query calls\n"; for (int i = 0; i < m; i++) { cin >> temp.L; cin >> temp.R; q.push_back(temp); } queryResults(a, n, q, m); return 0; } ================================================ FILE: Maths/MOs-Algorithm/README.md ================================================ # This folder is empty. ================================================ FILE: Maths/Number-Theory/Armstrong_Number/ArmstrongNumber.java ================================================ // Implementing Armstrong Number using Java // Code written by Sayan Manna import java.util.*; public class ArmstrongNum { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.println("Enter the number : "); int number = scanner.nextInt(); int originalNumber, remainder, result = 0; originalNumber = number; while (originalNumber != 0) { remainder = originalNumber % 10; result += Math.pow(remainder, 3); originalNumber /= 10; } if(result == number) System.out.println(number + " is an Armstrong number."); else System.out.println(number + " is not an Armstrong number."); } } ================================================ FILE: Maths/Number-Theory/Armstrong_Number/Armstrong_Number.c ================================================ #include using namespace std; int main() { //The number of test cases cout << "Enter the number of testcases" << endl; int t; scanf("%d", &t); while(t--){ int n,rem,ans=0; printf("Enter a Number: "); scanf("%d", &c); int n1=n; while(n1>0){ rem = n1%10; ans = ans + (rem*rem*rem); n1 = n1/10; } if(ans == n) printf("The number %d is an armstrong number", n); else printf("The number %d is not an armstrong number", n); } ================================================ FILE: Maths/Number-Theory/Armstrong_Number/armstrong.py ================================================ def check_armstrong(num): sums = 0 p = num while num != 0: digit = num % 10 sums += pow(digit, 3) num //= 10 if sums == p: return "Yes" else: return "No" number = int(input("Enter a number: ")) result = check_armstrong(number) print(result) ================================================ FILE: Maths/Number-Theory/Armstrong_Number/armstrongin.java ================================================ public class Armstrong { public static void main(String[] args) { int number = 371, originalNumber, remainder, result = 0; originalNumber = number; while (originalNumber != 0) { remainder = originalNumber % 10; result += Math.pow(remainder, 3); originalNumber /= 10; } if(result == number) System.out.println(number + " is an Armstrong number."); else System.out.println(number + " is not an Armstrong number."); } } ================================================ FILE: Maths/Number-Theory/Armstrong_Number/armstrongnumber.cpp ================================================ /* This is a code for armstrong number Code written by Manas Ranjan Swain */ #include #define ll long long int using namespace std; int main() { //The number of test cases cout << "Enter the number of testcases" << endl; int t; cin >> t; while(t--){ ll n,rem,ans=0; cout << "Enter a number" << endl; cin >> n; ll n1=n; while(n1>0){ rem = n1%10; ans = ans + (rem*rem*rem); n1 = n1/10; } if(ans == n) cout << "The number " << n << " is an armstrong number" << endl; else cout << "The number " << n << " is not an armstrong number" << endl; } } ================================================ FILE: Maths/Number-Theory/Armstrong_Number/armstrongnumber.js ================================================ // program to check an Armstrong number of n digits // take an input let number = prompt("Enter a positive integer"); let numberOfDigits = number.length; let sum = 0; // create a temporary variable let temp = number; while (temp > 0) { let remainder = temp % 10; sum += remainder ** numberOfDigits; // removing last digit from the number temp = parseInt(temp / 10); // convert float into integer } if (sum == number) { console.log(`${number} is an Armstrong number`); } else { console.log(`${number} is not an Armstrong number.`); } ================================================ FILE: Maths/Number-Theory/Extended Euclidean Algorithm/extendEuclid.cpp ================================================ // C++ program to demonstrate working of // extended Euclidean Algorithm #include using namespace std; // Function for extended Euclidean Algorithm int gcdExtended(int a, int b, int *x, int *y) { // Base Case if (a == 0) { *x = 0; *y = 1; return b; } int x1, y1; // To store results of recursive call int gcd = gcdExtended(b%a, a, &x1, &y1); // Update x and y using results of // recursive call *x = y1 - (b/a) * x1; *y = x1; return gcd; } // Driver Code int main() { int x, y, a = 35, b = 15; int g = gcdExtended(a, b, &x, &y); cout << "GCD(" << a << ", " << b << ") = " << g << endl; return 0; } ================================================ FILE: Maths/Number-Theory/Extended Euclidean Algorithm/extendEuclid.py ================================================ # Python program to demonstrate working of extended Euclidean Algorithm # function for extended Euclidean Algorithm def gcdExtended(a, b): # Base Case if a == 0: return b, 0, 1 gcd, x1, y1 = gcdExtended(b % a, a) # Update x and y using results of recursive # call x = y1 - (b // a) * x1 y = x1 return gcd, x, y # Driver code first_number, second_number = 35, 15 g, x, y = gcdExtended(first_number, second_number) print("gcd(", first_number, ",", second_number, ") = ", g) ================================================ FILE: Maths/Number-Theory/Fibonacci_Number/Fibonacci.cs ================================================ using System; using System.Text; public static class Fibonacci { //The Fibonacci Sequence is described as a sequence of numbers in which each number is the sum of the two preceding ones, starting from 0 and 1 //Creating the sequence 0, 1, 1, 2, 3, 5, 8, 12, ... //The following method shows how recursion can be used to calculate the value of any given index in the Fibonacci Sequence, //with indexes 0 and 1 used as termination condition public static int GetValue(int index) { if (index <= 0) return 0; if (index == 1) return 1; return GetValue(index-1) + GetValue(index-2); } } //use dotnet-script to test this Console.WriteLine("Please enter the index to be computed"); var input = Console.ReadLine(); var index = 0; while(!Int32.TryParse(input, out index)) { Console.WriteLine("Please enter the index to be computed"); input = Console.ReadLine(); } var fibonacciValue = Fibonacci.GetValue(index); Console.WriteLine($"The value for index {index} is {fibonacciValue}"); ================================================ FILE: Maths/Number-Theory/Fibonacci_Number/FibonacciNumbers.java ================================================ import java.util.Scanner; public class FibonacciNumbers { public static void main(String[] args) { // TODO Auto-generated method stub Scanner sc = new Scanner(System.in); int n1 = 0, n2 = 1, ni, i; System.out.print("Enter number in series : "); int number = sc.nextInt(); // printing 0 and 1 System.out.print(n1 + " " + n2); // loop starts from 2 as 0 and 1 are already printed for (i = 2; i < number; i++) { ni = n1 + n2; System.out.print(" " + ni); n1 = n2; n2 = ni; } } } ================================================ FILE: Maths/Number-Theory/Fibonacci_Number/Fibonacci_Number.clj ================================================ ; lazy sequence of fibonacci (def fibonacci (map first (iterate (fn [[a b]] [b (+ a b)]) [0 1]))) (defn generate-fibonacci [n] (take n fibonacci)) (print (generate-fibonacci 30)) ; will print ; (0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765 10946 17711 28657 46368 75025 121393 196418 317811 514229) ================================================ FILE: Maths/Number-Theory/Fibonacci_Number/Fibonacci_Number.cpp ================================================ #include using namespace std; int main() { int n, t1 = 0, t2 = 1, nextTerm = 0; cout << "Enter the number of terms: "; cin >> n; cout << "Fibonacci Series: "; for (int i = 1; i <= n; ++i) { // Prints the first two terms. if(i == 1) { cout << " " << t1; continue; } if(i == 2) { cout << t2 << " "; continue; } nextTerm = t1 + t2; t1 = t2; t2 = nextTerm; cout << nextTerm << " "; } return 0; } ================================================ FILE: Maths/Number-Theory/Fibonacci_Number/Fibonacci_Number.py ================================================ def fibonacci(number): # return 0 and 1 for first and second terms if number == 0: return 0 elif number == 1: return 1 else: # return the sum of two numbers return fibonacci(number - 1) + fibonacci(number - 2) # read the total number of items in Fibonacci series max_item_input = input("Enter the number of items in Fibonacci series\n") max_item = int(max_item_input) # iterate from 0 till number of terms for count in range(max_item): print(fibonacci(count), end=",") ================================================ FILE: Maths/Number-Theory/Fibonacci_Number/fibonacci.sh ================================================ fibonacci() { if [ $1 -le 0 ] then echo -n "invalid input !" elif [ $1 == 1 ] then echo -n "0 " elif [ $1 == 2 ] then echo -n "1 " else echo -n "$[`fibonacci $[$1-2]` + `fibonacci $[$1 - 1]` ] " fi } echo "Enter a number: " read n fibonacci $n echo ================================================ FILE: Maths/Number-Theory/Perfect_Number/Perfect Number.cpp ================================================ #include #include using namespace std; int main(){ int n,i=1,sum=0; cout << "Enter a number: "; cin >> n; while(i #include using namespace std; int main() { int i, n, num, sum = 0; cout << "Enter The Number" << endl; cin >> num; for (i = 1; i <= sqrt(num); i++) { if (num % i == 0) { if (num / i == 1) { sum = 0; } else { sum = sum + i; } if (num / i != i && num / i != num) { sum = sum + (num / i); } } } if (sum == num) { printf("PERFECT NUMBER \n"); } else { printf("NOT A PERFECT NUMBER \n"); } return 0; } ================================================ FILE: Maths/Number-Theory/Perfect_Number/perfectnumber.js ================================================ function is_perfect(number) { var temp = 0; for (var i = 1; i <= number / 2; i++) { if (number % i === 0) { temp += i; } } if (temp === number && temp !== 0) { console.log("It is a perfect number."); } else { console.log("It is not a perfect number."); } } is_perfect(28); //enter the number here ================================================ FILE: Maths/Number-Theory/Perfect_Number/perfectnumber.php ================================================ function isPerfect($n) { $sum = 1; for ($i = 2; $i * $i <= $n; $i++) { if ($n % $i == 0) { if($i * $i != $n) { $sum = $sum + $i + (int)($n / $i); } else { $sum = $sum + $i; } } } if ($sum == $n && $n != 1) { echo "$n is a perfect number"; } else { echo "$n is not a perfect number"; } } isPerfect(6); ================================================ FILE: Maths/Number-Theory/README.md ================================================ # This folder is empty. ================================================ FILE: Maths/Number-Theory/Segmented_Sieve/README.md ================================================ ## This folder is empty. ================================================ FILE: Maths/Number-Theory/Segmented_Sieve/Segmented_Sieve.php ================================================ #include void SieveOfEratosthenes(int num) { /*Boolean array to mark a number is prime or not*/ bool prime[num+1]; int i,j; /*Initialisation(Mark all number as prime)*/ for(i=0;i<=num;i++) prime[i]=true; /*Zero is not prime*/ prime[0]=false; /*One is not prime*/ prime[1]=false; /*Mark all non prime number as false*/ for(i=2;i<=num;i++){ if(prime[i]==true){ for(j=i*i;j<=num;j+=i) prime[j]=false; } } /*Print all the prime numbers*/ for(i=2;i<=num;i++){ if(prime[i]==true) printf("%d ",i); } printf("\n"); } int main() { int num; /*Take input from the user*/ scanf("%d",&num); /*Prime number generation using Sieve of Eratosthenes*/ SieveOfEratosthenes(num); return 0; } ================================================ FILE: Maths/Number-Theory/Sieve_of_Eratosthenes/SieveOfEratosthenes.cs ================================================ using System; using System.Collections; using System.Collections.Generic; using System.Linq; class SieveOfEratosthenes { // Implementation using the Sieve of Eratosthenes algorithm private static int[] GetAllPrimesUpTo(int num) // Includes num { if (num < 2) { return new int[0]; } BitArray primes = new BitArray(num + 1); primes[2] = true; for (int i = 3; i < num; i += 2) { primes[i] = true; } for (int i = 0; i * i < num; i++) { if (primes[i]) { for (int primeMultiple = i * i; primeMultiple < num; primeMultiple += i) { primes[primeMultiple] = false; } } } List primesList = new List(); for (int i = 0; i < primes.Length; i++) { if (primes[i]) { primesList.Add(i); } } return primesList.ToArray(); } static void Main(string[] args) { // Test Cases: // Small Number // 3 // 2 // 1 // 0 // Negative Number // Large Number int[] primes = GetAllPrimesUpTo(100).ToArray(); Console.WriteLine($"Primes Found: {primes.Length}"); // Primes Found: 25 primes = GetAllPrimesUpTo(3).ToArray(); Console.WriteLine($"Primes Found: {primes.Length}"); // Primes Found: 1 primes = GetAllPrimesUpTo(2).ToArray(); Console.WriteLine($"Primes Found: {primes.Length}"); // Primes Found: 1 primes = GetAllPrimesUpTo(1).ToArray(); Console.WriteLine($"Primes Found: {primes.Length}"); // Primes Found: 0 primes = GetAllPrimesUpTo(0).ToArray(); Console.WriteLine($"Primes Found: {primes.Length}"); // Primes Found: 0 primes = GetAllPrimesUpTo(-100).ToArray(); Console.WriteLine($"Primes Found: {primes.Length}"); // Primes Found: 0 primes = GetAllPrimesUpTo(1000000000).ToArray(); // 1 Billion Console.WriteLine($"Primes Found: {primes.Length}"); // Primes Found: 50847534 Console.ReadLine(); } } ================================================ FILE: Maths/Number-Theory/Sieve_of_Eratosthenes/Sieve_of_Erastosthenes.rb ================================================ class SieveOfErastosthenes def initialize(limit) @limit = limit @primes = initial_array end # Auto invokation of the class def self.call(limit) new(limit).call end def call find_primes @primes.select { |n| n }.length # Select only prime numbers in array and return only prime values. end private def initial_array (0..@limit).map {|i| i >= 2 ? true : false} end # Iterates over all truthies values to filter multiples and get primes def find_primes index = 0 while index < @primes.length do find_multiples(index) if @primes[index] index += 1 end end # Finds all multiples of the current index number, starting with its square. def find_multiples(index) multiples_index = index * index while multiples_index < @primes.length do @primes[multiples_index] = false multiples_index += index end end end puts SieveOfErastosthenes.call(-1) # 0 puts SieveOfErastosthenes.call(1) # 0 puts SieveOfErastosthenes.call(100) # 25 puts SieveOfErastosthenes.call(1000000) # 78498 ================================================ FILE: Maths/Number-Theory/Sieve_of_Eratosthenes/Sieve_of_Erastosthenes.ts ================================================ const getAllPrimesUpToNumber = (num: number): number[] => { //Prefill array up to max num. const maxNumArray: boolean[] = new Array(num).fill(true) //Won't find any primes > sqrt of num. const limit = Math.floor(Math.sqrt(num)) //Increment by 2, as no even numbers besides 2 are prime. for (let i = 3; i < limit; i += 2) { if (maxNumArray[i]) { //Remove multiples of primes. for (let j = i * i; j < num; j += i * 2) { maxNumArray[j] = false } } } //Initialize with 2, as it is the only even prime and we have not checked them. const primes: number[] = [2] //Push all items that are truthy to primes array. for (let i = 3; i < num; i += 2) { maxNumArray[i] && primes.push(i) } return primes } console.log(getAllPrimesUpToNumber(10000000)) ================================================ FILE: Maths/Number-Theory/Sieve_of_Eratosthenes/Sieve_of_Eratosthenes.c ================================================ #include int main() { int number,i,j; printf("Enter the number\n"); scanf("%d",&number); int primes[number+1]; //populating array with naturals numbers for(i = 2; i<=number; i++) primes[i] = i; i = 2; while ((i*i) <= number) { if (primes[i] != 0) { for(j=2; j number) break; else // Instead of deleteing , making elemnets 0 primes[primes[i]*j]=0; } } i++; } for(i = 2; i<=number; i++) { //If number is not 0 then it is prime if (primes[i]!=0) printf("%d\n",primes[i]); } return 0; } ================================================ FILE: Maths/Number-Theory/Sieve_of_Eratosthenes/Sieve_of_Eratosthenes.cpp ================================================ // C++ program to print all primes smaller than or equal to // n using Sieve of Eratosthenes #include using namespace std; void SieveOfEratosthenes(int n) { // Create a boolean array "prime[0..n]" and initialize // all entries it as true. A value in prime[i] will // finally be false if i is Not a prime, else true. bool prime[n+1]; memset(prime, true, sizeof(prime)); for (int p=2; p*p<=n; p++) { // If prime[p] is not changed, then it is a prime if (prime[p] == true) { // Update all multiples of p greater than or // equal to the square of it // numbers which are multiple of p and are // less than p^2 are already been marked. for (int i=p*p; i<=n; i += p) prime[i] = false; } } // Print all prime numbers for (int p=2; p<=n; p++) if (prime[p]) cout << p << " "; } // Driver Program to test above function int main() { int n = 30; cout << "Following are the prime numbers smaller " << " than or equal to " << n << endl; SieveOfEratosthenes(n); return 0; } ================================================ FILE: Maths/Number-Theory/Sieve_of_Eratosthenes/Sieve_of_Eratosthenes.go ================================================ package main import "fmt" func checkPrime(n int) bool { if n > 1 { if n == 2 { return true } for i := 2; i < n; i++ { if n % i == 0 { return false } } } else { return false } return true } func generateSieve(n int) []int { var sieve []int for i := 1; i < n; i++ { if checkPrime(i) { sieve = append(sieve, i) } } return sieve } func main() { fmt.Println(generateSieve(500)) } ================================================ FILE: Maths/Number-Theory/Sieve_of_Eratosthenes/SieveofErastosthenes.java ================================================ public class PrimeSieve { public static void main(String[] args) { int n = Integer.parseInt(args[0]); // initially assume all integers are prime boolean[] isPrime = new boolean[n+1]; for (int i = 2; i <= n; i++) { isPrime[i] = true; } // mark non-primes <= n using Sieve of Eratosthenes for (int factor = 2; factor*factor <= n; factor++) { // if factor is prime, then mark multiples of factor as nonprime // suffices to consider mutiples factor, factor+1, ..., n/factor if (isPrime[factor]) { for (int j = factor; factor*j <= n; j++) { isPrime[factor*j] = false; } } } // count primes int primes = 0; for (int i = 2; i <= n; i++) { if (isPrime[i]) primes++; } System.out.println("The number of primes <= " + n + " is " + primes); } } ================================================ FILE: Maths/Number-Theory/Sieve_of_Eratosthenes/prime_and_base.py ================================================ #include using namespace std; char letterconverter(int number) { return 'A' + (number-10); } int main() { vector primes; int num, flag, x, base2, i, upto; // Take input from user cout << "Find prime numbers upto : "; cin >> upto; for(num = 2; num <= upto; num++) { flag = 0; for(i = 2; i <= (num / 2); i++) { if(num % i == 0) { flag = 1; break; } } // If the number is prime then store it in primes vector if(flag == 0) primes.push_back(num); } // Printing all primes between [2, N] cout << endl << "All prime numbers upto " << upto << " are : " << endl; for(i=0; i>base2; for (int j =0; j 0) { x = num % base2; if(x <= 9) { temp += to_string(x); } else { temp += letterconverter(x); } num /= base2; } reverse(temp.begin(), temp.end()); cout< 1: fs.append(n) return fs # Finding sum of digits of prime factor of the given number def getIntLetterCount(n): return sum([int(l) for l in list(str(n))]) def isSmithNumber(n): return sum([getIntLetterCount(f) for f in factors(n)]) == getIntLetterCount(n) # Driver Code : if __name__ == '__main__': # Input the number to be checked whether Smith number or not n = input() if isSmithNumber(n): print ("It is Smith Number") else: print ("It is not a Smith Number") # The first few Smith Numbers are as follows : 4 22 27 58 85 94 121 166 202 265 274 319 346 355... ================================================ FILE: Maths/Number-Theory/Smith_number/smith_numbers_till_n.cpp ================================================ // ---------------------------------PROBLEM STATEMENT-------------------------------- //Given a number n, the task is to find out whether this number is smith number or not. //Smith Number is a composite number whose sum of digits is equal to the //sum of digits in its prime factorization. #include using namespace std; int num; // array to store prime numbers vector is_prime; // function for sieve of Sundaram void sieve_of_sundaram() { // sieve of sundaram will give primes smaller than 2+2*n for a given number n // we will reduce num to num/2 as it won't effect our answer // is_marked array is used to separate numbers of the form i+j+2*i*j from others where 1 <= i <= j bool is_marked[num/2 + 100] = {0}; //logic : // marking all numbers i where 2*i+1 is not prime for (int i=1; i<=(sqrt(num)-1)/2; i++) for (int j=(i*(i+1))<<1; j<=num/2; j=j+2*i+1) is_marked[j] = true; is_prime.push_back(2);// as 2 is the first prime number // rest primes are pushed in is_prime vecto, they are of the form 2*i + 1 where is_marked[i] is false. for (int i=1; i<=num/2; i++) if (is_marked[i] == false) is_prime.push_back(2*i + 1); } // function to check if a number is Smith number or not bool is_smith_number(int n) { int initial_n = n;// storing the initial value of n in a variable int sum_of_digits = 0;// to store the sum of digits of prime factores of n for (int i = 0; is_prime[i] <= n/2; i++) { while (n % is_prime[i] == 0) { //adding the digits of primes[i] to sum_of_digits of primes[i] is a prime factor int p = is_prime[i]; n = n/p; while (p > 0) { sum_of_digits += (p % 10); p = p/10; } } } // if n is not 1, one prime factor of n still exist and we need to sum its digits too if (n != 1 && n != initial_n) { while (n > 0) { sum_of_digits = sum_of_digits + n%10; n = n/10; } } // after covering all the prime factors of initial n, we add the digits of initial n too int sumDigits = 0; while (initial_n > 0) { sumDigits = sumDigits + initial_n % 10; initial_n = initial_n/10; } // we return true only if the sum of digits in prime factors of inital n and sum of digits // of initial n are same return (sum_of_digits == sumDigits); } // main function int main() { int n; // taking input for number n cout<<"Enter the value of n: "; cin>>n; num=n; // calling the function sieve_of_sundaram sieve_of_sundaram(); // printing smith numbers present between 1 and n cout << "Smith numbers present between 1 and n: \n"; for (int i=1; i<=n; i++) { if (is_smith_number(i)) cout << i << " "; } return 0; } ================================================ FILE: Maths/Number-Theory/Strong_Number/strong_number.c ================================================ #include int main() { int n; int sum=0; printf("Enter a number"); scanf("%d",&n); int k=n; int r; while(k!=0) { r=k%10; int f=fact(r); k=k/10; sum=sum+f; } if(sum==n) { printf("\nNumber is a strong"); } else { printf("\nNumber is not a strong"); } return 0; } int fact(int r) { int mul=1; for(int i=1;i<=r;i++) { mul=mul*i; } return mul; } ================================================ FILE: Maths/Number-Theory/Strong_Number/strong_number.cpp ================================================ #include using namespace std; int main() { int n,i; int fact,rem; cout << "\nEnter a number : "; cin >> n; cout << endl; int sum = 0; int temp = n; while(n) { i = 1,fact = 1; rem = n % 10; while(i <= rem) { fact = fact * i; i++; } sum = sum + fact; n = n / 10; } if(sum == temp) cout << temp << " is a strong number\n"; else cout << temp << " is not a strong number\n"; return 0; } ================================================ FILE: Maths/Number-Theory/Strong_Number/strong_number.java ================================================ import java.util.*; public class Main { public static void main(String[] args) { int n,i; int fact,rem; Scanner sc = new Scanner(System.in); System.out.print("\nEnter the number : "); n = sc.nextInt(); int sum = 0; int temp = n; while(n != 0) { i = 1; fact = 1; rem = n % 10; while(i <= rem) { fact = fact * i; i++; } sum = sum + fact; n = n / 10; } if(sum == temp) System.out.println(temp + " is a strong number\n"); else System.out.println(temp + " is not a strong number\n"); System.out.println(); } } ================================================ FILE: Maths/Number-Theory/Strong_Number/strong_number.py ================================================ n= int(input("Enter the number : ")) sum = 0 temp = n while (n): i = 1 fact = 1 rem = int(n % 10) while(i <= rem): fact = fact * i i = i + 1 sum = sum + fact n = int(n / 10) if(sum == temp): print(temp,end = "") print(" is a strong number") else: print(temp,end = "") print(" is not a strong number") ================================================ FILE: Maths/Number-Theory/Strong_Number/strong_number.sh ================================================ !#bin/bash echo enter the value of n read n sum=0 k=$n while [ $n -gt 0 ] do d=`echo $n%10|bc` fact=1 i=1 while [ $i -le $d ] do fact=`echo $fact*$i|bc` i=`echo $i+1|bc` done sum=`echo $sum+$fact|bc` n=`echo $n/10|bc` done if [ $sum -eq $k ] then echo it is strong number else echo it is not strong number fi ================================================ FILE: Maths/Number-Theory/Tribonacci_Number/nthTribonacci.kt ================================================ fun nthTribonacci(n: Int): Int{ //create a dp array of size n+1 filled with 0's val dp = IntArray(n+1){0} for(i in 0..n){ if(i < 3) dp[i] = i/2 //since first three elements are 0, 0 and 1 //so we can cleverly write dp[i] = i/2 else //otherwise, the sum of preceeding three values is the ith Tribonacci dp[i] = dp[i - 1] + dp[i - 2] + dp[i - 3] } return dp[n] } fun main(){ //read input value of n val n = readLine()!!.toInt() //print the corresponding output println(nthTribonacci(n)) } ================================================ FILE: Maths/Number-Theory/Ugly_Number/README.md ================================================ ## This folder is empty. ================================================ FILE: Maths/Number-Theory/Ugly_Number/UglyNumber.go ================================================ // This file has the implementation to check whether a number is Ugly or not package main import ( "bufio" "fmt" "os" "strconv" "strings" ) // Check whether the function is ugly or not func isUgly(num int) bool { for num >= 2 { if num%2 == 0 { num /= 2 } else if num%3 == 0 { num /= 3 } else if num%5 == 0 { num /= 5 } else { return false } } return num == 1 } func main() { reader := bufio.NewReader(os.Stdin) fmt.Print("Enter Number: ") input, _ := reader.ReadString('\n') fmt.Println(input) input = strings.TrimSuffix(input, "\n") inputNum, err := strconv.Atoi(input) if err != nil { fmt.Println("Input Number is not valid", input, err) return } if isUgly(inputNum) { fmt.Println("Input Number is Ugly Number") } else { fmt.Println("Input number is not Ugly") } } ================================================ FILE: Maths/Number-Theory/Ugly_Number/UglyNumbers.sh ================================================ #!/bin/bash echo "Enter a positive integer : " read x while [ $x -ne 1 ] do if [ $((x%2)) -eq 0 ] then let "x/=2" elif [ $((x%3)) -eq 0 ] then let "x/=3" elif [ $((x%5)) -eq 0 ] then let "x/=5" else let "n=1" echo "It is not a Ugly Number." break fi done if [ $((n)) -eq 0 ] then echo "It is a Ugly Number." fi exit ================================================ FILE: Maths/Number-Theory/Ugly_Number/Ugly_Number.c ================================================ # include # include int main() { int n , x = 0; printf("\n\n Check whether a given number is an ugly number:\n"); printf("----------------------------------------------------\n"); printf("Input an integer number: "); scanf("%d",&n); if (n <= 0) printf("Input a correct number."); while (n != 1) { if (n % 5 == 0) n /= 5; else if (n % 3 == 0) n /= 3; else if (n % 2 == 0) n /= 2; else { printf("It is not an ugly number.\n"); x = 1; break; } } if(x == 0) printf("It is an ugly number.\n"); } ================================================ FILE: Maths/Number-Theory/Ugly_Number/Ugly_Number.java ================================================ //Implementing Ugly Number in Java import java.util.*; class Solution{ //function to calculate whether ugly number or not public boolean isUgly(int number) { if (number <= 0){ return false; } if (number == 1){ return true; } if (number % 2 == 0) { return isUgly(number/2); } if (number % 3 == 0) { return isUgly(number/3); } if (number % 5 == 0) { return isUgly(number/5); } return false; } } //main class public class Ugly_Number { public static void main(String[] args){ Scanner scanner = new Scanner(System.in); System.out.println("Enter the number: "); int input_number = scanner.nextInt(); Solution object = new Solution(); boolean answer = object.isUgly(input_number); if(answer==true) System.out.println("Number is Ugly"); else System.out.println("Number is not Ugly"); } } ================================================ FILE: Maths/Number-Theory/Ugly_Number/Ugly_Number.js ================================================ const uglyNumber = (number) => { //determine if a number is prime const numIsPrime = (num) => { for (let i = 2; i <= Math.sqrt(num); i++) { if (num % i === 0) { return false; } } return num > 1; } const primeFactors = []; const uglyPrimeFactors = [2, 3, 5] //push distinct prime factors to the array for (let i = 2; i <= number; i++) { while (numIsPrime(i) && number % i === 0) { if (!primeFactors.includes(i)) { primeFactors.push(i); } number /= i; } } //find out if number is an ugly number i.e has prime factors consisting of 2, 3, or 5 const numberIsUgly = primeFactors.some(factor => uglyPrimeFactors.includes(factor)) ? true : false; return numberIsUgly; } ================================================ FILE: Maths/Number-Theory/Ugly_Number/Ugly_Number.php ================================================ using namespace std; unsigned getNthUglyNo(unsigned n) { unsigned ugly[n]; unsigned i2 = 0, i3 = 0, i5 = 0; unsigned next_multiple_of_2 = 2; unsigned next_multiple_of_3 = 3; unsigned next_multiple_of_5 = 5; unsigned next_ugly_no = 1; ugly[0] = 1; for (int i=1; i>n; cout << getNthUglyNo(n); return 0; } ================================================ FILE: Maths/Number-Theory/Ugly_Number/Ugly_Numbers.sh ================================================ #!/bin/bash echo "Enter a positive integer : " read x while [ $x != 1 ] do if [ $x%2 == 0 ] then $x = $x/2 fi done echo "done" exit ================================================ FILE: Maths/README.md ================================================ # Index * [Algebra](Algebra/) * [Calculus](Calculus/) * [Discrete](Discrete/) * [Geometry](Geometry/) * [MOs-Algorithm](MOs-Algorithm/) * [Number-Theory](Number-Theory/) * [Series](Series/) * [Statistics](Statistics/) ================================================ FILE: Maths/Series/Arithmetic_Progression/AP.py ================================================ def AP(a,d,n): sum=0 curr_term=a for i in range(1,n+1): print(curr_term, end=' ') curr_term =curr_term + d a = 5 d = 1 n = 10 AP(a, d, n) ================================================ FILE: Maths/Series/Arithmetic_Progression/Arithematic_Progression.cpp ================================================ #include using namespace std; int main() { int A,N,D;//A=First Term,N= N th term, D=Common Difference A=5; N=8; D=2; for(int i=0;i void main(){ int a, n, d, i; printf("Enter the first term: "); scanf("%d", &a); printf("Enter the number of terms: "); scanf("%d", &n); printf("Enter the difference between the terms: "); scanf("%d", &d); printf("AP: "); for (i = 0; i < n; i++) printf("%d ", a + (i * d)); } ================================================ FILE: Maths/Series/Arithmetic_Progression/Arithmetic_Progression.java ================================================ import java.util.Scanner; public class Arithmetic_Progression { public static void main(String[] args) { Scanner sc = new Scanner(System.in); StringBuffer answer; double firstTerm, prevTerm, commonDiff; int numTerms; // user prompts System.out.print("What is the first term in the arithmetic progression? "); firstTerm = sc.nextDouble(); System.out.print("How many terms? "); numTerms = sc.nextInt(); System.out.print("What is the difference between each term? "); commonDiff = sc.nextDouble(); answer = new StringBuffer(firstTerm + " "); prevTerm = firstTerm; for (int i = 0; i < numTerms; i++) { prevTerm += commonDiff; answer.append(prevTerm + " "); } System.out.println(answer.toString()); } } ================================================ FILE: Maths/Series/Arithmetic_Progression/Arithmetic_Progression.js ================================================ /* * These functions can run in any JS environment: they're specific-agnostic. * Basically, they help getting an entire arithmetic progression, * calculating a progression's nth term or the sum of the progression * faster without using iterations. */ /* * Function to calculate an arithmetic progression, starting from a term, * with given difference, up to a given number of terms. * This function follows this formula: * an = a + n * d * @param {Number} firstTerm - The term which starts the progression; * @param {Number} difference - The common difference of the progression; * @param {Number} nTerms - The maximum number of terms you wish to know; * @returns {Number[]} - The [nTerms] terms of the arithmetic progression. */ function arithmeticProgression(firstTerm, difference, nTerms) { const terms = []; for (let term = firstTerm; (term / difference) < nTerms; term += difference) { terms.push(term); } return terms; } /* * Function to calculate the nth term of an arithmetic progression. * This function follows this formula: * an = a1 + (n-1)d * @param {Number} nTerm - The nth term you wish to know; * @param {Number} firstTerm - The term which starts the progression; * @param {Number} difference - The common difference of the progression; * @returns {Number} - The nth term of the arithmetic progression. */ function arithmeticProgressionNthTerm(nTerm, firstTerm, difference) { return firstTerm + ((nTerm - 1) * difference); } /* * Function to calculate the arithmetic series of an arithmetic progression, * which is the sum of all the progression's terms, starting from a term * and ending with another, without knowing the difference. * This function follows this formula: * S = 1/2 * n * (a1 + an) * @param {Number} firstTerm - The term which starts the progression; * @param {Number} lastTerm - The last term of the progression; * @param {Number} nTerms - The number of terms which compose the progression; * @returns {Number} - The arithmetic series of the progression. */ function arithmeticSeries(firstTerm, lastTerm, nTerms) { return 1 / 2 * nTerms * ( firstTerm + lastTerm ); } /* * There is no need to create a function to calculate * the difference between two terms, because, well, * that's just a difference. * lastTerm - firstTerm = common difference of the progression. */ ================================================ FILE: Maths/Series/Arithmetic_Progression/Arithmetic_Progression.php ================================================ ================================================ FILE: Maths/Series/Arithmetic_Progression/Arithmetic_Progression.sh ================================================ #!/bin/bash echo "Enter first term of the AP : " read a echo "Enter the common differnce :" read d echo "Enter number of terms :" read n for ((i=0;i<=n;i++)) do echo $((a+(i*d))) done ================================================ FILE: Maths/Series/Arithmetic_Progression/Arithmetic_Progression.ts ================================================ /* * This class can run in any TS environment or be compiled to any JS environment: they're specific-agnostic. * Basically, it helps getting an entire arithmetic progression, calculating a progression's nth term or the * sum of the progression faster without using iterations. */ class ArithmeticProgression { firstTerm: number; difference?: number; /* * @constructor * @params {Number} [firstTerm=0] - The first term of the progression is required for all methods in this class, so it's a required param. * @params {Number} [difference=1] - If known, this is the common difference between the progression's terms. It's required for the two main methods. */ constructor(firstTerm: number = 0, difference: number = 1) { this.firstTerm = firstTerm; this.difference = difference; } /* * Method to calculate an arithmetic progression, starting from a term, * with given difference, up to a given number of terms. * The "difference" parameter in the constructor is required. * This method follows this formula: * an = a + n * d * @param {Number} nTerms - The maximum number of terms you wish to know; * @returns {Number[]} - The [nTerms] terms of the arithmetic progression. */ calculate(nTerms: number): number[] { const terms = []; for (let term = this.firstTerm; (term / this.difference) < nTerms; term += this.difference) { terms.push(term); } return terms; } /* * Method to calculate the nth term of an arithmetic progression. * The "difference" parameter in the constructor is required. * This method follows this formula: * an = a1 + (n-1)d * @param {Number} nTerm - The nth term you wish to know; * @returns {Number} - The nth term of the arithmetic progression. */ getNthTerm(nTerm: number): number { return this.firstTerm + ((nTerm - 1) * this.difference); } /* * Method to calculate the arithmetic series of an arithmetic progression, * which is the sum of all the progression's terms, starting from a term * and ending with another, without knowing the difference. * This method follows this formula: * S = 1/2 * n * (a1 + an) * @param {Number} lastTerm - The last term of the progression; * @param {Number} nTerms - The number of terms which compose the progression; * @returns {Number} - The arithmetic series of the progression. */ getSeries(lastTerm: number, nTerms: number): number { return 1 / 2 * nTerms * ( this.firstTerm + lastTerm ); } /* * There is no need to create a method to calculate * the difference between two terms, because, well, * that's just a difference. * lastTerm - firstTerm = common difference of the progression. * I'll do it anyways, because a method which does it can be handy. * @param {Number} secondTerm - The second term to get the difference along with the first; * @param {Boolean} abs - If you want the result as an absolute value or not; * @returns {Number} - The difference between the first and second terms. */ getDifference(secondTerm: number, abs: boolean): number { return abs ? Math.abs(secondTerm - this.firstTerm) : secondTerm - this.firstTerm; } } ================================================ FILE: Maths/Series/Arithmetic_Progression/README.md ================================================ ## This folder is empty. ================================================ FILE: Maths/Series/Fibonacci/Fibonacci.c ================================================ // Nothing Special #include #include int main() { int32_t t1 = 0 , t2 = 1 , next_term; int32_t n; scanf("%" PRId32 , &n); puts("Fibonacci Series ..."); for (int32_t i = 0; i <= n; i++) { printf("%" PRId32 "\t" , t1); next_term = t1 + t2; t1 = t2; t2 = next_term; } printf("\n"); return 0; } ================================================ FILE: Maths/Series/Fibonacci/Fibonacci.cpp ================================================ #include using namespace std; int fib(int n) { int a = 0, b = 1, c, i; if( n == 0) return a; for(i = 2; i <= n; i++) { c = a + b; a = b; b = c; } return b; } int main(){ int n; cin>>n; cout << fib(n); return 0; } ================================================ FILE: Maths/Series/Fibonacci/Fibonacci.sh ================================================ #!/bin/bash echo "Enter number of terms in Fibonacci Series : " read n f0=0 f1=1 for((i=0;i<=n;i++)) do f=$f0+$f1 f0=$f1 f1=$f echo $((f)) done ================================================ FILE: Maths/Series/Fibonacci/Fiboncci.py ================================================ def fibonacci(number): # return 0 and 1 for first and second terms if number == 0: return 0 elif number == 1: return 1 else: # return the sum of two numbers return fibonacci(number - 1) + fibonacci(number - 2) # read the total number of items in Fibonacci series max_item_input = input("Enter the number of items in Fibonacci series\n") max_item = int(max_item_input) # iterate from 0 till number of terms for count in range(max_item): print(fibonacci(count), end=",") ================================================ FILE: Maths/Series/Fibonacci/README.md ================================================ ## This folder is empty. ================================================ FILE: Maths/Series/Fibonacci/fibonacci.cpp ================================================ #include using namespace std; int fib(int n) { int a = 0, b = 1, c, i; if( n == 0) return a; for(i = 2; i <= n; i++) { c = a + b; a = b; b = c; } return b; } int main(){ int n; cin>>n; cout << fib(n); return 0; } ================================================ FILE: Maths/Series/Fibonacci/fibonacci.java ================================================ public class Fibonacci { public static void main(String[] args) { int n = 10, t1 = 0, t2 = 1; System.out.print("First " + n + " terms: "); for (int i = 1; i <= n; ++i) { System.out.print(t1 + " + "); int sum = t1 + t2; t1 = t2; t2 = sum; } } } ================================================ FILE: Maths/Series/Geometric_Progression/Geometric Progression.py ================================================ def gp(a,r,n): for i in range(n): temp = a*pow(r,i) print(temp,end=" ") a = int(input()) r = int(input()) n = int(input()) gp(a,r,n) ================================================ FILE: Maths/Series/Geometric_Progression/GeometricProgression.cs ================================================ using System; class GeometricProgression { static int gp(int a, int q, int n){ return ((int) (a * Math.Pow(q, n-1))); } static void Main() { int a = Convert.ToInt32(Console.ReadLine()); int q = Convert.ToInt32(Console.ReadLine()); int n = Convert.ToInt32(Console.ReadLine()); Console.WriteLine("" + gp(a,q,n)); } } ================================================ FILE: Maths/Series/Geometric_Progression/GeometricProgression.java ================================================ import java.lang.*; public class Main { //Function that prints GP for given value of a, r and n where nth GP=a*r^(n-1) static void GP(int a, int r, int n){ for(int i=0;i using namespace std; int main() { long d,n,a; long an; cout<<"Enter first term : "; cin>>a; cout<<"Enter difference : "; cin>>d; cout<<"Enter number of terms :"; cin>>n; cout<<"Harmonic progression : "; for(int y=1;y<=n;y++) { an=a+(y-1)*d; cout<<"1/"< #include int main() { int terms, i, first, denominator, diff; float sum = 0.0; printf("Enter the number of terms in HP series\n"); scanf("%d", &terms); printf("Enter denominator of first term and common difference of HP series\n"); scanf("%d %d", &first, &diff); denominator = first; printf("HP SERIES\n"); for(i = 0; i < terms; i++) { printf("1/%d ", denominator); sum += 1/(float)denominator; denominator += diff; } printf("\nSum of the HP series till %d terms is %f\n", terms, sum); getch(); return 0; } /*Enter the number of terms in HP series 5 Enter denominator of first term and common difference of HP series 2 4 HP SERIES 1/2 1/6 1/10 1/14 1/18 Sum of the HP series till 5 terms is 0.893651*/ ================================================ FILE: Maths/Series/Harmonic_Progression/Harmonic_Expression.java ================================================ import java.util.Scanner; public class Harmonic_Expression{ public static void main(String args[]){ Scanner scan = new Scanner(System.in); long difference, startTerm, numberOfTerms; System.out.print("Enter Starting Term : "); startTerm = scan.nextLong(); System.out.print("Enter Difference : "); difference = scan.nextLong(); System.out.print("Enter Number of Terms : "); numberOfTerms = scan.nextLong(); if( startTerm == 0 ){ System.out.println("Invalid start of Harmonic Progression."); } else{ System.out.println("Sequence is :"); for(int i = 1; i <= numberOfTerms; i++){ System.out.print(String.format("1/%s",(startTerm+((i-1)*difference)))); if(i!=numberOfTerms) System.out.print(" , "); } } System.out.println(); } } ================================================ FILE: Maths/Series/Harmonic_Progression/README.md ================================================ ## This folder is empty. ================================================ FILE: Maths/Series/Harmonic_Progression/SumOfHP.swift ================================================ // // SumOfHP.swift // Hacktoberfest // // Created by Dipankar Goswami on 03/10/20. // import Foundation func getHPSum(first_term: Double, common_diff: Double, no_of_terms: Int) -> Double { var res:Double = 0.0 for i in 0...no_of_terms-1 { res = res + 1/(first_term + Double(i) * common_diff) } return res } var first_term = Double(readLine()!)! var common_diff = Double(readLine()!)! var no_of_terms = Int(readLine()!)! /* Following Code blocm checks if any of the term in arithmatic progression can be zero. In that case corresponding term in HP is undefined. Checks are - 1. If first term is zero. 2. if negative of (first_term/common_diff) is a positive integer between 1 and number of terms (inclusive) */ if first_term == 0 || (common_diff != 0 && Int(first_term) % Int(common_diff) == 0 && (Int(first_term/common_diff ) * (-1) < no_of_terms && Int(first_term/common_diff) * -1 > 0)) { print("Harmonic progression potentially contains zero as one of the terms.") } else { let res = getHPSum(first_term: first_term, common_diff: common_diff, no_of_terms: no_of_terms) print("Sum of Harmonic progression for given inputs is \(res)") } ================================================ FILE: Maths/Series/Harmonic_Progression/harmonic_progression.py ================================================ def HP(a,d,n): curr_term=a for i in range(1,n+1): temp=a+(i-1)*d print(1/temp) a = 2 d = 1 n = 5 HP(a, d, n) ================================================ FILE: Maths/Series/Lucas_Series/Lucas_Series.c ================================================ #include #include int main() { int first_term, second_term, third_term; int limit, count; printf("Enter the Limit :-\n"); scanf("%d", &limit); first_term = 2; second_term = 1; printf("Series :-\n"); for(count = 0; count < limit; count++) { printf("%d ", first_term); third_term = first_term + second_term; first_term = second_term; second_term = third_term; } printf("\n"); return 0; } ================================================ FILE: Maths/Series/Lucas_Series/Lucas_Series.cpp ================================================ #include using namespace std; int main() { int term_1 = 2; int term_2 = 1; int next_term; int num_terms; cout << "Number of terms to be found: "; cin >> num_terms; cout << "The first " << num_terms << " of the Lucas Series are:\n"; for (int i = 1; i <= num_terms; i++) { cout << term_1 << "\t"; next_term = term_1 + term_2; term_1 = term_2; term_2 = next_term; } cout << "\n"; } ================================================ FILE: Maths/Series/Lucas_Series/Lucas_Series.go ================================================ package main import ( "bufio" "fmt" "os" "strconv" "strings" ) func printLucasSeries(size int) { // Print first two terms l1 := 2 l2 := 1 fmt.Print(l1, " ", l2, " ") for i := 2; i < size; i++ { l2 = l1 + l2 l1 = l2 - l1 fmt.Print(l2, " ") } fmt.Println() } func main() { reader := bufio.NewReader(os.Stdin) fmt.Print("Enter the size of sequence (Number of values) for Lucas Series: ") input, _ := reader.ReadString('\n') input = strings.TrimSuffix(input, "\n") inputNum, err := strconv.Atoi(input) if err != nil { fmt.Println("Input is not valid, Please enter a valid number", input, err) return } fmt.Printf("The first %v numbers in Lucas Series are \n", inputNum) printLucasSeries(inputNum) } ================================================ FILE: Maths/Series/Lucas_Series/Lucas_Series.php ================================================ ================================================ FILE: Maths/Series/Lucas_Series/README.md ================================================ ## This folder is empty. ================================================ FILE: Maths/Series/Lucas_Series/lucas_series.cs ================================================ using System; class Program { static void Main(string[] args) { Console.WriteLine("How many Lucas numbers do you want to write out?"); int count = int.Parse(Console.ReadLine()); ulong first = 2; ulong second = 1; Console.WriteLine(first); Console.WriteLine(second); ulong number; for (int i = 0; i < count - 2; i++) { number = first + second; first = second; second = number; Console.WriteLine(number); } Console.ReadLine(); // otherwise the console closes } } ================================================ FILE: Maths/Series/Lucas_Series/lucas_series.py ================================================ def LucasSum(N): a = 2 b = 1 c = 0 print(a) while (b <= N): c = a + b print(c) a = b b = c # Driver code N = int(input()) LucasSum(N) ================================================ FILE: Maths/Series/Lucas_Series/lucas_series.ts ================================================ // This is required for console input var readline = require('readline'); var rl = readline.createInterface({ input: process.stdin, output: process.stdout }); rl.question("Number of terms to be found: ", function(answer) { let first = 2; let second = 1; let result; console.log(first); console.log(second); for (let i = 0; i < +answer - 2; i++) { result = first + second; console.log(result); first = second; second = result; } rl.close(); }); ================================================ FILE: Maths/Series/Modular_Exponentiation/Modular_Exponentiation.cpp ================================================ #include #include using namespace std; int main(){ int b, e, m; int power, res; cout<<"Enter the base value: "; cin>>b; cout<<"Enter the exponent value: "; cin>>e; cout<<"Enter the modulus value: "; cin>>m; power = pow(b,e); res = power % m; cout<<"The modular exponentiation value of given set of values is: "< Runtime - O(log (b)) --------------------------------------------------------------- NOTE : In python, pow() function implements this idea --------------------------------------------------------------- """ def modularExp(a, b, m): ''' Performs modular Exponentiation, that is a^b % m fast. @ Args: a - (int) mantissa / base b - (int) exponent m - (int) number with respect to which modulus is calculated @ Return: y - (int) the value of (a ^ b) % m ''' # Base Case - a == 0, return 0; b == 0, return 1 if a == 0: return 0 if b == 0: return 1 y = 0 # Final Value # If b is odd, then b & 1(bitwise AND) == 1, else 0 # We do not use b % 2 here as bitwise operations might be # faster for larger b value # b is odd if b & 1: y = a % m # Break as per step 1 above y = (y * modularExp(a, b - 1, m) % m) % m # Break as per step 2 above else: y = modularExp(a, b // 2, m) y = (y * y) % m # Break as per step 2 above # this is to ensure that y is not negative return ((y + m) % m) #------------------------------------------------------ if __name__ == "__main__": a, b, m = list(map(int, input("Enter a, b, m: ").split())) print(modularExp(a, b, m)) ================================================ FILE: Maths/Series/Modular_Exponentiation/README.md ================================================ # Modular Exponentiation Modular Exponentiation is useful for calculating (a ^ b) % m. This has applications in cryptography. This is a divide and conquer algorithm. #### Contributed by Sandip Dutta ================================================ FILE: Maths/Series/Modular_Exponentiation/modular_exponentiation.c ================================================ #include #include int main(){ int b, e, m; printf("Enter the base value: "); scanf("%d", &b); printf("Enter the exponent value: "); scanf("%d", &e); printf("Enter the modulus value: "); scanf("%d", &m); int power, res; power = pow(b,e); res = power%m; printf("The modular exponentiation of the given set of values is: %d",res); return 0; } ================================================ FILE: Maths/Series/Modular_Exponentiation/modular_exponentiation.cpp ================================================ #include #include using namespace std; int main(){ int b, e, m; int power, res; cout<<"Enter the base value: "; cin>>b; cout<<"Enter the exponent value: "; cin>>e; cout<<"Enter the modulus value: "; cin>>m; power = pow(b,e); res = power % m; cout<<"The modular exponentiation value of given set of values is: "< void main(){ int p,i,j; int remainder = 2; int divident,divisor; printf("Enter Number\n"); scanf("%d",&p); for(i = 2 ; i < p ; i++){ divident = p; divisor = i; while(divisor != 0){ remainder = divident % divisor; divident = divisor; divisor = remainder; } if(divident == 1){ printf("Relatively Prime Number is : %d \n" ,i); } } } /* Output: Enter Number 8 Relatively Prime Number is : 3 Relatively Prime Number is : 5 Relatively Prime Number is : 7 */ ================================================ FILE: Maths/Series/Relative_Primes/RelativePrimes.java ================================================ public class relativelyPrime { static int gcd(int a, int b) { if (b == 0) return a; return gcd(b, a % b); } private static boolean relativelyPrime(int a, int b) { return gcd(a,b) == 1; } public static void main(String[] args) { int n = 10,m = 9; System.out.println(n+" and "+ m+" is relative Prime "+relativelyPrime(n, m)); } } ================================================ FILE: Maths/Series/Relative_Primes/RelativePrimes.php ================================================ $int2) return gcd($int1 - $int2, $int2); return gcd($int1, $int2 - $int1); } // check if they are both relatively prime or not function isRelativelyPrime($int1, $int2) { $result = gcd($int1, $int2) == 1 ? "is relatively prime \n": "is not relatively prime \n"; return $result; } echo isRelativelyPrime(4, 9); echo isRelativelyPrime(6, 8); ================================================ FILE: Maths/Series/Relative_Primes/RelativePrimes.py ================================================ def gcd(num1, num2): if num2 == 0: return num1 return gcd(num2, num1 % num2) def is_relative_prime(num1, num2): if gcd(num1, num2) == 1: return True return False number = int(input("Enter a number: ")) print("Numbers that are relatively prime to ", number," are:") for i in range(2, number): if is_relative_prime(number, i): print(i) """ Example: Enter a number: 9 Numbers that are relatively prime to 9 are: 2 4 5 7 8 """ ================================================ FILE: Maths/Series/Relative_Primes/Relative_Prime.cpp ================================================ #include// this includes all the predefined libraries required in the program; using namespace std; int main() { int num1,num2; //The value of two numbers is being entered below cin>>num1; cin>>num2; //we will use the _gcd function to find the gcd or hcf of the numbers that have been entered. int hcf; hcf=__gcd(num1,num2); if(hcf==1) cout<<"The numbers are relatively prime"; else cout<<"The numbers are not relatively prime"; return 0; } ================================================ FILE: Maths/Series/Relative_Primes/Relative_Primes.go ================================================ package main import ( "fmt" "math/big" ) func main() { num1 := big.NewInt(0) num2 := big.NewInt(0) greatest := big.NewInt(0) fmt.Scanln(num1) fmt.Scanln(num2) greatest.GCD(nil, nil, num1, num2) if greatest.Int64() == 1 { fmt.Println("The numbers are relatively prime") } else { fmt.Println("The numbers are not relatively prime") } } ================================================ FILE: Maths/Series/Sum_of_AP/Sum_Of_AP.CPP ================================================ #include #include // Function to check whether given sequence is in AP or not // The common differences for the sequence is calculated and checked int is_ap(int ap[],int terms,int common_difference[]) { int index=0; // Looping through elements to get the common differences between them in given sequence while(index<(terms-1)) { // Storing current common difference by substracting prev number from next number common_difference[index]=ap[index+1]-ap[index]; // If the index is not zero and if current commmon difference // is not equal to previous common difference then sequence is not in AP if ((index!=0) && (common_difference[index] != common_difference[index-1])) break; index += 1; } // If loop runs upto index becoming terms-1 then sequence in AP // as all common difference are same, hence returning 1 if(index==(terms-1)) return 1; // otherwise returning -1 else return -1; } // Function to calculate sum if number of terms is even int evensum_ap(int ap[], int terms, int common_difference[]) { int sum; // Implementing the formula for sum of AP with even no of terms = (n/2)*(2*a +(n-1)*d) sum = (terms / 2) * ((2 * ap[0]) + ((terms - 1) * common_difference[0])); return sum; } // Function to calculate sum if number of terms is odd int oddsum_ap(int ap[], int terms, int common_difference[]) { int sum; // Implementing the formula for sum of AP with odd no of terms = n*(a+((n-1)/2)*d) sum = terms*(ap[0]+((terms-1)/2)*common_difference[0]); return sum; } // Driver Code void main() { clrscr(); int terms; // Taking input for no of terms cout<<"Enter the no of terms :"<>terms; // Initialising the two arrays for sequence and common difference int ap[100], common_difference[100]; // Taking input for terms in sequence cout<<"Enter the terms of sequence :"<>ap[i]; // If sequence not in AP, print message for the same if(is_ap(ap,terms,common_difference)==-1) cout<<"Sequence is not an AP."< float AP( float a, float d, int n){ return ( ( n / 2)*( ( 2 * a ) + ( ( n - 1 )* d ) ) ); } int main(){ float d = 0, a = 0, result = 0; int n = 0; printf("Enter the First Term [a], Common Difference[d], Number of Terms[n] of an Arithmetic Series :"); scanf("%f%f%d", &a, &d, &n ); result = AP( a, d, n); printf("The sum of the Series : %0.2f\n", result); return 0; } ================================================ FILE: Maths/Series/Sum_of_AP/Sum_of_AP.go ================================================ /* This code takes input a, d & n and computes sum of Arithmetic Progression . Language : Golang Author : Pulkit Sapra */ package main //Package fmt implements formatted I/O with functions analogous to C's printf and scanf. import ( "fmt" ) // Function to compute AP : Return Type : float64 func sum_of_AP(a float64, d float64, n float64) float64{ return ((n/2)*(2*a + (n-1)*d)) } // Main Function func main() { fmt.Println("Please enter initial element(a) ,common difference(d) and n") // Declaring variables and their types. var a,d,n float64 // Taking input for a,d & n fmt.Scan(&a) fmt.Scan(&d) fmt.Scan(&n) //Function call ans := sum_of_AP(a,d,n) fmt.Println(ans) } ================================================ FILE: Maths/Series/Sum_of_AP/Sum_of_AP.js ================================================ /* Arithmetic progression if a sequence of number has same common difference. Here a is first term of series d is common difference n is number of terms */ const readline = require('readline') const rl = readline.createInterface({ input: process.stdin, output: process.stdout }) const inputParams = () => new Promise(resolve => rl.question('\nEnter first term (a)\n> ', a => rl.question('Enter common difference (d)\n> ', d => rl.question('Enter the number of elements (n) \n> ', n => { a = parseInt(a) d = parseInt(d) n = parseInt(n) rl.close() resolve({ a, d, n }) }) ) ) ) const sumOfAP = (a, d, n) => { let sum = 0; let i = 0; while (i < n) { sum += a; a += d; i++; } return sum; } inputParams() .then(({ a, d, n }) => { console.log(`\nSum of arithmetic progression: \ ${sumOfAP(a, d, n)}`) }) /* For testin purpose let a = 1; let d = 1.5; let n = 10; console.log(sumOfAP(a, d, n)); */ ================================================ FILE: Maths/Series/Sum_of_AP/Sum_of_AP_JAVA/SumOfAP.ctxt ================================================ #BlueJ class context comment0.target=SumOfAP comment1.params=a\ d\ n comment1.target=float\ sumOfAP(float,\ float,\ int) comment2.params=args comment2.target=void\ main(java.lang.String[]) numComments=3 ================================================ FILE: Maths/Series/Sum_of_AP/Sum_of_AP_JAVA/Sum_of_AP.java ================================================ // JAVA Program to find the sum of AP Series import java.util.Scanner; class SumOfAP{ // Function to find sum of AP. static float sumOfAP(float a, float d, int n) { float sum = 0; for (int i = 0; i < n; i++) { sum = sum + a; a = a + d; } return sum; } // Driver function public static void main(String args[]) { Scanner sc= new Scanner(System.in); System.out.println("Enter the number of elements in the series:"); int n=sc.nextInt(); System.out.println("Enter the first element of the series:"); float a =sc.nextFloat(); System.out.println("Enter the common difference of the elements in the series:"); float d =sc.nextFloat(); System.out.println(sumOfAP(a, d, n)); } } ================================================ FILE: Maths/Series/Sum_of_GP/README.md ================================================ ## This folder is empty. ================================================ FILE: Maths/Series/Sum_of_GP/Sum_Of_GP.c ================================================ /*** Guidelines to run this code: ->Ensure you have latest version of c compiler ->Compile and Run either through User Interface or Command Line. Example for gcc compiler, gcc Sum_Of_GP.c ./a.out(for Linux) or a(for Windows) ***/ /*** About the approach: ->Formula used: a(r^n - 1)/(r - 1) . a is first term . r is common ratio . n is number of terms of the geometric sequence ->some values of common ratio are handled differently ->Time Complexity: O(n) where n is number of terms in the geometric sequence ->Space Complexity: O(1) ->It is considered that a,r and n are given by the user and sum is within double datatype limits ***/ #include /* arguments: base value and the exponent term returns: result obtained by calculating the power of the base raised to the exponent term given */ double power(double base,double exponent) { double result = 1.0; for(int i = 1;i <= exponent;i++) { result *= base; } return result; } int main() { double first_term; double common_ratio; double num_terms; //take the first term as input from the user printf("Enter the first term of the GP Sequence:"); scanf("%lf",&first_term); //take the common ratio as input from the user printf("Enter the common ratio of the GP Sequence:"); scanf("%lf",&common_ratio); //take the number of terms as input from the user printf("Enter the number of terms in the GP Sequence:"); scanf("%lf",&num_terms); //wrong case:number_of_terms is negative if(num_terms < 0) { printf("Sum of the given Geometric Sequence is not possible due to negative number of terms\n"); } //case 1:common_ratio is zero,hence the general formula fails as 0/0 is encountered else if(common_ratio == 0) { printf("Sum of the given Geometric Sequence is %lf\n",first_term); } //case 2:common_ratio is one,hence again the general formula fails as 0/0 is encountered else if(common_ratio == 1) { printf("Sum of the given Geometric Sequence is %lf\n",first_term * num_terms); } //case 3:other values else { double result = (first_term * (power(common_ratio,num_terms) - 1)) / (common_ratio - 1); printf("Sum of the given Geometric Sequence is %lf\n",result); } return 0; } ================================================ FILE: Maths/Series/Sum_of_GP/Sum_Of_GP.cpp ================================================ #include #include using namespace std; int main() { float A,R; int N; A=1; R=2; N=5; float Sum=A*(pow(R,N)-1)/(R-1); cout< -1 && commonRatio < 1) { System.out.println("Geometric progression sum to infinity is: " + sumGPToInfinity(firstTerm, commonRatio)); } else { System.out.println("Common ratio for sum to infinity should be between -1 and 1"); return; } } else { System.out.println("Geometric Progression sum is: " + sumGP(firstTerm, commonRatio, numberOfTerms)); } } } ================================================ FILE: Maths/Series/Sum_of_GP/Sum_of_GP.py ================================================ """A geometric progression, also known as a geometric sequence, is a sequence of numbers where each term after the first is found by multiplying the previous one by a fixed, non-zero number called the common ratio. a, a*r, a*r*r,.... forms a GP. where a is the first element and r is the common ratio. Sum of GP is given by a*(r^n - 1)/(r - 1) where n is the number of terms.""" def sumOfGP(a,r,n): return a*(pow(r,n)-1)/(r-1) a = 2 r = 2 n = 15 print(sumOfGP(a,r,n)) ================================================ FILE: Maths/Series/Sum_of_HP/HP_sum.py ================================================ def HP(a,d,n): sum=0 curr_term=a for i in range(1,n+1): temp=a+(i-1)*d sum+=(round((1/temp),5)) print(sum) a = 2 d = 1 n = 5 HP(a, d, n) ================================================ FILE: Maths/Series/Sum_of_HP/Sum_of_HP.cpp ================================================ Harmonic progression is a series whose inverse will be an arithmetic progression. i.e. if for a harmonic progression A1, A2, A3.. An, there is an arithmetic progression 1/A1, 1/A2, 1/A3. So, a general HP is : 1/a, 1/(a+d), 1/(a+2d), … 1/(a + nd),where 1/a is the first term and d is the common difference of the reversed AP. Input:a = 3, d = 2, n = 5 Output:The sum of HP is 0.878211 Execution:Sum = ⅓ + ⅕ + 1/7 + 1/9 + 1/11 = 0.878211 Code: #include using namespace std; float findSeriesSum(int a, int d, int n){ float sumVal = 0; float term = 0; for(float i = 1; i <= n; i++){ term = (1.0)/(float)(a + (i-1)*d); sumVal += term; } return sumVal; } int main(){ int n, a, d ; cin>>n>>a>>d; cout<<"The sum of HP is "<No particular formula used . 1/a is reciprocal of first term . d is common difference for reciprocal . n is number of terms of the harmonic sequence ->sum of all terms is found generating each term and adding them ->Time Complexity: O(n) where n is number of terms in the Harmonic sequence ->Space Complexity: O(1) ->It is considered that a,d and n are given by the user and sum is within double datatype limits ***/ using System.IO; using System; class Program { static void Main() { Console.WriteLine("Enter the reciprocal of first term in the Harmonic Sequence:"); double firstTerm = Convert.ToDouble(Console.ReadLine()); Console.WriteLine("Enter the common difference of reciprocal of terms in the Harmonic Sequence:"); double commonDiff = Convert.ToDouble(Console.ReadLine()); Console.WriteLine("Enter the number of terms in the Harmonic Sequence:"); int numTerms = Convert.ToInt32(Console.ReadLine()); double term = 1.0 / (firstTerm * 1.0); double sum = 0; if(firstTerm == 0 || numTerms < 0) { Console.WriteLine("Not possible to find sum of terms in the Harmonic Sequence for the given input"); return; } for(int i = 1;i <= numTerms;i++) { sum += term; //1.0 is multiplied in denominator to ensure it doesn't get implicitly converted to int term = 1.0 / (firstTerm + (i * commonDiff)) * 1.0 ; } Console.WriteLine("The sum of terms in the Harmonic Sequence are :" + sum); } } ================================================ FILE: Maths/Series/Sum_of_HP/hpSum.js ================================================ const readline = require('readline') const rl = readline.createInterface({ input: process.stdin, output: process.stdout }) // Basic implementation const hpSum = (a, d, n) => { let sum = 0; for (let i = 0; i < n; i++) { sum += 1 / (a + i * d) } return sum } // Recursive implementation const hpSumRecursive = (a, d, limit, sum = 0) => limit > 0 ? hpSumRecursive(a, d, limit - 1, sum + 1 / (a + (limit - 1) * d)) : sum const askQuestions = () => new Promise(resolve => rl.question('\nEnter a\n> ', a => rl.question('Enter d\n> ', d => rl.question('Enter the number of elements\n> ', n => { a = parseInt(a) d = parseInt(d) n = parseInt(n) rl.close() resolve({ a, d, n }) }) ) ) ) askQuestions() .then(({ a, d, n }) => { console.log(`\nA sum of a harmonic progression (basic alg) is \ ${hpSum(a, d, n)}`) console.log(`A sum of a harmonic progression (recursive alg) is \ ${hpSum(a, d, n)}\n`) }) ================================================ FILE: Maths/Series/Sum_of_N/Sum_of_n.c ================================================ /* Method:- Sum of first N natural number = (2 * N) * (N + 1); */ // C Program to find sum // of first n natural numbers #include int main() { // declaring the variables // where n is indicating the natural number // and S the sum of natural number int n,S; // taking input n from user scanf("%d",&n); // Calculating the sum // by Arithmetic Progression formula S = (2*n)*(n+1); // display the sum printf("%d",S); } ================================================ FILE: Maths/Series/Sum_of_N/sumOfNNumbers.sh ================================================ echo -n "Enter number : " read n # store single digit i=1 # store number of digit sum=0 # use while loop to caclulate the sum of all digits while [ $i -le $n ] do sum=$(( $sum + $i )) # calculate sum of digit i=$(( $i + 1 )) done echo "Sum of all digit is $sum" ================================================ FILE: Maths/Series/Sum_of_N/sum_of_n_natural_no.cpp ================================================ // Program to find sum of n natural numbers #include using namespace std; int main() { int n, sum, a=1; cout << "Enter number of terms: "; cin >> n; sum = (n*(n+a))/2; cout << "The sum of first " << n << " natural numbers are: " << sum << endl; return 0; } ================================================ FILE: Maths/Series/Sum_of_N/sum_of_n_natural_numbers.go ================================================ package main import ( "fmt" ) // Calculate the sum of N natural numbers // using the arithmetic progression formula Sn = n/2 * (2*a + (n-1)d) // Where: // n: numbers of terms // a: first term // d: common difference // for natural numbers the formula becomes: n/2 * (n+1) func sumNNaturalNumbers(terms uint) uint { return (terms * (terms + 1))/2; } func main() { var numberOfTerms uint; var sum uint; // Get user input fmt.Printf("Enter the number of terms: "); _, err := fmt.Scanf("%d", &numberOfTerms); // make sure the input is/contains a number if err != nil { fmt.Println("Invalid input !"); return; } // Calculate and display the sum sum = sumNNaturalNumbers(numberOfTerms); fmt.Println("The sum of the first", numberOfTerms, "natural number(s) is:", sum); } ================================================ FILE: Maths/Series/Sum_of_N/sumn.py ================================================ def sumn(n): s=(n*(n+1))/2 # finds the sum of first n natural numbers return s n=int(input()) # inputs th limit print(sumn(n)) ================================================ FILE: Maths/Series/Sum_of_N/sumofNnaturalnums.cs ================================================ using System; public class Exercise3 { public static void Main() { int i,n,sum=0; Console.Write("\n\n"); Console.Write("Input Value of terms : "); n= Convert.ToInt32(Console.ReadLine()); for(i=1;i<=n;i++) { sum+=i; } Console.Write("\nThe Sum of Natural Number upto {0} terms : {1} \n",n,sum); } } ================================================ FILE: Maths/Series/Sum_of_N/sumofNnaturalnums.py ================================================ # Sum of n natural Number in python3 .. try: n=int(input("Enter the Nth term upto which you want to calculate the sum: ")) a=1 d=1 ans = (n/2)*(2*a + (n-1)*d) print(ans) except ValueError: print("Please enter a valid integer with base 10.") ================================================ FILE: Maths/Series/Sum_of_N2/SumOf_n^2.C++ ================================================ /*Method:- Sum of square of first N natural number = (N * (N + 1) * (2*N + 1)) / 6; exmple:- For N =4, Sum = (4 * (4 + 1) * (2 * 4 + 1)) /6; = (4*5*9)/6 =180/6 = 30 For N =5, Sum = (5 * (5 + 1) * (2 * 5 + 1)) /6; = (5*6*11)/6 = 55 */ // CPP Program to find sum // of square of first n // natural numbers #include using namespace std; // Return the sum of square of // first n natural numbers int squaresum(int n) { return (n * (n + 1) * (2 * n + 1)) / 6; } // Driven Program int main() { int n = 4; cout << squaresum(n) << endl; return 0; } /*Output: 30 */ ================================================ FILE: Maths/Series/Sum_of_N2/Sum_Of_n^2.py ================================================ '''Python3 Program to find sum of square of first n natural numbers Return the sum of square of first n natural numbers. ''' def squaresum(n) : return (n * (n + 1) * (2 * n + 1)) // 6 ''' Avoiding early overflow: For large n,it would overflow. We can avoid overflow using n*(n+1) must be divisible by 2. return (n * (n + 1) / 2) * (2 * n + 1) / 3 use above code while large numbers ''' # Driven Program n =int (input("Enter the number:::")) print(squaresum(n)) #This code is contributed by Himik Nainwal ================================================ FILE: Maths/Series/Sum_of_N2/Sum_of_n^2.swift ================================================ /*Swift Implementation for sum of n^2*/ // func squaresum(input: Int) -> Int { return (input * (input + 1) * (2 * input + 1)) / 6; } ================================================ FILE: Maths/Series/Sum_of_N2/square_sum.cs ================================================ using System; class GFG { public static int squaresum(int n) { return (n * (n + 1) * (2 * n + 1)) / 6; } public static void Main() { int n = 10; Console.WriteLine(squaresum(n)); } } ================================================ FILE: Maths/Series/Sum_of_N2/sumOfNSquare.js ================================================ // Take Input from user var nTerm = parseInt( prompt( "Enter the nth term upto which you want to calculate the sum of n sqaure " ) ); // Get the Sum of n square var value = () => { return (nTerm * (nTerm + 1) * (2 * nTerm + 1)) / 6; }; // Print it console.log(value()); ================================================ FILE: Maths/Series/Sum_of_N2/sumOfn_squared.py ================================================ # Taking Input from the user n = int(input()) # Sum of n squared natural numbers using the formula - Σn2 = [n(n+1)(2n+1)]/6 print((n*(n+1)*(2*n+1))/6) ================================================ FILE: Maths/Series/Sum_of_N2/sumofnsqaure.php ================================================ ================================================ FILE: Maths/Series/Sum_of_N3/Sum of n3.cpp ================================================ /*Sum of n³*/ #include #include using namespace std; int main() { int n; cin >> n; // Input /*We have a mathematical formula according to which sum of cubes of first n natural numbers is given by ((n*(n+1))/2)*((n*(n+1))/2)*/ int ans = ((n*(n+1))/2)*((n*(n+1))/2); cout << ans << endl; // output return 0; } ================================================ FILE: Maths/Series/Sum_of_N3/sum of n^3.cpp ================================================ // Efficient CPP program to find sum of cubes // of first n natural numbers that avoids // overflow if result is going to be withing // limits. #include using namespace std; // Returns sum of first n natural // numbers int sumOfSeries(int n) { int x; if (n % 2 == 0) x = (n/2) * (n+1); else x = ((n + 1) / 2) * n; return x * x; } // Driver code int main() { int n; cout<<"Enter a number"<>n; cout << sumOfSeries(n); return 0; } ================================================ FILE: Maths/Series/Sum_of_N3/sumofncube.php ================================================ ================================================ FILE: Maths/Statistics/Compound_Interest/Compound_Interest.c ================================================ #include #include int main(){ double principle, rate, timeSpan; printf("Enter the principle amount\n"); scanf(" %lf", &principle); printf("Enter the compound rate of interest\n"); scanf(" %lf", &rate); printf("Enter the time span or number of times the amount gets compounded\n"); scanf(" %lf", &timeSpan); /* Calculate compound interest */ /*Formula to calculate final amount after applying compound interest is given by: FinalAmount = (principle)*((1 + (rate)/100)^(timeSpan))*/ double FinalAmount = principle * (pow((1 + rate / 100), timeSpan)); printf("Final amount after applying Compound interest = %lf\n", FinalAmount); return 0; } ================================================ FILE: Maths/Statistics/Compound_Interest/Compound_Interest.cpp ================================================ // Compound Interest C.I. = P(1+R/100)^t #include using namespace std; // helper function double compoundInterest(double p, double r, double t) { return p * pow( (1 + r/100), t ); } // driver function int main() { // variables are self-explanatory double principle; double rate; double time; cout<<"Enter the principle \n"; cin>>principle; cout<<"Enter the rate\n"; cin>>rate; cout<<"Enter the time"; cin>>time; cout<<"The compound interest is: "< /// Calculates the compound interest for the given values. /// private static double CalculateCompoundInterest(double initialAmount, double interestRate, int totalYears, int compundFrequency) { return (initialAmount * Math.Pow((1 + (interestRate / compundFrequency)), (compundFrequency * totalYears))); } ///

/// Main application function. /// static void Main() { double initialAmount, interestRate; int totalYears, compundFrequency; string userInput; Console.WriteLine("Enter the initial amount:"); userInput = Console.ReadLine(); if ((double.TryParse(userInput, out initialAmount) == false)) { Program.ExitAfterInvalidInput(); } Console.WriteLine("Enter the annual interest rate:"); userInput = Console.ReadLine(); if ((double.TryParse(userInput, out interestRate) == false)) { Program.ExitAfterInvalidInput(); } Console.WriteLine("Enter the number of years:"); userInput = Console.ReadLine(); if ((int.TryParse(userInput, out totalYears) == false)) { Program.ExitAfterInvalidInput(); } Console.WriteLine("Enter the times per year that interest will be compounded:"); userInput = Console.ReadLine(); if ((int.TryParse(userInput, out compundFrequency) == false)) { Program.ExitAfterInvalidInput(); } double totalAmount = Program.CalculateCompoundInterest(initialAmount, interestRate, totalYears, compundFrequency); string yearText = (totalYears > 1 ? "years" : "year"); Console.WriteLine(); Console.WriteLine(string.Format("In {0} {1} the total amount will be {2:#0.000}.", totalYears, yearText, totalAmount)); } /// /// Informs the user that an invalid value has been entered and exits the program. /// private static void ExitAfterInvalidInput() { Console.WriteLine("You've entered an invalid value. Exiting..."); Environment.Exit(1); } } ================================================ FILE: Maths/Statistics/Compound_Interest/Compound_Interest.html ================================================ Calculating Compound Interest using JavaScript

Calculate Compound Interest

================================================ FILE: Maths/Statistics/Compound_Interest/Compound_Interest.java ================================================ //Calculating Compound Interest import java.util.*; class Solution { //function to calculate compound interest double compound_interest(double principle,double rate,double time){ return principle * Math.pow((1 + rate/100), time); } } public class Compound_Interest { //main class public static void main(String[] args) { Scanner scanner = new Scanner(System.in); Solution object = new Solution(); double principle,rate,time; System.out.println("Enter the principle "); principle = scanner.nextFloat(); System.out.println("Enter the rate "); rate = scanner.nextFloat(); System.out.println("Enter the time period "); time = scanner.nextFloat(); System.out.println("The compound interest is: "+object.compound_interest(principle, rate, time)); } } ================================================ FILE: Maths/Statistics/Compound_Interest/Compound_Interest.js ================================================ var principle = 1000; var time = 2; var rate = 5; var ci = principle * Math.pow( (1 + rate/100), time); console.log("Compound Interest is: " + ci) ================================================ FILE: Maths/Statistics/Compound_Interest/Compound_Interest.py ================================================ # Python3 program to find compound # interest for given values. def compound_interest(principle, rate, time): # Calculates compound interest Amount = principle * (pow((1 + rate / 100), time)) CI = Amount - principle print("Compound interest is", CI) # Driver Code p = float(input("Enter principle amount: ")) r = float(input("Enter rate: ")) t = float(input("Enter time: ")) compound_interest(p, r, t) ================================================ FILE: Maths/Statistics/Compound_Interest/Compound_Interest.rb ================================================ #!/usr/bin/env ruby def calculateCompoundInterest(principle, rate, time) result = principle * ((1 + rate / 100) ** time) end puts "Enter your principle value:" principle = gets.to_f.round(2) puts "Enter your rate value:" rate = gets.to_f.round(2) puts "Enter your time value:" time = gets.to_i puts "Your compound interest is #{calculateCompoundInterest(principle, rate, time)}" ================================================ FILE: Maths/Statistics/Compound_Interest/Compound_Interest.ts ================================================ /* A TypeScript program to return Compound Interest Parameters: principal amount time interest rate number of times to compound per time period, all numbers Returns; compound interest, a number */ let compoundInterest = function (principal: number, time : number, rate : number, n: number) : number { return principal * (Math.pow((1 + (rate / n)), (n * time))); } //Test console.log(compoundInterest(1000, 2, 0.05, 1)); ================================================ FILE: Maths/Statistics/Confidence_Interval/Confidence_Interval.cpp ================================================ #include #include #include /** calculate the normal quantile (which is the inverse normal CDF, here calculated by Acklam's algorithm, according to https://stackedboxes.org/2017/05/01/acklams-normal-quantile-function/) * @param p probability * @return the p-quantile of the standard normal distribution */ double normalQuantile(const double p) { assert(0 <= p && p <= 1); double result = 0; if (p == 0) result = -INFINITY; else if (p == 1) result = INFINITY; else { const double a[] = { -3.969683028665376e+01, 2.209460984245205e+02, -2.759285104469687e+02, 1.383577518672690e+02, -3.066479806614716e+01, 2.506628277459239e+00 }; const double b[] = { -5.447609879822406e+01, 1.615858368580409e+02, -1.556989798598866e+02, 6.680131188771972e+01, -1.328068155288572e+01 }; const double c[] = { -7.784894002430293e-03, -3.223964580411365e-01, -2.400758277161838e+00, -2.549732539343734e+00, 4.374664141464968e+00, 2.938163982698783e+00 }; const double d[] = { 7.784695709041462e-03, 3.224671290700398e-01, 2.445134137142996e+00, 3.754408661907416e+00 }; const double p_low = 0.02425; const double p_high = 1 - p_low; if (p < p_low) // approximation for lower region { const double q = sqrt(-2*log(p)); result = (((((c[0]*q+c[1])*q+c[2])*q+c[3])*q+c[4])*q+c[5]) / ((((d[0]*q+d[1])*q+d[2])*q+d[3])*q+1); } else if (p_high < p) // approximation for upper region { const double q = sqrt(-2*log(1-p)); result = -(((((c[0]*q+c[1])*q+c[2])*q+c[3])*q+c[4])*q+c[5]) / ((((d[0]*q+d[1])*q+d[2])*q+d[3])*q+1); } else // approximation for central region { const double q = p - 0.5; const double r = q*q; result = (((((a[0]*r+a[1])*r+a[2])*r+a[3])*r+a[4])*r+a[5])*q / (((((b[0]*r+b[1])*r+b[2])*r+b[3])*r+b[4])*r+1); } } return result; } /** calculate the confidence interval * @param estimator estimator of which the CI should be calculated * @param standardError the estimator's standard error * @param confidenceLevel confidence level of the CI * @return the (confidenceLevel*100)% CI */ std::array confidence_interval(const double estimator, const double standardError, const double confidenceLevel) { assert(0 < confidenceLevel && confidenceLevel < 1); const double errorLevel = 1 - confidenceLevel; double lower = 0; double upper = 0; const double error = normalQuantile(1 - errorLevel/2.0) * standardError; lower = estimator - error; upper = estimator + error; std::array confidenceInterval{lower, upper}; return confidenceInterval; } // Test section: #include #include #include #include using namespace std; int main() { const double confidenceLevel = 0.99; const size_t sampleSize = 10000; vector sample(sampleSize); double sampleMean = 0; double sampleVariance = 0; // generate random sample of size sampleSize { default_random_engine generator; normal_distribution distribution(0.0,1.0); for(size_t i = 0; i < sampleSize; ++i) sample[i] = distribution(generator); } // calculate mean for (size_t i = 0; i < sampleSize; ++i) sampleMean += sample[i]; sampleMean /= sampleSize; // calculate variance for (size_t i = 0; i < sampleSize; ++i) sampleVariance += (sample[i] - sampleMean)*(sample[i] - sampleMean); sampleVariance /= sampleSize-1; // our estimator is the sample mean, whose standard deviation is given by const double estimatorStandardDeviation = sqrt(sampleVariance/sampleSize); auto confidenceInterval = confidence_interval(sampleMean, estimatorStandardDeviation, confidenceLevel); cout << "The random sample of " << sampleSize << " standard normal points yields the following estimator for the mean:" << endl << " estimator: " << sampleMean << endl << " " << setprecision(2) << confidenceLevel*100 << "% confidence interval: (" << setprecision(6) << confidenceInterval[0] << ", " << confidenceInterval[1] << ")" << endl; return 0; } ================================================ FILE: Maths/Statistics/Confidence_Interval/Confidence_Inverval.c ================================================ #include #include #include /** calculate the normal quantile (which is the inverse normal CDF, here calculated by Acklam's algorithm, according to https://stackedboxes.org/2017/05/01/acklams-normal-quantile-function/) * @param p probability * @return the p-quantile of the standard normal distribution */ double normalQuantile(const double p) { assert(0 <= p && p <= 1); double result = 0; if (p == 0) result = -INFINITY; else if (p == 1) result = INFINITY; else { const double a[] = { -3.969683028665376e+01, 2.209460984245205e+02, -2.759285104469687e+02, 1.383577518672690e+02, -3.066479806614716e+01, 2.506628277459239e+00 }; const double b[] = { -5.447609879822406e+01, 1.615858368580409e+02, -1.556989798598866e+02, 6.680131188771972e+01, -1.328068155288572e+01 }; const double c[] = { -7.784894002430293e-03, -3.223964580411365e-01, -2.400758277161838e+00, -2.549732539343734e+00, 4.374664141464968e+00, 2.938163982698783e+00 }; const double d[] = { 7.784695709041462e-03, 3.224671290700398e-01, 2.445134137142996e+00, 3.754408661907416e+00 }; const double p_low = 0.02425; const double p_high = 1 - p_low; if (p < p_low) // approximation for lower region { const double q = sqrt(-2*log(p)); result = (((((c[0]*q+c[1])*q+c[2])*q+c[3])*q+c[4])*q+c[5]) / ((((d[0]*q+d[1])*q+d[2])*q+d[3])*q+1); } else if (p_high < p) // approximation for upper region { const double q = sqrt(-2*log(1-p)); result = -(((((c[0]*q+c[1])*q+c[2])*q+c[3])*q+c[4])*q+c[5]) / ((((d[0]*q+d[1])*q+d[2])*q+d[3])*q+1); } else // approximation for central region { const double q = p - 0.5; const double r = q*q; result = (((((a[0]*r+a[1])*r+a[2])*r+a[3])*r+a[4])*r+a[5])*q / (((((b[0]*r+b[1])*r+b[2])*r+b[3])*r+b[4])*r+1); } } return result; } /** calculate the confidence interval * @param[in] estimator estimator of which the CI should be calculated * @param[in] standardError the estimator's standard error * @param[in] confidenceLevel confidence level of the CI * @param[out] confidenceInterval expected to be an array of 2 doubles, in which the lower and upper bounds of the (confidenceLevel*100)% CI are saved */ void confidence_interval(const double estimator, const double standardError, const double confidenceLevel, double confidenceInterval[]) { assert(0 < confidenceLevel && confidenceLevel < 1); const double errorLevel = 1 - confidenceLevel; double lower = 0; double upper = 0; const double error = normalQuantile(1 - errorLevel/2.0) * standardError; lower = estimator - error; upper = estimator + error; confidenceInterval[0] = lower; confidenceInterval[1] = upper; return; } /* Test section */ #include int main(void) { const double confidenceLevel = 0.99; double confidenceInterval[2]; const size_t sampleSize = 10000; double sample[sampleSize]; double sampleMean = 0; double sampleVariance = 0; // generate random sample of size sampleSize srand(0); for(size_t i = 0; i < sampleSize; ++i) { double uniformRandom = rand()/((double)RAND_MAX); sample[i] = normalQuantile(uniformRandom); } // calculate mean for (size_t i = 0; i < sampleSize; ++i) sampleMean += sample[i]; sampleMean /= sampleSize; // calculate variance for (size_t i = 0; i < sampleSize; ++i) sampleVariance += (sample[i] - sampleMean)*(sample[i] - sampleMean); sampleVariance /= sampleSize-1; // our estimator is the sample mean, whose standard deviation is given by const double estimatorStandardDeviation = sqrt(sampleVariance/sampleSize); confidence_interval(sampleMean, estimatorStandardDeviation, confidenceLevel, confidenceInterval); printf("The random sample of %zu standard normal points yields the following estimator for the mean:\n", sampleSize); printf(" estimator: %f\n", sampleMean); printf(" %2.1f %% confidence interval: (%f, %f)\n", confidenceLevel*100, confidenceInterval[0], confidenceInterval[1]); return EXIT_SUCCESS; } ================================================ FILE: Maths/Statistics/Confidence_Interval/README.md ================================================ ## This folder is empty. ================================================ FILE: Maths/Statistics/Confidence_Interval/confidenceInterval.js ================================================ // calculate 95 percentile confidence interval const hypothesis = Math.random() * 100; // get a random number in range [0, 100) const data = [] for (let i = 0; i < 1000; i++) { data.push(Math.random() * 200) // sample a dataset in range [0, 200) } const mean = data.reduce ((accumulator, currentValue) => { return accumulator + currentValue }, 0) / data.length const standardDeviation = Math.sqrt ( data.reduce((accumulator, nextElement) => accumulator + (nextElement - mean) , 0) / data.length ) const percentile = 0.95 function percentile_z(p) { if (p > 0.5) return -1 const a0 = 2.5066282; const a1 = -18.6150006; const a2 = 41.3911977; const a3 = -25.4410605; const b1 = -8.4735109; const b2 = 23.0833674; const b3 = -21.0622410; const b4 = 3.1308291; const c0 = -2.7871893; const c1 = -2.2979648; const c2 = 4.8501413; const c3 = 2.3212128; const d1 = 3.5438892; const d2 = 1.6370678 let r; let z; if (p > 0.42) { r = Math.sqrt(-Math.log(0.5-p)); z = (((c3*r+c2)*r+c1)*r+c0)/((d2*r+d1)*r+1); } else { r = p*p; z = p*(((a3*r+a2)*r+a1)*r+a0)/((((b4*r+b3)*r+b2)*r+b1)*r+1); } return z; } const confLo = mean - (percentile_z (percentile) * standardDeviation / Math.sqrt(data.length)) const confHi = mean + (percentile_z (percentile) * standardDeviation / Math.sqrt(data.length)) console.log(confLo, confHi) ================================================ FILE: Maths/Statistics/Confidence_Interval/confidence_interval.py ================================================ # bootstrap confidence intervals from numpy.random import seed from numpy.random import rand from numpy.random import randint from numpy import mean from numpy import median from numpy import percentile # seed the random number generator seed(1) # generate dataset dataset = 0.5 + rand(1000) * 0.5 # bootstrap scores = list() for _ in range(100): # bootstrap sample indices = randint(0, 1000, 1000) sample = dataset[indices] # calculate and store statistic statistic = mean(sample) scores.append(statistic) print('50th percentile (median) = %.3f' % median(scores)) # calculate 95% confidence intervals (100 - alpha) alpha = 5.0 # calculate lower percentile (e.g. 2.5) lower_p = alpha / 2.0 # retrieve observation at lower percentile lower = max(0.0, percentile(scores, lower_p)) print('%.1fth percentile = %.3f' % (lower_p, lower)) # calculate upper percentile (e.g. 97.5) upper_p = (100 - alpha) + (alpha / 2.0) # retrieve observation at upper percentile upper = min(1.0, percentile(scores, upper_p)) print('%.1fth percentile = %.3f' % (upper_p, upper)) ================================================ FILE: Maths/Statistics/Exponential_Smoothing/Exponential_Smoothing.cpp ================================================ ////////////////////////////////////////////////////////////////////////// /** * C++ implementation of Exponential Smoothing * * * * * * ////////////////////////////////////////////////////////////////////////// #ifndef HEADER_EXPONENTIAL_SMOOTHING_H #define HEADER_EXPONENTIAL_SMOOTHING_H #include #include #include /** Class data_vec defines a D-dimensional vector * \T Data type of vector * \D Dimension of vector */ template class es_vec { public: /** Default constructor*/ es_vec() { for (size_t i = 0; i < D; ++i) esv_data[i] = std::numeric_limits::lowest(); } /** Create a vector with an initial value _v for all elements */ es_vec(const T _v) { for (size_t i = 0; i < D; ++i) esv_data[i] = _v; } /** Copy constructor*/ es_vec(const es_vec & _vec) { for (size_t i = 0; i < D; ++i) esv_data[i] = _vec.esv_data[i]; } /** Destructor*/ ~es_vec() { } public: /** Reset the vector with a specified value _v */ void reset(const T _v = 0) { for (size_t i = 0; i < D; ++i) esv_data[i] = _v; } /** Init from a raw vector */ void init(const T* _data) { for (size_t i = 0; i < D; ++i) esv_data[i] = _data[i]; } /** Operator [] */ T & operator [] (const size_t _i) { return esv_data[_i]; } const T & operator [] (const size_t _i) const { return esv_data[_i]; } /** Operator = */ es_vec & operator = (const es_vec & _vec) { for (size_t i = 0; i < D; ++i) esv_data[i] = _vec.esv_data[i]; return *this; } /** Operator += */ es_vec & operator += (const es_vec & _vec) { for (size_t i = 0; i < D; ++i) esv_data[i] += _vec[i]; return *this; } /** Operator -= */ es_vec & operator -= (const es_vec & _vec) { for (size_t i = 0; i < D; ++i) esv_data[i] -= _vec[i]; return *this; } /** Operator *= */ es_vec & operator *= (const T _v) { for (size_t i = 0; i < D; ++i) esv_data[i] *= _v; return *this; } /** Operator /= */ es_vec & operator /= (const T _v) { for (size_t i = 0; i < D; ++i) esv_data[i] /= _v; return *this; } /** get the raw data vector */ T* raw_data() { return esv_data; } /** return the 2-norm of this vector */ const T norm() const { T norm(0); for (size_t i = 0; i < D; ++i) norm += esv_data[i] * esv_data[i]; return sqrt(norm); } /** ************* Friend functions to provide more operators ****************************** */ /** Operator + */ friend es_vec operator + (const es_vec & _vec1, const es_vec & _vec2) { return es_vec(_vec1) += _vec2; } /** Operator - */ friend es_vec operator - (const es_vec & _vec1, const es_vec & _vec2) { return es_vec(_vec1) -= _vec2; } /** Operator * */ friend es_vec operator * (const T _v, const es_vec & _vec) { return es_vec(_vec) *= _v; } friend es_vec operator * (const es_vec & _vec, const T _v) { return es_vec(_vec) *= _v; } /** Operator / */ friend es_vec operator / (const es_vec & _vec, const T _v) { return es_vec(_vec) /= _v; } /** Operator == */ friend const bool operator == (const es_vec & _vec1, const es_vec & _vec2) { for (size_t i = 0; i < D; ++i) { if (!_vec1[i] == _vec2[i]) return false; } return true; } /** Operator != */ friend const bool operator != (const es_vec & _vec1, const es_vec & _vec2) { for (size_t i = 0; i < D; ++i) { if (!_vec1[i] == _vec2[i]) return true; } return false; } /** Operator << */ friend std::ostream & operator << (std::ostream & _os, const es_vec & _vec) { _os << "["; for (size_t i = 0; i < D - 1; ++i) _os << _vec[i] << " "; _os << _vec[D - 1] << "]"; return _os; } private: T esv_data[D]; }; /** Single Exponential Smoothing Method * \T Data type float/double/double double... * \D Dimension of this class */ template class single_exponential_smoothing { public: /** Default constructor */ single_exponential_smoothing() : ses_smoothing_const(0.5), ses_counter(0), ses_vacillation_tolerance(0) { ses_curr_smoothed_ob.reset(); } /** Destructor */ ~single_exponential_smoothing() { } public: /** Set the value of smoothing constant in the range (0, 1) */ void set_smoothing_constant(const T _val) { assert(_val > 0 && _val < 1); ses_smoothing_const = _val; } /** Set the value of vacillation tolerance */ void set_vacillation_tolerance(const T _val) { ses_vacillation_tolerance = _val; } /** Push a new vec and pop its smoothed value as the return */ const es_vec push_to_pop(const es_vec _curr_raw_ob) { if(0 < ses_counter) { es_vec temp_last_smoothed_ob(ses_curr_smoothed_ob); ses_curr_smoothed_ob = ses_smoothing_const * _curr_raw_ob + (1 - ses_smoothing_const) * ses_curr_smoothed_ob; if ((ses_curr_smoothed_ob - temp_last_smoothed_ob).norm() < ses_vacillation_tolerance) { ses_curr_smoothed_ob = temp_last_smoothed_ob; } } else { ses_curr_smoothed_ob = _curr_raw_ob; } ++ses_counter; return ses_curr_smoothed_ob; } /** Get the current counter */ const size_t counter() const { return ses_counter; } /** Reset this class to initial state */ void reset() { ses_curr_smoothed_ob.reset(); ses_smoothing_const = 0.5; ses_counter = 0; ses_vacillation_tolerance = 0; } private: es_vec ses_curr_smoothed_ob; T ses_smoothing_const; size_t ses_counter; T ses_vacillation_tolerance; }; /** Double Exponential Smoothing Method * \T Data type float/double/double double... * \D Dimension of this class */ template class double_exponential_smoothing { public: /** Default constructor */ double_exponential_smoothing() : des_1st_smoothing_const(0.5), des_2nd_smoothing_const(0.5), des_counter(0), des_vacillation_tolerance(0) { des_curr_smoothed_ob.reset(); des_last_smoothed_ob.reset(); des_curr_correction_ob.reset(); } /** Destructor */ ~double_exponential_smoothing() { } public: /** Set the value of 1st smoothing constant in the range (0, 1) */ void set_1st_smoothing_constant(const T _val) { assert(_val > 0 && _val < 1); des_1st_smoothing_const = _val; } /** Set the value of 2nd smoothing constant in the range (0, 1) */ void set_2nd_smoothing_constant(const T _val) { assert(_val > 0 && _val < 1); des_2nd_smoothing_const = _val; } /** Set the value of vacillation tolerance */ void set_vacillation_tolerance(const T _val) { des_vacillation_tolerance = _val; } /** Push a new vec and pop its smoothed value as the return */ const es_vec push_to_pop(const es_vec _curr_raw_ob) { if (0 == des_counter) { des_curr_smoothed_ob = _curr_raw_ob; } else if (1 == des_counter) { des_curr_correction_ob = _curr_raw_ob - des_curr_smoothed_ob; des_last_smoothed_ob = des_curr_smoothed_ob; des_curr_smoothed_ob = des_1st_smoothing_const * _curr_raw_ob + (1 - des_1st_smoothing_const) * (des_curr_smoothed_ob + des_curr_correction_ob); if ((des_curr_smoothed_ob - des_last_smoothed_ob).norm() < des_vacillation_tolerance) { des_curr_smoothed_ob = des_last_smoothed_ob; } } else { des_curr_correction_ob = des_2nd_smoothing_const * (des_curr_smoothed_ob - des_last_smoothed_ob) + (1 - des_2nd_smoothing_const) * des_curr_correction_ob; des_last_smoothed_ob = des_curr_smoothed_ob; des_curr_smoothed_ob = des_1st_smoothing_const * _curr_raw_ob + (1 - des_1st_smoothing_const) * (des_curr_smoothed_ob + des_curr_correction_ob); if ((des_curr_smoothed_ob - des_last_smoothed_ob).norm() < des_vacillation_tolerance) { des_curr_smoothed_ob = des_last_smoothed_ob; } } ++des_counter; return des_curr_smoothed_ob; } /** Get the current counter */ const size_t counter() const { return des_counter; } /** Reset this class to initial state */ void reset() { des_curr_smoothed_ob.reset(); des_last_smoothed_ob.reset(); des_curr_correction_ob.reset(); des_1st_smoothing_const = 0.5; des_2nd_smoothing_const = 0.5; des_counter = 0; } private: es_vec des_curr_smoothed_ob; es_vec des_last_smoothed_ob; es_vec des_curr_correction_ob; T des_1st_smoothing_const; T des_2nd_smoothing_const; size_t des_counter; T des_vacillation_tolerance; }; #endif // HEADER_EXPONENTIAL_SMOOTHING_H ================================================ FILE: Maths/Statistics/Exponential_Smoothing/Exponential_Smoothing.java ================================================ import java.util.Arrays; public class DoubleExponentialSmoothingForLinearSeries { /** * Performs double exponential smoothing for given time series. *

* This method is suitable for fitting series with linear trend. * * @param data An array containing the recorded data of the time series * @param alpha Smoothing factor for data (0 < alpha < 1) * @param beta Smoothing factor for trend (0 < beta < 1) * @return Instance of model that can be used to forecast future values */ public static Model fit(double[] data, double alpha, double beta) { validateParams(alpha, beta); //validating values of alpha and beta double[] smoothedData = new double[data.length]; //array to store smoothed values double[] trends = new double[data.length + 1]; double[] levels = new double[data.length + 1]; //initializing values of parameters smoothedData[0] = data[0]; trends[0] = data[1] - data[0]; levels[0] = data[0]; for (int t = 0; t < data.length; t++) { smoothedData[t] = trends[t] + levels[t]; levels[t+1] = alpha * data[t] + (1 - alpha) * (levels[t] + trends[t]); trends[t+1] = beta * (levels[t+1] - levels[t]) + (1 - beta) * trends[t]; } return new Model(smoothedData, trends, levels, calculateSSE(data,smoothedData)); } private static double calculateSSE(double[] data, double[] smoothedData) { double sse = 0; for (int i = 0; i < data.length; i++) { sse+= Math.pow(smoothedData[i] - data[i],2); } return sse; } private static void validateParams(double alpha, double beta) { if (alpha < 0 || alpha > 1) { throw new RuntimeException("The value of alpha must be between 0 and 1"); } if (beta < 0 || beta > 1) { throw new RuntimeException("The value of beta must be between 0 and 1"); } } public static void main(String[] args) { double[] testData = {17.55, 21.86, 23.89, 26.93, 26.89, 28.83, 30.08, 30.95, 30.19, 31.58, 32.58, 33.48, 39.02, 41.39, 41.60}; Model model = DoubleExponentialSmoothingForLinearSeries.fit(testData, 0.8, 0.2); System.out.println("Input values: " + Arrays.toString(testData)); System.out.println("Smoothed values: " + Arrays.toString(model.getSmoothedData())); System.out.println("Trend: " + Arrays.toString(model.getTrend())); System.out.println("Level: " + Arrays.toString(model.getLevel())); System.out.println("Forecast: " + Arrays.toString(model.forecast(5))); System.out.println("Sum of squared error: " + model.getSSE()); } static class Model { private final double[] smoothedData; private final double[] trends; private final double[] levels; private final double sse; public Model(double[] smoothedData, double[] trends, double[] levels, double sse) { this.smoothedData = smoothedData; this.trends = trends; this.levels = levels; this.sse = sse; } /** * Forecasts future values. * * @param size no of future values that you need to forecast * @return forecast data */ double[] forecast(int size) { double[] forecastData = new double[size]; for (int i = 0; i < size; i++) { forecastData[i] = levels[levels.length - 1] + (i + 1) * trends[trends.length - 1]; } return forecastData; } public double[] getSmoothedData() { return smoothedData; } public double[] getTrend() { return trends; } public double[] getLevel() { return levels; } public double getSSE() { return sse; } } } ================================================ FILE: Maths/Statistics/Exponential_Smoothing/Exponential_Smoothing.rb ================================================ # module HoltWinters class << self # This method is the entry point. It calculates the initial values and returns the forecast # for the m periods. # Calculate initial values and return the forecast for m periods. # # y - Time series data. # alpha - Exponential smoothing coefficients for level # beta - Exponential smoothing coefficients for trend (increasing beta tightens fit) # gamma - Exponential smoothing coefficients for seasonal # period - A complete season's data consists of L periods. And we need # to estimate the trend factor from one period to the next. To # accomplish this, it is advisable to use two complete seasons; # that is, 2L periods. # y Time series array # alpha Level smoothing coefficient. # beta Trend smoothing coefficient (increasing beta tightens fit) # gamma Seasonal smoothing coefficient # period A complete season's data consists of L periods. And we need # to estimate the trend factor from one period to the next. To # accomplish this, it is advisable to use two complete seasons; # that is, 2L periods. # m Extrapolated future data points # - 4 quarterly # - 7 weekly # - 12 monthly # # m - Extrapolated future data points. # 4 quarterly # 7 weekly. # 12 monthly def forecast(y, alpha, beta, gamma, period, m) return nil if y.empty? seasons = y.size / period a0 = calculateInitialLevel(y, period) b0 = calculateInitialTrend(y, period) a0 = initial_level(y, period) b0 = initial_trend(y, period) seasonal_indices = calculateSeasonalIndices(y, period, seasons) seasonal = seasonal_indicies(y, period, seasons) calculateHoltWinters(y, a0, b0, alpha, beta, gamma, seasonal_indices, period, m); holt_winters(y, a0, b0, alpha, beta, gamma, seasonal, period, m); end def calculateHoltWinters(y, a0, b0, alpha, beta, gamma, seasonal_indicies, period, m) def holt_winters(y, a0, b0, alpha, beta, gamma, seasonal, period, m) st = Array.new(y.length, 0.0) bt = Array.new(y.length, 0.0) it = Array.new(y.length, 0.0) @@ -54,7 +53,7 @@ def calculateHoltWinters(y, a0, b0, alpha, beta, gamma, seasonal_indicies, perio bt[1] = b0 (0..period - 1).each do |i| it[i] = seasonal_indicies[i] it[i] = seasonal[i] end ft[m] = (st[0] + (m * bt[0])) * it[0] # This is actually 0 since bt[0] = 0 @@ -87,13 +86,13 @@ def calculateHoltWinters(y, a0, b0, alpha, beta, gamma, seasonal_indicies, perio # See: http://robjhyndman.com/researchtips/hw-initialization/ # 1st period's average can be taken. But y[0] works better. def calculateInitialLevel(y, period) def initial_level(y, period) y.first end # See: http://www.itl.nist.gov/div898/handbook/pmc/section4/pmc435.htm def calculateInitialTrend(y, period) def initial_trend(y, period) sum = 0 (0..period - 1).each do |i| @@ -105,32 +104,32 @@ def calculateInitialTrend(y, period) # See: http://www.itl.nist.gov/div898/handbook/pmc/section4/pmc435.htm def calculateSeasonalIndices(y, period, seasons) seasonalAverage = Array.new(seasons, 0.0) seasonalIndices = Array.new(period, 0.0) averagedObservations = Array.new(y.size, 0.0) def seasonal_indicies(y, period, seasons) seasonal_average = Array.new(seasons, 0.0) seasonal_indices = Array.new(period, 0.0) averaged_observations = Array.new(y.size, 0.0) (0..seasons - 1).each do |i| (0..period - 1).each do |j| seasonalAverage[i] += y[(i * period) + j] seasonal_average[i] += y[(i * period) + j] end seasonalAverage[i] /= period seasonal_average[i] /= period end (0..seasons - 1).each do |i| (0..period - 1).each do |j| averagedObservations[(i * period) + j] = y[(i * period) + j] / seasonalAverage[i] averaged_observations[(i * period) + j] = y[(i * period) + j] / seasonal_average[i] end end (0..period - 1).each do |i| (0..seasons - 1).each do |j| seasonalIndices[i] += averagedObservations[(j * period) + i] seasonal_indices[i] += averaged_observations[(j * period) + i] end seasonalIndices[i] /= seasons seasonal_indices[i] /= seasons end seasonalIndices seasonal_indices end end end ================================================ FILE: Maths/Statistics/Exponential_Smoothing/README.md ================================================ ## This folder is empty. ================================================ FILE: Maths/Statistics/K-means_Clustering/K-means_Clustering.py ================================================ import numpy as np import matplotlib.pyplot as plt from sklearn.datasets import make_blobs import random class Cluster: def __init__(self, center, name): self.center = center self.name = name self.points = [] def distance(self, point): return np.sqrt(np.sum((self.center - point) ** 2)) def relocate(self): self.center = np.mean(self.points, axis=0) self.points.clear() class KMeansCustom: def __init__(self, n_clusters=5, max_iters=20, n_init=10): self.max_iters = max_iters self.n_clusters = n_clusters self.n_init = n_init def fit(self, X): solutions = [] for init in range(self.n_init): clusters = [] for i in range(self.n_clusters): cluster = Cluster(center=random.choice(X), name=i) clusters.append(cluster) errors = [] for it in range(self.max_iters): # voting labels = [] for point in X: # collect distance of point to all clusters distances = [] for cluster in clusters: distance = cluster.distance(point) distances.append((distance, cluster.name)) # sort and select cluster with min distance distance, cluster_name = sorted(distances)[0] # point voted which cluster labels.append(cluster_name) # point which voted the cluster cluster = clusters[cluster_name] cluster.points.append(point) err = self.error(labels, clusters, X) errors.append(err) # taking mean of all the points in that cluster for cluster in clusters: cluster.relocate() solutions.append([errors[-1], labels, clusters]) sorted_sols = sorted(solutions, key=lambda item: item[0]) err, labels, clusters = sorted_sols[0] self.labels_ = np.array(labels) self.cluster_centers_ = np.array([cluster.center for cluster in clusters]) def error(self, labels, clusters, X): err = 0 for point, label in zip(X, labels): cluster = clusters[label] err += cluster.distance(point) return err / len(X) # Running by taking an example from sklearn's blobs X, _ = make_blobs(centers=4, random_state=42) plt.scatter(X[:, 0], X[:, 1]) model = KMeansCustom(4) model.fit(X) plt.scatter(X[:, 0], X[:, 1], c=model.labels_) for center in model.cluster_centers_: plt.scatter(center[0], center[1], s=120) plt.show() print(model.labels_) print(model.cluster_centers_) ================================================ FILE: Maths/Statistics/Logistic_Function/README.md ================================================ ## This folder is empty. ================================================ FILE: Maths/Statistics/Mean/mean.cpp ================================================ #include using namespace std; int mean(int arr[], int n){ int m = 0; for(int i=0; i> n; cout<<"Enter the numbers"; int arr[n]; for(int i=0; i>arr[i]; } int m = mean(arr,n); cout<<"The mean of numbers is: "< #include int main() { int arr[] = {1, 23, 423, 45, 34, 2, 36, 256, 2, 143}; int size = sizeof(arr) / sizeof(arr[0]); int sum = 0; float mean; for (int i = 0; i < size; i++) sum = sum + arr[i]; mean = (float)sum / size; printf("\nThe mean of %d numbers is %f\n", size, mean); return 0; } ================================================ FILE: Maths/Statistics/Mean/meanOfGivenNumbers.cs ================================================ using System.IO; using System; using System.Linq; class meanOfGivenNumbers { static void Main() { var arr = new int[] { 10, 17, 25, 30, 40, 55, 60, 70 }; double avg = Queryable.Average(arr.AsQueryable()); Console.WriteLine("Average = " + avg); } } ================================================ FILE: Maths/Statistics/Mean/meanOfGivenNumbers.js ================================================ var arr = [10, 17, 25, 30, 40, 55, 60, 70]; var total = 0; for (var i = 0; i < arr.length; i++) { total += arr[i]; } var avg = total / arr.length; console.log("Average of numbers is " + avg) ================================================ FILE: Maths/Statistics/Median/Median.c ================================================ #include void swap(int *p,int *q) { int t; t=*p; *p=*q; *q=t; } void sort(int a[],int n) { int i,j,temp; for(i = 0;i < n-1;i++) { for(j = 0;j < n-i-1;j++) { if(a[j] > a[j+1]) swap(&a[j],&a[j+1]); } } } int main() { int a[] = {6,3,8,5,1}; int n = 5; int sum,i; sort(a,n); n = (n+1) / 2 - 1; // -1 as array indexing in C starts from 0 printf("Median = %d ", a[n]); return 0; } ================================================ FILE: Maths/Statistics/Median/Median.java ================================================ package Maths_And_Stats.Statistics.Median; import java.util.Arrays; import java.util.Scanner; public class Median { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("Enter no of elements: "); int n = sc.nextInt(); int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = sc.nextInt(); } System.out.println("Elements are: "); for (int i = 0; i < n; i++) { System.out.print(arr[i]+" "); } System.out.println(); System.out.println("Median is:"+ findMedian(arr, n)); } private static double findMedian(int[] arr, int n) { Arrays.sort(arr); if(n % 2 != 0) { return (double) arr[n/2]; } else { return (double) (arr[(n - 1) / 2] + arr[n / 2] / 2.0); } } } ================================================ FILE: Maths/Statistics/Median/Median.js ================================================ var data = [7, 9, 12, 13, 16]; var length = data.length; var position = 0; var median = 0; data.sort(function (a, b) { return a - b; }); if (length % 2 === 0) { position = Math.ceil(length / 2) - 1; median = (data[position] + data[position + 1]) / 2; } else { position = Math.floor(length / 2); median = data[position]; } console.log("Median is : ", median); ================================================ FILE: Maths/Statistics/Median/Median.py ================================================ # Python program for finding median # list of elements to calculate median data = [7, 2, 3, 6, 7] # length of the list length = len(data) # Sort list data.sort() # check if the length of list is odd or even if length % 2 == 0: median1 = data[length//2] median2 = data[length//2 - 1] median = (median1 + median2)/2 else: median = data[length//2] # Print Median print("Median is: " + str(median)) ================================================ FILE: Maths/Statistics/Median/README.md ================================================ ## This folder is empty. ================================================ FILE: Maths/Statistics/Median/meadian.cpp ================================================ #include #include using namespace std; #define max 50 float median(int b[],int n) { sort(b,b+n); float c; if(n%2!=0) { c=b[n/2]; return c; } else { c=(b[(n-1)/2]+b[n/2])/2.0; return c; } } int main() { int a[max]; int n; cout<<"Enter the total number of elements"<>n; cout<<"Enter the elements"<>a[i]; } cout<<"Elements are: "< maxCount) { maxCount = count; mode = a[i]; multiModalSequence.add(mode); }else if(maxCount<=count && maxCount>0) { multiModalSequence.add(a[i]); multimodalCount=maxCount; } } //Print number sequence for display System.out.print("Sequence:["); for (int i = 0; i < n; i++) { if (i == n - 1) { System.out.print(a[i]); } else { System.out.print(a[i] + ","); } } System.out.println("]"); //find occurences int occurances = maxCount+1; //Display mode and occurences if (maxCount == 0) { System.out.println("There is no mode for the entered number sequence!!"); } else if(maxCount>multimodalCount) { System.out.println("Mode: " + mode); System.out.println("Occurences: " + occurances); }else { System.out.println("This is a multimodal sequence"); System.out.print("Modes :"); for(int x : multiModalSequence) { System.out.print(x+","); } System.out.println(); System.out.println("Occurences(Each Mode): "+occurances); } } } ================================================ FILE: Maths/Statistics/Mode/README.md ================================================ ## This folder is empty. ================================================ FILE: Maths/Statistics/Mode/mode.c ================================================ #include #define max 50 int mode(int b[],int n) { int maxcount=0; int mode=0; for(int i=0;imaxcount) { maxcount=c; mode=b[i]; } } return mode; } int main() { int n; printf("Enter total number of elements\n"); scanf("%d",&n); int a[max]; printf("Enter the elements \n"); for(int i=0;i using namespace std; void mode(int [], int); int main() { int a[1000], n, i; cout << "Enter no. of elements: "; cin >> n; cout << "Enter data: "; for(i=0; i> a[i]; } mode(a, n); return 0; } void mode(int arr[], int num) { int i, k, flag=0, mode=0; for(i=0; i flag) { flag = count; mode = arr[i]; } } cout << "Mode is: " << mode << endl; } ================================================ FILE: Maths/Statistics/Mode/mode.js ================================================ var arrayOne = []; var counter=0,repeater,temp,mode; var number1 = prompt("Enter Size of Array/Set -> "); for(var i=0;i"); } for(var i=0;i counter){ mode = temp; counter = repeater; } } alert("Mode of the entered Set is -> " + mode); ================================================ FILE: Maths/Statistics/Mode/mode.php ================================================ 0: #append first number in array to list numbersList[0].append(numbersArray[0]) index = 0 for i in range(1,len(numbersArray)): testNumber = numbersArray[i] compareNumber = numbersArray[i-1] if testNumber == compareNumber: numbersList[index].append(testNumber) else: index += 1 numbersList[index].append(testNumber) #print(numbersList) else: print("Error! No numbers in dataset") counts = [] for i in numbersList: count = len(i) counts.append(count) #print(counts) maxCounts = max(counts) resultList = [] for i in range(len(counts)): if counts[i] == maxCounts: resultRow = numbersList[i] result = resultRow[0] resultList.append(result) print("These are your mode(s):") print(resultList) ================================================ FILE: Maths/Statistics/README.md ================================================ ## This folder is empty. ================================================ FILE: Maths/Statistics/Standard_Deviation/README.md ================================================ ## This folder is empty. ================================================ FILE: Maths/Statistics/Standard_Deviation/Standard_Deviation.c ================================================ #include #include //function to calculate standard deviation float calculateSD(float data[],int n); int main() { int i,n; printf("Enter total No. of elements: "); scanf("%d", &n); float data[n]; printf("Enter %d elements: ",n); for (i = 0; i < n; ++i) scanf("%f", &data[i]); printf("\nStandard Deviation = %.6f", calculateSD(data,n)); return 0; } float calculateSD(float data[],int n) { float sum = 0.0, mean, SD = 0.0; int i; for (i = 0; i < n; ++i) { sum += data[i]; } mean = sum / n; for (i = 0; i < n; ++i) SD += pow(data[i] - mean, 2); return sqrt(SD / n); } ================================================ FILE: Maths/Statistics/Standard_Deviation/Standard_Deviation.cpp ================================================ #include #include using namespace std; float standardDeviation(float data[]) { float sum = 0.0, mean, standardDeviation = 0.0; int i; for(i = 0; i < 10; ++i) { sum += data[i]; } mean = sum/10; for(i = 0; i < 10; ++i) standardDeviation += pow(data[i] - mean, 2); return sqrt(standardDeviation / 10); }; int main() { int i; float data[10]; cout << "Enter 10 elements: "; for(i = 0; i < 10; ++i) cin >> data[i]; cout << endl << "Standard Deviation = " << standardDeviation(data); return 0; } ================================================ FILE: Maths/Statistics/Standard_Deviation/Standard_Deviation.js ================================================ var data = [12, 43, 52, 13, 1, 63, 100, 22, 67, 239]; var sum = data.reduce((acc, val) => acc + val, 0); var mean = sum / data.length; var standardDeviation = data.reduce((acc, val) => acc + Math.pow(val - mean, 2), 0); //Square of the sum of each value minus the mean standardDeviation = Math.sqrt(standardDeviation / data.length); //Square root of the previously obtained value over the size of the population console.log(standardDeviation); ================================================ FILE: Maths/Statistics/Standard_Deviation/Standard_Deviation.py ================================================ # Python code to demonstrate stdev() function # importing Statistics module import statistics # creating a simple data - set sample = [1, 2, 3, 4, 5] # Prints standard deviation # xbar is set to default value of 1 print("Standard Deviation of sample is % s " % (statistics.stdev(sample))) ================================================ FILE: Maths/Statistics/Standard_Deviation/Standard_Deviation.swift ================================================ import Foundation func getStdDeviation(input:[Int], population: Bool = true) -> Double { var sq_sum = 0.0 //Calculate Mean of given inout array var sum = 0 for number in input { sum += number } let mean = Double(sum) / Double(input.count) //calculate the sum of squared difference between mean and each element in the input for number in input { sq_sum = sq_sum + pow(Double(number) - mean, 2) } //Divisor depends on if its population stddev or sample stddev let div = population ? input.count : input.count - 1 return sqrt(sq_sum / Double(div)) } let input = readLine()!.split(separator: " ").map { Int(String($0))! } let population_stdDev = getStdDeviation(input: input) print("Population Standard Deviation for given input series is \(population_stdDev)") let sample_stdDev = getStdDeviation(input: input, population: false) print("Sample Standard Deviation for given input series is \(sample_stdDev)") ================================================ FILE: README.md ================================================


GitHub pull requests GitHub issues

## Index * [Data Structures](Data-Structures/) * [Algorithms](Algorithms/) * [Maths And Stats](Maths/) * [Collection](Collection/) * [STL](STL/) ## How To Contribute ### 1. Fork The Repo ![1](https://user-images.githubusercontent.com/54521023/94943081-d19a1700-04f4-11eb-81dc-b5bd1a3b9adb.png) ### 2. Go The Issue Section ![2](https://user-images.githubusercontent.com/54521023/94943088-d363da80-04f4-11eb-80e5-444999c5fb42.png) ### 3.1 Choose An Existing Issue ![3](https://user-images.githubusercontent.com/54521023/94943091-d4950780-04f4-11eb-96ce-1bd08c260cbd.png) ### 3.2 Or You Can Create A New One ![4](https://user-images.githubusercontent.com/54521023/94943089-d3fc7100-04f4-11eb-92a4-51d6363a99b4.png) * Before opening a new issue make sure that similar kind of issue doesn't already exist. ### 4. Check For The Languages Available ![5](https://user-images.githubusercontent.com/54521023/135753314-d67a67b5-3e57-48c5-b58e-076e442f3849.png) ### 5. Comment In The Stated Syntax ![6](https://user-images.githubusercontent.com/54521023/135754330-be6aa099-2ccf-44c7-aebe-e9348c23ae82.png) * **Language In Which You Will Contribute => Time Required By You To Push The Changes** * Ask for the issue that you plan to complete. * Do not wait to get assigned. * Please try to push the changes in less than or equal to the stated(by you only) time period. Failing to do that, your comment will be discarded and the language will be made available to other participants. * Try to avoid any casual communication. ### 6 Create A New Branch ![7](https://user-images.githubusercontent.com/54521023/94954691-18910800-0507-11eb-95c5-df953d74db3e.png) ### 7. Create A New File with A Relevant Name ![8](https://user-images.githubusercontent.com/54521023/94943103-d8288e80-04f4-11eb-8839-64eb73bf308a.png) * Make sure to follow the [naming convection](https://github.com/ahampriyanshu/algo_ds_101/blob/main/CONTRIBUTING.md#naming-convention) ![9](https://user-images.githubusercontent.com/54521023/135753421-9420757f-1a7d-47fa-b5a3-7943ab96ec39.png) ### 8. Commit The File ![10](https://user-images.githubusercontent.com/54521023/135758806-f9c0a445-4553-475d-a02f-0f1d7e5b802c.png) ### 10. Compare And Pull ![11](https://user-images.githubusercontent.com/54521023/135753640-38554923-9dd3-43a7-bd5a-ab3c33dbac05.png) * [Before pulling make sure your branch is up-to-date](#sync-your-forked-repository) ### 11. Give Relevant PR Message ![12](https://user-images.githubusercontent.com/54521023/135753639-bcf2b0d2-763c-49fd-be9f-9b4175d29c3d.png) ### 12. Enter Related Issue No ![13](https://user-images.githubusercontent.com/54521023/94943135-dfe83300-04f4-11eb-8db8-639077cf8b9c.png) ### 13. Fill Up The Checkboxe(s) ![14](https://user-images.githubusercontent.com/54521023/135755940-ef41a77d-2e4b-4518-96f2-2a6643b8def7.png) ### 14. Create A Pull Request ![15](https://user-images.githubusercontent.com/54521023/94943157-e37bba00-04f4-11eb-8d5e-cd65c93bf842.png) ### 15. Congrats 🎉 ![16](https://user-images.githubusercontent.com/54521023/135753630-0d898e7e-1533-4278-9288-25ec08a3836e.png) ### 20. Wait Till Your PR Gets Merged ![17](https://user-images.githubusercontent.com/54521023/135753819-76a75d6d-b15e-4096-8f4c-11ad1d5e3e17.png) ## Want To Document The Repo ? * Click [here](https://github.com/ahampriyanshu/algo_ds_101/issues/new?assignees=octocat&labels=Hacktoberfest2021%2CHacktoberfest%2Cnew+submssion%2Cfirst+timer%2Cgood+first+issue%2Cdocumentation&template=Documentation.yml&title=Directory+You+Purpose+to+Document) to know more ## How To Commit In CLI ```bash $ git clone git@github.com:your_username/algo_ds_101.git $ git checkout -b BranchName $ git add . $ git commit -m 'message' $ git push -u origin BranchName ``` ## Sync Your Forked Repository ### CLI ```bash $ git fetch --all --prune $ git checkout main $ git reset --hard upstream/main $ git push origin main ``` ### GUI ![18](https://user-images.githubusercontent.com/54521023/135514252-18bab611-4683-4d3c-a8a8-03117292fbb7.png) ![19](https://user-images.githubusercontent.com/54521023/135514247-020bb6e8-b869-4668-a350-89081a4ed5a8.png) ![20](https://user-images.githubusercontent.com/54521023/135514235-9e40abdf-ed8c-4954-9bc3-a9e6d41fad49.png) ## Contributing Guidelines Read [contributing guidelines](CONTRIBUTING.md/) ## Contributors Meet our wonderful [contributors](CONTRIBUTORS.md/) ## Code of Conduct Read our [code of conduct](CODE_OF_CONDUCT.md/). ## License [MIT License](LICENSE/). ================================================ FILE: STL/Array/Array.cpp ================================================ #include #include using namespace std; int main() { // Taking inputs using array template from C++ STL.. array arr1 = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; array arr2 = {11, 12, 13, 14, 15, 16, 17, 18, 19, 20}; cout << "Before Swap :" << endl; cout << "Elements in the first array : "; for (int i = 0; i < 10; i++) cout << arr1.at(i) << " "; // This method returns value in the array at the given range. cout << "\nElements in the second array : "; for (int i = 0; i < 10; i++) cout << arr2.at(i) << " "; arr1.swap(arr2); // Swapping two arrays.. cout << "\n\nAfter Swap :" << endl; cout << "Elements in the first array : "; for (int i = 0; i < 10; i++) cout << arr1.at(i) << " "; cout << "\nElements in the second array : "; for (int i = 0; i < 10; i++) cout << arr2.at(i) << " "; return 0; } ================================================ FILE: STL/Map/MultiMap/multimap.cpp ================================================ #include #include #include using namespace std; int main() { multimap gquiz1; // empty multimap container // insert elements in random order gquiz1.insert(pair (1, 40)); gquiz1.insert(pair (2, 30)); gquiz1.insert(pair (3, 60)); gquiz1.insert(pair (4, 20)); gquiz1.insert(pair (5, 50)); gquiz1.insert(pair (6, 50)); gquiz1.insert(pair (6, 10)); // printing multimap gquiz1 multimap :: iterator itr; cout << "\nThe multimap gquiz1 is : \n"; cout << "\tKEY\tELEMENT\n"; for (itr = gquiz1.begin(); itr != gquiz1.end(); ++itr) { cout << '\t' << itr->first << '\t' << itr->second << '\n'; } cout << endl; // assigning the elements from gquiz1 to gquiz2 multimap gquiz2(gquiz1.begin(),gquiz1.end()); // print all elements of the multimap gquiz2 cout << "\nThe multimap gquiz2 after assign from gquiz1 is : \n"; cout << "\tKEY\tELEMENT\n"; for (itr = gquiz2.begin(); itr != gquiz2.end(); ++itr) { cout << '\t' << itr->first << '\t' << itr->second << '\n'; } cout << endl; // remove all elements up to element with value 30 in gquiz2 cout << "\ngquiz2 after removal of elements less than key=3 : \n"; cout << "\tKEY\tELEMENT\n"; gquiz2.erase(gquiz2.begin(), gquiz2.find(3)); for (itr = gquiz2.begin(); itr != gquiz2.end(); ++itr) { cout << '\t' << itr->first << '\t' << itr->second << '\n'; } // remove all elements with key = 4 int num; num = gquiz2.erase(4); cout << "\ngquiz2.erase(4) : "; cout << num << " removed \n" ; cout << "\tKEY\tELEMENT\n"; for (itr = gquiz2.begin(); itr != gquiz2.end(); ++itr) { cout << '\t' << itr->first << '\t' << itr->second << '\n'; } cout << endl; //lower bound and upper bound for multimap gquiz1 key = 5 cout << "gquiz1.lower_bound(5) : " << "\tKEY = "; cout << gquiz1.lower_bound(5)->first << '\t'; cout << "\tELEMENT = " << gquiz1.lower_bound(5)->second << endl; cout << "gquiz1.upper_bound(5) : " << "\tKEY = "; cout << gquiz1.upper_bound(5)->first << '\t'; cout << "\tELEMENT = " << gquiz1.upper_bound(5)->second << endl; return 0; } ================================================ FILE: STL/Map/Unodered-Map/unorderedmap.cpp ================================================ // C++ program to demonstrate functionality of unordered_map #include #include using namespace std; int main() { // Declaring umap to be of type // key will be of string type and mapped value will // be of int type unordered_map umap; // inserting values by using [] operator string s1, s2 ,s3; cin>>s1>>s2>>s3; int a,b,c; cin>>a>>b>>c; umap[s1] = a; umap[s2] = b; umap[s3] = c; // Traversing an unordered map for (auto x : umap) cout << x.first << " " << x.second << endl; } ================================================ FILE: STL/Map/map.cpp ================================================ #include #include #include using namespace std; int main() { map gquiz1; gquiz1.insert(pair(1, 40)); gquiz1.insert(pair(2, 30)); gquiz1.insert(pair(3, 60)); gquiz1.insert(pair(4, 20)); gquiz1.insert(pair(5, 50)); gquiz1.insert(pair(6, 50)); gquiz1.insert(pair(7, 10)); map::iterator itr; cout << "\nThe map gquiz1 is : \n"; cout << "\tKEY\tELEMENT\n"; for (itr = gquiz1.begin(); itr != gquiz1.end(); ++itr) { cout << '\t' << itr->first << '\t' << itr->second << '\n'; } cout << endl; map gquiz2(gquiz1.begin(), gquiz1.end()); cout << "\nThe map gquiz2 after" << " assign from gquiz1 is : \n"; cout << "\tKEY\tELEMENT\n"; for (itr = gquiz2.begin(); itr != gquiz2.end(); ++itr) { cout << '\t' << itr->first << '\t' << itr->second << '\n'; } cout << endl; cout << "\ngquiz2 after removal of" " elements less than key=3 : \n"; cout << "\tKEY\tELEMENT\n"; gquiz2.erase(gquiz2.begin(), gquiz2.find(3)); for (itr = gquiz2.begin(); itr != gquiz2.end(); ++itr) { cout << '\t' << itr->first << '\t' << itr->second << '\n'; } int num; num = gquiz2.erase(4); cout << "\ngquiz2.erase(4) : "; cout << num << " removed \n"; cout << "\tKEY\tELEMENT\n"; for (itr = gquiz2.begin(); itr != gquiz2.end(); ++itr) { cout << '\t' << itr->first << '\t' << itr->second << '\n'; } cout << endl; cout << "gquiz1.lower_bound(5) : " << "\tKEY = "; cout << gquiz1.lower_bound(5)->first << '\t'; cout << "\tELEMENT = " << gquiz1.lower_bound(5)->second << endl; cout << "gquiz1.upper_bound(5) : " << "\tKEY = "; cout << gquiz1.upper_bound(5)->first << '\t'; cout << "\tELEMENT = " << gquiz1.upper_bound(5)->second << endl; return 0; } ================================================ FILE: STL/Queue/Deque/README.md ================================================ # Deque Deque or double-ended queue is an abstract data type that generalizes a queue, for which elements can be added to or removed from either the front or back. ================================================ FILE: STL/Queue/Deque/deque.cpp ================================================ #include using namespace std; int main(){ dequeq; //q={} q.push_back(1); // inserts an element at back //q={1} q.push_front(2); //inserts an element at front //q={2,1} cout<< q.at(1)<<'\n'; //prints elemant at position 1 {1} cout< using namespace std; int main(int argc, char const *argv[]) { //make a prioity_queue p_queue pq; //insert element element in p_queue pq.push(12); //find the size of q_queue cout << pq.size(); //check if p_queue is empty pq.empty(); //remove element from p-queue pq.pop(); //print top most element. cout << pq.top(); /* This is by-default max- prioity_queue, to make min-queue, simple multiply -1 to all the elements or use p_queue, greater> pq; */ return 0; } ================================================ FILE: STL/Queue/Queue.cpp ================================================ /*Functions to demonstrate queue in STL Operations: empty(), size(), front(), back(), push(g), pop()*/ #include using namespace std; //QUEUE is a FIFO data structure, where insertion and deletion of element is done at opposite ends. void print(queue q){ while(!q.empty()){ cout << q.front(); q.pop(); } } int main(int argc, char const *argv[]) { //declaration of queue queue q; //add element to QUEUE q.push(1); //print the front item of queue. q.front(); //print the last item of queue. q.back(); //delete item from queue. q.pop(); //check if queue is empty. q.empty(); //returns 0 or 1. //check the size of queue. q.size(); //iterator to queue. auto it = q.begin(); queue it = q.end(); //print queue, you can't use a normal for loop and iterator methord to print the queue. print(q); return 0; } ================================================ FILE: STL/README.md ================================================ # Index * [Array](Array/) * [Vector](Vector/) * [Map](Map/) * [Set](Set/) * [Stack](Stack/) * [Queue](Queue/) ================================================ FILE: STL/Set/Unodered-Set/UnorderedSet.cpp ================================================ #include using namespace std ; int main() { // declaring unordered_set for storing int type values unordered_set s ; // for inserting an element s.insert(1) ; s.insert(2) ; s.insert(3) ; s.insert(4) ; // count of an element // count will be either 1 (the element is in the set) or 0 (the element is not in the set) // because set/unordered_set only contain distinct elements cout << s.count(1) << endl ; // 1 cout << s.count(2) << endl ; // 1 cout << s.count(5) << endl ; // 0 cout << s.count(6) << endl ; // 0 // for erasing an element s.erase(1) ; cout << s.count(1) << endl ; // 0 s.erase(2) ; cout << s.count(2) << endl ; // 0 // insert never adds an element if it is already there cout << s.count(1) << endl ; // 0 s.insert(1) ; cout << s.count(1) << endl ; // 1 s.insert(1) ; cout << s.count(1) << endl ; // 1 , the count is still one // size of an unordered_set cout << s.size() << endl ; // 3 , and we know that the elements are 1 , 3 , 4 // how to access an unordered_set // we can't access an unordered_set or a set by using [] notation // for printing/accessing the elements of set we can simply do this for(auto x:s) { cout << x << " " ; // it will print the elements of the s } cout << endl ; // by using iterators // Iterators are generally used to access elements of an unordered_set/set/vector auto x = s.begin() ; // this will point to the first element of unordered_set // we can access the element by using '*' symbol cout << *x << endl ; // note: the output of the above line is not fixed // it can be a any value from the unordered set elements // it will print the elements of the s // s.end() point towards the next position from last element // that's why will we continue our loop till iterator is not equal to s.end() // once iterator becomes equal to s.end() the loop will stop immediately for (auto it = s.begin(); it != s.end(); it++) { cout << *it << " " ; } cout << endl ; // search for an element // s.find(x) will tells that whether 'x' is presents in unordered set or not // and if s does not contain x then it will points towards s.end() auto it=s.find(8) ; if(it==s.end()) // means element is not found { cout << "element is not found" << endl ; } else { cout << "element is found" << endl ; } // above line will print 'element is not found' , because 8 is not presents in s return 0 ; } ================================================ FILE: STL/Set/set.cpp ================================================ #include using namespace std; //set is a ordered pair of item, this data structure is used when you need all the //elements to be always sorted. int main() { set > s1; s1.insert(40); s1.insert(30); s1.insert(60); s1.insert(20); s1.insert(50); s1.insert(50); s1.insert(10); set > :: iterator itr; cout << "\nThe set s1 is : "; for (itr = s1.begin(); itr != s1.end(); ++itr) { cout << '\t' << *itr; } cout << endl; set s2(s1.begin(), s1.end()); cout << "\nThe set s2 after assign from s1 is : "; for (itr = s2.begin(); itr != s2.end(); ++itr) { cout << '\t' << *itr; } cout << endl; cout << "\ns2 after removal of elements less than 30 : "; s2.erase(s2.begin(), s2.find(30)); for (itr = s2.begin(); itr != s2.end(); ++itr) { cout << '\t' << *itr; } int num; num = s2.erase (50); cout << "\ns2.erase(50) : "; cout << num << " removed \t" ; for (itr = s2.begin(); itr != s2.end(); ++itr) { cout << '\t' << *itr; } cout << endl; cout << "s1.lower_bound(40) : " << *s1.lower_bound(40) << endl; cout << "s1.upper_bound(40) : " << *s1.upper_bound(40) << endl; cout << "s2.lower_bound(40) : " << *s2.lower_bound(40) << endl; cout << "s2.upper_bound(40) : " << *s2.upper_bound(40) << endl; // find an item in set. O(logn) auto it = s2.find(1) //if item is not found it returns end() iterator. return 0; } /* Set is similar to multiset, unordered set except the fact that. unorderedset is implemented using hash table, hence insert, delete, find is much faster than set. */ ================================================ FILE: STL/Stack/stack.cpp ================================================ #include using namespace std; //Stack follows FILO int main(int argc, char const *argv[]) { //make a stack. stack s; //add item to stack s.push(1); //remove item from stack. s.pop(); //find size of stack s.size(); //find the top most item in stack. s.top(); //check if stack is empty s.empty(); return 0; } ================================================ FILE: STL/Vector/Vector.cpp ================================================ #include using namespace std; //Vector are dyanmic arrays, internally they are normal C style arrays. int main() { // initilise empty vector vector empty_vec; // {} ,empty vector //make a vector with default values vector empty_vec = {12,23,45}; // {12,23,45} //make a vector with values from vector or array int arr[] = {1,2,3,4,5}; vector v1(arr,arr+n); //make a vector with array values vector v2(v1.begin(), v1.end()); //make a new vector with old vector vector v3(10,0); //vector of size 10 with default value 0. //add a value to vector v.push_back(45); //insert value at the vector at end. //remove value from vector v.pop_back(); //insert at a specific position. v.insert(v.begin(), 101); //v.insert(position, value) //print the value at ith position. cout << v.at(i); //insert at a specific position a number of times. v.insert(v.begin(), 10, 5); //v.insert(position, number of times to insert, //value this insert 5, 10 times at the begin of vector. //copy a vector vector v1 = {1,2,3,4,5}; vector v1(v1.begin(), v1.end(), v2.begin()); // (start address of copy, end address of copy //starting address of where to copy) //methord-2 vector v5; int arr[] = {1,2,3,4,5} v5.assign(arr, arr+n); //methord -3 vector v6; v6.assign(10,0); //assign 10, 0s to vector v6. (size, value) //delete a value from vector. v.erase(it); //it = iterator to that delete position. //remove all values. v.clear(); v = {}; //both methord works //resize an vector. vector v = {1,2,3,4,4,4}; v.resize(4); //now it only contain 4 items from start rest all delets. v.resize(10);// {1,2,3,4,4,4,0,0,0,0} //how many items are in between 2 iterator. auto it = v.begin(); auto it2 = v.end(); cout << distance(it, it2); // print number of items at vector v. return 0; } ================================================ FILE: _config.yml ================================================ theme: jekyll-theme-cayman