Repository: BaReinhard/Hacktoberfest-Data-Structure-and-Algorithms Branch: master Commit: f10437d8129b Files: 313 Total size: 481.8 KB Directory structure: gitextract_z9vtg38d/ ├── .gitignore ├── .vscode/ │ └── settings.json ├── CONTRIBUTING.md ├── LICENSE ├── README.md ├── algorithms/ │ ├── EuclideanAlgorithm/ │ │ ├── c/ │ │ │ └── euclid.c │ │ └── python/ │ │ └── euclideanAlgorithm.py │ ├── Graph/ │ │ └── connected_components_in_undirected_graph/ │ │ └── python/ │ │ └── ConnectedComponents.py │ ├── a_search/ │ │ └── cpp/ │ │ └── a_star.cpp │ ├── backtracking/ │ │ └── c/ │ │ ├── n_queens_problem.c │ │ ├── rat_in_a_maze_problem.c │ │ ├── sudoku_problem.c │ │ └── the_knight_tour_problem.c │ ├── bellman_ford/ │ │ ├── cpp/ │ │ │ └── bellman_ford.cpp │ │ └── java/ │ │ └── BellmanFord.java │ ├── bfs/ │ │ ├── cpp/ │ │ │ └── bfs.cpp │ │ └── java/ │ │ └── Graph.java │ ├── binary_search/ │ │ ├── PHP/ │ │ │ └── binarysearch.php │ │ ├── binary_search.md │ │ ├── c/ │ │ │ └── binary_search.c │ │ ├── cpp/ │ │ │ └── binary_search.cpp │ │ ├── java/ │ │ │ └── binarysearch.java │ │ ├── javascript/ │ │ │ └── binary_search.js │ │ ├── python/ │ │ │ └── binary_search.py │ │ └── ruby/ │ │ └── binary_search.rb │ ├── bipartite_check/ │ │ └── cpp/ │ │ └── bipartite.cpp │ ├── bitwise/ │ │ ├── cpp/ │ │ │ └── generating_subsets.cpp │ │ └── java/ │ │ ├── AddTwoNumbersWithoutPlusOperator.java │ │ ├── BinaryPalidrome.java │ │ ├── NegateANumberWithoutPlusOperator.java │ │ ├── Optimized_permutation │ │ └── Subsets.java │ ├── bogo_sort/ │ │ ├── java/ │ │ │ └── BogoSort.java │ │ ├── python/ │ │ │ └── bogo.py │ │ └── ruby/ │ │ └── bogo_sort.rb │ ├── breadth_first_search/ │ │ └── cpp/ │ │ └── bfs.cpp │ ├── bubble_sort/ │ │ ├── README.md │ │ ├── assembly_mips/ │ │ │ └── bubble_sort.asm │ │ ├── bash/ │ │ │ └── bubblesort.sh │ │ ├── c/ │ │ │ └── bubble_sort.c │ │ ├── cpp/ │ │ │ ├── bubble_sort_1.cpp │ │ │ └── bubblesort.cpp │ │ ├── crystal/ │ │ │ └── bubble_sort.cr │ │ ├── csharp/ │ │ │ └── BubbleSort.cs │ │ ├── elixir/ │ │ │ ├── README.md │ │ │ └── bubblesort.ex │ │ ├── go/ │ │ │ └── bubble-sort-algorithm.go │ │ ├── haskell/ │ │ │ └── bubble_sort.hs │ │ ├── java/ │ │ │ ├── BubbleSortExample.java │ │ │ └── GenericBubbleSort.java │ │ ├── javascript/ │ │ │ ├── bubble-sort.js │ │ │ ├── bubbleSort.js │ │ │ └── main_bs.js │ │ ├── kotlin/ │ │ │ └── bubblesort.kt │ │ ├── objetive-c/ │ │ │ └── BubbleSort.m │ │ ├── perl/ │ │ │ └── BubbleSort.pl │ │ ├── power_shell/ │ │ │ └── bubble_sort.ps1 │ │ ├── python/ │ │ │ └── bubble_sort.py │ │ ├── ruby/ │ │ │ └── bubble_sort.rb │ │ ├── swift/ │ │ │ └── bubble_sort.swift │ │ └── vb/ │ │ └── bubble_sort.bas │ ├── bucket_sort/ │ │ ├── bucket_sort.cpp │ │ ├── bucket_sort.java │ │ ├── bucket_sort.py │ │ └── c/ │ │ └── bucket_sort.c │ ├── caesar_cipher/ │ │ ├── java/ │ │ │ └── caesar.java │ │ └── javascript/ │ │ └── caesarCipher.js │ ├── check_pallindrome_number/ │ │ ├── c/ │ │ │ └── checkPalindrome.c │ │ └── cpp/ │ │ └── checkPall.cpp │ ├── closest/ │ │ └── java/ │ │ └── Closest.java │ ├── count_sort/ │ │ └── javascript/ │ │ └── count_sort.js │ ├── cycle_sort/ │ │ └── java/ │ │ └── cycleSort.java │ ├── decoding/ │ │ └── c/ │ │ └── base64_decoder.c │ ├── dfs/ │ │ ├── cpp/ │ │ │ └── dfs.cpp │ │ ├── java/ │ │ │ └── Graph.java │ │ └── python/ │ │ └── Dfs.py │ ├── dijkstra/ │ │ ├── cpp/ │ │ │ └── Dijkstras.cpp │ │ ├── java/ │ │ │ └── ShortestPath.java │ │ └── python/ │ │ └── djikstra.py │ ├── doomsday/ │ │ ├── java/ │ │ │ └── doomsday.java │ │ └── javascript/ │ │ └── doomsday.js │ ├── dynamic_programming/ │ │ ├── c/ │ │ │ ├── 0_1_knapsack_problem.c │ │ │ ├── Coin_change_DP.c │ │ │ ├── coinChange.c │ │ │ ├── count_no_of_ways_to_reach_nth_stair.c │ │ │ ├── longestIncreasingSubsequence.c │ │ │ ├── longestRepeatedSequence.c │ │ │ ├── longest_pallindrome_sequence.c │ │ │ ├── maxSumIncSequence.c │ │ │ └── subsetSum.c │ │ ├── cpp/ │ │ │ ├── kadens.cpp │ │ │ ├── nCr.cpp │ │ │ └── subset_sum.cpp │ │ └── java/ │ │ └── MinCostPath.java │ ├── encoding/ │ │ └── base64_encoder.c │ ├── fibonacci/ │ │ └── cpp/ │ │ └── constexpr-fibonacci.cpp │ ├── floyd_warshall/ │ │ └── java/ │ │ └── ShortestPath.java │ ├── greedy_search/ │ │ └── cpp/ │ │ └── prims_algorithm.cpp │ ├── heap_sort/ │ │ ├── crystal/ │ │ │ └── heap_sort.cr │ │ ├── java/ │ │ │ ├── heap_sort.java │ │ │ └── heapsort.java │ │ ├── javascript/ │ │ │ └── heap_sort.js │ │ └── python/ │ │ └── heap_sort.py │ ├── histogram_equalization/ │ │ └── java/ │ │ └── HistogramEqualization.java │ ├── huffmann_algorithm/ │ │ └── java/ │ │ └── Huffman.java │ ├── insertion_sort/ │ │ ├── ada/ │ │ │ └── insertion_sort.adb │ │ ├── c/ │ │ │ └── InsertionSort.c │ │ ├── cpp/ │ │ │ └── insertion_sort.cpp │ │ ├── crystal/ │ │ │ └── insertion_sort.cr │ │ ├── java/ │ │ │ └── InsertionSort.java │ │ ├── javascript/ │ │ │ ├── insertionSort.js │ │ │ └── insertion_sort.js │ │ ├── python/ │ │ │ └── insertionsort.py3 │ │ └── ruby/ │ │ └── insertion_sort.rb │ ├── inversion_count/ │ │ └── cpp/ │ │ └── inversion_count.cpp │ ├── jarvis/ │ │ └── cpp/ │ │ └── jarvis.cpp │ ├── johnson_algorithm/ │ │ └── cpp/ │ │ └── johnson_algorithm.cpp │ ├── kmp_search/ │ │ ├── cpp/ │ │ │ └── KMPSearch.cpp │ │ ├── java/ │ │ │ └── KMPSearch.java │ │ └── python/ │ │ └── KMPSearch.py │ ├── linear_search/ │ │ ├── c/ │ │ │ └── linearsearch.C │ │ ├── cpp/ │ │ │ └── linearSearch.cpp │ │ ├── java/ │ │ │ └── LinearSearch.java │ │ ├── javascript/ │ │ │ └── linear_search.js │ │ └── python/ │ │ └── linear_search.py │ ├── longest_common_subsequence/ │ │ ├── cpp/ │ │ │ └── LongestCommonSubsequence.cpp │ │ ├── javaj/ │ │ │ └── LCS.java │ │ ├── javascript/ │ │ │ └── longest_common_subsequence.js │ │ └── python/ │ │ └── LCS.py │ ├── longest_common_substring/ │ │ └── java/ │ │ └── LongestCommonSubString.java │ ├── matrix_chain_multiplication/ │ │ ├── cpp/ │ │ │ └── MCM.cpp │ │ ├── java/ │ │ │ └── MCM.java │ │ └── python/ │ │ └── MCM.py │ ├── merge_sort/ │ │ ├── c#/ │ │ │ └── MergeSort.cs │ │ ├── cpp/ │ │ │ └── merge_sort.cpp │ │ ├── haskell/ │ │ │ └── merge_sort.hs │ │ ├── java/ │ │ │ └── merge_sort.java │ │ ├── javascript/ │ │ │ └── MergeSort.js │ │ ├── python/ │ │ │ └── merge_sort.py │ │ └── ruby/ │ │ └── merge_sort.rb │ ├── minimum_spanning_tree/ │ │ └── cpp/ │ │ └── MST.cpp │ ├── optimal_binary_search_tree/ │ │ └── java/ │ │ └── OptimalBst.java │ ├── parse_tree/ │ │ └── python/ │ │ └── parse_tree.py │ ├── permutations/ │ │ ├── java/ │ │ │ └── Permutation.java │ │ └── javascript/ │ │ └── permutations.js │ ├── quick_sort/ │ │ ├── ada/ │ │ │ └── quick_sort.adb │ │ ├── c/ │ │ │ └── quick_sort.c │ │ ├── cpp/ │ │ │ └── quickSort.cpp │ │ ├── csharp/ │ │ │ ├── QuickSort.cs │ │ │ └── quicksort.cs │ │ ├── haskell/ │ │ │ └── quicksort.hs │ │ ├── java/ │ │ │ └── QuickSort.java │ │ ├── javascript/ │ │ │ └── quick_sort.js │ │ ├── kotlin/ │ │ │ └── quicksort.kt │ │ ├── python/ │ │ │ └── quicksort.py │ │ └── ruby/ │ │ └── quick_sort.rb │ ├── rabin_karp/ │ │ └── java/ │ │ └── RabinKarp.java │ ├── radixsort/ │ │ ├── c++/ │ │ │ └── radixsort.cpp │ │ └── python/ │ │ └── lsd_radixsort.py │ ├── selection_sort/ │ │ ├── c/ │ │ │ └── SelectionSort.c │ │ ├── crystal/ │ │ │ └── selection_sort.cr │ │ ├── java/ │ │ │ └── SelectionSort.java │ │ ├── javascript/ │ │ │ └── selection_sort.js │ │ ├── python/ │ │ │ └── selection_sort.py │ │ └── ruby/ │ │ └── selection_sort.rb │ ├── shell_sort/ │ │ ├── C/ │ │ │ └── ShellSort.c │ │ ├── C++/ │ │ │ └── ShellSort.cpp │ │ ├── Java/ │ │ │ └── ShellSort.java │ │ └── python/ │ │ └── shellsort.py │ ├── sieve_of_eratosthenes/ │ │ ├── cpp/ │ │ │ └── sieve_of_eratosthenes.cpp │ │ ├── java/ │ │ │ └── sieve.java │ │ ├── javascript/ │ │ │ └── sieve.js │ │ └── python/ │ │ └── sieve.py │ ├── sort/ │ │ └── heap_sort/ │ │ └── java/ │ │ └── heap_sort.java │ ├── strings/ │ │ └── cpp/ │ │ └── anagrams.cpp │ └── tower_of_hanoi/ │ ├── cpp/ │ │ └── tower_of_hanoi.cpp │ ├── java/ │ │ └── towers_of_hanoi.java │ ├── javascript/ │ │ └── tower_of_hanoi.js │ ├── php/ │ │ └── towers_of_hanoi.php │ └── python/ │ └── tower_of_hanoi.py ├── data_structures/ │ ├── arraylist/ │ │ └── java/ │ │ └── arraylist.java │ ├── avl_tree/ │ │ ├── java/ │ │ │ └── AVL.java │ │ └── javascript/ │ │ └── avl.js │ ├── bag/ │ │ └── java/ │ │ └── Bag.java │ ├── binary_search_tree/ │ │ ├── binary_search_tree.md │ │ ├── c/ │ │ │ └── BSTtraversal.c │ │ ├── cpp/ │ │ │ └── BST.h │ │ ├── java/ │ │ │ ├── binary_search_tree.java │ │ │ └── bst_operations/ │ │ │ ├── CheckBST.java │ │ │ ├── CorrectBST.java │ │ │ ├── FindAncestor.java │ │ │ ├── InorderSuccessor.java │ │ │ ├── LargestBST.java │ │ │ ├── LevelOrder.java │ │ │ ├── MorrisTraversal.java │ │ │ ├── Node.java │ │ │ └── PathFromRootToNode.java │ │ ├── javascript/ │ │ │ ├── binary_tree.js │ │ │ ├── binary_tree_search.js │ │ │ ├── breadth_first_search.js │ │ │ └── depth_first_search.js │ │ └── python/ │ │ ├── bst.py │ │ ├── bst1.py │ │ └── bst2.py │ ├── binary_tree/ │ │ ├── c/ │ │ │ └── diameterBT.c │ │ ├── cpp/ │ │ │ ├── binary_tree.cpp │ │ │ └── boundaryTraversal.cpp │ │ ├── csharp/ │ │ │ └── BinaryTree.cs │ │ ├── java/ │ │ │ ├── binary_tree_bfs.java │ │ │ └── binary_tree_dfs.java │ │ └── python/ │ │ └── binary_tree.py │ ├── bloom_filter/ │ │ └── python/ │ │ └── bloom_filter.py │ ├── circular_queue/ │ │ ├── circular_queue.md │ │ ├── cpp/ │ │ │ └── circular queue.cpp │ │ ├── java/ │ │ │ └── circular_queue.java │ │ └── python/ │ │ └── circular_queue.py │ ├── d_heap/ │ │ └── c/ │ │ └── d_heap.c │ ├── dimaeter_of_a_tree/ │ │ ├── cpp/ │ │ │ └── Diameter.cpp │ │ ├── diameter_of_a_tree.md │ │ └── java/ │ │ └── Diameter.java │ ├── double_linked_list/ │ │ └── cpp/ │ │ └── doublelinkedlist.cpp │ ├── doubly_linked_list/ │ │ ├── java/ │ │ │ └── DoublyLinkedList.java │ │ └── python/ │ │ └── DoublyLinkedList.py │ ├── generic_tree/ │ │ └── java/ │ │ └── gt.java │ ├── graph/ │ │ ├── cpp/ │ │ │ └── graph.cpp │ │ └── python/ │ │ └── graph.py │ ├── hash_table/ │ │ ├── cpp/ │ │ │ └── hashtable.h │ │ ├── csharp/ │ │ │ └── hash_table.cs │ │ ├── java/ │ │ │ └── Hash_table.java │ │ └── python/ │ │ └── hashTable.py │ ├── hashmap/ │ │ └── java/ │ │ └── hashmap.java │ ├── hashset/ │ │ └── java/ │ │ └── hashset.java │ ├── heap/ │ │ ├── cpp/ │ │ │ └── MinHeap.h │ │ ├── java/ │ │ │ ├── Heap.java │ │ │ └── heaps.java │ │ ├── python/ │ │ │ └── minheap.py │ │ └── ruby/ │ │ └── heap.rb │ ├── heapify_insert_extract_min/ │ │ └── cpp/ │ │ └── max-heap_functions.cpp │ ├── left_learning_red_black_tree/ │ │ ├── c/ │ │ │ └── llrb_tree.c │ │ └── java/ │ │ └── left_leaning_red_black_tree.java │ ├── linked_list/ │ │ ├── c/ │ │ │ └── linked_list.c │ │ ├── cpp/ │ │ │ ├── LinkedList.cpp │ │ │ └── singly_linked_list.cpp │ │ ├── csharp/ │ │ │ └── LinkedList.cs │ │ ├── go/ │ │ │ └── linked_list.go │ │ ├── java/ │ │ │ ├── LinkedList.java │ │ │ ├── LinkedListLinkedList.java │ │ │ └── LinkedListTest.java │ │ ├── kotlin/ │ │ │ └── LinkedList.kt │ │ ├── linked_list.md │ │ ├── python/ │ │ │ └── linked_list.py │ │ └── ruby/ │ │ └── linked_list.rb │ ├── linked_list_queue/ │ │ └── cpp/ │ │ └── queue_linked_list.cpp │ ├── min_heap/ │ │ └── cpp/ │ │ ├── impl_minHeap.cpp │ │ ├── minHeap.cpp │ │ └── minHeap.hpp │ ├── mirror_of_a_tree.java/ │ │ └── java/ │ │ └── Mirror.java │ ├── mirrot_of_a_tree.cpp/ │ │ └── mirror.cpp │ ├── mst/ │ │ ├── cpp/ │ │ │ └── mst.cpp │ │ └── java/ │ │ └── prims.java │ ├── priority_queue/ │ │ └── c/ │ │ └── priority_queue.cpp │ ├── queue/ │ │ ├── c/ │ │ │ └── queue.c │ │ ├── cpp/ │ │ │ ├── Queue.cpp │ │ │ └── Queue.h │ │ ├── csharp/ │ │ │ └── Queue.cs │ │ ├── go/ │ │ │ └── queue.go │ │ ├── java/ │ │ │ └── IterableQueue.java │ │ ├── javascript/ │ │ │ ├── queue_ES5.js │ │ │ └── queue_ES6.js │ │ ├── kotlin/ │ │ │ └── IterableQueue.kt │ │ ├── php/ │ │ │ └── queue.php │ │ ├── python/ │ │ │ └── queue_two_stacks.py │ │ └── ruby/ │ │ └── queue.rb │ ├── simple_queue/ │ │ ├── java/ │ │ │ ├── QueueImplementation.java │ │ │ ├── arrayQueue.java │ │ │ └── queue.java │ │ ├── python/ │ │ │ └── queue.py │ │ └── simple_queue.md │ ├── stack/ │ │ ├── c/ │ │ │ └── stack1.c │ │ ├── c#/ │ │ │ ├── main.cs │ │ │ └── stack.cs │ │ ├── cpp/ │ │ │ ├── celement.h │ │ │ ├── cstack.cpp │ │ │ ├── cstack.h │ │ │ ├── cstack.test.cpp │ │ │ ├── stack_balanced_paranthesis.cpp │ │ │ ├── templated_stack.cpp │ │ │ └── templated_stack.hpp │ │ ├── crystal/ │ │ │ └── stack.cr │ │ ├── csharp/ │ │ │ └── Stack.cs │ │ ├── go/ │ │ │ └── stack.go │ │ ├── java/ │ │ │ ├── Node.java │ │ │ ├── Stack.java │ │ │ └── integer_stack.java │ │ ├── javascript/ │ │ │ ├── stack.js │ │ │ └── usingstack.js │ │ ├── lisp/ │ │ │ ├── Stack.bak │ │ │ └── Stack.rkt │ │ ├── php/ │ │ │ └── stack.php │ │ ├── python/ │ │ │ └── stack.py │ │ └── ruby/ │ │ └── stack.rb │ ├── treemap/ │ │ └── java/ │ │ └── treemap.java │ ├── treeset/ │ │ └── java/ │ │ └── treeset.java │ ├── trie/ │ │ ├── Trie.md │ │ ├── java/ │ │ │ └── Trie.java │ │ └── javascript/ │ │ └── Trie.js │ └── union_find/ │ ├── cpp/ │ │ └── UnionFind.cpp │ ├── java/ │ │ └── UnionFind.java │ ├── python/ │ │ └── UnionFind.py │ └── union_find.md ├── design_patterns/ │ └── behavioral/ │ └── javascript/ │ ├── mediator-example.js │ └── mediator.js └── package.json ================================================ FILE CONTENTS ================================================ ================================================ FILE: .gitignore ================================================ *.out javascript/node_modules .idea ================================================ FILE: .vscode/settings.json ================================================ { "files.associations": { "vector": "cpp" } } ================================================ FILE: CONTRIBUTING.md ================================================ # Contributing to this repo **Implementing new File/Directory Structure** * Try to keep things as modular as possible, the new file/directory structure should be: ``` /data_structures/structure/language/file ex: /data_structures/char_stack/cpp/cstack.cpp /algorithms/algorithm/language/file ex: /algorithms/bubble_sort/cpp/bubble_sort.cpp ``` ## How To: 1. `git clone https://github.com/bareinhard/Hacktoberfest-Data-Structure-and-Algorithms` 2. `git checkout -b ` 3. Code your files in the proper directory based on the instructions above 4. add all your files `git add your/directory/path/to/file/` (see new directory structure above) 5. commit your file changes `git commit -m "Whatever you did here, e.g. created linkedlist class in C++"` 6. push your changes `git push origin ` 7. Create a Pull Request to master ### Alternate via Web 1. Fork Repo on Web Page 2. Make your changes on your forked repo 3. Make Pull Request to master ================================================ FILE: LICENSE ================================================ GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. {one line to give the program's name and a brief idea of what it does.} Copyright (C) {year} {name of author} This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: {project} Copyright (C) {year} {fullname} This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read . ================================================ FILE: README.md ================================================ # Hacktoberfest-Data-Structure-and-Algorithms A repository containing data structures and algorithms, regardless of language. No longer active ***Not Affiliated with Digital Ocean or Hacktoberfest*** ![Hacktoberfest](https://pbs.twimg.com/media/Dn4njsBXkAEQWZs.jpg) # CONTRIBUTING! # Contributing to this repo **Implementing new File/Directory Structure** * Try to keep things as modular as possible, the new file/directory structure should be: ``` /data_structures/structure/language/file ex: /data_structures/char_stack/cpp/cstack.cpp /algorithms/algorithm/language/file ex: /algorithms/bubble_sort/cpp/bubble_sort.cpp ``` ## How To: 1. Fork Repo on Web Page 2. `git clone https://github.com/{your-username}/Hacktoberfest-Data-Structure-and-Algorithms` 3. Code your files in the proper directory based on the instructions above 4. add all your files `git add your/directory/path/to/file/` (see new directory structure above) 5. commit your file changes `git commit -m "Whatever you did here, e.g. created linkedlist class in C++"` 6. push your changes `git push` 7. Create a Pull Request to master on Web Page ### Alternate via Web 1. Fork Repo on Web Page 2. Make your changes on your forked repo 3. Make Pull Request to master #### Credits Logo created with: http://logomakr.com ================================================ FILE: algorithms/EuclideanAlgorithm/c/euclid.c ================================================ #include int gcd(int x, int y){ if(x == 0) return y; return gcd(y % x, x); } void main(){ int hcf, a, b; printf("Enter the 2 numbers: "); scanf("%d%d",&a, &b); hcf = gcd(a, b); printf("The HCF is: %d\n",hcf); } ================================================ FILE: algorithms/EuclideanAlgorithm/python/euclideanAlgorithm.py ================================================ def euclidean(a,b):#for natural numbers a,b #sanitize the inputs a=int(a) b=int(b) if(not(a and b)):#if either are 0 return(0) if(b>a):#to have it so a>=b temp=a a=b b=temp while(1): remainder=a%b a=b b=remainder if(b==0): return(a) ================================================ FILE: algorithms/Graph/connected_components_in_undirected_graph/python/ConnectedComponents.py ================================================ ''' Question source -- LeetCode Given n nodes labeled from 0 to n - 1 and a list of undirected edges (where each edge is a pair of nodes), write a function to find the number of connected components in an undirected graph. ''' def countComponents( n, edges): """ :type n: int :type edges: List[List[int]] :rtype: int """ # finds the path recursively def find(data, i): if i != data[i]: data[i] = find(data, data[i]) return data[i] # creates the union find data structure def union(data, i, j): root_i, root_j = find(data, i), find(data, j) if root_i != root_j: data[root_i] = root_j data = [i for i in range(n)] for i,j in edges: union(data, i, j) # set data structure to eliminate the possibilities of duplicates. res = set() # union-find the roots of the each nodes in the components. for i in range(n): res.add(find(data,i)) # the total length of the root nodes determine the total number of components. return len(res) print(countComponents(5, [[0, 1], [1, 2], [3, 4]])) ================================================ FILE: algorithms/a_search/cpp/a_star.cpp ================================================ // A C++ Program to implement A* Search Algorithm #include using namespace std; #define ROW 9 #define COL 10 // Creating a shortcut for int, int pair type typedef pair Pair; // Creating a shortcut for pair> type typedef pair> pPair; // A structure to hold the neccesary parameters struct cell { // Row and Column index of its parent // Note that 0 <= i <= ROW-1 & 0 <= j <= COL-1 int parent_i, parent_j; // f = g + h double f, g, h; }; // A Utility Function to check whether given cell (row, col) // is a valid cell or not. bool isValid(int row, int col) { // Returns true if row number and column number // is in range return (row >= 0) && (row < ROW) && (col >= 0) && (col < COL); } // A Utility Function to check whether the given cell is // blocked or not bool isUnBlocked(int grid[][COL], int row, int col) { // Returns true if the cell is not blocked else false if (grid[row][col] == 1) return (true); else return (false); } // A Utility Function to check whether destination cell has // been reached or not bool isDestination(int row, int col, Pair dest) { if (row == dest.first && col == dest.second) return (true); else return (false); } // A Utility Function to calculate the 'h' heuristics. double calculateHValue(int row, int col, Pair dest) { // Return using the distance formula return ((double)sqrt ((row-dest.first)*(row-dest.first) + (col-dest.second)*(col-dest.second))); } // A Utility Function to trace the path from the source // to destination 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; } // A Function to find the shortest path between // a given source cell to a destination cell according // to A* Search Algorithm 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 the destination cell is the same as source cell if (isDestination(src.first, src.second, dest) == true) { printf ("We are already at the destination\n"); return; } // Create a closed list and initialise it to false which means // that no cell has been included yet // This closed list is implemented as a boolean 2D array bool closedList[ROW][COL]; memset(closedList, false, sizeof (closedList)); // Declare a 2D array of structure to hold the details //of that cell cell cellDetails[ROW][COL]; int i, j; for (i=0; i> where f = g + h, and i, j are the row and column index of that cell Note that 0 <= i <= ROW-1 & 0 <= j <= COL-1 This open list is implenented as a set of pair of pair.*/ set openList; // Put the starting cell on the open list and set its // 'f' as 0 openList.insert(make_pair (0.0, make_pair (i, j))); // We set this boolean value as false as initially // the destination is not reached. bool foundDest = false; while (!openList.empty()) { pPair p = *openList.begin(); // Remove this vertex from the open list openList.erase(openList.begin()); // Add this vertex to the open list i = p.second.first; j = p.second.second; closedList[i][j] = true; /* Generating all the 8 successor of this cell N.W N N.E \ | / \ | / W----Cell----E / | \ / | \ S.W S S.E Cell-->Popped Cell (i, j) N --> North (i-1, j) S --> South (i+1, j) E --> East (i, j+1) W --> West (i, j-1) N.E--> North-East (i-1, j+1) N.W--> North-West (i-1, j-1) S.E--> South-East (i+1, j+1) S.W--> South-West (i+1, j-1)*/ // To store the 'g', 'h' and 'f' of the 8 successors double gNew, hNew, fNew; //----------- 1st Successor (North) ------------ // Only process this cell if this is a valid one if (isValid(i-1, j) == true) { // If the destination cell is the same as the // current successor 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; } // 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] == false && isUnBlocked(grid, i-1, j) == true) { gNew = cellDetails[i][j].g + 1.0; hNew = calculateHValue (i-1, j, dest); fNew = gNew + hNew; // If it isn’t on the open list, add it to // the open list. Make the current square // the parent of this square. Record the // f, g, and h costs of the square cell // OR // If it is on the open list already, check // to see if this path to that square is better, // using 'f' cost as the measure. 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; } } } //----------- 2nd Successor (South) ------------ // Only process this cell if this is a valid one if (isValid(i+1, j) == true) { // If the destination cell is the same as the // current successor 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; } // 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] == false && isUnBlocked(grid, i+1, j) == true) { gNew = cellDetails[i][j].g + 1.0; hNew = calculateHValue(i+1, j, dest); fNew = gNew + hNew; // If it isn’t on the open list, add it to // the open list. Make the current square // the parent of this square. Record the // f, g, and h costs of the square cell // OR // If it is on the open list already, check // to see if this path to that square is better, // using 'f' cost as the measure. 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; } } } //----------- 3rd Successor (East) ------------ // Only process this cell if this is a valid one 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; } // 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][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 it isn’t on the open list, add it to // the open list. Make the current square // the parent of this square. Record the // f, g, and h costs of the square cell // OR // If it is on the open list already, check // to see if this path to that square is better, // using 'f' cost as the measure. 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; } } } //----------- 4th Successor (West) ------------ // Only process this cell if this is a valid one 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; } // 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][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 it isn’t on the open list, add it to // the open list. Make the current square // the parent of this square. Record the // f, g, and h costs of the square cell // OR // If it is on the open list already, check // to see if this path to that square is better, // using 'f' cost as the measure. 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 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 it isn’t on the open list, add it to // the open list. Make the current square // the parent of this square. Record the // f, g, and h costs of the square cell // OR // If it is on the open list already, check // to see if this path to that square is better, // using 'f' cost as the measure. 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; } } } //----------- 6th Successor (North-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 it isn’t on the open list, add it to // the open list. Make the current square // the parent of this square. Record the // f, g, and h costs of the square cell // OR // If it is on the open list already, check // to see if this path to that square is better, // using 'f' cost as the measure. 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; } // 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 it isn’t on the open list, add it to // the open list. Make the current square // the parent of this square. Record the // f, g, and h costs of the square cell // OR // If it is on the open list already, check // to see if this path to that square is better, // using 'f' cost as the measure. 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 it isn’t on the open list, add it to // the open list. Make the current square // the parent of this square. Record the // f, g, and h costs of the square cell // OR // If it is on the open list already, check // to see if this path to that square is better, // using 'f' cost as the measure. 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; } } } } // When the destination cell is not found and the open // list is empty, then we conclude that we failed to // reach the destiantion cell. This may happen when the // there is no way to destination cell (due to blockages) 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/backtracking/c/n_queens_problem.c ================================================ /* C/C++ program to solve N Queen Problem using backtracking */ #define N 4 #include /* A utility function to print solution */ void printSolution(int board[N][N]) { for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) printf(" %d ", board[i][j]); printf("n"); } } /* A utility function to check if a queen can be placed on board[row][col]. Note that this function is called when "col" queens are already placed in columns from 0 to col -1. So we need to check only left side for attacking queens */ bool isSafe(int board[N][N], int row, int col) { int i, j; /* Check this row on left side */ for (i = 0; i < col; i++) if (board[row][i]) return false; /* Check upper diagonal on left side */ for (i=row, j=col; i>=0 && j>=0; i--, j--) if (board[i][j]) return false; /* Check lower diagonal on left side */ for (i=row, j=col; j>=0 && i= N) return true; /* Consider this column and try placing this queen in all rows one by one */ for (int i = 0; i < N; i++) { /* Check if queen can be placed on board[i][col] */ 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) ) return true; /* If placing queen in board[i][col] doesn't lead to a solution, then remove queen from board[i][col] */ board[i][col] = 0; // BACKTRACK } } /* If queen can not be place in any row in this colum col then return false */ return false; } /* This function solves the N Queen problem using Backtracking. It mainly uses solveNQUtil() to solve the problem. It returns false if queens cannot be placed, otherwise return true and prints placement of queens in the form of 1s. Please note that there may be more than one solutions, this function prints one of the feasible solutions.*/ bool solveNQ() { int board[N][N] = { {0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0} }; if ( solveNQUtil(board, 0) == false ) { printf("Solution does not exist"); return false; } printSolution(board); return true; } // driver program to test above function int main() { solveNQ(); return 0; } ================================================ FILE: algorithms/backtracking/c/rat_in_a_maze_problem.c ================================================ /* C/C++ program to solve Rat in a Maze problem using backtracking */ #include // Maze size #define N 4 bool solveMazeUtil(int maze[N][N], int x, int y, int sol[N][N]); /* A utility function to print solution matrix sol[N][N] */ void printSolution(int sol[N][N]) { for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) printf(" %d ", sol[i][j]); printf("\n"); } } /* A utility function to check if x,y is valid index for N*N maze */ bool isSafe(int maze[N][N], int x, int y) { // if (x,y outside maze) return false if(x >= 0 && x < N && y >= 0 && y < N && maze[x][y] == 1) return true; return false; } /* This function solves the Maze problem using Backtracking. It mainly uses solveMazeUtil() to solve the problem. It returns false if no path is possible, otherwise return true and prints the path in the form of 1s. Please note that there may be more than one solutions, this function prints one of the feasible solutions.*/ bool solveMaze(int maze[N][N]) { int sol[N][N] = { {0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0} }; if(solveMazeUtil(maze, 0, 0, sol) == false) { printf("Solution doesn't exist"); return false; } printSolution(sol); return true; } /* A recursive utility function to solve Maze problem */ bool solveMazeUtil(int maze[N][N], int x, int y, int sol[N][N]) { // if (x,y is goal) return true if(x == N-1 && y == N-1) { sol[x][y] = 1; return true; } // Check if maze[x][y] is valid if(isSafe(maze, x, y) == true) { // mark x,y as part of solution path sol[x][y] = 1; /* Move forward in x direction */ if (solveMazeUtil(maze, x+1, y, sol) == true) return true; /* If moving in x direction doesn't give solution then Move down in y direction */ if (solveMazeUtil(maze, x, y+1, sol) == true) return true; /* If none of the above movements work then BACKTRACK: unmark x,y as part of solution path */ sol[x][y] = 0; return false; } return false; } // driver program to test above function int main() { int maze[N][N] = { {1, 0, 0, 0}, {1, 1, 0, 1}, {0, 1, 0, 0}, {1, 1, 1, 1} }; solveMaze(maze); return 0; } ================================================ FILE: algorithms/backtracking/c/sudoku_problem.c ================================================ // A Backtracking program in C++ to solve Sudoku problem #include // UNASSIGNED is used for empty cells in sudoku grid #define UNASSIGNED 0 // N is used for size of Sudoku grid. Size will be NxN #define N 9 // This function finds an entry in grid that is still unassigned bool FindUnassignedLocation(int grid[N][N], int &row, int &col); // Checks whether it will be legal to assign num to the given row,col bool isSafe(int grid[N][N], int row, int col, int num); /* Takes a partially filled-in grid and attempts to assign values to all unassigned locations in such a way to meet the requirements for Sudoku solution (non-duplication across rows, columns, and boxes) */ bool SolveSudoku(int grid[N][N]) { int row, col; // If there is no unassigned location, we are done if (!FindUnassignedLocation(grid, row, col)) return true; // success! // consider digits 1 to 9 for (int num = 1; num <= 9; num++) { // if looks promising if (isSafe(grid, row, col, num)) { // make tentative assignment grid[row][col] = num; // return, if success, yay! if (SolveSudoku(grid)) return true; // failure, unmake & try again grid[row][col] = UNASSIGNED; } } return false; // this triggers backtracking } /* Searches the grid to find an entry that is still unassigned. If found, the reference parameters row, col will be set the location that is unassigned, and true is returned. If no unassigned entries remain, false is returned. */ 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; } /* Returns a boolean which indicates whether any assigned entry in the specified row matches the given number. */ 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; } /* Returns a boolean which indicates whether any assigned entry in the specified column matches the given number. */ 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; } /* Returns a boolean which indicates whether any assigned entry within the specified 3x3 box matches the given number. */ 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; } /* Returns a boolean which indicates whether it will be legal to assign num to the given row,col location. */ bool isSafe(int grid[N][N], int row, int col, int num) { /* Check if 'num' is not already placed in current row, current column and current 3x3 box */ return !UsedInRow(grid, row, num) && !UsedInCol(grid, col, num) && !UsedInBox(grid, row - row%3 , col - col%3, num); } /* A utility function to print grid */ void printGrid(int grid[N][N]) { for (int row = 0; row < N; row++) { for (int col = 0; col < N; col++) printf("%2d", grid[row][col]); printf("n"); } } /* Driver Program to test above functions */ int main() { // 0 means unassigned cells 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 printf("No solution exists"); return 0; } ================================================ FILE: algorithms/backtracking/c/the_knight_tour_problem.c ================================================ // C program for Knight Tour problem #include #define N 8 int solveKTUtil(int x, int y, int movei, int sol[N][N], int xMove[], int yMove[]); /* A utility function to check if i,j are valid indexes for N*N chessboard */ bool isSafe(int x, int y, int sol[N][N]) { return ( x >= 0 && x < N && y >= 0 && y < N && sol[x][y] == -1); } /* A utility function to print solution matrix sol[N][N] */ void printSolution(int sol[N][N]) { for (int x = 0; x < N; x++) { for (int y = 0; y < N; y++) printf(" %2d ", sol[x][y]); printf("\n"); } } /* This function solves the Knight Tour problem using Backtracking. This function mainly uses solveKTUtil() to solve the problem. It returns false if no complete tour is possible, otherwise return true and prints the tour. Please note that there may be more than one solutions, this function prints one of the feasible solutions. */ bool solveKT() { int sol[N][N]; /* Initialization of solution matrix */ for (int x = 0; x < N; x++) for (int y = 0; y < N; y++) sol[x][y] = -1; /* xMove[] and yMove[] define next move of Knight. xMove[] is for next value of x coordinate yMove[] is for next value of y coordinate */ int xMove[8] = { 2, 1, -1, -2, -2, -1, 1, 2 }; int yMove[8] = { 1, 2, 2, 1, -1, -2, -2, -1 }; // Since the Knight is initially at the first block sol[0][0] = 0; /* Start from 0,0 and explore all tours using solveKTUtil() */ if (solveKTUtil(0, 0, 1, sol, xMove, yMove) == false) { printf("Solution does not exist"); return false; } else printSolution(sol); return true; } /* A recursive utility function to solve Knight Tour problem */ int solveKTUtil(int x, int y, int movei, int sol[N][N], int xMove[N], int yMove[N]) { int k, next_x, next_y; if (movei == N*N) return true; /* Try all next moves from the current coordinate x, y */ for (k = 0; k < 8; k++) { next_x = x + xMove[k]; next_y = y + yMove[k]; if (isSafe(next_x, next_y, sol)) { sol[next_x][next_y] = movei; if (solveKTUtil(next_x, next_y, movei+1, sol, xMove, yMove) == true) return true; else sol[next_x][next_y] = -1;// backtracking } } return false; } /* Driver program to test above functions */ int main() { solveKT(); return 0; } ================================================ FILE: algorithms/bellman_ford/cpp/bellman_ford.cpp ================================================ /* 1. shortest path from source to vertices 2. can be used for negetive weights 3.can be used to detect neg cycle. */ #include using namespace std; #define pii pair #define mp make_pair #define INF (1<<20); pair G[1000]; int dis[1000]; int main() { int nodes,edges; cin>>nodes>>edges; for(int i=0;i>u>>v>>w; G[i]=mp(u,mp(v,w)); // v[v].push_back(mp(u,w)); for undirected; } for(int i=1;i<=nodes;i++) dis[i]=INF; dis[1]=0; for(int i=0;idis[u]+w) { dis[v]=dis[u]+w; } } } bool negc=false; for(int j=0;jdis[u]+w) { negc=true; break; } } if(negc) cout<<"negetive cycle"; else { for(int i=1;i<=nodes;i++) { cout<<"1"<<" - "< edgeList; public Graph(int v) { this.V = v; edgeList = new LinkedList(); } public void bellmanFord(int src) { if (src < 0 || src > (V - 1)) { System.out.println("Invalid starting vertex"); return; } int dist[] = new int[V]; for (int i=0; i (V - 1) || dest > (V - 1)) { return false; } Edge edge = new Edge(src, dest, weight); edgeList.add(edge); return true; } public static void main(String[] args) { int V = 5; Graph graph = new Graph(V); graph.addEdge(0, 1, -1); graph.addEdge(0, 2, 4); graph.addEdge(1, 2, 3); graph.addEdge(1, 3, 2); graph.addEdge(1, 4, 2); graph.addEdge(3, 2, 5); graph.addEdge(3, 1, 1); graph.addEdge(4, 3, -3); graph.bellmanFord(1); } } ================================================ FILE: algorithms/bfs/cpp/bfs.cpp ================================================ #import #import #import class Vertex { public: Vertex(std::string n); Vertex * prev; //predecessor Vertex *next; //for queue purposes int dist; std::string name; std::vector neighbours; }; Vertex::Vertex(std::string n) { prev = nullptr; next = nullptr; dist = -1; name = n; } class Queue{ public: Queue(Vertex *first){ head = first; tail = first; first->dist = 0; } void Enqueue(Vertex *pred_, Vertex * cur) { if(head == nullptr) { head = cur; } cur->dist = pred_->dist+1; cur->prev = pred_; tail->next = cur; tail = cur; } Vertex * Dequeue(){ Vertex *tmp = head; head = head->next; return tmp; } bool isEmpty(){ return head== nullptr; } bool isInQueue(Vertex v){ Vertex *iter = head; while(iter != nullptr) { if (iter->name == v.name) return true; iter = iter->next; } return false; } Vertex *head; Vertex *tail; }; void BFS(Vertex *root) { Queue q(root); Vertex *cur; int dist=0; root->dist = 0; while(!q.isEmpty()) { cur = q.Dequeue(); for (Vertex *v : cur->neighbours) { if (q.isInQueue(*v)) continue; cur->dist = dist; q.Enqueue(cur,v); } dist++; } } int main() { Vertex v1("v1"); Vertex v2("v2"); Vertex v3("v3"); Vertex v4("v4"); v1.neighbours.emplace_back(&v2); v1.neighbours.emplace_back(&v3); v2.neighbours.emplace_back(&v3); v3.neighbours.emplace_back(&v4); v1.neighbours.emplace_back(&v4); BFS(&v1); std::cout << v1.dist << " v2prevname" << v2.prev->name << " " << v3.dist << " " << v4.dist; return 0; } ================================================ FILE: algorithms/bfs/java/Graph.java ================================================ import java.util.*; /** * Represents a directed graph using adjacency list */ public class Graph { private int vertexNumber; private LinkedList[] adj; /** * * @param v number of vertex */ public Graph(int v) { vertexNumber = v; adj = new LinkedList[v]; for (int i = 0; i < v; ++i) adj[i] = new LinkedList(); } /** * Add edge into graph * @param v vertex * @param w vertex */ public void addEdge(int v, int w) { adj[v].add(w); } /** * Prints BFS traversal from a given source vertex * @param source source vertex */ public void BFS(int source) { boolean visited[] = new boolean[vertexNumber]; LinkedList queue = new LinkedList<>(); visited[source] = true; queue.add(source); while (queue.size() != 0) { source = queue.poll(); System.out.print(source + " "); for (Integer n : (Iterable) adj[source]) { if (!visited[n]) { visited[n] = true; queue.add(n); } } } } /** * Test * @param args */ 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); g.BFS(2); } } ================================================ FILE: algorithms/binary_search/PHP/binarysearch.php ================================================ '; print_r( $sourceArr ); echo ''; echo ( $position >= 0 ) ? 'Keyword ' . $keyword . ' is found at position: ' . $position : 'Your keyword is not found.'; ?> ================================================ FILE: algorithms/binary_search/binary_search.md ================================================ ## ELI5 **Binary Serch** is a way of searching for a thing in a list of things. The list must be sorted, that is, it must be in order of some comparable value or the it won't work. First, we go to the middle of the list and see if the item value equals to the value we want to find. Then, if our value is less/greater than the item in the middle, we work on a new list (which starts from the middle and all the way to the bottom or top) and everything on the bottom or top side. We keep doing this until we find the value we were looking for or if were fluctuating between two elements. ## Pros * It takes much less time than a reqular sequential search. * Average case of O(log n) vs O(n) for a linear search ## Cons * The list must be sorted ## Technical Explanation If we have the list `a = [45,64,68,46,70,6,46,4,6,48]` And we want to find an element if it exists in the list or not The naive solution is to go in the list element by element, ask if this is the element I'm looking for or not. The worst case is that the element is not in the list, or at the end of it, then the time Complexity it takes to end the search process is O(n); We can to do better. Here comes the **Binary Search**, Pseudocode for Binary Searching: Given an array A of n elements with values or records A0, A1, ..., An−1, sorted such that A0 ≤ A1 ≤ ... ≤ An−1, and target value T, the following subroutine uses binary search to find the index of T in A.[7] 1. Set L to 0 and R to n − 1. 2. If L > R, the search terminates as unsuccessful. 3. Set m (the position of the middle element) to the floor (the largest previous integer) of (L + R) / 2. 4. If Am < T, set L to m + 1 and go to step 2. 5. If Am > T, set R to m − 1 and go to step 2. 6. Now Am = T, the search is done; return m. ## Pros * The Time Complexity is O(log(n)) * Binary search adds a small amount of complexity for large performance gains. * Simple to write. * One of the fastest way to find elements in a list. ## Cons * The list must be sorted, which is, * The complexity can increase when the collection is not stored in a simple structure, such as a list. * The list has to be sorted. * Doesn't help in reducing the time much and adds complexity for small arrays. ================================================ FILE: algorithms/binary_search/c/binary_search.c ================================================ #include int binarySearch(int arr[], int l, int r, int key) { if (r >= l) { int mid = l + (r - l)/2; // If the element is present at the middle if (arr[mid] == key) return mid; // If element is smaller than mid, then it can only be present in left subarray else if (arr[mid] > key) return binarySearch(arr, l, mid-1, key); // Else the element can only be present in right subarray return binarySearch(arr, mid+1, r, key); } // 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 key = 10; int result = binarySearch(arr, 0, n-1, key); (result == -1) ? printf("Element is not present in array") : printf("Element is present at index %d", result); return 0; } ================================================ FILE: algorithms/binary_search/cpp/binary_search.cpp ================================================ //saru95, cruxiu :) #include /* cout and cin */ #include /* steady_clock::now */ bool binarySearchIterative(int list[], int first, int end, int item){ int middle; while(first <= end){ middle = (first + end)/2; if(list[middle] == item) { return true; } if(list[middle] < item) { first = middle + 1; } else { end = middle - 1; } } return false; } bool binarySearchRecursive(int list[], int first, int end, int item){ int middle = (first + end)/2; if(list[middle] == item){ return true; } if(first >= end){ return false; } if(list[middle] < item){ return binarySearchRecursive(list, middle+1, end, item); } else { return binarySearchRecursive(list, first, middle-1, item); } } int main(int argc, char const *argv[]){ std::cout << "Please, enter the size of the list." << std::endl; int size, value, option; bool find; std::cin >> size; int *list = new int[size]; for(int i = 0; i < size; i++){ std::cout << "Enter the element " << i << " of the list." << std::endl; std::cin >> list[i]; } std::cout << "Now, enter a value to be searched in the list." << std::endl; std::cin >> value; std::cout << "Now, would you like to use a binary search iterative (0) or a binary search recursive(1)." << std::endl; std::cin >> option; switch (option) { case 0: { auto start = std::chrono::steady_clock::now(); find = binarySearchIterative(list, 0, size-1, value); auto end = std::chrono::steady_clock::now(); auto diff = end - start; if(find) { std::cout << "You find the element using the binary search iterative." << std::endl; } else{ std::cout << "You not find the element using the binary search iterative." << std::endl; } std::cout << "And the time of search was" << std::chrono::duration (diff).count() << " ms." << std::endl; } break; case 1: { auto start = std::chrono::steady_clock::now(); find = binarySearchRecursive(list, 0, size-1, value); auto end = std::chrono::steady_clock::now(); auto diff = start - end; if(find) { std::cout << "You find the element using the binary search recursive." << std::endl; } else{ std::cout << "You not find the element using the binary search recursive." << std::endl; } std::cout << "And the time of search was" << std::chrono::duration (diff).count() << " ms." << std::endl; } break; default: std::cout << "This isn't a valid option, please restart the program." << std::endl; break; } delete[] list; return 0; } ================================================ FILE: algorithms/binary_search/java/binarysearch.java ================================================ // Java implementation of Binary Search class BinarySearch { // Returns index of x if it is present in arr[l..r], else return -1 int binarySearch(int ar[], int l, int r, int x){ if(ar.length == 0) { return -1; } if (r >= l){ int mid = l + (r - l) / 2; // If the search is present at the mid postion if (ar[mid] == x){ return mid; } // If element is smaller than mid, then it can only be in left subarray if (ar[mid] > x){ return binarySearch(ar, l, mid - 1, x); } // Else the element can only be present in right subarray return binarySearch(ar, mid + 1, r, x); } // We reach here when element is not present in array return -1; } // Main method for testing public static void main(String args[]) { BinarySearch ob = new BinarySearch(); int arr[] = {1, 4, 5, 10, 11, 27, 36, 67, 90}; int n = arr.length; int x = 10; int result = ob.binarySearch(arr, 0, n - 1, x); if (result == -1){ System.out.println("Element not present"); } else{ System.out.println("Element found at index " + result); } } } ================================================ FILE: algorithms/binary_search/javascript/binary_search.js ================================================ function binarySearch(ar, el, compare_fn) { var m = 0; var n = ar.length - 1; while (m <= n) { var k = (n + m) >> 1; var cmp = compare_fn(el, ar[k]); if (cmp > 0) { m = k + 1; } else if(cmp < 0) { n = k - 1; } else { return k; } } return -m - 1; } ================================================ FILE: algorithms/binary_search/python/binary_search.py ================================================ #Simple implementation of the binary search def b_search(a,s,start,end): target = int((start+end)/2) if start > end: return -1 if s == a[target]: return target if s > a[target]: return b_search(a,s, target+1, end) if s < a[target]: return b_search(a,s, start, target-1) #input: s = target, a = array print('Insert array (list of ints separated by a space): ') a = list(map(int, input().split())) print('Insert target: ') s = int(input()) print('Pos: ') print(b_search(a,s,0,len(a)-1)) ================================================ FILE: algorithms/binary_search/ruby/binary_search.rb ================================================ def binary_search(an_array, item) first = 0 last = an_array.length - 1 while first <= last i = (first + last) / 2 if an_array[i] == item return i elsif an_array[i] > item last = i - 1 elsif an_array[i] < item first = i + 1 else return -1 end end end arr = [0,1,2,3,4,27,5,6,7,8,9] binary_search(arr, 27) # => 5 ================================================ FILE: algorithms/bipartite_check/cpp/bipartite.cpp ================================================ #include using namespace std; int col[100]; int G[100][100]; int nodes,edges; bool bipartite(int src) { col[src]=1; queue q; q.push(src); while(!q.empty()) { int u=q.front(); q.pop(); for(int i=1;i<=nodes;i++) { if(G[u][i]==1 && col[i]==-1) { col[i]=1-col[u]; q.push(i); } else if(G[u][i]==1 && col[i]==col[u]) return false; } } return true; } int main() { cin>>nodes>>edges; for(int i=0;i<100;i++) { col[i]=-1; for(int j=0;j<100;j++) { G[i][j]=0; } } for(int i=0;i>u>>v; G[u][v]=1; G[v][u]=1; } cout< #include #define pb push_back using namespace std; int main(void) { vector v = {1,2,3}; int numSubsets = 1 << v.size(); for(int i = 0; i < numSubsets; ++i) { int pos = v.size() - 1; int subsetMask = i; cout << "{ "; while(subsetMask > 0) { if(subsetMask & 1) cout << v[pos] << " "; subsetMask >>= 1; pos--; } cout << "}\n"; } return 0; } ================================================ FILE: algorithms/bitwise/java/AddTwoNumbersWithoutPlusOperator.java ================================================ public class AddTwoNumbersWithoutPlusOperator { public static void main(String[] args) { int a = 10; int b = 90; add(a, b); } private static void add(int a, int b) { int carry; while (b != 0) { carry = a & b; a = a ^ b; b = carry << 1; } System.out.println("The sum " + a); } } ================================================ FILE: algorithms/bitwise/java/BinaryPalidrome.java ================================================ public class BinaryPalidrome { // check if binary representation of a number is palidrome public static void main(String[] args) { int n = 153; if (new BinaryPalidrome().isPalidrome(n)) { System.out.println("Yes, the binary representation of the number " + n + " is palidrome."); } else { System.out.println("No, the binary representation of the number " + n + " is not a palidrome."); } } private boolean isPalidrome(int n) { int m = getTotalBits(n) - 1; int i = 0; while (i <= m) { if (kthBit(n, i) != kthBit(n, m)) { return false; } i++; m--; } return true; } private int kthBit(int n, int kthBit) { return (n & 1 << kthBit) > 0 ? 1 : 0; } private int getTotalBits(int n) { int totalBits = 0; while (n != 0) { totalBits++; n = n >> 1; } return totalBits; } } ================================================ FILE: algorithms/bitwise/java/NegateANumberWithoutPlusOperator.java ================================================ public class NegateANumberWithoutPlusOperator { public static void main(String[] args) { NegateANumberWithoutPlusOperator number = new NegateANumberWithoutPlusOperator(); int n = 54; System.out.println("Negation of number " + n + " is " + number.negate(n)); } private int negate(int n) { n = ~n; return add(n, 1); } private int add(int a, int b) { int carry; while (b != 0) { carry = a & b; a = a ^ b; b = carry << 1; } return a; } } ================================================ FILE: algorithms/bitwise/java/Optimized_permutation ================================================ //Initial values int x = 0; int y = 1; //Optimzed permutation: x = x ^ y; y = x ^ y; x = x ^ y; //Yields: x = 1 and y = 0 ================================================ FILE: algorithms/bitwise/java/Subsets.java ================================================ /** * Subsets of a set: * input: array of size of n elements * output: 2^n subsets */ public class Subsets { public static void main(String[] args) { char[] array = {'a', 'b', 'c'}; Subsets set = new Subsets(); set.printSubsets(array); } private void printSubsets(char[] set) { int n = set.length; int totalSubsets = 1 << n; for (int i = 0; i < totalSubsets; i++) { System.out.print("{ "); for (int j = 0; j < n; j++) { if ((i & (1 << j)) > 0) { System.out.print(set[j] + " "); } } System.out.println(" }"); } } } ================================================ FILE: algorithms/bogo_sort/java/BogoSort.java ================================================ import java.util.Arrays; import java.util.List; import java.util.Collections; public class BogoSort { public static List bogoSort(List nums) { if (isSorted(nums)) { return nums; } for (;;) { Collections.shuffle(nums); if (isSorted(nums)) { break; } } return nums; } public static boolean isSorted(List x) { for (int i = 0; i < x.size() - 1; i++) { if (x.get(i) > x.get(i + 1)) { return false; } } return true; } } ================================================ FILE: algorithms/bogo_sort/python/bogo.py ================================================ from random import * seed() x = [] for i in range(0, 10): x.append(randint(0, 100)) def inorder(x): i = 0 j = len(x) while i + 1 < j: if x[i] > x[i + 1]: return False i += 1 return True def bogo(x): while not inorder(x): shuffle(x) return x ================================================ FILE: algorithms/bogo_sort/ruby/bogo_sort.rb ================================================ def bogosort(arr) arr.shuffle! while !arr.each_cons(2).all? do |x, y| x <= y end end array = [ 0, 5, 4, 3, 2, 8, 7, 1, 9, 6] bogosort(array) puts array # => 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ================================================ FILE: algorithms/breadth_first_search/cpp/bfs.cpp ================================================ #include #include using namespace std; // This class represents a directed graph using adjacency list representation class Graph { int V; // No. of vertices list *adj; // Pointer to an array containing adjacency lists public: Graph(int V); // Constructor void addEdge(int v, int w); // function to add an edge to graph void BFS(int s); // prints BFS traversal from a given source 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); } } } } 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); cout << "Following is Breadth First Traversal " << "(starting from vertex 2) n"; g.BFS(2); return 0; } ================================================ FILE: algorithms/bubble_sort/README.md ================================================ # Bubble Sort This folder contains examples of the bubble sort algorithm in the following programming languages: * bash * C * C++ * Crystal * C# * Elixir * Go * Haskell * Java * JavaScript * Kotlin * Objective-C * Power Shell * Python * Ruby * Swift * Visual Basic ================================================ FILE: algorithms/bubble_sort/assembly_mips/bubble_sort.asm ================================================ ## Data declaration section .data # these are globals # array of word long ints myarray: .word 23, 4, 34, 55, 87, 24, 99, 12, 233, 45, 43245, 23, 45, 68, 69 mysize: .word 15 .text ## Assembly language instructions go in text segment j main # very first, goto main. bubblesort: # inputs: # ra must be set before calling this and contain the location to where this will return after execution # a0 must be the base address of the array of integers to print # a1 must be the size of the array to print (or the number of elements in the array to print) # outputs: only output is the system "display", no return values # saved registers: no need as this internally only uses t registers # # internal register uses # t0 = address of base of myarray from input $a0 # t1 = value of mysize from input $a1 # t2 is used to put address, once calculated of array[index] # t3 is used to put address, once calculated of array[index + 1] # t4 is used to put the value of array[index] # t5 is used to put the value of array[index + 1] # t6 bool hold comparison result between t2 and t3 # t7 bool hasChanged. Keep track of if changes have been made in array # t8 is used to hold comparison result # t9 = index into array add $t0 $0 $a0 # move a0 to t0 via an add statement move $t1 $a1 # move a1 to t1 via the move command # either of the above commands work. Before you choose, look at the # assembled version of each command ################################################################################# #print array (unsorted) add $t9 $0 $0 # initialize the counter before the loop printunsorted: #do stuff sll $t2 $t9 2 # multiply index by 4 add $t2 $t0 $t2 # add base address of array to 4*index lw $a0 0($t2) # put value of myarray[index] into a0 li $v0, 1 # load instruction 1 (print an int whose value is in a0) syscall li $v0, 11 #load instruction 11 (print single char whose value is in a0) addi $a0, $0, 0x20 #load ascii char 32 = 0x20 = 'space' syscall addi $t9 $t9 1 # increment counter slt $t8 $t9 $t1 # compare counter t9 to size t1 bne $t8 $0 printunsorted # loop if $t9 < size #end printsorted li $v0, 11 #load instruction 11 (print single char whose value is in a0) addi $a0, $0, 0x0A #load ascii char 32 = 0x0A = 'new line' syscall ################################################################################# addi $t1 $t1 -1 #loop for (size - 1) outer: move $t7 $0 # set default value of register inside beginning of outer do-while loop add $t9 $0 $0 # initialize the counter before the loop inner: #do stuff sll $t2 $t9 2 # multiply index by 4 add $t2 $t0 $t2 # add base address of array to 4*index addi $t3 $t2 4 #place address of myarray[index + 1] in t3 lw $t4 0($t2) # put value of myarray[index] into t2 ### change from lw $a0 0($t2) # put value of myarray[index] into t2 #which is used to be able to call print syscall, which uses $a0 lw $t5 0($t3) #put value of myarray[index + 1] into t3 slt $t6 $t5 $t4 #compare myarray[index + 1] < myarray[index] beq $t6 $0 noswap # don't swap if in correct relative location #swap sw $t5 0($t2) # myarray[index] = myarray[index + 1] sw $t4 0($t3) # myarray[index + 1] = myarray[index] (value before swap) addi $t7 $t7 1 # set default value of register inside beginning of outer do-while loop noswap:#skipped past swap operations addi $t9 $t9 1 # increment counter slt $t8 $t9 $t1 # compare counter t9 to size t1 bne $t8 $0 inner # loop if $t9 < size #end inner bne $t7 $0 outer # loop if $t0 != 0 (hasChanged) #end outer ################################################################################# addi $t1 $t1 1 #reset size of loop counter #print array (sorted) add $t9 $0 $0 # initialize the counter before the loop printsorted: #do stuff sll $t2 $t9 2 # multiply index by 4 add $t2 $t0 $t2 # add base address of array to 4*index move $a3 $a0 lw $a0 0($t2) # put value of myarray[index] into a0 li $v0, 1 # load instruction 1 (print an int whose value is in a0) syscall li $v0, 11 #load instruction 11 (print single char whose value is in a0) addi $a0, $0, 0x20 #load ascii char 32 = 0x20 = 'space' syscall addi $t9 $t9 1 # increment counter slt $t8 $t9 $t1 # compare counter t9 to size t1 bne $t8 $0 printsorted # loop if $t9 < size ################################################################################# jr $ra #leave function main: ## Start of code section la $a0 myarray lw $a1 mysize jal bubblesort # jump to bubblesort and put current address in $ra so that it can come # back (ie return to here after function call) leave: li $v0, 10 # load system instruction 10 (terminate program) into v0 register syscall ================================================ FILE: algorithms/bubble_sort/bash/bubblesort.sh ================================================ #!/bin/bash echo "enter maximum number" read n echo "enter Numbers in array:" for (( i = 0; i < $n; i++ )) do read nos[$i] done for (( i = 0; i < $n ; i++ )) do for (( j = $i; j < $n; j++ )) do if [ ${nos[$i]} -gt ${nos[$j]} ]; then t=${nos[$i]} nos[$i]=${nos[$j]} nos[$j]=$t fi done done # Printing the sorted number echo -e "\nSorted Numbers " for (( i=0; i < $n; i++ )) do echo ${nos[$i]} done ================================================ FILE: algorithms/bubble_sort/c/bubble_sort.c ================================================ //algorithm of bubble sort in c //start from the first elemnent /*1. start comparing it with the next element 2. swap the element with the first smaller element it encounters. 3. every traversal pushes the largest element towards the end. */ 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() { int i,j,k; int a[5]; for(i=0;i<5;i++) scanf("%d",&a[i]); bubblesort(a,5); for(i=0;i<5;i++) printf("%d\n",a[i]); return 0; } ================================================ FILE: algorithms/bubble_sort/cpp/bubble_sort_1.cpp ================================================ #include using namespace std; //global variables for ease of use long long int array[1000],n,temp; //function for bubble sort void bubble_sort() { for(register long long int i=0;iarray[j+1]) { temp=array[j]; array[j]=array[j+1]; array[j+1]=temp; } } } } int main() { // Enter the number of elements cin>>n; //Entering the elements for(register long long int i=0;i>array[i]; } //buuble sort bubble_sort(); //Sorted order for(register long long int i=0;i #include void main() { clrscr(); int n, i, arr[50], j, temp; cout<<"Enter total number of elements :"; cin>>n; cout<<"Enter "<>arr[i]; } cout<<"Sorting array using bubble sort technique...\n"; for(i=0; i<(n-1); i++) { for(j=0; j<(n-i-1); j++) { if(arr[j]>arr[j+1]) { temp=arr[j]; arr[j]=arr[j+1]; arr[j+1]=temp; } } } cout<<"Elements sorted successfully..!!\n"; cout<<"Sorted list in ascending order :\n"; for(i=0; i array[i + 1] array[i], array[i + 1] = array[i + 1], array[i] swapped = true end i += 1 break if i == array.size - 1 end break if !swapped count += 1 break if count == array.size - 1 end array end numbers = [4, 2, 8, 1, 0, 10] puts "Unsorted: #{numbers}" puts "Sorted: #{bubbleSort(numbers)}" ================================================ FILE: algorithms/bubble_sort/csharp/BubbleSort.cs ================================================ using System; using System.Collections.Generic; public class BubbleSort { private static void Main(string[] args) { Console.WriteLine("Input the elements of the array"); var isNumber = true; var userInput = new List(); while (isNumber) { var input = Console.ReadLine(); if (int.TryParse(input, out var temp )) { userInput.Add(temp); } else { isNumber = false; } } Console.Write('\n'); Console.WriteLine("Array before Sorting with Bubble Sort"); foreach (var entry in userInput) { Console.Write(entry + " "); } BubbleSort(userInput); Console.Write('\n'); Console.WriteLine("Array after Sorting with Bubble Sort"); foreach (var entry in userInput) { Console.Write(entry + " "); } Console.Read(); } private static void BubbleSort(IList list) { var n = list.Count; do { var newn = 1; for (var i = 0; i < n - 1; i++) { if (list[i] <= list[i + 1]) { continue; } var temp = list[i]; list[i] = list[i + 1]; list[i + 1] = temp; newn = i + 1; } n = newn; } while (n > 1); } } ================================================ FILE: algorithms/bubble_sort/elixir/README.md ================================================ # Elixir BubbleSort A simple implementation of the bubble sort algorithm in Elixir. Example of usage: ``` iex(1)> c("bubblesort.ex") [BubbleSort] iex(2)> BubbleSort.sort(1..1_000 |> Enum.reverse) [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, ...] ``` ================================================ FILE: algorithms/bubble_sort/elixir/bubblesort.ex ================================================ defmodule BubbleSort do def sort([]), do: [] def sort(list) do round = swap(list) cond do round == list -> list true -> sort(round) end end defp swap([head | []]), do: [head] defp swap([head | [second | tail]]) do cond do head < second -> [head | swap([second | tail])] true -> [second | swap([head | tail])] end end end ================================================ FILE: algorithms/bubble_sort/go/bubble-sort-algorithm.go ================================================ package main import "fmt" func main() { var numbers []int = []int{5, 4, 2, 3, 1, 0} fmt.Println("Unsorted:", numbers) bubbleSort(numbers) fmt.Println("Sorted:", numbers) } func bubbleSort(numbers []int) { var N int = len(numbers) var i int for i = 0; i < N; i++ { sweep(numbers) } } func sweep(numbers []int) { var N int = len(numbers) var firstIndex int = 0 var secondIndex int = 1 for secondIndex < N { var firstNumber int = numbers[firstIndex] var secondNumber int = numbers[secondIndex] if firstNumber > secondNumber { numbers[firstIndex] = secondNumber numbers[secondIndex] = firstNumber } firstIndex++ secondIndex++ } } ================================================ FILE: algorithms/bubble_sort/haskell/bubble_sort.hs ================================================ import Debug.Trace main :: IO() main = do let sorted = bubbleSort [6, 5, 3, 1, 8, 7, 2, 4] :: [Integer] print sorted bubbleSort :: (Ord a, Show a) => [a] -> [a] --bubbleSort lst | trace ("sorting: " ++ show lst) False = undefined bubbleSort [] = [] bubbleSort [x] = [x] bubbleSort (x:y:rest) = bubbleSort (init bubbled) ++ [last bubbled] where (first, second) = if x > y then (y,x) else (x,y) bubbled = first : bubbleSort (second:rest) ================================================ FILE: algorithms/bubble_sort/java/BubbleSortExample.java ================================================ import java.util.Scanner; public class BubbleSortExample { private static void bubbleSort(int[] arr) { int n = arr.length; int temp = 0; for(int i=0; i < n; i++){ for(int j=1; j < (n-i); j++){ if(arr[j-1] > arr[j]){ //swap elements temp = arr[j-1]; arr[j-1] = arr[j]; arr[j] = temp; } } } } public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.println("Input the size of array"); int n = in.nextInt(); int[] arr = new int[n]; System.out.println("Input the elements of array"); for(int i=0; i> void bubble_sort(T array[]){ boolean swapped; int indexOfLastUnsortedElement = array.length; do{ swapped = false; for(int i=0; i < indexOfLastUnsortedElement - 1; i++){ if(array[i].compareTo(array[i+1]) > 0){ swap(i, array); swapped = true; } } indexOfLastUnsortedElement--; printArray(array); }while(swapped); } private static void swap(int index, T[] array){ T temp = array[index]; array[index] = array[index + 1]; array[index + 1] = temp; } private static void printArray(T[] input){ for(int i = 0; i < input.length; i++){ System.out.print(input[i] + " "); } System.out.print("\n"); } public static void main(String[] args){ bubble_sort(new Integer[] {4, 2, 9, 6, 23, 12, 34, 0, 1}); bubble_sort(new String[] { "c", "a", "e", "d", "b" }); } } ================================================ FILE: algorithms/bubble_sort/javascript/bubble-sort.js ================================================ function bubbleSort(a) { let swapped; do { swapped = false; for (let i=0; i < a.length-1; i++) { if (a[i] > a[i+1]) { let temp = a[i]; a[i] = a[i+1]; a[i+1] = temp; swapped = true; } } } while (swapped); return a; } ================================================ FILE: algorithms/bubble_sort/javascript/bubbleSort.js ================================================ function bubbleSort(array) { let len = array.length; let temp; for (let i = 0; i < len; i++) { for (let j = 0; j < len; j++) { if (array[i] < array[j]) { temp = array[i]; array[i] = array[j]; array[j] = temp; } } } } // export default bubbleSort; module.exports = bubbleSort; ================================================ FILE: algorithms/bubble_sort/javascript/main_bs.js ================================================ let bubbleSort = require('./bubbleSort'); // import bubbleSort from './bubbleSort'; let rl = require('readline'); // import rl from 'readline'; // allow input through console let prompt = rl.createInterface(process.stdin, process.stdout); let array = []; let flag = true; console.log('Enter all the values. Press q to stop input'); function readInput() { prompt.question('>>', function(inp) { if (inp == 'q') { console.log('initial array: ', array); bubbleSort(array); console.log('final array: ', array); return prompt.close(); } array.push(Number(inp)); readInput(); }); } readInput(); ================================================ FILE: algorithms/bubble_sort/kotlin/bubblesort.kt ================================================ public class bubbleSort : Algorithm{ public override fun sort(arr: Array): Array { var swappedElements : Boolean; do { swappedElem = false; for (i in 0..arr.size - 2){ if (arr[i] > arr[i + 1]){ swap(arr, i, i + 1); swappedElem = true; } } } while (swappedElem); return arr; } public override fun getName(): String { return "BubbleSort Algorithm"; } } ================================================ FILE: algorithms/bubble_sort/objetive-c/BubbleSort.m ================================================ - (NSArray *)bubbleSort:(NSArray *)unsortedArray { //create mutable copy of the array NSMutableArray *unsortedMutableArray = [unsortedArray mutableCopy]; for (int i = 0; i < unsortedMutableArray.count; ++i) { for (int j = 0; j < (unsortedMutableArray.count - i - 1); ++j) { //reading integer values of the current and the next elements in the array NSInteger currElement = [unsortedMutableArray[j] integerValue]; NSInteger nextElement = [unsortedMutableArray[j + 1] integerValue]; //comparing the elements if (currElement > nextElement) { NSNumber *temp = unsortedMutableArray[j]; //keeping the current element in a temp //swapping the elements unsortedMutableArray[j] = unsortedMutableArray[j + 1]; unsortedMutableArray[j + 1] = temp; } } } //return the sorted array return [NSArray arrayWithArray:unsortedMutableArray]; } ================================================ FILE: algorithms/bubble_sort/perl/BubbleSort.pl ================================================ my @array = ( 5, 6, 3, 1, 7, 3, 2, 9, 10, 4 ); for my $x ( reverse 1 .. $#array ) { for my $y ( 0 .. $x - 1 ) { @array[ $y, $y + 1 ] = @array[ $y + 1, $y ] if $array[$y] > $array[ $y + 1 ]; } } print "@array\n"; ================================================ FILE: algorithms/bubble_sort/power_shell/bubble_sort.ps1 ================================================ function bubblesort ($a) { $l = $a.Length $hasChanged = $true while ($hasChanged) { $hasChanged = $false $l-- for ($i = 0; $i -lt $l; $i++) { if ($a[$i] -gt $a[$i+1]) { $a[$i], $a[$i+1] = $a[$i+1], $a[$i] $hasChanged = $true } } } } ================================================ FILE: algorithms/bubble_sort/python/bubble_sort.py ================================================ def bubbleSort(a): n = len(a) sorted = False while not sorted: sorted = True for i in range(0, n - 1): if a[i] > a[i + 1]: sorted = False a[i], a[i + 1] = a[i + 1], a[i] a = [12, 33, 1, 3, 54, 32, 78, 54, 99, 6] print(a) bubbleSort(a) print(a) ================================================ FILE: algorithms/bubble_sort/ruby/bubble_sort.rb ================================================ def bubble_sort(array) n = array.length loop do swapped = false (n-1).times do |i| next unless array[i] > array[i+1] array[i], array[i+1] = array[i+1], array[i] swapped = true end break if not swapped end array end arr = [1,4,5,2,6,7,8,3] bubble_sort(arr) # => [1, 2, 3, 4, 5, 6, 7, 8] ================================================ FILE: algorithms/bubble_sort/swift/bubble_sort.swift ================================================ func bubbleSort(unsortedArray: Array) -> Array { //mutable copy of the initial array var mutableArray = unsortedArray //double looping through the array for i in 0.. mutableArray[j + 1] as! Int) { let temp = mutableArray[j] //storing into a temp value //swapping the elements mutableArray[j] = mutableArray[j + 1] mutableArray[j + 1] = temp } } } //returning the sorted array let sortedArray = mutableArray return sortedArray } ================================================ FILE: algorithms/bubble_sort/vb/bubble_sort.bas ================================================ Option Explicit 'VB6 Specific Private Sub bubble_sort() Dim i As Integer Dim j As Integer Dim k As Integer Dim array_unsorted(1001) As String Dim array_sorted(1001) As String Dim temp As String Dim swapped As Boolean i = 1000 j = 0 Do swapped = False For j = 1 To i - 1 If LCase(array_unsorted(j)) > LCase(array_unsorted(j + 1)) Then temp = array_unsorted(j) array_unsorted(j) = array_unsorted(j + 1) array_unsorted(j + 1) = temp swapped = True End If Next j i = i - 1 Loop Until Not swapped For k = 1 To 1000 array_sorted(k) = array_unsorted(k) Next k End Sub ================================================ FILE: algorithms/bucket_sort/bucket_sort.cpp ================================================ // C++ program to sort an array using bucket sort #include #include #include using namespace std; // Function to sort arr[] of size n using bucket sort void bucketSort(float arr[], int n) { // 1) Create n empty buckets vector b[n]; // 2) Put array elements in different buckets for (int i=0; i maxValue) maxValue = sequence[i]; return maxValue; } public static void main(String args[]) { System.out .println("Sorting of randomly generated numbers using BUCKET SORT"); Random random = new Random(); int N = 20; int[] sequence = new int[N]; for (int i = 0; i < N; i++) sequence[i] = Math.abs(random.nextInt(100)); int maxValue = maxValue(sequence); System.out.println("\nOriginal Sequence: "); printSequence(sequence); System.out.println("\nSorted Sequence: "); printSequence(sort(sequence, maxValue)); } } ================================================ FILE: algorithms/bucket_sort/bucket_sort.py ================================================ def bucketsort( A ): # get hash codes code = hashing( A ) buckets = [list() for _ in range( code[1] )] # distribute data into buckets: O(n) for i in A: x = re_hashing( i, code ) buck = buckets[x] buck.append( i ) # Sort each bucket: O(n). # I mentioned above that the worst case for bucket sort is counting # sort. That's because in the worst case, bucket sort may end up # with one bucket per key. In such case, sorting each bucket would # take 1^2 = O(1). Even after allowing for some probabilistic # variance, to sort each bucket would still take 2-1/n, which is # still a constant. Hence, sorting all the buckets takes O(n). for bucket in buckets: insertionsort( bucket ) ndx = 0 # merge the buckets: O(n) for b in range( len( buckets ) ): for v in buckets[b]: A[ndx] = v ndx += 1 import math def hashing( A ): m = A[0] for i in range( 1, len( A ) ): if ( m < A[i] ): m = A[i] result = [m, int( math.sqrt( len( A ) ) )] return result def re_hashing( i, code ): return int( i / code[0] * ( code[1] - 1 ) ) ================================================ FILE: algorithms/bucket_sort/c/bucket_sort.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/caesar_cipher/java/caesar.java ================================================ /** Author : FAHRI YARDIMCI A Java implementation of Caesar Cipher. /It is a type of substitution cipher in which each letter in the plaintext is replaced by a letter some fixed number of positions down the alphabet. / **/ import java.util.Scanner; public class Caesar { public static String encode (String message,int shift) { String encoded = ""; for(int i = 0 ; i=65 && current<= 90) { int numAlphabet = message.charAt(i); if(shift + numAlphabet > 90) { int j = 90 - numAlphabet; char nextKey = (char)(65 + (shift - j - 1)); encoded += nextKey; } else { char nextKey = (char)(current + shift); encoded += nextKey; } } else if (current>=97 && current <= 122) { int numAlphabet = message.charAt(i); if(shift + numAlphabet > 122) { int j = 122 - numAlphabet; char nextKey = (char)(97 + (shift - j - 1)); encoded += nextKey; } else { char nextKey = (char)(current + shift); encoded += nextKey; } } } return encoded; } public static String decode (String message,int shift) { String decoded = ""; for(int i = 0 ; i=65 && current<= 90) { int numAlphabet = message.charAt(i); if(numAlphabet - shift < 65) { int j = numAlphabet - 65; char nextKey = (char)(90 - (shift - j - 1)); decoded += nextKey; } else { char nextKey = (char)(current - shift); decoded += nextKey; } } else if (current>=97 && current <= 122) { int numAlphabet = message.charAt(i); if(numAlphabet - shift < 97) { int j = numAlphabet - 97; char nextKey = (char)(122 - (shift - j - 1)); decoded += nextKey; } else { char nextKey = (char)(current - shift); decoded += nextKey; } } } return decoded; } public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.println("Please enter the message (Latin Alphabet)"); String message = input.nextLine(); System.out.println(message); System.out.println("Please enter the shift number"); int shift = input.nextInt() % 26; System.out.println("(E)ncode or (D)ecode ?"); char choice = input.next().charAt(0); if(choice == 'E' || choice=='e') System.out.println("ENCODED MESSAGE IS \n" + encode(message,shift)); //send our function to handle if(choice =='D' || choice =='d') System.out.println("DECODED MESSAGE IS \n" + decode(message,shift)); } } ================================================ FILE: algorithms/caesar_cipher/javascript/caesarCipher.js ================================================ const LEGAL_VALUES = 'abcdefghijklmnopqrstuvwxyz'; const START_CODE = 'a'.charCodeAt(0); const END_CODE = 'z'.charCodeAt(0); class CaesarCipher { constructor(key) { if (key === undefined) { this.generateKey(); } else { this.key = key; this.validateKey(); } } generateKey() { this.key = ''; for (let i = 0; i < 100; i++) { let randomIdx = Math.floor(Math.random() * 26); this.key += LEGAL_VALUES.charAt(randomIdx); } } validateKey() { const emptyKey = this.key.length < 1; const hasInvalidChars = this.key.split('').some(letter => { return LEGAL_VALUES.indexOf(letter) === -1; }); if (emptyKey || hasInvalidChars) { throw new Error('Bad key'); } } encode(decodedMessage) { let longKey = this.key; let encodedMessage = ""; while (longKey.length < decodedMessage.length) { longKey += longKey; } decodedMessage.split('').forEach((letter, idx) => { const currentKeyCode = longKey.charCodeAt(idx); const offset = (currentKeyCode - START_CODE); let newCharCode = letter.charCodeAt(0) + offset; if (newCharCode > END_CODE) { newCharCode -= LEGAL_VALUES.length; } encodedMessage += String.fromCharCode(newCharCode); }); return encodedMessage; } decode(encodedMessage) { let longKey = this.key; let decodedMessage = ""; while (longKey.length < encodedMessage.length) { longKey += longKey; } encodedMessage.split('').forEach((letter, idx) => { const currentKeyCode = longKey.charCodeAt(idx); const offset = (currentKeyCode - START_CODE); let newCharCode = letter.charCodeAt(0) - offset; if (newCharCode < START_CODE) { newCharCode += LEGAL_VALUES.length; } decodedMessage += String.fromCharCode(newCharCode); }); return decodedMessage; } } module.exports = CaesarCipher; ================================================ FILE: algorithms/check_pallindrome_number/c/checkPalindrome.c ================================================ #include #include int checkPall(char str[]) { for(int i = 0; i < strlen(str); i++) { if(str[i] != str[strlen(str)-i-1]) { return 0; } } return 1; } int main() { char str[10000]; gets(str); if(checkPall(str)) { printf("YES"); } else { printf("NO"); } return 0; } ================================================ FILE: algorithms/check_pallindrome_number/cpp/checkPall.cpp ================================================ #include #include #include using namespace std; int checkPall(char str[]) { for(int i = 0; i < strlen(str); i++) { if(str[i] != str[strlen(str)-i-1]) { return 0; } } return 1; } int main() { char str[10000]; cin >> str; if(checkPall(str)) { cout << "YES" << endl; } else { cout << "NO" << endl; } return 0; } ================================================ FILE: algorithms/closest/java/Closest.java ================================================ package algorithms.closest.java; import java.util.ArrayList; import java.util.Collections; import java.util.Scanner; /* This algorithm searches through a list of integers and finds the distance between the two closest element. It then prints this integer. */ public class Closest { public static void main(String[] args) { //get input Scanner sc = new Scanner(System.in).useDelimiter(" "); ArrayList input = new ArrayList<>(); //add input to ArrayList while (sc.hasNextInt()) { input.add(sc.nextInt()); } //sort the list Collections.sort(input); //initialize closest values, with the first two elements in the list int closest = input.get(1)-input.get(0); //check all elements in the list for(int i = 2; i < input.size(); i++) { //change closest if we find two elements with a shorter distance. closest = Math.min(closest, input.get(i)-input.get(i-1)); } //print the shortest distance System.out.println(closest); } } ================================================ FILE: algorithms/count_sort/javascript/count_sort.js ================================================ "use strict"; var countSort = (arr, range)=>{ /** * Consider the input is in range of 1 to 9 */ // this can vary depending on your input array let countArr = []; //Initialise count array to 0; for(let i=0; i <= range; i++){ countArr[i] = 0; } for(let i=0; i < arr.length; i++){ ++countArr[arr[i]]; } for(let i=1; i<= countArr.length-1; i++){ countArr[i] += countArr[i-1]; } //Take the sorted array and insert the data of input array based on the count array and // decrease the value by 1 every time the element is inserted in sorted array let sortedArray = new Array(arr.length -1); for(let i=0; i #include #include #include static char b64_arr[] = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/'}; int val(char x){ for (int i = 0; i < 64; ++i){ if(x == b64_arr[i]) return i; } return -1; } int main() { char *str = "TWFuIGlzIGRpc3Rpbmd1aXNoZWQsIG5vdCBvbmx5IGJ5IGhpcyByZWFzb24sIGJ1dCBieSB0aGlzIHNpbmd1bGFyIHBhc3Npb24gZnJvbSBvdGhlciBhbmltYWxzLCB3aGljaCBpcyBhIGx1c3Qgb2YgdGhlIG1pbmQsIHRoYXQgYnkgYSBwZXJzZXZlcmFuY2Ugb2YgZGVsaWdodCBpbiB0aGUgY29udGludWVkIGFuZCBpbmRlZmF0aWdhYmxlIGdlbmVyYXRpb24gb2Yga25vd2xlZGdlLCBleGNlZWRzIHRoZSBzaG9ydCB2ZWhlbWVuY2Ugb2YgYW55IGNhcm5hbCBwbGVhc3VyZS4="; int in = -1; int len = strlen(str); int outlen = (int)ceil(len/4.0)*3; char *result = (char *)malloc(sizeof(char)*outlen); for (int i = 0; i < len; i += 4) { int x = 0; if(str[i+2] != '=' && str[i+3] != '='){ x |= (val(str[i]) << 18); x |= (val(str[i+1]) << 12); x |= (val(str[i+2]) << 6); x |= (val(str[i+3])); result[++in] = (x >> 16) & (0xFF); result[++in] = (x >> 8) & (0xFF); result[++in] = (x) & (0xFF); } else if(str[i+2] != '='){ x |= (val(str[i]) << 18); x |= (val(str[i+1]) << 12); x |= (val(str[i+2]) << 6); result[++in] = (x >> 16) & (0xFF); result[++in] = (x >> 8) & (0xFF); } else{ x |= (val(str[i]) << 18); x |= (val(str[i+1]) << 12); result[++in] = (x >> 16) & (0xFF); } } if(in < outlen) result[++in] = '\0'; printf("%s\n", result); return 0; } ================================================ FILE: algorithms/dfs/cpp/dfs.cpp ================================================ #import #import #import class Vertex { public: Vertex(std::string n); bool visited; Vertex * prev; //predecessor int dist; std::string name; std::vector neighbours; }; Vertex::Vertex(std::string n) { prev = nullptr; dist = -1; name = n; } void VisitVertex(Vertex *v, Vertex * predecessor){ v->prev = predecessor; v->visited = true; for (Vertex * successor : v->neighbours) { if (!successor->visited) VisitVertex(successor,v); } } void DFS(std::vector graph){ Vertex * predecessor = nullptr; for (Vertex * v: graph ) { v->visited = false; } for (Vertex * v: graph ) { if (!v->visited) VisitVertex(v, predecessor); predecessor = v; } } int main() { //testing Vertex v1("v1"); Vertex v2("v2"); Vertex v3("v3"); Vertex v4("v4"); v1.neighbours.emplace_back(&v2); v1.neighbours.emplace_back(&v3); v4.neighbours.emplace_back(&v3); v3.neighbours.emplace_back(&v4); v1.neighbours.emplace_back(&v4); std::vector graph; graph.emplace_back(&v1); graph.emplace_back(&v2); graph.emplace_back(&v3); graph.emplace_back(&v4); DFS(graph); std::cout << "v1 prev: " << v1.prev <name <name <name < adj[]; /** * * @param v number of vertex */ Graph(int v) { vertexNumber = v; adj = new LinkedList[v]; for (int i=0; i #include // Number of vertices in the graph #define V 9 // A utility function to find the vertex with minimum distance value, from // the set of vertices not yet included in shortest path tree int minDistance(int dist[], bool sptSet[]) { // 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; } // A utility function to print the constructed distance array int printSolution(int dist[], int n) { printf("Vertex Distance from Sourcen"); for (int i = 0; i < V; i++) printf("%d tt %dn", i, dist[i]); } // Funtion that implements Dijkstra's single source shortest path algorithm // for a graph represented using adjacency matrix representation void dijkstra(int graph[V][V], int src) { int dist[V]; // The output array. dist[i] will hold the shortest // distance from src to i bool sptSet[V]; // sptSet[i] will true if vertex i is included in shortest // path tree or shortest distance from src to i is finalized // Initialize all distances as INFINITE and stpSet[] as false for (int i = 0; i < V; i++) dist[i] = INT_MAX, sptSet[i] = false; // Distance of source vertex from itself is always 0 dist[src] = 0; // Find shortest path for all vertices for (int count = 0; count < V-1; count++) { // Pick the minimum distance vertex from the set of vertices not // yet processed. u is always equal to src in first iteration. int u = minDistance(dist, sptSet); // Mark the picked vertex as processed sptSet[u] = true; // Update dist value of the adjacent vertices of the picked vertex. for (int v = 0; v < V; v++) // Update dist[v] only if is not in sptSet, there is an edge from // u to v, and total weight of path from src to v through u is // smaller than current value of dist[v] if (!sptSet[v] && graph[u][v] && dist[u] != INT_MAX && dist[u]+graph[u][v] < dist[v]) dist[v] = dist[u] + graph[u][v]; } // print the constructed distance array printSolution(dist, V); } // driver program to test above function int main() { /* Let us create the example graph discussed above */ int graph[V][V] = {{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} }; dijkstra(graph, 0); return 0; } ================================================ FILE: algorithms/dijkstra/java/ShortestPath.java ================================================ /** * A Java program for Dijkstra's single source shortest path algorithm. * The program is for adjacency matrix representation of the graph */ public class ShortestPath { private static final int vertexNumber = 9; private int minDistance(int dist[], Boolean sptSet[]) { int min = Integer.MAX_VALUE; int minIndex = -1; for (int v = 0; v < vertexNumber; v++) { if (!sptSet[v] && dist[v] <= min) { min = dist[v]; minIndex = v; } } return minIndex; } private void printSolution(int dist[]) { System.out.println("Vertex Distance from Source"); for (int i = 0; i < vertexNumber; i++) System.out.println(i + " \t\t " + dist[i]); } /** * Dijkstra's single source shortest path * * @param graph The graph represented using adjacency matrix * @param source Source vertex */ public void dijkstra(int graph[][], int source) { int dist[] = new int[vertexNumber]; Boolean sptSet[] = new Boolean[vertexNumber]; for (int i = 0; i < vertexNumber; i++) { dist[i] = Integer.MAX_VALUE; sptSet[i] = false; } dist[source] = 0; for (int count = 0; count < vertexNumber-1; count++) { int u = minDistance(dist, sptSet); sptSet[u] = true; for (int v = 0; v < vertexNumber; 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); } /** * Usage * @param args */ 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} }; ShortestPath t = new ShortestPath(); t.dijkstra(graph, 0); } } ================================================ FILE: algorithms/dijkstra/python/djikstra.py ================================================ class Graph: def __init__(self): self.nodes = set() self.edges = defaultdict(list) self.distances = {} def add_node(self, value): self.nodes.add(value) def add_edge(self, from_node, to_node, distance): self.edges[from_node].append(to_node) self.edges[to_node].append(from_node) self.distances[(from_node, to_node)] = distance def dijsktra(graph, initial): visited = {initial: 0} path = {} nodes = set(graph.nodes) while nodes: min_node = None for node in nodes: if node in visited: if min_node is None: min_node = node elif visited[node] < visited[min_node]: min_node = node if min_node is None: break nodes.remove(min_node) current_weight = visited[min_node] for edge in graph.edges[min_node]: weight = current_weight + graph.distances[(min_node, edge)] if edge not in visited or weight < visited[edge]: visited[edge] = weight path[edge] = min_node return visited, path ================================================ FILE: algorithms/doomsday/java/doomsday.java ================================================ /** * Determines the day of the week. * * @author Atom * */ public class Doomsday { /** * Determines the day of the week using Tomohiko Sakamoto's Algorithm * to calculate Day of Week based on Gregorian calendar. * * @param y year * @param m month * @param d day * @return day of the week (0 = sunday, 6 = saturday) */ public static int dow(int y, int m, int d) { final int[] t = { 0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4 }; y -= (m < 3) ? 1 : 0; return (y + y/4 - y/100 + y/400 + t[m-1] + d) % 7; } /** * Determines the day of the week using Tomohiko Sakamoto's Algorithm * to calculate Day of Week based on Gregorian calendar. * * @param y year * @param m month * @param d day * @return day of the week */ public static String dowS(int y, int m, int d) { switch (dow(y, m, d)) { case 0: return "Sunday"; case 1: return "Monday"; case 2: return "Tuesday"; case 3: return "Wednesday"; case 4: return "Thursday"; case 5: return "Friday"; case 6: return "Saturday"; default: System.out.println("Unknown dow"); } return null; } public static void main(String[] args) { System.out.println(dow(1886, 5, 1) + ": " + dowS(1886, 5, 1)); System.out.println(dow(1948, 12, 10) + ": " + dowS(1948, 12, 10)); System.out.println(dow(2001, 1, 15) + ": " + dowS(2001, 1, 15)); System.out.println(dow(2017, 10, 10) + ": " + dowS(2017, 10, 10)); System.out.println(dow(2018, 1, 1) + ": " + dowS(2018, 1, 1)); System.out.println(dow(2018, 2, 16) + ": " + dowS(2018, 2, 16)); System.out.println(dow(2018, 5, 17) + ": " + dowS(2018, 5, 17)); } } ================================================ FILE: algorithms/doomsday/javascript/doomsday.js ================================================ function dayOfTheWeek(y, m, d) { const t = [0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4] y -= m < 3; return (y + Math.floor(y/4) - Math.floor(y/100) + Math.floor(y/400) + t[m-1] + d) % 7; } const dayMapping = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'] const tests = [ [1886, 5, 1], [1948, 12, 10], [2001, 1, 15], [2017, 10, 10], [2018, 1, 1], [2018, 2, 16], [2018, 5, 17], ] tests.forEach(test => console.log(test.join('/') + ': ' + dayMapping[dayOfTheWeek(...test)])) ================================================ FILE: algorithms/dynamic_programming/c/0_1_knapsack_problem.c ================================================ // A Dynamic Programming based solution for 0-1 Knapsack problem #include // A utility function that returns maximum of two integers int max(int a, int b) { return (a > b)? a : b; } // Returns the maximum value that can be put in a knapsack of capacity W int knapSack(int W, int wt[], int val[], int n) { int i, w; int K[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]; } int main() { int val[] = {60, 100, 120}; int wt[] = {10, 20, 30}; int W = 50; int n = sizeof(val)/sizeof(val[0]); printf("%d", knapSack(W, wt, val, n)); return 0; } ================================================ FILE: algorithms/dynamic_programming/c/Coin_change_DP.c ================================================ //Coin change problem : /* Given a value N, if we want to make change for N cents, and we have infinite supply of each of S = { S1, S2, .. , Sm} valued coins, how many ways can we make the change? The order of coins doesn’t matter. For example, for N = 4 and S = {1,2,3}, there are four solutions: {1,1,1,1},{1,1,2},{2,2},{1,3}. So output should be 4. For N = 10 and S = {2, 5, 3, 6}, there are five solutions: {2,2,2,2,2}, {2,2,3,3}, {2,2,6}, {2,3,5} and {5,5}. So the output should be 5. */ #include int count( int S[], int m, int n ) { int i, j, x, y; // We need n+1 rows as the table is consturcted in bottom up manner using // the base case 0 value case (n = 0) int table[n+1][m]; // Fill the enteries for 0 value case (n = 0) for (i=0; i= 0)? table[i - S[j]][j]: 0; // Count of solutions excluding S[j] y = (j >= 1)? table[i][j-1]: 0; // total count table[i][j] = x + y; } } return table[n][m-1]; } // Driver program to test above function int main() { int arr[] = {1, 2, 3}; int m = sizeof(arr)/sizeof(arr[0]); int n = 4; printf(" %d ", count(arr, m, n)); return 0; } ================================================ FILE: algorithms/dynamic_programming/c/coinChange.c ================================================ #include int count( int S[], int m, int n ) { // table[i] will be storing the number of solutions for // value i. We need n+1 rows as the table is consturcted // in bottom up manner using the base case (n = 0) int table[n+1]; // Initialize all table values as 0 memset(table, 0, sizeof(table)); // Base case (If given value is 0) table[0] = 1; // Pick all coins one by one and update the table[] values // after the index greater than or equal to the value of the // picked coin for(int i=0; i // A recursive function used by countWays int countWaysUtil(int n, int m) { int res[n]; res[0] = 1; res[1] = 1; for (int i=2; i #include /* lis() returns the length of the longest increasing subsequence in arr[] of size n */ int lis( int arr[], int n ) { int *lis, i, j, max = 0; lis = (int*) malloc ( sizeof( int ) * n ); /* Initialize LIS values for all indexes */ for (i = 0; i < n; i++ ) lis[i] = 1; /* Compute optimized LIS values in bottom up manner */ for (i = 1; i < n; i++ ) for (j = 0; j < i; j++ ) if ( arr[i] > arr[j] && lis[i] < lis[j] + 1) lis[i] = lis[j] + 1; /* Pick maximum of all LIS values */ for (i = 0; i < n; i++ ) if (max < lis[i]) max = lis[i]; /* Free memory to avoid memory leak */ free(lis); return max; } /* Driver program to test above function */ int main() { int arr[] = { 10, 22, 9, 33, 21, 50, 41, 60 }; int n = sizeof(arr)/sizeof(arr[0]); printf("Length of lis is %dn", lis( arr, n ) ); return 0; } ================================================ FILE: algorithms/dynamic_programming/c/longestRepeatedSequence.c ================================================ // C++ program to find the longest repeated // subsequence #include using namespace std; // This function mainly returns LCS(str, str) // with a condition that same characters at // same index are not considered. string longestRepeatedSubSeq(string str) { // THIS PART OF CODE IS SAME AS BELOW POST. // IT FILLS dp[][] // http://www.geeksforgeeks.org/longest-repeating-subsequence/ // OR the code mentioned above. int n = str.length(); int dp[n+1][n+1]; for (int i=0; i<=n; i++) for (int j=0; j<=n; j++) dp[i][j] = 0; for (int i=1; i<=n; i++) for (int j=1; j<=n; j++) if (str[i-1] == str[j-1] && i != j) dp[i][j] = 1 + dp[i-1][j-1]; else dp[i][j] = max(dp[i][j-1], dp[i-1][j]); // THIS PART OF CODE FINDS THE RESULT STRING USING DP[][] // Initialize result string res = ""; // Traverse dp[][] from bottom right int i = n, j = n; while (i > 0 && j > 0) { // If this cell is same as diagonally // adjacent cell just above it, then // same characters are present at // str[i-1] and str[j-1]. Append any // of them to result. if (dp[i][j] == dp[i-1][j-1] + 1) { res = res + str[i-1]; i--; j--; } // Otherwise we move to the side // that that gave us maximum result else if (dp[i][j] == dp[i-1][j]) i--; else j--; } // Since we traverse dp[][] from bottom, // we get result in reverse order. reverse(res.begin(), res.end()); return res; } // Driver Program int main() { string str = "AABEBCDD"; cout << longestRepeatedSubSeq(str); return 0; } ================================================ FILE: algorithms/dynamic_programming/c/longest_pallindrome_sequence.c ================================================ # A Dynamic Programming based Python program for LPS problem # Returns the length of the longest palindromic subsequence in seq #include #include // A utility function to get max of two integers int max (int x, int y) { return (x > y)? x : y; } // Returns the length of the longest palindromic subsequence in seq int lps(char *str) { int n = strlen(str); int i, j, cl; int L[n][n]; // Create a table to store results of subproblems // Strings of length 1 are palindrome of lentgh 1 for (i = 0; i < n; i++) L[i][i] = 1; // Build the table. Note that the lower diagonal values of table are // useless and not filled in the process. The values are filled in a // manner similar to Matrix Chain Multiplication DP solution (See // http://www.geeksforgeeks.org/archives/15553). cl is length of // substring for (cl=2; cl<=n; cl++) { for (i=0; i /* maxSumIS() returns the maximum sum of increasing subsequence in arr[] of size n */ int maxSumIS( int arr[], int n ) { int i, j, max = 0; int msis[n]; /* Initialize msis values for all indexes */ for ( i = 0; i < n; i++ ) msis[i] = arr[i]; /* Compute maximum sum values in bottom up manner */ for ( i = 1; i < n; i++ ) for ( j = 0; j < i; j++ ) if ( arr[i] > arr[j] && msis[i] < msis[j] + arr[i]) msis[i] = msis[j] + arr[i]; /* Pick maximum of all msis values */ for ( i = 0; i < n; i++ ) if ( max < msis[i] ) max = msis[i]; return max; } /* Driver program to test above function */ int main() { int arr[] = {1, 101, 2, 3, 100, 4, 5}; int n = sizeof(arr)/sizeof(arr[0]); printf("Sum of maximum sum increasing subsequence is %dn", maxSumIS( arr, n ) ); return 0; } ================================================ FILE: algorithms/dynamic_programming/c/subsetSum.c ================================================ // A recursive solution for subset sum problem #include // Returns true if there is a subset of set[] with sun equal to given sum bool isSubsetSum(int set[], 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 (set[n-1] > sum) return isSubsetSum(set, 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(set, n-1, sum) || isSubsetSum(set, n-1, sum-set[n-1]); } // Driver program to test above function int main() { int set[] = {3, 34, 4, 12, 5, 2}; int sum = 9; int n = sizeof(set)/sizeof(set[0]); if (isSubsetSum(set, n, sum) == true) printf("Found a subset with given sum"); else printf("No subset with given sum"); return 0; } ================================================ FILE: algorithms/dynamic_programming/cpp/kadens.cpp ================================================ // C++ program to print largest contiguous array sum #include #include using namespace std; int maxSubArraySum(int a[], int size) { int max_so_far = INT_MIN, max_ending_here = 0; for (int i = 0; i < size; i++) { max_ending_here = max_ending_here + a[i]; if (max_so_far < max_ending_here) max_so_far = max_ending_here; if (max_ending_here < 0) max_ending_here = 0; } return max_so_far; } /*Driver program to test maxSubArraySum*/ int main() { int a[] = {-2, -3, 4, -1, -2, 1, 5, -3}; int n = sizeof(a)/sizeof(a[0]); int max_sum = maxSubArraySum(a, n); cout << "Maximum contiguous sum is " << max_sum; return 0; } ================================================ FILE: algorithms/dynamic_programming/cpp/nCr.cpp ================================================ #include using namespace std; // Returns nCr % p int nCrModp(int n, int r, int p) { // The array C is going to store last row of // pascal triangle at the end. And last entry // of last row is nCr int C[r+1]; memset(C, 0, sizeof(C)); C[0] = 1; // Top row of Pascal Triangle // One by constructs remaining rows of Pascal // Triangle from top to bottom for (int i = 1; i <= n; i++) { // Fill entries of current row using previous // row values for (int j = min(i, r); j > 0; j--) // nCj = (n-1)Cj + (n-1)C(j-1); C[j] = (C[j] + C[j-1])%p; } return C[r]; } // Driver program int main() { int n = 10, r = 2, p = 13; cout << "Value of nCr % p is " << nCrModp(n, r, p); return 0; } ================================================ FILE: algorithms/dynamic_programming/cpp/subset_sum.cpp ================================================ #include using namespace std; int arr[1000]; int sum=0; int cache[100][100]; int m_diff(int idx,int sub_sum) { if(cache[idx][sub_sum]) return cache[idx][sub_sum]; if(idx==0) { cache[0][sub_sum]=abs((sum-sub_sum)-sub_sum); return cache[0][sub_sum]; } cache[idx][sub_sum]=min(m_diff(idx-1,sub_sum-arr[idx]),m_diff(idx-1,sub_sum)); return cache[idx][sub_sum]; } int main() { memset(cache,0,sizeof cache); int n; cin>>n; for(int i=0;i>arr[i]; sum+=arr[i]; } cout<= 0; j--) { storage[m - 1][j] = storage[m - 1][j + 1] + arr[m - 1][j]; } // Last Column for (int i = m - 2; i >= 0; i--) { storage[i][n - 1] = storage[i + 1][n - 1] + arr[i][n - 1]; } for (int i = m - 2; i >= 0; i--) { for (int j = n - 2; j >= 0; j--) { storage[i][j] = arr[i][j] + Math.min(storage[i][j + 1], Math.min( storage[i + 1][j + 1], storage[i + 1][j])); } } return storage[0][0]+arr[row][column]; } public static void main(String args[]) { Scanner s = new Scanner(System.in); int rows = s.nextInt(); int columns = s.nextInt(); int arr[][] = new int[rows][columns]; for (int i = 0; i < rows; i++) { for (int j = 0; j < columns; j++) { arr[i][j] = s.nextInt(); } } int row = s.nextInt(); int column = s.nextInt(); System.out.println(minCostPathDP(arr,row,column)); s.close(); } } ================================================ FILE: algorithms/encoding/base64_encoder.c ================================================ // C implementation of base64 encoder for converting ASCII string format into radix-64 representation. #include #include #include #include static char b64_arr[] = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/'}; int main() { char *str = "Man is distinguished, not only by his reason, but by this singular passion from other animals, which is a lust of the mind, that by a perseverance of delight in the continued and indefatigable generation of knowledge, exceeds the short vehemence of any carnal pleasure."; int in = -1; int len = strlen(str); int outlen = (int)ceil(len/3.0)*4; char *result = (char *)malloc(sizeof(char)*outlen); for (int i = 0; i < len; i += 3) { int x = 0; if(str[i+1] != '\0' && str[i+2] != '\0'){ x |= (str[i] << 16); x |= (str[i+1] << 8); x |= (str[i+2]); result[++in] = b64_arr[(x >> 18) & (0x3F)]; result[++in] = b64_arr[(x >> 12) & (0x3F)]; result[++in] = b64_arr[(x >> 6) & (0x3F)]; result[++in] = b64_arr[(x) & (0x3F)]; } else if(str[i+1] != '\0'){ x |= (str[i] << 16); x |= (str[i+1] << 8); result[++in] = b64_arr[(x >> 18) & (0x3F)]; result[++in] = b64_arr[(x >> 12) & (0x3F)]; result[++in] = b64_arr[(x >> 6) & (0x3F)]; result[++in] = '='; } else{ x |= (str[i] << 16); result[++in] = b64_arr[(x >> 18) & (0x3F)]; result[++in] = b64_arr[(x >> 12) & (0x3F)]; result[++in] = '='; result[++in] = '='; } } if(in < outlen) result[++in] = '\0'; printf("%s\n", result); return 0; } ================================================ FILE: algorithms/fibonacci/cpp/constexpr-fibonacci.cpp ================================================ // Computes a specific index of the Fibonacci sequence // Can be computed at compile-time under certain conditions constexpr unsigned int fibonacci(unsigned int index) { constexpr auto gr = (1 + std::sqrt(5)) / 2; if(index == 0) { return 0; } else if(index == 1) { return 1; } return static_cast( (std::pow(gr, index) - std::pow(1 - gr, index)) / sqrt(5) ); } ================================================ FILE: algorithms/floyd_warshall/java/ShortestPath.java ================================================ /** * A Java program for Floyd Warshall All Pairs Shortest * Path algorithm. */ public class ShortestPath { private final static int VERTEX_NUMBER = 4; private final static int MAX_VALUE = 999999; public void floydWarshall(int graph[][]) { int dist[][] = new int[VERTEX_NUMBER][VERTEX_NUMBER]; int i, j, k; for (i = 0; i < VERTEX_NUMBER; i++) for (j = 0; j < VERTEX_NUMBER; j++) dist[i][j] = graph[i][j]; for (k = 0; k < VERTEX_NUMBER; k++) { for (i = 0; i < VERTEX_NUMBER; i++) { for (j = 0; j < VERTEX_NUMBER; j++) { if (dist[i][k] + dist[k][j] < dist[i][j]) { dist[i][j] = dist[i][k] + dist[k][j]; } } } } printSolution(dist); } private void printSolution(int dist[][]) { for (int i = 0; i < VERTEX_NUMBER; ++i) { for (int j = 0; j < VERTEX_NUMBER; ++j) { if (dist[i][j] == MAX_VALUE) { System.out.print("INF "); } else { System.out.print(dist[i][j] + " "); } } System.out.println(); } } /** * Test * @param args */ public static void main (String[] args) { int graph[][] = { {0, 5, MAX_VALUE, 10}, {MAX_VALUE, 0, 3, MAX_VALUE}, {MAX_VALUE, MAX_VALUE, 0, 1}, {MAX_VALUE, MAX_VALUE, MAX_VALUE, 0} }; ShortestPath a = new ShortestPath(); a.floydWarshall(graph); } } ================================================ FILE: algorithms/greedy_search/cpp/prims_algorithm.cpp ================================================ #include using namespace std; int minkey(int key[], bool mstset[],int n) { int min_index; int Min = INT_MAX; for(int i=0;i>n; int cost[n][n]; memset(cost,0,sizeof(cost)); int m; cout<<"enter the number of edges in the graph\n"; cin>>m; vector > edgelist(m); for(int i=0;i>a>>b>>c; edgelist[i] = make_pair(a,b); cost[a][b] =c; cost[b][a] =c; } bool mstset[n]; pair edge[n]; int key[n]; for(int i=0;i 0 array[0], array[bottom] = array[bottom], array[0] sift_down(array, 0, bottom) bottom -= 1 end array end def to_heap(array) i = (array.size/2) - 1 while i >= 0 sift_down(array, i, array.size) i -= 1 end array end def sift_down(array, i, max) i_big, c1, c2 = 0, 0, 0 while i < max i_big = i c1 = (2*i) + 1 c2 = c1 + 1 if c1 < max && array[c1] > array[i_big] i_big = c1 end if c2 < max && array[c2] > array[i_big] i_big = c2 end break if i_big == i array[i], array[i_big] = array[i_big], array[i] i = i_big end array end numbers = [4, 2, 8, 1, 30, 0, 10, 16] puts "Unsorted: #{numbers}" puts "Sorted: #{heap_sort(numbers)}" ================================================ FILE: algorithms/heap_sort/java/heap_sort.java ================================================ /* * Java Program to Implement Heap Sort */ import java.util.Scanner; /* Class HeapSort */ public class HeapSort { private static int N; /* Sort Function */ public static void sort(int arr[]) { heapify(arr); for (int i = N; i > 0; i--) { swap(arr,0, i); N = N-1; maxheap(arr, 0); } } /* Function to build a heap */ public static void heapify(int arr[]) { N = arr.length-1; for (int i = N/2; i >= 0; i--) maxheap(arr, i); } /* Function to swap largest element in heap */ public static void maxheap(int arr[], int i) { int left = 2*i ; int right = 2*i + 1; int max = i; if (left <= N && arr[left] > arr[i]) max = left; if (right <= N && arr[right] > arr[max]) max = right; if (max != i) { swap(arr, i, max); maxheap(arr, max); } } /* Function to swap two numbers in an array */ public static void swap(int arr[], int i, int j) { int tmp = arr[i]; arr[i] = arr[j]; arr[j] = tmp; } /* Main method */ public static void main(String[] args) { Scanner scan = new Scanner( System.in ); System.out.println("Heap Sort Test\n"); int n, i; /* Accept number of elements */ System.out.println("Enter number of integer elements"); n = scan.nextInt(); /* Make array of n elements */ int arr[] = new int[ n ]; /* Accept elements */ System.out.println("\nEnter "+ n +" integer elements"); for (i = 0; i < n; i++) arr[i] = scan.nextInt(); /* Call method sort */ sort(arr); /* Print sorted Array */ System.out.println("\nElements after sorting "); for (i = 0; i < n; i++) System.out.print(arr[i]+" "); System.out.println(); } } ================================================ FILE: algorithms/heap_sort/java/heapsort.java ================================================ //Java program for Heap Sort class heapsort { public void sort(int arr[]) { int n = arr.length; // Build heap (rearrange array) for (int i = n / 2 - 1; i >= 0; i--) heapify(arr, n, i); // One by one extract an element from heap for (int i=n-1; i>=0; i--) { // Move current root to end int temp = arr[0]; arr[0] = arr[i]; arr[i] = temp; // call max heapify on the reduced heap heapify(arr, i, 0); } } // To heapify a subtree rooted with node i which is // an index in arr[]. n is size of heap void heapify(int arr[], int n, int i) { int largest = i; // Initialize largest as root int l = 2*i + 1; // left = 2*i + 1 int r = 2*i + 2; // right = 2*i + 2 // If left child is larger than root if (l < n && arr[l] > arr[largest]) largest = l; // If right child is larger than largest so far if (r < n && arr[r] > arr[largest]) largest = r; // If largest is not root if (largest != i) { int swap = arr[i]; arr[i] = arr[largest]; arr[largest] = swap; // Recursively heapify the affected sub-tree heapify(arr, n, largest); } } /* A utility function to print array of size n */ static void printArray(int arr[]) { int n = arr.length; for (int i=0; i input[max]) { max = left; } if (right < array_length && input[right] > input[max]) { max = right; } if (max != i) { swap(input, i, max); heap_root(input, max); } } function swap(input, index_A, index_B) { var temp = input[index_A]; input[index_A] = input[index_B]; input[index_B] = temp; } function heapSort(input) { array_length = input.length; for (var i = Math.floor(array_length / 2); i >= 0; i -= 1) { heap_root(input, i); } for (i = input.length - 1; i > 0; i--) { swap(input, 0, i); array_length--; heap_root(input, 0); } } var arr = [3, 0, 2, 5, -1, 4, 1]; heapSort(arr); console.log(arr); ================================================ FILE: algorithms/heap_sort/python/heap_sort.py ================================================ from heapq import heappush, heappop def heap_sort(heap_iterable): ''' Heap sort implementation ''' heap = [] for val in heap_iterable: heappush(heap, val) return [heappop(heap) for _ in range(len(heap))] # Test if __name__ == '__main__': test_cases = ( [1, 3, 5, 7, 9, 2, 4, 6, 8, 0], [3, 15, 68, 34, 39, 85, 85, 71, 47, 84], [3, 10, 68, 34, 15, 85, 85, 71, 47, 84, 39], [2, 10, 3, 34, 15, 68, 85, 71, 47, 84, 39, 85], [1, 10, 2, 34, 15, 3, 85, 71, 47, 84, 39, 85, 68], range(50) ) for iterable in test_cases: assert heap_sort(iterable) == sorted(iterable) ================================================ FILE: algorithms/histogram_equalization/java/HistogramEqualization.java ================================================ /* * This file has been created by github user vn17. * Feel free to use it for any purpose. * * This file makes extensive use of Java 8 lambdas. * * For more details on the algorithm, * refer to @see https://en.wikipedia.org/wiki/Histogram_equalization */ package Java; import java.util.Arrays; import java.util.HashMap; import java.util.stream.IntStream; import static java.util.stream.Collectors.joining; public class HistogramEqualization { public static void main(String[] args) { ImageMatrix imageMatrix = new ImageMatrix(new int[][]{{2, 3, 1}, {3, 4, 6}, {7, 3, 6}}); System.out.println("Input Matrix: \n" + imageMatrix); System.out.println("Frequency: \t" + imageMatrix.frequency() + "\nCDF: \t\t" + imageMatrix.cdf() + "\n"); ImageMatrix equalizedImageMatrix = imageMatrix.equalize(); System.out.println("Histogram Equalized Matrix: \n" + equalizedImageMatrix); } } class ImageMatrix { private static final int NUMBER_OF_LEVELS = 8;//This is the intensity range. // Eg. For a 3 bit per pixel image, the intensity value is 8. private int cdfMin = -1;//This is the cdf of the minimum intensity value private int size;//Size of the image. 3 x 3 = 9 in this case private int[][] imageArray;//3 x 3 Array to store intensity values at each pixel private HashMap frequency;//HashMap to store the frequency of each intensity value i.e. // the number of times each value has appeared in the 3 x 3 array. private HashMap cdf;//HashMap to store the CDF of each intensity value i.e. // the sum of the frequency values of all intensities lesser than the current intensity level. public ImageMatrix(int[][] arr) { this.imageArray = arr; this.size = (int) Arrays.stream(arr).flatMapToInt(IntStream::of).count(); } public int getFrequency(int key) { if (frequency == null) calculateFrequency(); return frequency().get(key); } public int getCdf(int key) { if (cdf == null) calculateCdf(); return cdf().get(key); } public HashMap frequency() { if (frequency == null) calculateFrequency(); return frequency; } public HashMap cdf() { if (cdf == null) calculateCdf(); return cdf; } /** * This method calculates the frequency of each intensity value in the given intensity range. */ private void calculateFrequency() { this.frequency = new HashMap<>(); Arrays.stream(imageArray)//Get the 2D array .flatMapToInt(IntStream::of)//Convert it to a 1D array .forEach(intensity -> {//Increment the frequency value for intensity by 1 if (frequency.containsKey(intensity)) frequency.put(intensity, frequency.get(intensity) + 1); else frequency.put(intensity, 1); }); } /** * This method calculates the CDF by adding all the intensity values lesser than the current value. */ private void calculateCdf() { if (frequency == null) calculateFrequency(); cdf = (HashMap) frequency().clone(); cdf.keySet().stream() .sorted().mapToInt(Integer::intValue) .reduce(0, (previousSum, currentKey) -> { int sum = previousSum + cdf.get(currentKey); cdf.put(currentKey, sum); if (cdfMin == -1)//To store the cdf of the minimum intensity value cdfMin = sum; return sum; }); } /** * This method applies the equalization formula to each element in the matrix. * @return */ public ImageMatrix equalize() { int[][] equalizedArray = Arrays.stream(imageArray) .map(p -> Arrays.stream(p).map(q -> (getCdf(q) - cdfMin) * (NUMBER_OF_LEVELS - 2) / (size - 1) + 1).toArray()) .toArray(int[][]::new); return new ImageMatrix(equalizedArray); } /** * Prints a 2D array line by line for each array. * @return */ @Override public String toString() { return Arrays.stream(imageArray).map(s -> String.format("%s\n", Arrays.toString(s))).collect(joining()); } } ================================================ FILE: algorithms/huffmann_algorithm/java/Huffman.java ================================================ package Lecture25; import java.util.HashMap; import java.util.Set; import Lecture19.BinaryTree; import Lecture21.Heap; public class Huffman { private HashMap encoder; private HashMap decoder; public Huffman(String sourceString){ // 1. prepare freq map HashMap freqMap = new HashMap<>(); for(int i = 0; i < sourceString.length(); i++){ char ch = sourceString.charAt(i); if(freqMap.containsKey(ch)){ freqMap.put(ch, freqMap.get(ch) + 1); } else { freqMap.put(ch, 1); } } // 2. Prepare bt's for each key freqmap and add to a min heap Heap minHeap = new Heap<>(true); Set allChars = freqMap.keySet(); for(Character ch: allChars){ BinaryTree bt = new BinaryTree(ch, null, null); Pair pair = new Pair(freqMap.get(ch), bt); minHeap.add(pair.cost, pair); } // 3. till the heap is empty, we pull out two, create a new and enter it back while(minHeap.size() != 1){ Pair p1 = minHeap.removeHP(); Pair p2 = minHeap.removeHP(); BinaryTree bt = new BinaryTree(0, p1.bt, p2.bt); Pair p = new Pair(p1.cost + p2.cost, bt); minHeap.add(p.cost, p); } // 4. Get final tree out of heap Pair fp = minHeap.removeHP(); BinaryTree ft = fp.bt; // 5. Get enc, dec filled this.encoder = new HashMap<>(); this.decoder = new HashMap<>(); ft.traversalForHC(encoder, decoder); } // input - aaaaaaaaaaaaaaaaafadsfaaaaaaaaaaaaaaaaaaaabbbbbbbbbbbbbbbbbbccccccccc // output - 11110101010101111100001101010101010101 public String encode(String str){ String rv = ""; for(int i = 0; i < str.length(); i++){ rv += encoder.get(str.charAt(i)); } return rv; } // input - 11110101010101111100001101010101010101 // output - aaaaaaaaaaaaaaaaafadsfaaaaaaaaaaaaaaaaaaaabbbbbbbbbbbbbbbbbbccccccccc public String decode(String str){ String rv = ""; String key = ""; for(int i = 0; i < str.length(); i++){ key += str.charAt(i); if(decoder.containsKey(key)){ rv += decoder.get(key); key = ""; } } return rv; } private class Pair { int cost; BinaryTree bt; Pair(int cost, BinaryTree bt){ this.cost = cost; this.bt = bt; } } } ================================================ FILE: algorithms/insertion_sort/ada/insertion_sort.adb ================================================ with Ada.Containers.Vectors; with Ada.Numerics.Discrete_Random; with Ada.Text_IO; with Ada.Integer_Text_IO; use Ada.Text_IO; use Ada.Integer_Text_IO; procedure Insertion_Sort is ------------------------------ -- Constant, types, package -- ------------------------------ ARRAY_SIZE : constant Natural := 10; RANGE_MIN : constant Integer := 1; RANGE_MAX : constant Integer := 100; package P_Vectors is new Ada.Containers.Vectors (Positive, Integer); use P_Vectors; ----------------------- -- Method prototype -- ----------------------- -- Initializing an array with default values function Init_Vector return Vector; procedure Put (Tab : Vector); procedure Swap (a : in out Integer; b : in out Integer); function Sort (T : Vector) return Vector; ----------------------------- -- Declaration of methods -- ----------------------------- function Init_Vector return Vector is subtype T_Interval is Integer range RANGE_MIN .. RANGE_MAX; package P_Random is new Ada.numerics.discrete_random (T_Interval); use P_Random; seed : Generator; T : Vector; begin Reset (seed); for i in 1 .. ARRAY_SIZE loop Append (T, Random (seed)); end loop; return T; end Init_Vector; procedure Put (Tab : Vector) is begin for e of Tab loop Put (e, Width => 0); Put (";"); end loop; end Put; procedure Swap (a : in out Integer; b : in out Integer) is c : constant Integer := a; begin a := b; b := c; end Swap; function Sort (T : Vector) return Vector is Tab : Vector := T; begin for i in First_Index (T) + 1 .. Last_Index (T) loop for j in reverse First_Index (T) + 1 .. i loop exit when Tab (j - 1) <= Tab (j); Swap (Tab (j - 1), Tab (j)); end loop; end loop; return Tab; end Sort; --------------- -- Variables -- --------------- T : Vector := Init_Vector; begin Put ("Array : "); Put (T); New_Line; T := Sort (T); Put ("Sorted array : "); Put (T); end Insertion_Sort; ================================================ FILE: algorithms/insertion_sort/c/InsertionSort.c ================================================ // C program for insertion sort #include /* Function to sort an array using insertion sort */ void insertionSort(int ar[], int n) { int i, key, j; for (i = 1; i < n; i++) { key = ar[i]; j = i-1; /* Move elements with indices from 0 to i-1 that are greater than key, to one position ahead of their current position */ while (j >= 0 && ar[j] > key) { ar[j+1] = ar[j]; j = j-1; } ar[j+1] = key; } } // method to print array void print(int ar[], int n) { for (int i=0; i < n; i++){ printf("%d ", ar[i]); } } /* To test insertion sort function */ int main() { int arr[] = {10, 29, 1, 9, 37, 24, 6, 3, 11}; // Calculates array size int n = sizeof(arr) / sizeof(arr[0]); insertionSort(arr, n); print(arr, n); return 0; } ================================================ FILE: algorithms/insertion_sort/cpp/insertion_sort.cpp ================================================ // // Created by radligna on 05.10.17. // // C++ program for insertion sort //needed to print the sorted array #include /* Function to sort an array using insertion sort */ void insertionSort( int tab[], int arraySize ) { int temp, iter2; for( int iter1 = 1; iter1 < arraySize; iter1++ ) { temp = tab[iter1]; for( iter2 = iter1 - 1; iter2 >= 0 and tab[iter2] > temp; iter2-- ) tab[ iter2 + 1 ] = tab[ iter2 ]; tab[ iter2 + 1 ] = temp; } } // method to print array void printArray(int arr[], int arraySize) { for (int i=0; i < arraySize; i++) std::cout< 0 && array[i-1] > array[i] array[i], array[i - 1] = array[i - 1], array[i] i -= 1 end x += 1 break if x == array.size end array end numbers = [4, 2, 8, 1, 30, 0, 10, 16] puts "Unsorted: #{numbers}" puts "Sorted: #{insertion_sort(numbers)}" ================================================ FILE: algorithms/insertion_sort/java/InsertionSort.java ================================================ class InsertionSort { /* This class sorts an array using insertion sort */ public static int[] insertionSort(int[] array) { int key, previousIndex; for (int index = 1; index < array.length; index++) { key = array[index]; previousIndex = index - 1; while(previousIndex >= 0 && array[previousIndex] > key){ array[previousIndex + 1] = array[previousIndex]; previousIndex -= 1; array[previousIndex + 1] = key; } } return array; } public static void main(String[] args) { int[] array = new int[10]; for (int i = 10; i > 0 ; i--) { array[10 - i] = i; } int[] sortedArray = insertionSort(array); for (int i: sortedArray) { System.out.print(i + " "); } } } ================================================ FILE: algorithms/insertion_sort/javascript/insertionSort.js ================================================ function insertionSort(array) { for (let i = 0; i < array.length; i++) { let temp = array[i]; let j = i - 1; while (j >= 0 && array[j] > temp) { array[j + 1] = array[j]; j--; } array[j + 1] = temp; } return array; } ================================================ FILE: algorithms/insertion_sort/javascript/insertion_sort.js ================================================ function insertionSort(unsortedList) { let len = unsortedList.length; for (let i = 1; i < len; i++) { let ele = unsortedList[i]; for (var j = i - 1; j >= 0 && (unsortedList[j] > ele); j--) { unsortedList[j+1] = unsortedList[j]; } unsortedList[j+1] = ele; } } ================================================ FILE: algorithms/insertion_sort/python/insertionsort.py3 ================================================ # Python program for implementation of Insertion Sort # Function to do insertion sort def insertionSort(arr): # Traverse through 1 to len(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 #Test case arr = [12, 11, 13, 5, 6] insertionSort(arr) for i in range(len(arr)): print ("%d" %arr[i]) ================================================ FILE: algorithms/insertion_sort/ruby/insertion_sort.rb ================================================ def insertion_sort(numbers) for i in 1...numbers.length key = numbers[i] j = i - 1 while j >= 0 and numbers[j] > key numbers[j+1] = numbers[j] j = j - 1 end numbers[j+1] = key end numbers end unsorted = [5, 2, 6, 7, 20, 9, 1, 3] puts "Unsorted " + unsorted.inspect sorted = insertion_sort(unsorted) puts "Sorted " + sorted.inspect ================================================ FILE: algorithms/inversion_count/cpp/inversion_count.cpp ================================================ #include using namespace std; long merge(vector &arr, vector &tmp, int left, int mid, int right) { int i = left; int k = left; int j = mid; long count = 0; while(i <= (mid-1) && j <= right) { if(arr[i] <= arr[j] ) tmp[k++] = arr[i++]; else { tmp[k++] = arr[j++]; count += mid - i; } } while(i <= mid - 1) tmp[k++] = arr[i++]; while(j <= right) tmp[k++] = arr[j++]; for (int i = left; i <= right; ++i) { arr[i] = tmp[i]; } return count; } long mergeSort(vector &arr, vector &tmp, int left, int right) { long count = 0; int mid; if(left < right) { mid = (right + left)/2; count += mergeSort(arr, tmp, left, mid); count += mergeSort(arr, tmp , mid+1 , right); count += merge(arr, tmp, left, mid+1, right); } return count; } long countInversions(vector arr) { vector tmp(arr.size()); return mergeSort(arr, tmp, 0, arr.size()-1); } int main() { int n; cin >> n; vector arr(n); for(int arr_i = 0; arr_i < n; arr_i++) { cin >> arr[arr_i]; } long result = countInversions(arr); cout << result << endl; return 0; } ================================================ FILE: algorithms/jarvis/cpp/jarvis.cpp ================================================ /*Given a set of points in the plane. the convex hull of the set is the smallest convex polygon that contains all the points of it.*/ #include using namespace std; struct Point { int x, y; }; // To find orientation of ordered triplet (p, q, r). // The function returns following values // 0 --> p, q and r are colinear // 1 --> Clockwise // 2 --> Counterclockwise int orientation(Point p, Point q, Point r) { int val = (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y); if (val == 0) return 0; // colinear return (val > 0)? 1: 2; // clock or counterclock wise } // Prints convex hull of a set of n points. void convexHull(Point points[], int n) { // There must be at least 3 points if (n < 3) return; // Initialize Result vector hull; // Find the leftmost point int l = 0; for (int i = 1; i < n; i++) if (points[i].x < points[l].x) l = i; // Start from leftmost point, keep moving counterclockwise // until reach the start point again. This loop runs O(h) // times where h is number of points in result or output. int p = l, q; do { // Add current point to result hull.push_back(points[p]); // Search for a point 'q' such that orientation(p, x, // q) is counterclockwise for all points 'x'. The idea // is to keep track of last visited most counterclock- // wise point in q. If any point 'i' is more counterclock- // wise than q, then update q. q = (p+1)%n; for (int i = 0; i < n; i++) { // If i is more counterclockwise than current q, then // update q if (orientation(points[p], points[i], points[q]) == 2) q = i; } // Now q is the most counterclockwise with respect to p // Set p as q for next iteration, so that q is added to // result 'hull' p = q; } while (p != l); // While we don't come to first point // Print Result for (int i = 0; i < hull.size(); i++) cout << "(" << hull[i].x << ", " << hull[i].y << ")\n"; } ================================================ FILE: algorithms/johnson_algorithm/cpp/johnson_algorithm.cpp ================================================ #include #include using namespace std; int min(int a, int b); int cost[10][10], a[10][10], i, j, k, c; int min(int a, int b) { if (a < b) return a; else return b; } int main(int argc, char **argv) { int n, m; cout << "Enter no of vertices"; cin >> n; cout << "Enter no of edges"; cin >> m; cout << "Enter the\nEDGE Cost\n"; for (k = 1; k <= m; k++) { cin >> i >> j >> c; a[i][j] = cost[i][j] = c; } for (i = 1; i <= n; i++) for (j = 1; j <= n; j++) { if (a[i][j] == 0 && i != j) a[i][j] = 31999; } for (k = 1; k <= n; k++) for (i = 1; i <= n; i++) for (j = 1; j <= n; j++) a[i][j] = min(a[i][j], a[i][k] + a[k][j]); cout << "Resultant adj matrix\n"; for (i = 1; i <= n; i++) { for (j = 1; j <= n; j++) { if (a[i][j] != 31999) cout << a[i][j] << " "; } cout << "\n"; } return 0; } ================================================ FILE: algorithms/kmp_search/cpp/KMPSearch.cpp ================================================ //CPP Implementation of Knuth-Morris-Pratt(KMP) algorithm for pattern matching in a given text string. #include #define MAX 10000 using namespace std; char text[MAX],pattern[MAX]; int prefix_array[MAX],m,n; void Compute_Prefix_Array(); int Kmp_Search(); int main(void) { int find_pattern; cout<<"Specify Input Text: "; cin>>text; cout<<"Specify Input Pattern: "; cin>>pattern; m=strlen(text); n=strlen(pattern); find_pattern=Kmp_Search(); if(find_pattern>=0) { cout<<"\nMatching Pattern FOUND at position "<-1 && pattern[k+1]!=text[i]) { k=prefix_array[k]; } if(text[i] == pattern[k+1]) { k++; } if(k==n-1) { return i-k+1; } } return -1; } void Compute_Prefix_Array() { int k=-1; int i=1; prefix_array[0]=k; for(i=1;i-1&&pattern[k+1]!=pattern[i]) { k=prefix_array[k]; } if(pattern[i]==pattern[k+1]) { k++; } prefix_array[i]=k; } } /* SAMPLE OUTPUT: Specify Input Text: ababdabacdababcabab Specify Input Pattern: ababcabab Matching Pattern FOUND at position 11 in the input Text. */ ================================================ FILE: algorithms/kmp_search/java/KMPSearch.java ================================================ public class KMPSearch { public static void main(String[] args) { new KMPSearch().demo(); } private void demo() { String s1 = "abcxabcdabxabcdabcdabcypo"; String s2 = "abcdabcy"; int[] prefixArray = new int[s2.length()]; calculatePrefixArray(s2, prefixArray); for (int i = 0, j = 0; i < s1.length(); i++) { if (s1.charAt(i) == s2.charAt(j)) { j++; } else { if (j != 0) { j = prefixArray[j - 1]; i--; } } if (j == s2.length()) { int index = i - j + 1; System.out.println("Pattern found at index " + index); System.out.println(s1.substring(index, index+s2.length())); return; } } System.out.println("Pattern not found"); } private void calculatePrefixArray(String s, int[] prefixArray) { int j = 0; prefixArray[j] = 0; for (int i = 1; i < s.length(); i++) { if (s.charAt(i) == s.charAt(j)) { prefixArray[i] = j + 1; j++; } else { if (j == 0) { prefixArray[i] = 0; } else { j = prefixArray[j - 1]; while (j != 0) { if (s.charAt(j) == s.charAt(i)) { prefixArray[i] = j + 1; break; } else { j--; } } if (j == 0) { prefixArray[i] = 0; } } } } } } ================================================ FILE: algorithms/kmp_search/python/KMPSearch.py ================================================ class KMP: def partial(self, pattern): """ Calculate partial match table: String -> [Int]""" ret = [0] for i in range(1, len(pattern)): j = ret[i - 1] while j > 0 and pattern[j] != pattern[i]: j = ret[j - 1] ret.append(j + 1 if pattern[j] == pattern[i] else j) return ret def search(self, T, P): """ KMP search main algorithm: String -> String -> [Int] Return all the matching position of pattern string P in S """ partial, ret, j = self.partial(P), [], 0 for i in range(len(T)): while j > 0 and T[i] != P[j]: j = partial[j - 1] if T[i] == P[j]: j += 1 if j == len(P): ret.append(i - (j - 1)) j = 0 return ret ================================================ FILE: algorithms/linear_search/c/linearsearch.C ================================================ #include // linear search function int linear(int a[], int n, int x){ for(int i = 0; i < n; i++){ // if element found return its position if(a[i] == x){ return i + 1; } } // If element not in array return -1; } int main(){ // Sample array int a[] = {1, 2, 5, 10, 7, 11, 8, 9, 22, 3}; //Size of array int n = sizeof(a) / sizeof(a[0]); // Element to be searched int x = 7; // Return value after search int c = linear(a, n, x); if(c == -1) printf("Element not present in list"); else printf("Element is at position %d", c); return 0; } ================================================ FILE: algorithms/linear_search/cpp/linearSearch.cpp ================================================ #include using namespace std; int linearSearch(int* arr, int size, int num){ for(int i = 0; i < size; i++){ if(arr[i] == num){ return i; } } return -1; } int main(){ int arr[] = {1, 2, 5, 10, 7, 11, 8, 9, 22, 3}; int size = sizeof(arr) / sizeof(arr[0]); int num = 7; int result = linearSearch(arr, size, num); if(result == -1) cout << "Element not present in list" << endl; else cout << "Element is at position " << result << endl; return 0; } ================================================ FILE: algorithms/linear_search/java/LinearSearch.java ================================================ import java.util.Scanner; public class LinearSearch { public static void main(String args[]) { int i; int desiredNumber; int numList[]; Scanner in = new Scanner(System.in); numList = new int[] {1,2,3,4,5,6,7,8,9,10}; System.out.println("Desired Number: "); desiredNumber = in.nextInt(); for (i = 0; i < numList.length; i++) { if (numList[i] == desiredNumber) { System.out.println("Number found in the array"); break; } } if (i == numList.length) System.out.println("Number not in the array"); } } ================================================ FILE: algorithms/linear_search/javascript/linear_search.js ================================================ var linearSearch = function(list, target){ var result = null, i = 0, value; for(; i < list.length; i++){ value = list[i]; if(value === target){ result = i; break; } } return result; }; ================================================ FILE: algorithms/linear_search/python/linear_search.py ================================================ def linear_search(a,target): i = 0 while i < len(a) and a[i] != target: i = i+1 return i < len(a); #input: target = target, a = array print('Insert array (list of ints separated by a space): ') #For example: "1 2 3 4" a = list(map(int, input().split())) print('Insert target: ') target = int(input()) print('Pos: ') print(linear_search(a,target)) ================================================ FILE: algorithms/longest_common_subsequence/cpp/LongestCommonSubsequence.cpp ================================================ /* Dynamic Programming C/C++ implementation of LCS problem */ #include int max(int a, int b); /* Returns length of LCS for X[0..m-1], Y[0..n-1] */ int lcs( char *X, char *Y, int m, int n ) { int L[m+1][n+1]; int i, j; /* Following steps build L[m+1][n+1] in bottom up fashion. Note that L[i][j] contains length of LCS of X[0..i-1] and Y[0..j-1] */ for (i=0; i<=m; i++) { for (j=0; j<=n; j++) { if (i == 0 || j == 0) L[i][j] = 0; else if (X[i-1] == Y[j-1]) L[i][j] = L[i-1][j-1] + 1; else L[i][j] = max(L[i-1][j], L[i][j-1]); } } /* L[m][n] contains length of LCS for X[0..n-1] and Y[0..m-1] */ return L[m][n]; } /* Utility function to get max of 2 integers */ int max(int a, int b) { return (a > b)? a : b; } /* Driver program to test above function */ int main() { char X[] = "AGGTAB"; char Y[] = "GXTXAYB"; int m = strlen(X); int n = strlen(Y); printf("Length of LCS is %dn", lcs( X, Y, m, n ) ); return 0; } ================================================ FILE: algorithms/longest_common_subsequence/javaj/LCS.java ================================================ /* Returns length of LCS for X[0..m-1], Y[0..n-1] */ int lcs( char[] X, char[] Y, int m, int n ) { int L[][] = new int[m+1][n+1]; /* Following steps build L[m+1][n+1] in bottom up fashion. Note that L[i][j] contains length of LCS of X[0..i-1] and Y[0..j-1] */ for (int i=0; i<=m; i++) { for (int j=0; j<=n; j++) { if (i == 0 || j == 0) L[i][j] = 0; else if (X[i-1] == Y[j-1]) L[i][j] = L[i-1][j-1] + 1; else L[i][j] = max(L[i-1][j], L[i][j-1]); } } return L[m][n]; } /* Utility function to get max of 2 integers */ int max(int a, int b) { return (a > b)? a : b; } public static void main(String[] args) { LongestCommonSubsequence lcs = new LongestCommonSubsequence(); String s1 = "AGGTAB"; String s2 = "GXTXAYB"; char[] X=s1.toCharArray(); char[] Y=s2.toCharArray(); int m = X.length; int n = Y.length; System.out.println("Length of LCS is" + " " + lcs.lcs( X, Y, m, n ) ); } } ================================================ FILE: algorithms/longest_common_subsequence/javascript/longest_common_subsequence.js ================================================ function lcs(a, b) { var aSub = a.substr(0, a.length - 1); var bSub = b.substr(0, b.length - 1); if (a.length === 0 || b.length === 0) { return ''; } else if (a.charAt(a.length - 1) === b.charAt(b.length - 1)) { return lcs(aSub, bSub) + a.charAt(a.length - 1); } else { var x = lcs(a, bSub); var y = lcs(aSub, b); return (x.length > y.length) ? x : y; } } ================================================ FILE: algorithms/longest_common_subsequence/python/LCS.py ================================================ # Dynamic Programming implementation of LCS problem def lcs(X , Y): # find the length of the strings m = len(X) n = len(Y) # declaring the array for storing the dp values L = [[None]*(n+1) for i in xrange(m+1)] """Following steps build L[m+1][n+1] in bottom up fashion Note: L[i][j] contains length of LCS of X[0..i-1] and Y[0..j-1]""" for i in range(m+1): for j in range(n+1): if i == 0 or j == 0 : L[i][j] = 0 elif X[i-1] == Y[j-1]: L[i][j] = L[i-1][j-1]+1 else: L[i][j] = max(L[i-1][j] , L[i][j-1]) # L[m][n] contains the length of LCS of X[0..n-1] & Y[0..m-1] return L[m][n] #end of function lcs # Driver program to test the above function X = "AGGTAB" Y = "GXTXAYB" print "Length of LCS is ", lcs(X, Y) ================================================ FILE: algorithms/longest_common_substring/java/LongestCommonSubString.java ================================================ import java.util.Arrays; class StringManager { public static String findLongestCommonSubString(String str1, String str2) throws NullPointerException { char[] x = str1.toCharArray(); char[] y = str2.toCharArray(); int LCSMatrix[][] = new int[x.length+1][y.length+1]; int length = 0; int indexOfLastCharX = 0; for(int i = 0; i < x.length; i++){ for(int j = 0; j < y.length; j++){ if(x[i] == y[j]){ if(i == 0 || j == 0){ LCSMatrix[i][j] = 1; if(LCSMatrix[i][j] > length){ length = LCSMatrix[i][j]; indexOfLastCharX = i; } } else { LCSMatrix[i][j] = LCSMatrix[i-1][j-1] + 1; if(LCSMatrix[i][j] > length){ length = LCSMatrix[i][j]; indexOfLastCharX = i; } } } else { LCSMatrix[i][j] = 0; } } } if(indexOfLastCharX == 0) return ""; int indexOfFirstCharX = indexOfLastCharX - length + 1; return new String(Arrays.copyOfRange(x, indexOfFirstCharX, indexOfLastCharX + 1)); } public static void main(String[] args){ String test1 = "immeasurable"; String test2 = "measure"; String result = findLongestCommonSubString(test1, test2); System.out.println(result); } } ================================================ FILE: algorithms/matrix_chain_multiplication/cpp/MCM.cpp ================================================ // See the Cormen book for details of the following algorithm #include #include // Matrix Ai has dimension p[i-1] x p[i] for i = 1..n int MatrixChainOrder(int p[], int n) { /* For simplicity of the program, one extra row and one extra column are allocated in m[][]. 0th row and 0th column of m[][] are not used */ int m[n][n]; int i, j, k, L, q; /* m[i,j] = Minimum number of scalar multiplications needed to compute the matrix A[i]A[i+1]...A[j] = A[i..j] where dimension of A[i] is p[i-1] x p[i] */ // cost is zero when multiplying one matrix. for (i=1; i= v.Length || u[i] < v[j])) { t[k] = u[i]; i++; } else { t[k] = v[j]; j++; } } return t; } } } ================================================ FILE: algorithms/merge_sort/cpp/merge_sort.cpp ================================================ #include int a[50]; void merge(int,int,int); void merge_sort(int low,int high) { int mid; if(lowmid) { for(k=j;k<=high;k++) { b[i]=a[k]; i++; } } else { for(k=h;k<=mid;k++) { b[i]=a[k]; i++; } } for(k=low;k<=high;k++) a[k]=b[k]; } void main() { int num,i; cout<<"******************************************************************* *************"<>num; cout<>a[i] ; } merge_sort(1,num); cout<[a] -> [a] -> [a] merge [] ys = ys merge xs [] = xs merge (x:xs) (y:ys) | x > y = y:x:(merge xs ys) | y >= x = x:y:(merge xs ys) mergeSort' :: Ord a => Int -> [a] -> [a] mergeSort' 1 [x] = [x] mergeSort' len xs = merge (mergeSort' middle left) (mergeSort' (len-middle) right) where middle = len `div` 2 (left, right) = splitAt middle xs mergeSort :: Ord a => [a] -> [a] mergeSort [] = [] mergeSort [x] = [x] mergeSort xs = mergeSort' (length xs) xs ================================================ FILE: algorithms/merge_sort/java/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] private static 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 [1, 2, 3, 4, 5, 6, 7, 8, 9] ================================================ FILE: algorithms/minimum_spanning_tree/cpp/MST.cpp ================================================ #include #include using namespace std; int parent[1000]; int size[1000]; //// union find void init() { for(int i=0;i<1000;i++) { parent[i]=i; } } int root(int i) { while(parent[i]!=i) { parent[i]=parent[parent[i]]; i=parent[i]; } return i; } void unio(int a,int b) { int root_a=root(a); int root_b=root(b); parent[root_a]=parent[root_b]; } ////// krushkal() #define ll long long #define mp make_pair vector > > v; ll nodes,edges; ll kruskal(){ int x,y; ll cost=0,mincost=0; // step 2. loop through sorted array until all nodes are in same set for(ll i=0;i>nodes>>edges; for(int i=0;i>a>>b>>w; v.push_back(make_pair(w, make_pair(a, b))); } // 1. step is to sort all the edges by its weights sort(v.begin(),v.end()); cout<<"ans ="< { if (arr.length === 0) { result.push(m); } else { for (let i = 0; i < arr.length; i++) { let current = arr.slice(); let next = current.splice(i, 1); permute(current.slice(), m.concat(next), result); }; }; }; ================================================ FILE: algorithms/quick_sort/ada/quick_sort.adb ================================================ with Ada.Containers.Vectors; with Ada.Numerics.Discrete_Random; with Ada.Text_IO; with Ada.Integer_Text_IO; use Ada.Text_IO; use Ada.Integer_Text_IO; procedure Quick_Sort is ------------------------------ -- Constant, types, package -- ------------------------------ ARRAY_SIZE : constant Natural := 10; RANGE_MIN : constant Integer := 1; RANGE_MAX : constant Integer := 100; package P_Vectors is new Ada.Containers.Vectors (Positive, Integer); use P_Vectors; ----------------------- -- Method prototype -- ----------------------- -- Initializing an array with default values function Init_Vector return Vector; procedure Put (Tab : Vector); procedure Swap (a : in out Integer; b : in out Integer); function Sort (T : Vector) return Vector; ----------------------------- -- Declaration of methods -- ----------------------------- function Init_Vector return Vector is subtype T_Interval is Integer range RANGE_MIN .. RANGE_MAX; package P_Random is new Ada.numerics.discrete_random (T_Interval); use P_Random; seed : Generator; T : Vector; begin Reset (seed); for i in 1 .. ARRAY_SIZE loop Append (T, Random (seed)); end loop; return T; end Init_Vector; procedure Put (Tab : Vector) is begin for e of Tab loop Put (e, Width => 0); Put (";"); end loop; end Put; procedure Swap (a : in out Integer; b : in out Integer) is c : constant Integer := a; begin a := b; b := c; end Swap; function Sort (T : Vector) return Vector is ----------------------- -- Method prototype -- ----------------------- procedure Sort (T : in out Vector; First, Last : Integer); ----------------------------- -- Declaration of methods -- ----------------------------- procedure Sort (T : in out Vector; First, Last : Integer) is Pivot : Integer := (First + Last) / 2; j : Integer := First + 1; begin if First < Last then Swap (T (First), T (Pivot)); Pivot := First; for i in First + 1 .. Last loop if T (i) < T (Pivot) then Swap (T (i), T (j)); j := j + 1; end if; end loop; Swap (T (Pivot), T (j - 1)); Pivot := j - 1; Sort (T, First, Pivot - 1); Sort (T, Pivot + 1, Last); end if; end Sort; --------------- -- Variables -- --------------- Tab : Vector := T; begin Sort (Tab, First_Index (Tab), Last_Index (Tab)); return Tab; end Sort; --------------- -- Variables -- --------------- T : Vector := Init_Vector; begin Put ("Array : "); Put (T); New_Line; T := Sort (T); Put ("Sorted array : "); Put (T); end Quick_Sort; ================================================ FILE: algorithms/quick_sort/c/quick_sort.c ================================================ #include void quicksort(int number[25],int first,int last){ int i, j, pivot, temp; if(firstnumber[pivot]) j--; if(i #include using namespace std; void quickSort(vector&,int,int); int partition(vector&, int,int); int main() { vector A = {6,10,13,5,8,3,2,25,4,11}; int start = 0; int end = 10; cout << "Before:" << endl; for(auto value : A) cout << value <<" "; cout << endl; quickSort(A, start, end); cout << "After: " << endl; for(auto value : A) cout << value <<" "; cout << endl; } void quickSort(vector& A, int start,int end) { int pivot; if(start < end) { pivot=partition(A, start, end); quickSort(A, start, pivot); quickSort(A, pivot+1, end); } } int partition(vector& A, int start,int end) { int x = A[start]; int i = start; int j; for(j = start+1; j < end; j++) { if(A[j]<=x) { i=i+1; swap(A[i],A[j]); } } swap(A[i],A[start]); return i; } ================================================ FILE: algorithms/quick_sort/csharp/QuickSort.cs ================================================ using System; namespace QuickSort { class QuickSort { static void Main(string[] args) { int[] array = { 3, 10, 7, 9, 1, 5, 8 }; QuickSort qs = new QuickSort(); qs.Sort(array, 0, array.Length - 1); foreach (var item in array) { Console.Write(item.ToString() + ","); } } void Sort(int[] arr, int low, int high) { if (low < high) { int index = Partition(arr, low, high); Sort(arr, low, index - 1); Sort(arr, index + 1, high); } } int Partition(int[] arr, int low, int high) { int pivot = arr[high]; int i = (low - 1); for (int j = low; j < high; j++) { if (arr[j] <= pivot) { i++; int aux = arr[i]; arr[i] = arr[j]; arr[j] = aux; } } int temp = arr[i + 1]; arr[i + 1] = arr[high]; arr[high] = temp; return i + 1; } } } ================================================ FILE: algorithms/quick_sort/csharp/quicksort.cs ================================================ using System; using System.Collections.Generic; /// /// Class for QuickSort /// public class QuickSort { /// /// Main Function /// /// private static void Main(string[] args) { // array declaration var arr = new[] { 9, 7, 5, 11, 12, 2, 14, 3, 10, 4, 6 }; // printing original array Console.Write('\n'); Console.WriteLine("Array before Sorting with Bubble Sort"); foreach (var entry in arr) { Console.Write(entry + " "); } // Sorting Array and printing the sorted array Qsort(arr, 0, arr.Length - 1); Console.Write('\n'); Console.WriteLine("Array after Sorting with Bubble Sort"); foreach (var entry in arr) { Console.Write(entry + " "); } Console.Read(); } /// /// Method for sorting an array /// /// Takes the array /// Left key /// Right Key private static void Qsort(IList list, int left, int right) { if (left >= right) { return; // no sorting for array having either one or zero elements } var teiler = Partition(list, left, right); Qsort(list, left, teiler - 1); Qsort(list, teiler + 1, right); } private static int Partition(IList list, int left, int right) { var i = left; var j = right - 1; var pivot = list[right]; do { while (list[i] <= pivot && i < right) { i++; } while (list[j] >= pivot && j > left) { j--; } if (i < j) { Swap(list, i, j); } } while (i < j); if (list[i] > pivot) { Swap(list, i, right); } return i; } /// /// Swapping of two elements /// /// Array to be swapped /// i th index /// j th index private static void Swap(IList arr, int i, int j) { var tmp = arr[i]; arr[i] = arr[j]; arr[j] = tmp; } } ================================================ FILE: algorithms/quick_sort/haskell/quicksort.hs ================================================ quicksort [] = [] quicksort (p:xs) = (quicksort lesser) ++ [p] ++ (quicksort greater) where (lesser, greater) = partition (< p) xs ================================================ FILE: algorithms/quick_sort/java/QuickSort.java ================================================ public class QuickSort{ static void quickSort(int[] arr,int start, int end){ if (start < end){ int pivot_pos = partition(arr,start,end); quickSort (arr,start, pivot_pos-1); quickSort (arr,pivot_pos+1, end); } } static int partition(int [] arr, int start, int end){ int pivot = arr[end]; int i = start, j = end - 1; while (i <= j) { if (arr[j] <= pivot && arr[i] > pivot){ swap(arr,i,j); } if (arr[i] <= pivot) { i++; } if (arr [j] > pivot){ j--; } } swap(arr,i,end); return i; } static void swap(int[] arr,int i, int j){ int tmp = arr[i] ; arr[i] = arr[j]; arr[j] = tmp; } static void print(int [] arr){ for (int i = 0; i < arr.length; i++) System.out.print(arr[i] + " "); System.out.println(); } public static void main(String [] args){ int [] arr = {9, 7, 5, 11, 12, 2, 14, 3, 10, 4, 6}; System.out.print("Before: "); print(arr); quickSort(arr,0, arr.length-1); System.out.print("After: "); print(arr); } } ================================================ FILE: algorithms/quick_sort/javascript/quick_sort.js ================================================ /* Quicksort implementation in JavaScript */ function quicksort(arr, p, r) { if ( p < r ) { q = partition(arr, p, r); quicksort(arr, p, q-1); quicksort(arr, q+1, r); } return arr; } function partition(arr, p, r) { x = arr[r]; i = p-1; var temp; for(var j = p; j < r; j++) { if (arr[j] < x) { i++; temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } } i++; temp = arr[i]; arr[i] = arr[r]; arr[r] = temp; return i; } var arr = [9, 8, 7, 6, 5, 4, 3, 2, 1]; console.log(quicksort(arr, 0, arr.length-1)); ================================================ FILE: algorithms/quick_sort/kotlin/quicksort.kt ================================================ class QuickSort { private fun quickSort(arr: IntArray, start: Int, end: Int) { if (start < end) { val pivot_pos = partition(arr, start, end) quickSort(arr, start, pivot_pos - 1) quickSort(arr, pivot_pos + 1, end) } } private fun partition(arr: IntArray, start: Int, end: Int): Int { val pivot = arr[end] var i = start var j = end - 1 while (i <= j) { if (arr[j] <= pivot && arr[i] > pivot) { swap(arr, i, j) } if (arr[i] <= pivot) { i++ } if (arr[j] > pivot) { j-- } } swap(arr, i, end) return i } private fun swap(arr: IntArray, i: Int, j: Int) { val tmp = arr[i] arr[i] = arr[j] arr[j] = tmp } private fun print(arr: IntArray) { for (i in arr.indices) { print(arr[i].toString() + " ") } print('\n') } fun main() { val arr = intArrayOf(9, 7, 5, 11, 12, 2, 14, 3, 10, 4, 6) print("Before: ") print(arr) quickSort(arr, 0, arr.size - 1) print("After: ") print(arr) } } ================================================ FILE: algorithms/quick_sort/python/quicksort.py ================================================ def partition(li, start, end): pivot = li[start] left = start + 1 right = end done = False while not done: while left <= right and li[left] <= pivot: left += 1 while right >= left and li[right] >= pivot: right -= 1 if right < left: done = True else: li[left], li[right] = li[right], li[left] li[start], li[right] = li[right], li[start] return right def quicksort(li, start=0, end=None): if not end: end = len(li) - 1 if start < end: pivot = partition(li, start, end) # Recursively perform same operation on first and last halves of list quicksort(li, start, pivot - 1) quicksort(li, pivot + 1, end) return li ================================================ FILE: algorithms/quick_sort/ruby/quick_sort.rb ================================================ def quicksort(array) return array if array.length <= 1 pivot_index = (array.length / 2).to_i pivot_value = array[pivot_index] array.delete_at(pivot_index) lesser = Array.new greater = Array.new array.each do |x| if x <= pivot_value lesser << x else greater << x end end quicksort(lesser) + [pivot_value] + quicksort(greater) end arr = [1,8,4,5,7,3,9,2,6] quicksort(arr) # => [1, 2, 3, 4, 5, 6, 7, 8, 9] ================================================ FILE: algorithms/rabin_karp/java/RabinKarp.java ================================================ import java.math.BigInteger; import java.util.Random; public class RabinKarp { private long patHash; private int M; private long Q; private int R; private long RM; public RabinKarp(String pat) { M=pat.length(); R=256; Q=longPrimeNumber(); RM=1; for (int i=1;i<=M-1;i++) { RM=(R*RM)%Q; } } private long hash(String key,int M) { long h=0; for (int i=0;i using namespace std; int getMax(int arr[], int n) { int mx = arr[0]; for (int i = 1; i < n; i++) if (arr[i] > mx) mx = arr[i]; return mx; } void countSort(int arr[], int n, int exp) { int output[n]; int i, count[10] = {0}; for (i = 0; i < n; i++) count[ (arr[i]/exp)%10 ]++; for (i = 1; i < 10; i++) count[i] += count[i - 1]; for (i = n - 1; i >= 0; i--) { output[count[ (arr[i]/exp)%10 ] - 1] = arr[i]; count[ (arr[i]/exp)%10 ]--; } for (i = 0; i < n; i++) arr[i] = output[i]; } void radixsort(int arr[], int n) { int m = getMax(arr, n); for (int exp = 1; m/exp > 0; exp *= 10) countSort(arr, n, exp); } void print(int arr[], int n) { for (int i = 0; i < n; i++) cout << arr[i] << " "; } int main() { int arr[] = {170, 45, 75, 90, 802, 24, 2, 66}; int n = sizeof(arr)/sizeof(arr[0]); radixsort(arr, n); print(arr, n); return 0; } ================================================ FILE: algorithms/radixsort/python/lsd_radixsort.py ================================================ import functools def get_digit(number, digit): return int((number % (10 ** digit)) / (10 ** (digit - 1))) def lsd_radix_sort(array): MAX_DIGITS = 10 for digit in range(1, MAX_DIGITS + 1): buckets = [[] for _ in range(10)] for number in array: buckets[get_digit(number, digit)].append(number) array = functools.reduce(lambda x, y: x + y, buckets, []) return array if __name__ == '__main__': print (lsd_radix_sort([43, 1243, 354, 0, 1, 22])) print (lsd_radix_sort([2, 10])) print (lsd_radix_sort([1])) print (lsd_radix_sort([])) ================================================ FILE: algorithms/selection_sort/c/SelectionSort.c ================================================ #include const int SIZE=100; void SelectionSort(int arr[SIZE]){ int i,j,temp,min=999999,index; for (i = 0; i < SIZE; i++) { for (j = i; j < SIZE; j++) { if(arr[j] array[j] min_index = j end j += 1 break if j == array.size end array[i], array[min_index] = array[min_index], array[i] i += 1 break if i == array.size end array end numbers = [4, 2, 8, 1, 30, 0, 10, 16] puts "Unsorted: #{numbers}" puts "Sorted: #{selection_sort(numbers)}" ================================================ FILE: algorithms/selection_sort/java/SelectionSort.java ================================================ // Java program for implementation of Selection Sort class SelectionSort { // Implementation of Selection Sort void sort(int ar[]) { int n = ar.length; for (int i = 0; i < n-1; i++) { int min = i, temp; for (int j = i+1; j < n; j++) if (ar[j] < ar[min]){ min = j; } temp = ar[min]; ar[min] = ar[i]; ar[i] = temp; } } // Prints the array void printArray(int arr[]) { int n = arr.length; for (int i = 0; i < n; i++) System.out.print(arr[i] + " "); } // Main function to test public static void main(String args[]) { SelectionSort ob = new SelectionSort(); int arr[] = {79, 34, 7, 23, 11, 10, 99, 1, 15, 11}; ob.sort(arr); System.out.println("Sorted array:"); ob.printArray(arr); } } ================================================ FILE: algorithms/selection_sort/javascript/selection_sort.js ================================================ var selectionSort = function(array){ for(var i = 0; i < array.length; i++){ //set min to the current iteration of i var min = i; for(var j = i+1; j < array.length; j++){ if(array[j] < array[min]){ min = j; } } var temp = array[i]; array[i] = array[min]; array[min] = temp; } return array; }; ================================================ FILE: algorithms/selection_sort/python/selection_sort.py ================================================ # -*- coding: utf-8 -*- """ Created on Sun Oct 1 21:17 2017 @author: john2ksonn Just a simple implementation of the selectionsort algo """ def selectionsort(a): n = len(a) left = 0 while left < n: minVal = left for i in range(left + 1, n): if(a[i] < a[minVal]): minVal = i temp = a[left] a[left] = a[minVal] a[minVal] = temp left += 1 a = [12, 33, 1, 3, 54, 32, 78, 54, 99, 6] print(a) selectionsort(a) print(a) ================================================ FILE: algorithms/selection_sort/ruby/selection_sort.rb ================================================ def selection_sort(input_arr) arr = input_arr.dup n = arr.size - 1 n.times do |i| index_min = i (i + 1).upto(n) do |j| index_min = j if arr[j] < arr[index_min] end arr[i], arr[index_min] = arr[index_min], arr[i] if index_min != i end arr end arr = [1,8,4,5,7,3,9,2,6] selection_sort(arr) # => [1, 2, 3, 4, 5, 6, 7, 8, 9] ================================================ FILE: algorithms/shell_sort/C/ShellSort.c ================================================ #include void shellsort(int arr[], int num) { int i, j, k, tmp; for (i = num / 2; i > 0; i = i / 2) { for (j = i; j < num; j++) { for(k = j - i; k >= 0; k = k - i) { if (arr[k+i] >= arr[k]) break; else { tmp = arr[k]; arr[k] = arr[k+i]; arr[k+i] = tmp; } } } } } int main() { int arr[] = {12, 34, 54, 2, 3}, i; int n = sizeof(arr)/sizeof(arr[0]); shellsort(arr, n); printf("\n Sorted array is: "); for (i = 0; i < n; i++) printf("%d ", arr[i]); return 0; } ================================================ FILE: algorithms/shell_sort/C++/ShellSort.cpp ================================================ // C++ implementation of Shell Sort #include using namespace std; /* function to sort arr using shellSort */ int shellSort(int arr[], int n) { // Start with a big gap, then reduce the gap for (int gap = n/2; gap > 0; gap /= 2) { // Do a gapped insertion sort for this gap size. // The first gap elements a[0..gap-1] are already in gapped order // keep adding one more element until the entire array is // gap sorted for (int i = gap; i < n; i += 1) { // add a[i] to the elements that have been gap sorted // save a[i] in temp and make a hole at position i int temp = arr[i]; // shift earlier gap-sorted elements up until the correct // location for a[i] is found int j; for (j = i; j >= gap && arr[j - gap] > temp; j -= gap) arr[j] = arr[j - gap]; // put temp (the original a[i]) in its correct location arr[j] = temp; } } return 0; } void printArray(int arr[], int n) { for (int i=0; i 0; gap /= 2) { // Do a gapped insertion sort for this gap size. // The first gap elements a[0..gap-1] are already // in gapped order keep adding one more element // until the entire array is gap sorted for (int i = gap; i < n; i += 1) { // add a[i] to the elements that have been gap // sorted save a[i] in temp and make a hole at // position i int temp = arr[i]; // shift earlier gap-sorted elements up until // the correct location for a[i] is found int j; for (j = i; j >= gap && arr[j - gap] > temp; j -= gap) arr[j] = arr[j - gap]; // put temp (the original a[i]) in its correct // location arr[j] = temp; } } return 0; } // Driver method public static void main(String args[]) { int arr[] = {12, 34, 54, 2, 3}; System.out.println("Array before sorting"); printArray(arr); ShellSort ob = new ShellSort(); ob.sort(arr); System.out.println("Array after sorting"); printArray(arr); } } ================================================ FILE: algorithms/shell_sort/python/shellsort.py ================================================ def shellSort(arr): # Start with a big gap, then reduce the gap n = len(arr) gap = n/2 # Do a gapped insertion sort for this gap size. # The first gap elements a[0..gap-1] are already in gapped # order keep adding one more element until the entire array # is gap sorted while gap > 0: for i in range(gap,n): # add a[i] to the elements that have been gap sorted # save a[i] in temp and make a hole at position i temp = arr[i] # shift earlier gap-sorted elements up until the correct # location for a[i] is found j = i while j >= gap and arr[j-gap] >temp: arr[j] = arr[j-gap] j -= gap # put temp (the original a[i]) in its correct location arr[j] = temp gap /= 2 ================================================ FILE: algorithms/sieve_of_eratosthenes/cpp/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 for (int i=p*2; 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 = 100; cout << "Following are the prime numbers smaller " << " than or equal to " << n << endl; SieveOfEratosthenes(n); return 0; } ================================================ FILE: algorithms/sieve_of_eratosthenes/java/sieve.java ================================================ import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class sieve { /* * Function which finds all the prime numbers less than or equal to n */ private void sievefunction(int n, boolean primearr[]) { int i; int j; // Begin from the first prime (2) for(i = 2 ; i*i<=n ; i++) { // remove the multipes of the number i if it is prime if(primearr[i] == true) { // loops into all the multiples of i sby incrementing with i at every step for(j = i*2 ; j<=n ; j = j+i) { // marking them as false since they are not prime primearr[j] = false; } } } } /* * Function for printing all the primes obtained in the end */ private void print(int n, boolean primearr[]) { int k; for(k = 2 ; k<=n; k++) { if(primearr[k] == true) { System.out.print(k + " "); } } } public static void main(String args[]) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String a = br.readLine(); // Take user input int n = Integer.parseInt(a); // n denotes the number upto which primes have to be displayed // initialise the boolean array primearr with all true values // at the end of the algorithm only those values will be true that are prime boolean[] primearr = new boolean[n+1]; for(int i = 0 ; i<=n ; i++) { primearr[i] = true; } sieve g = new sieve(); // calling the sievefunction given n and boolean primearr g.sievefunction(n, primearr); // printing the primes obtained in the end g.print(n, primearr); } } ================================================ FILE: algorithms/sieve_of_eratosthenes/javascript/sieve.js ================================================ let sieveOfEratosthenes = function(n) { let array = []; let upperLimit = Math.sqrt(n); let output = []; for (let i = 0; i < n; i++) { array.push(true); } for (let i = 2; i <= upperLimit; i++) { if (array[i]) { for (let j = i * i; j < n; j += i) { array[j] = false; } } } for (let i = 2; i < n; i++) { if (array[i]) { output.push(i); } } return output; }; ================================================ FILE: algorithms/sieve_of_eratosthenes/python/sieve.py ================================================ def run_sieve(N, isPrime): for i in range(N+1): if isPrime[i]: for j in range(i+1, N+1): if j % i == 0: isPrime[j] = False def print_sieve(N, isPrime): for i in range(N+1): if isPrime[i]: print i, def sieve(N): isPrime = [True] * (N+1) isPrime[0], isPrime[1] = False, False run_sieve(N, isPrime) print_sieve(N, isPrime) sieve(int(input("Input size of sieve: "))) ================================================ FILE: algorithms/sort/heap_sort/java/heap_sort.java ================================================ // Java program for implementation of Heap Sort public class HeapSort { public void sort(int arr[]) { int n = arr.length; // Build heap (rearrange array) for (int i = n / 2 - 1; i >= 0; i--) heapify(arr, n, i); // One by one extract an element from heap for (int i=n-1; i>=0; i--) { // Move current root to end int temp = arr[0]; arr[0] = arr[i]; arr[i] = temp; // call max heapify on the reduced heap heapify(arr, i, 0); } } // To heapify a subtree rooted with node i which is // an index in arr[]. n is size of heap void heapify(int arr[], int n, int i) { int largest = i; // Initialize largest as root int l = 2*i + 1; // left = 2*i + 1 int r = 2*i + 2; // right = 2*i + 2 // If left child is larger than root if (l < n && arr[l] > arr[largest]) largest = l; // If right child is larger than largest so far if (r < n && arr[r] > arr[largest]) largest = r; // If largest is not root if (largest != i) { int swap = arr[i]; arr[i] = arr[largest]; arr[largest] = swap; // Recursively heapify the affected sub-tree heapify(arr, n, largest); } } /* 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; bool isAnagram(string a, string b) { sort(a.begin(),a.end()); sort(b.begin(),b.end()); if(a.compare(b)==0) return true; return false; } vector findAnagrams(string arr[], int n) { vector v; for(int i=0;i"< ress = findAnagrams(arr, n); for(int i=0;i using namespace std; int moves(0); void Hanoi(int m, char a, char b, char c); int main(){ int discs; cout << "Enter the number of discs: " << endl; cin >> discs; Hanoi(discs, 'A', 'B', 'C'); cout << "It took " << moves << " moves. " << endl; return 0; } void Hanoi(int m, char a, char b, char c) { moves++; if(m == 1){ cout << "Move disc " << m << " from " << a << " to " << c << endl; } else{ Hanoi(m-1, a,c,b); cout << "Move disc " << m << " from " << a << " to " << c << endl; Hanoi(m-1,b,a,c); } } ================================================ FILE: algorithms/tower_of_hanoi/java/towers_of_hanoi.java ================================================ public class TowersOfHanoi { public void solve(int n, String start, String auxiliary, String end) { if (n == 1) { System.out.println(start + " -> " + end); } else { solve(n - 1, start, end, auxiliary); System.out.println(start + " -> " + end); solve(n - 1, auxiliary, start, end); } } public static void main(String[] args) { TowersOfHanoi towersOfHanoi = new TowersOfHanoi(); System.out.print("Enter number of discs: "); Scanner scanner = new Scanner(System.in); int discs = scanner.nextInt(); towersOfHanoi.solve(discs, "A", "B", "C"); } } ================================================ FILE: algorithms/tower_of_hanoi/javascript/tower_of_hanoi.js ================================================ // Prints the movement function moveDisk(from_pole, to_pole) { console.log("Moving disk from " + from_pole + " to " + to_pole); } // Tower of Hanoi implementation function towerOfHanoi(height, from_pole=1, to_pole=2, aux=3) { if (height > 0) { towerOfHanoi(height - 1, from_pole, to_pole, aux); moveDisk(from_pole, to_pole); towerOfHanoi(height - 1, aux, from_pole, to_pole); } } towerOfHanoi(3); ================================================ FILE: algorithms/tower_of_hanoi/php/towers_of_hanoi.php ================================================ = 1){ move($n-1, $src,$temp, $dest); printf("Moving %d -> %d ",$src, $dest); echo "
"; move($n-1, $temp , $dest , $src); } } move(3,1,3,2); ?> ================================================ FILE: algorithms/tower_of_hanoi/python/tower_of_hanoi.py ================================================ def move_disk(from_pole, to_pole): ''' Prints the movement ''' print('Moving disk from', from_pole, ' to ', to_pole) def tower_of_hanoi(height, from_pole=1, to_pole=2, aux=3): ''' Tower of Hanoi implementation ''' if height > 0: tower_of_hanoi(height - 1, from_pole, to_pole, aux) move_disk(from_pole, to_pole) tower_of_hanoi(height - 1, aux, from_pole, to_pole) if __name__ == '__main__': tower_of_hanoi(3) ================================================ FILE: data_structures/arraylist/java/arraylist.java ================================================ import java.util.*; public class arraylist { public static void main(String args[]) { // create an array list ArrayList al = new ArrayList(); System.out.println("Initial size of al: " + al.size()); // add elements to the array list al.add("C"); al.add("A"); al.add("E"); al.add("B"); al.add("D"); al.add("F"); al.add(1, "A2"); System.out.println("Size of al after additions: " + al.size()); // display the array list System.out.println("Contents of al: " + al); // Remove elements from the array list al.remove("F"); al.remove(2); System.out.println("Size of al after deletions: " + al.size()); System.out.println("Contents of al: " + al); } } ================================================ FILE: data_structures/avl_tree/java/AVL.java ================================================ public class AVL { class Node { private int data, height; private Node left, right; public Node(int data, int height) { this.data = data; this.height = height; } } Node root = null; private int getHeight(Node root) { if(root == null) return 0; return root.height; } private int getBalance(Node root) { if(root == null) return 0; return (getHeight(root.left) - getHeight(root.right)); } private Node rightRotate(Node root) { Node temp1 = root.left; Node temp2 = temp1.right; temp1.right = root; root.left = temp2; root.height = Math.max(getHeight(root.left), getHeight(root.right)) + 1; temp1.height = Math.max(getHeight(temp1.left), getHeight(temp1.right)) + 1; return temp1; } private Node leftRotate(Node root) { Node temp1 = root.right; Node temp2 = temp1.left; temp1.left = root; root.right = temp2; root.height = Math.max(getHeight(root.left), getHeight(root.right)) + 1; temp1.height = Math.max(getHeight(temp1.left), getHeight(temp1.right)) + 1; return temp1; } public void insert(int data) { root = insert(root, data, 0); } private Node insert(Node root, int data, int height) { if(root == null) return new Node(data, height); else if(root.data > data) root.left = insert(root.left, data, height+1); else if(root.data < data) root.right = insert(root.right, data, height+1); else return root; int balance = getBalance(root); if(balance > 1 && data < root.left.data) { return rightRotate(root); } else if(balance > 1 && data > root.left.data) { root.left = leftRotate(root.left); return rightRotate(root); } else if(balance < -1 && data > root.right.data) { return leftRotate(root); } else if(balance < -1 && data < root.right.data) { root.right = rightRotate(root.right); return leftRotate(root); } return root; } public void preorder() { preorder(root); } private void preorder(Node root) { if(root == null) return; System.out.println(root.data); preorder(root.left); preorder(root.right); } public static void main(String[] args) { AVL a1 = new AVL(); a1.insert(10); a1.insert(20); a1.insert(30); a1.insert(40); a1.insert(50); a1.insert(25); a1.preorder(); } } ================================================ FILE: data_structures/avl_tree/javascript/avl.js ================================================ var Node = function (value) { this.left = null; this.right = null; this.value = value; this.balance = 0; }; var AVL = function () { this._root = null; this._size = 0; this.get = function (value){ if (this._root === null) return null; return this._get(value, this._root).value; }; this._get = function (value, root){ if(root === null) return null; if (value == root.value) return root; if (value < root.value) return this._get(value, root.left); else return this._get(value, root.right); }; this.insert = function (value){ this._root = this._insert(value, this._root); this._size++; this._root = this.rebalance(this._root, value); }; this._insert = function (value, root){ if (root === null) return new Node(value); if (value < root.value) root.left = this._insert(value, root.left); else if (value > root.value) root.right = this._insert(value, root.right); else this._size--; return root; } this.Height = function (node){ if (node !== null) return 1 + Math.max( this.Height(node.left), this.Height(node.right) ); return 0; }; this.rotateLeft = function (n){ temp = n; n = n.right; temp.right = n.left; n.left = temp; return n; }; this.rotateRight = function (n){ temp = n; n = n.left; temp.left = n.right; n.right = temp; return n; }; this.rebalance = function(node, value){ if(node === null) return null; if(node.value > value) node.left = this.rebalance(node.left, value); else if(node.value < value) node.right = this.rebalance(node.right, value); this.setBalance(node); if (node.balance == -2){ if (this.Height(node.left.left) >= this.Height(node.left.right)) node = this.rotateRight(node); else node = this.rotateLeftThenRight(node); } else if (node.balance == 2){ if (this.Height(node.right.right) >= this.Height(node.right.left)) node = this.rotateLeft(node); else node = this.rotateRightThenLeft(node); } return node; } this.rotateLeftThenRight = function(node){ node.left = this.rotateLeft(node.left); node = this.rotateRight(node); return node; } this.rotateRightThenLeft = function(node){ node.right = this.rotateRight(node.right); node = this.rotateLeft(node); return node; } this.setBalance = function(node){ if(node === null) return null; node.balance = this.Height(node.right) - this.Height(node.left); return node; } this.delete = function(value){ this._root = this._delete(this._root, value); this._root = this.rebalance(this._root, value); if(this._root === null)return; } this._delete = function(node, value){ if (node === null) return null; var cmp; if(node.value < value) cmp = -1; else if(node.value > value) cmp = 1; else cmp = 0; if (cmp > 0) node.left = this._delete (node.left, value); else if (cmp < 0) node.right = this._delete (node.right, value); else{ if (node.right === null) return node.left; if (node.left === null) return node.right; if(node.right === null && node.left === null) return null; var temp = this._Min(node.right); node.value = temp.value; node.right = this._DeleteMin(node.right); } return node; } this.Min = function(){ return this._Min(this._root); } this._Min = function(r){ var temp = r; while(temp.left !== null) temp = temp.left; return temp; } this.DeleteMin = function(){ this._DeleteMin(this._root); } this._DeleteMin = function(n){ if(n.left !== null) n.left = this._DeleteMin(n.left); else{ if(n.right !== null) return n.right; else return null; } return n; } }; ================================================ FILE: data_structures/bag/java/Bag.java ================================================ package bag.java; import java.util.Iterator; import java.util.NoSuchElementException; /** * Collection which does not allow removing elements (only collect and iterate) * * @param - the generic type of an element in this bag */ public class Bag implements Iterable { private Node firstElement; // first element of the bag private int size; // size of bag private static class Node { private Element content; private Node nextElement; } /** * Create an empty bag */ public Bag() { firstElement = null; size = 0; } /** * @return true if this bag is empty, false otherwise */ public boolean isEmpty() { return firstElement == null; } /** * @return the number of elements */ public int size() { return size; } /** * @param element - the element to add */ public void add(Element element) { Node oldfirst = firstElement; firstElement = new Node<>(); firstElement.content = element; firstElement.nextElement = oldfirst; size++; } /** * Checks if the bag contains a specific element * * @param element which you want to look for * @return true if bag contains element, otherwise false */ public boolean contains(Element element) { Iterator iterator = this.iterator(); while(iterator.hasNext()) { if (iterator.next().equals(element)) { return true; } } return false; } /** * @return an iterator that iterates over the elements in this bag in arbitrary order */ public Iterator iterator() { return new ListIterator<>(firstElement); } @SuppressWarnings("hiding") private class ListIterator implements Iterator { private Node currentElement; public ListIterator(Node firstElement) { currentElement = firstElement; } public boolean hasNext() { return currentElement != null; } /** * remove is not allowed in a bag */ @Override public void remove() { throw new UnsupportedOperationException(); } public Element next() { if (!hasNext()) throw new NoSuchElementException(); Element element = currentElement.content; currentElement = currentElement.nextElement; return element; } } /** * main-method for testing */ public static void main(String[] args) { Bag bag = new Bag<>(); bag.add("1"); bag.add("1"); bag.add("2"); System.out.println("size of bag = " + bag.size()); for (String s : bag) { System.out.println(s); } System.out.println(bag.contains(null)); System.out.println(bag.contains("1")); System.out.println(bag.contains("3")); } } ================================================ FILE: data_structures/binary_search_tree/binary_search_tree.md ================================================ ## ELI5 A tree is a container that stores items in sorted order in memory.It's like the inversed version of an actual tree. ### Pros * BSTs allow fast lookup, addition and removal of items. ### Cons * Tree gets skewed to one side when we save sorted items.The advantage of fast operations is lost. ## Technical Explaination Binary Search Tree is a node-based binary tree data structure. *NODE: All items are stored in nodes. *ROOT: The top node in a tree. *CHILD: A node directly connected to another node when moving away from the Root.Each node can have 0 to 2 child nodes.Left child's value is smaller than its parent and right child's value is greater than its parent. *LEAVES: Nodes with no child nodes. *HEIGHT: Number of edges on the longest path between the root and a leaf. *DEPTH: The depth of a node is the number of edges from the tree's root node to the node. Storing 2,4,1,10,3 in a BST: 2 / \ 1 4 / \ 3 10 ### Pros * Time Complexity of insertion,deletion and search is O(h). h=height of tree i.e. O(log n) which is less than linked list and array. n=number of nodes ### Cons * For a skewed binary tree time complexity of insertion,deletion and search is O(n). As for a skewed binary tree height h is O(n). e.g 2,3,4,5 2 \ 3 \ 4 \ 5 ================================================ FILE: data_structures/binary_search_tree/c/BSTtraversal.c ================================================ // C program for different tree traversals #include #include /* A binary tree node has data, pointer to left child and a pointer to right child */ struct node { int data; struct node* left; struct node* right; }; /* Helper function that allocates a new node with the given data and NULL left and right pointers. */ 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); } /* Given a binary tree, print its nodes according to the "bottom-up" postorder traversal. */ void printPostorder(struct node* node) { if (node == NULL) return; // first recur on left subtree printPostorder(node->left); // then recur on right subtree printPostorder(node->right); // now deal with the node printf("%d ", node->data); } /* Given a binary tree, print its nodes in inorder*/ void printInorder(struct node* node) { if (node == NULL) return; /* first recur on left child */ printInorder(node->left); /* then print the data of node */ printf("%d ", node->data); /* now recur on right child */ printInorder(node->right); } /* Given a binary tree, print its nodes in preorder*/ void printPreorder(struct node* node) { if (node == NULL) return; /* first print data of node */ printf("%d ", node->data); /* then recur on left sutree */ printPreorder(node->left); /* now recur on right subtree */ printPreorder(node->right); } /* Driver program to test above functions*/ 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("\nPreorder traversal of binary tree is \n"); printPreorder(root); printf("\nInorder traversal of binary tree is \n"); printInorder(root); printf("\nPostorder traversal of binary tree is \n"); printPostorder(root); getchar(); return 0; } ================================================ FILE: data_structures/binary_search_tree/cpp/BST.h ================================================ /** A simple BST in C++ Author: PryDt */ #ifndef BST_H #define BST_H #include template class BinarySearchTree { public: // constructor BinarySearchTree() { root = nullptr; } ~BinarySearchTree() { destroy(root); } // insert void insert(T data) { insert(data, root); } // find min int findMin() { return findMin(root); } // remove node void remove(T data) { remove(data, root); } // check if a number is in tree bool find(T data) { return find(data, root); } // print tree in order out to stdout void printTree() { std::cout << "[ "; print(root); std::cout << " ]\n"; } private: // basic building block of tree struct Node { T key; // value of node Node *left; // smaller Node *right; // greater }; void destroy(Node *n) { if(n == nullptr) return; destroy(n->left); destroy(n->right); delete n; } // helper function print void print(Node *ptr) { if (root != nullptr) { if (ptr->left != nullptr) { print(ptr->left); } std::cout << ptr->key << " "; if (ptr->right != nullptr) { print(ptr->right); } } else { std::cout << "Binary Search Tree is empty\n"; } } // internals for find function bool find(T data, Node *n) { if(data == n->key) return true; if(data > n->key && n->right != nullptr) return find(data, n->right); if(data < n->key && n->left != nullptr) return find(data, n->left); return false; } // find min int findMin(Node *ptr) { if (root == nullptr) { std::cout << "findMin(): BST is empty\n"; return -324243; } else { if (ptr->left != nullptr) { return findMin(ptr->left); } else { return ptr->key; } } } // make a new node Node *createLeaf(T data) { Node *n = new Node(); n->key = data; n->left = nullptr; n->right = nullptr; return n; } void insert(T data, Node *ptr) { if (root == nullptr) { root = createLeaf(data); return; } else if (data < ptr->key) { if (ptr->left != nullptr) insert(data, ptr->left); else { ptr->left = createLeaf(data); return; } } else if (data > ptr->key) { if (ptr->right != nullptr) insert(data, ptr->right); else { ptr->right = createLeaf(data); return; } } else { std::cout << "Attempted to add duplicate key in BST\n"; } } // remove match void removeMatch(Node *parent, Node *match, bool left) { if (root != nullptr) { Node *delptr; int small; // case A: 0 children if (match->left == nullptr && match->right == nullptr) { delptr = match; left ? parent->left = nullptr : parent->right = nullptr; delete delptr; } // case B: 1 child else if ((match->left == nullptr) != (match->right == nullptr)) { (left) ? ((match->right != nullptr) ? parent->left = parent->right : parent->left = parent->left) : (match->right != nullptr ? parent->right = match->right : parent->right = match->left); (match->right != nullptr) ? match->right = nullptr : match->left = nullptr; delptr = match; delete delptr; } // case C: 2 children else { small = findMin(match->right); remove(small, match); match->key = small; } } else { std::cout << "removeMatch(): cannot remove match, BST empty\n"; } } // removes root of tree (used in special cases) void removeRootMatch() { if (root == nullptr) { std::cout << "removeRootMatch(): BST is empty\n"; return; } Node *delptr = root; int small; // case A: 0 children if (root->left == nullptr && root->right == nullptr) { root = nullptr; delete delptr; } // case B: 1 child else if ((root->left == nullptr) != (root->right == nullptr)) { root = (root->left != nullptr) ? root->left : root->right; (root->right != nullptr) ? delptr->right = nullptr : delptr->left = nullptr; delete delptr; } // case C: 2 children else { small = findMin(root->right); remove(small, root); root->key = small; } } void remove(T data, Node *parent) { if (root == nullptr) { std::cout << "remove(): FAILED, BST is empty\n"; } else { if (root->key == data) { removeRootMatch(); } else { if (data < parent->key && parent->left != nullptr) { parent->left->key == data ? removeMatch(parent, parent->left, true) : remove(data, parent->left); } else if (data > parent->key && parent->right != nullptr) { parent->right->key == data ? removeMatch(parent, parent->right, false) : remove(data, parent->right); } else { std::cout << "remove(): The key(" << data << ") was not found in BST\n"; } } } } // root of the tree Node *root; }; // typedef for convenience typedef BinarySearchTree intBST; #endif // BST_H ================================================ FILE: data_structures/binary_search_tree/java/binary_search_tree.java ================================================ /* ** Binary tree & Binary tree search implementation in java */ /* **Input patterns **create 25 15 9 18 2 90 25 42 60 35 1 19 10 100 3 - create the binary tree **print - print the binary tree in sorted order **search 15 **delete 15 **search 15 **search 13 **add 13 **search 13 **pre-order **in-order **post-order ** ** */ import java.util.Scanner; import java.util.LinkedList; class Node { //create a Node class private int value; private Node left; private Node right; public Node getLeft() { return this.left; } public void setLeft(Node e) { this.left = e; } public Node getRight() { return this.right; } public void setRight(Node e) { this.right = e; } public void setValue(int value) { this.value = value; } public int getValue() { return this.value; } } /** * * @author Thuvarakan */ public class BinarySearchTree { public static void main(String[] args){ Scanner scanner = new Scanner(System.in); BinSearchTree th = new BinSearchTree(); Node root = null; String line; while ((line = scanner.nextLine() )!= null) { String[] tokens = line.split(" "); //check the instructions switch (tokens[0]) { //if instruction is create case "create": { int[] a = new int[tokens.length - 1]; for (int i = 0; i < a.length; i++) { a[i] = Integer.parseInt(tokens[i + 1]); } root = th.createTree(a); if (root != null) { System.out.println("S"); } else { System.out.println("F"); } break; } //if instruction is print case "print": th.print_tree(root); break; //if instruction is search case "search": if (th.searchValue(root, Integer.parseInt(tokens[1])) != null) { System.out.println("T"); } else { System.out.println("F"); } break; //if instruction is delete case "delete": if (th.deleteValue(root, Integer.parseInt(tokens[1]))) { System.out.println("S"); } else { System.out.println("F"); } break; //if instruction is add case "add": if (th.addValue(root, Integer.parseInt(tokens[1]))) { System.out.println("S"); } else { System.out.println("F"); } break; //if instruction is pre-order case "pre-order": th.traverse_preorder(root); System.out.println(); break; //if instruction is in-order case "in-order": th.traverse_inorder(root); System.out.println(); break; //if instruction is post-order case "post-order": th.traverse_postorder(root); System.out.println(); break; } } } } class Bintree { public boolean addLeftChild(Node parent, int newvalue) { //add left child for binary tree if (parent.getLeft() == null) { parent.setLeft(new Node()); parent.getLeft().setValue(newvalue); return true; } return false; } public boolean addRightChild(Node parent, int newvalue) { //add right child for binary tree if (parent.getRight() == null) { parent.setRight(new Node()); parent.getRight().setValue(newvalue); return true; } return false; } public Node createTree(int[] elements) { //create a new tree LinkedList lisa = new LinkedList<>(); Node root = new Node(); Node root1 = root; root.setValue(elements[0]); lisa.addLast(root); int i = 1; while (!lisa.isEmpty()) { root = lisa.removeFirst(); if (i < elements.length) { this.addLeftChild(root, elements[i]); lisa.addLast(root.getLeft()); i++; if (i < elements.length) { this.addRightChild(root, elements[i]); lisa.addLast(root.getRight()); i++; } } else { return root1; } } return root1; } public boolean expandTree(Node root, int[] elements) { //expand tree LinkedList nodeList = new LinkedList<>(); //create a linkedlist nodeList.addLast(root); int i = 0; while (!nodeList.isEmpty()) { //run until finish all array elements root = nodeList.removeFirst(); if (i < elements.length) { if (root.getLeft() == null) { this.addLeftChild(root, elements[i]); nodeList.addLast(root.getLeft()); i++; } else { nodeList.addLast(root.getLeft()); } if (i < elements.length) { if (root.getRight() == null) { this.addRightChild(root, elements[i]); nodeList.addLast(root.getRight()); i++; } else { nodeList.addLast(root.getRight()); } } } else { return true; } } return false; } public void traverse_inorder(Node root) { //inorder traversal if (root != null) { traverse_inorder(root.getLeft()); System.out.print(root.getValue() + " "); traverse_inorder(root.getRight()); } } public void traverse_preorder(Node root) { //inorder traversal if (root != null) { System.out.print(root.getValue() + " "); traverse_preorder(root.getLeft()); traverse_preorder(root.getRight()); } } public void traverse_postorder(Node root) { //postorder traversal if (root != null) { traverse_postorder(root.getLeft()); traverse_postorder(root.getRight()); System.out.print(root.getValue() + " "); } } } class BinSearchTree extends Bintree { //create binary search tree public Node insert(Node root, int key) { //define a insert method //recursivly check and add the value in the correct place if (root == null) { root = new Node(); root.setValue(key); } else if (key < root.getValue()) { root.setLeft(insert(root.getLeft(), key)); } else { root.setRight(insert(root.getRight(), key)); } return root; } @Override public Node createTree(int[] p) { //create Binary search tree Node thua = null; Node roots = null; for (int i = 0; i < p.length; i++) { thua = this.insert(thua, p[i]); if (i == 0) { roots = thua; } } return roots; } public boolean addValue(Node root, int newvalue) { //add value to the binary search tree if (this.searchValue(root, newvalue) == null) { if (root == null) { root = new Node(); root.setValue(newvalue); } else if (newvalue < root.getValue()) { root.setLeft(insert(root.getLeft(), newvalue)); } else { root.setRight(insert(root.getRight(), newvalue)); } return true; } return false; } public boolean deleteValue(Node root, int value) { //delete a given value from tree Node parentNode = root; Node deleteNode; Node replaceNode; if (root == null) { return false; } if (this.searchValue(root, value) == null) { //Checks whether a given value exists return false; } deleteNode = root; //get the node being deleted & its parent Node while (deleteNode != null && deleteNode.getValue() != value) { parentNode = deleteNode; if (value < deleteNode.getValue()) { deleteNode = deleteNode.getLeft(); } else if (value > deleteNode.getValue()) { deleteNode = deleteNode.getRight(); } } if (deleteNode.getLeft() == null && deleteNode.getRight() == null) { //when delete node don't has any child node if (parentNode.getLeft() == deleteNode) { parentNode.setLeft(null); return true; } else { parentNode.setRight(null); return true; } } if (deleteNode.getLeft() != null && deleteNode.getRight() == null) { // when it has only a left child if (parentNode.getLeft() == deleteNode) { parentNode.setLeft(deleteNode.getLeft()); return true; } else { parentNode.setRight(deleteNode.getLeft()); return true; } } if (deleteNode.getLeft() == null && deleteNode.getRight() != null) { // when it has only a right child if (parentNode.getLeft() == deleteNode) { parentNode.setLeft(deleteNode.getRight()); return true; } else { parentNode.setRight(deleteNode.getRight()); return true; } } if (deleteNode.getLeft() != null && deleteNode.getRight() != null) { //when it has two child nodes parentNode = deleteNode; replaceNode = deleteNode.getRight(); if (replaceNode.getLeft() == null) { deleteNode.setValue(replaceNode.getValue()); deleteNode.setRight(replaceNode.getRight()); return true; } //find the replace node and its parent while (replaceNode.getLeft() != null) { parentNode = replaceNode; replaceNode = replaceNode.getLeft(); } deleteNode.setValue(replaceNode.getValue()); parentNode.setLeft(replaceNode.getRight()); return true; } return false; } public Node searchValue(Node root, int key) { //find the node of the given value Node refNode = root; while (refNode != null) { //get the node of the key value if (key == refNode.getValue()) { return refNode; } else if (key < refNode.getValue()) { refNode = refNode.getLeft(); } else { refNode = refNode.getRight(); } } return null; } public void print_tree(Node root) { this.traverse_inorder(root); //print binary search tree in sorted order System.out.println(); } } ================================================ FILE: data_structures/binary_search_tree/java/bst_operations/CheckBST.java ================================================ package bst_operations; public class CheckBST { public static void main(String[] args) { new CheckBST().demo(); } private void demo() { Node n = new Node(4); // left n.left = new Node(2); n.left.left = new Node(1); n.left.right = new Node(3); //right n.right = new Node(5); System.out.println(isBST(n, Integer.MIN_VALUE, Integer.MAX_VALUE)); } private boolean isBST(Node n, int min, int max) { if (n == null) { return true; } if (n.data < min || n.data > max) { return false; } if(n.data == max || n.data == min) { System.out.println("duplication of data"); return false; } return isBST(n.left, min, n.data) && isBST(n.right, n.data, max); } } ================================================ FILE: data_structures/binary_search_tree/java/bst_operations/CorrectBST.java ================================================ package bst_operations; import java.util.ArrayList; /** * Two nodes of a BST are swapped, correct the BST */ public class CorrectBST { public static void main(String[] args) { new CorrectBST().demo(); } private void demo() { Node n = new Node(10); n.left = new Node(5); n.left.left = new Node(2); n.left.right = new Node(20); n.right = new Node(8); /* 10 / \ 5 8 / \ 2 20 */ ArrayList list = new ArrayList(); display(n); balanceBST(n, list, Integer.MIN_VALUE, Integer.MAX_VALUE); System.out.println(); list.get(0).data = list.get(0).data + list.get(1).data; list.get(1).data = list.get(0).data - list.get(1).data; list.get(0).data = list.get(0).data - list.get(1).data; System.out.println("After"); display(n); } private void display(Node n) { if (n != null) { display(n.left); System.out.print(n.data + "\t"); display(n.right); } } private void balanceBST(Node n, ArrayList list, int min, int max) { if (n == null) { return; } if (n.data > max || n.data < min) { list.add(n); } balanceBST(n.left, list, min, n.data); balanceBST(n.right, list, n.data, max); } } ================================================ FILE: data_structures/binary_search_tree/java/bst_operations/FindAncestor.java ================================================ package bst_operations; /** * Created by kalsi on 30/08/17. * find lowest ancestor of two items * I assumed both the elements are present in the tree */ public class FindAncestor { public static void main(String[] args) { new FindAncestor().demo(); } private void demo() { Node n = new Node(8); // left n.left = new Node(3); n.left.left = new Node(1); n.left.right = new Node(6); n.left.right.left = new Node(4); n.left.right.right = new Node(7); //right n.right = new Node(10); n.right.right = new Node(14); n.right.right.left = new Node(13); /* 8 3 10 1 6 14 4 7 13 * * */ int m1 = 4; int m2 = 7; Node ancestor = lowestAncestor(n, m1, m2); System.out.println("Lowest ancestor is : " + ancestor.data); System.out.println("Distance from root to ancestor is: " + findDistance(n, ancestor)); } private int findDistance(Node n, Node ancestor) { return findDistanceUtil(n,ancestor, 0); } private int findDistanceUtil(Node n, Node ancestor, int level) { if(n == null || ancestor == null) { return 0; } if(n.data == ancestor.data) { return level; } level++; return findDistanceUtil(n.left, ancestor, level) + findDistanceUtil(n.right, ancestor, level); } private Node lowestAncestor(Node n, int m1, int m2) { if (n == null) { return null; } if (n.data == m2 || n.data == m1) { return n; } Node left = lowestAncestor(n.left, m1, m2); Node right = lowestAncestor(n.right, m1, m2); if (left != null && right != null) { return n; } return left == null ? right : left; } } ================================================ FILE: data_structures/binary_search_tree/java/bst_operations/InorderSuccessor.java ================================================ package bst_operations; public class InorderSuccessor { public static void main(String[] args) { new InorderSuccessor().demo(); } private void demo() { Node n = new Node(8); // left n.left = new Node(3); n.left.left = new Node(1); n.left.right = new Node(6); n.left.right.left = new Node(4); n.left.right.right = new Node(7); //right n.right = new Node(10); n.right.right = new Node(14); n.right.right.left = new Node(13); /* 8 3 10 1 6 14 4 7 13 * * */ System.out.println(getNextSuccessor(n, new Node(8))); } private Integer getNextSuccessor(Node root, Node target) { if (root == null || target == null) { return null; } Boolean found = false; Node candidate = null; Node current = root; while (current != null) { if (current.data == target.data) { found = true; current = current.right; } else if (current.data > target.data) { candidate = current; current = current.left; } else { current = current.right; } } return found && candidate != null ? candidate.data : null; } } ================================================ FILE: data_structures/binary_search_tree/java/bst_operations/LargestBST.java ================================================ package bst_operations; /** * Created by kalsi on 06/09/17. */ public class LargestBST { class BSTCount { Boolean isBST; int count; } class BST { int max; Node n; public BST() { max = -1; n = null; } } public static void main(String[] args) { new LargestBST().demo(); } private void demo() { Node n = new Node(50); // left n.left = new Node(30); n.left.left = new Node(5); n.left.right = new Node(20); //right n.right = new Node(60); n.right.left = new Node(45); n.right.right = new Node(70); n.right.right.left = new Node(65); n.right.right.right = new Node(80); /* 50 / \ 30 60 / \ / \ 5 20 45 70 / \ 65 80 */ largestBST(n); } private void largestBST(Node n) { BST bst = new BST(); BSTCount bstCount = new BSTCount(); largestBSTUtil(n, bst, bstCount); System.out.println("Largest BST: " + bst.n.data); System.out.println("Count: " + bst.max); } private void largestBSTUtil(Node n, BST bst, BSTCount bstCount) { if (n == null) { return; } isBST(n, bstCount); if (bstCount.isBST && bstCount.count > bst.max) { bst.max = bstCount.count; bst.n = n; } largestBSTUtil(n.left, bst, bstCount); largestBSTUtil(n.right, bst, bstCount); } private void isBST(Node n, BSTCount bstCount) { bstCount.count = 0; bstCount.isBST = false; bstCount.isBST = isBSTUtil(n, Integer.MIN_VALUE, Integer.MAX_VALUE, bstCount); } private Boolean isBSTUtil(Node n, int minValue, int maxValue, BSTCount c) { if (n == null) { return true; } if (minValue < n.data && n.data < maxValue) { c.count++; return isBSTUtil(n.left, minValue, n.data, c) && isBSTUtil(n.right, n.data, maxValue, c); } return false; } } ================================================ FILE: data_structures/binary_search_tree/java/bst_operations/LevelOrder.java ================================================ package bst_operations; import java.util.*; /** * Created by kalsi on 01/09/17. */ public class LevelOrder { public static void main(String[] args) { new LevelOrder().demo(); } private void demo() { Node n = new Node(8); // left n.left = new Node(3); n.left.left = new Node(1); n.left.right = new Node(6); n.left.right.left = new Node(4); n.left.right.right = new Node(7); //right n.right = new Node(10); n.right.right = new Node(14); n.right.right.left = new Node(13); /* 8 3 10 1 6 14 4 7 13 * * */ System.out.println("Without zigzag"); displayLevelOrder(n, false); //without zigzag System.out.println("With zigzag"); displayLevelOrder(n, true); //with zigzag } private void displayLevelOrder(Node n, Boolean zigzag) { if (n == null) { return; } Boolean flag = true; Deque parents = new LinkedList(); parents.add(n); while (!parents.isEmpty()) { print(parents, flag, zigzag); flag = !flag; int count = parents.size(); while (count-- > 0) { Node removedParent = parents.removeFirst(); if (removedParent.left != null) { parents.addLast(removedParent.left); } if (removedParent.right != null) { parents.addLast(removedParent.right); } } System.out.println(); } } private void print(Deque parents, Boolean flag, Boolean zigzag) { Iterator iterator = parents.descendingIterator(); if (!zigzag || flag) { iterator = parents.iterator(); } while (iterator.hasNext()) { System.out.print(iterator.next().data + "\t"); } } } ================================================ FILE: data_structures/binary_search_tree/java/bst_operations/MorrisTraversal.java ================================================ package bst_operations; /** * Created by kalsi on 30/08/17. * Inorder traversal without recursion or stacks */ public class MorrisTraversal { public static void main(String[] args) { new MorrisTraversal().demo(); } private void demo() { Node n = new Node(8); // left n.left = new Node(3); n.left.left = new Node(1); n.left.right = new Node(6); n.left.right.left = new Node(4); n.left.right.right = new Node(7); //right n.right = new Node(10); n.right.right = new Node(14); n.right.right.left = new Node(13); /* 8 3 10 1 6 14 4 7 13 * * */ inorderIterative(n); } private void inorderIterative(Node n) { while (n != null) { if (n.left == null) { System.out.print(n.data + "\t"); n = n.right; } Node predecessor = getPredecessor(n); if (predecessor.right == null) { predecessor.right = n; n = n.left; } else { predecessor.right = null; System.out.print(n.data + "\t"); n = n.right; } } } private Node getPredecessor(Node n) { Node temp = n.left; while( temp.right != null && temp.right != n) { temp = temp.right; } return temp; } } ================================================ FILE: data_structures/binary_search_tree/java/bst_operations/Node.java ================================================ package bst_operations; public class Node { int data; Node left; Node right; public Node(int d) { data = d; } } ================================================ FILE: data_structures/binary_search_tree/java/bst_operations/PathFromRootToNode.java ================================================ package bst_operations; import java.util.ArrayList; /** * Created by kalsi on 30/08/17. * Path from root to node */ public class PathFromRootToNode { Boolean found = false; public static void main(String[] args) { new PathFromRootToNode().demo(); } private void demo() { Node n = new Node(8); // left n.left = new Node(3); n.left.left = new Node(1); n.left.right = new Node(6); n.left.right.left = new Node(4); n.left.right.right = new Node(7); //right n.right = new Node(10); n.right.right = new Node(14); n.right.right.left = new Node(13); /* 8 3 10 1 6 14 4 7 13 * * */ ArrayList al = new ArrayList(); findPath(n, 13, al); display(al); } private void display(ArrayList al) { System.out.println("--"); for (Node n : al) { System.out.print(n.data + " --> "); } System.out.println("NULL"); } private void findPath(Node n, int data, ArrayList al) { if (n != null && !found) { al.add(n); findPath(n.left, data, al); if (n.data == data) { found = true; } findPath(n.right, data, al); if (!found) { al.remove(al.size() - 1); } } } } ================================================ FILE: data_structures/binary_search_tree/javascript/binary_tree.js ================================================ // Cleaner Logging export const _ = (...vals) => console.log(...vals); // Create BST Node export function BST(val) { let self = Object.create(BST.prototype); // Create Based Properties of BST Node self.value = val; self.right = undefined; self.left = undefined; // Insert Function, to properly place value in tree structure return self; } BST.prototype.insert = function(value) { let node = BST(value); function recurse(bst) { if (bst.value > value && bst.left === undefined) { bst.left = node; } else if (bst.value > value) { recurse(bst.left); } else if (bst.value < value && bst.right === undefined) { bst.right = node; } else if (bst.value < value) { recurse(bst.right); } } recurse(this); }; ================================================ FILE: data_structures/binary_search_tree/javascript/binary_tree_search.js ================================================ import { _, BST } from './binary_tree'; // Recursive binary search BST.prototype.contains = function(value) { var doesContain = false; function recurse(bst) { if (bst.value === value) { doesContain = true; } else if (bst.left !== undefined && value < bst.value) { recurse(bst.left); } else if (bst.right !== undefined && value > bst.value) { recurse(bst.right); } } recurse(this); return doesContain; }; BST.prototype.binarySearch = function(value) { let bst = this; let returnVal = null; let it = 0; function recurse(bst) { it++; if (bst.value === value) { returnVal = { bst, it }; } else if (bst.left !== undefined && value < bst.value) { recurse(bst.left); } else if (bst.right !== undefined && value > bst.value) { recurse(bst.right); } } recurse(this); return returnVal; }; BST.prototype.binarySearchIterative = function(value) { let bst = this; let it = 0; let found = false; while (!found) { it++; if (bst.value === value) { return { bst, it }; } else if (bst.left !== undefined && value < bst.value) { bst = bst.left; } else if (bst.right !== undefined && value > bst.value) { bst = bst.right; } else { found = true; } } return { bst: null, it }; }; let _bst = BST(5); _bst.insert(3); _bst.insert(4); _bst.insert(1); _bst.insert(2); _bst.insert(0); _bst.insert(8); _bst.insert(7); _bst.insert(9); _bst.insert(6); let num = 3; _(`Binary Search for ${num}: `, _bst.binarySearchIterative(num)); ================================================ FILE: data_structures/binary_search_tree/javascript/breadth_first_search.js ================================================ import { _, BST } from './binary_tree'; // Create Queue Class let Queue = () => { let _data = []; return { enqueue(val) { _data.push(val); }, dequeue() { return _data.splice(0, 1)[0]; }, isEmpty() { return _data.length === 0; }, Top() { return _data[0]; }, }; }; // Test Queue // let que = Queue(); // que.enqueue(1); // que.enqueue(2); // que.enqueue(3); // _(que.dequeue()); // _(que.dequeue()); // _(que.dequeue()); BST.prototype.breadthFirstLog = function(callback) { let bst = this; let queue = Queue(); let firstRun = true; function recurse(bst) { callback.call(bst, bst.value); if (!queue.isEmpty() || (bst.left !== undefined || bst.right !== undefined) || firstRun) { if (firstRun) { firstRun = false; } if (bst.left !== undefined) { queue.enqueue(bst.left); } if (bst.right !== undefined) { queue.enqueue(bst.right); } recurse(queue.dequeue()); } } recurse(this); }; BST.prototype.breadthFirstSearch = function(searchVal) { let queue = Queue(); let firstRun = true; let it = 0; let returnVal = null; function recurse(bst) { it++; _(bst.value, searchVal); if (bst.value === searchVal) { // Set Return for BST Node and how many recursive iterations there were returnVal = { bst, it }; } else { if (!queue.isEmpty() || (bst.left !== undefined || bst.right !== undefined) || firstRun) { if (firstRun) { firstRun = false; } if (bst.left !== undefined) { queue.enqueue(bst.left); } if (bst.right !== undefined) { queue.enqueue(bst.right); } if (!queue.isEmpty()) { recurse(queue.dequeue()); } } } } recurse(this); if (returnVal === null) { returnVal = { bst: null, it }; } return returnVal; }; BST.prototype.breadthFirstSearchIterative = function(searchVal) { let bst = this; let queue = Queue(); let firstRun = true; let it = 0; do { it++; _(bst.value, searchVal); if (bst.value === searchVal) { // Set Return for BST Node and how many recursive iterations there were return { bst, it }; } else { if (!queue.isEmpty() || (bst.left !== undefined || bst.right !== undefined) || firstRun) { if (firstRun) { firstRun = false; } if (bst.left !== undefined) { queue.enqueue(bst.left); } if (bst.right !== undefined) { queue.enqueue(bst.right); } bst = queue.dequeue(); } } } while (!queue.isEmpty() || bst !== undefined); return { BST: null, it }; }; let _bst = BST(5); _bst.insert(3); _bst.insert(4); _bst.insert(1); _bst.insert(2); _bst.insert(0); _bst.insert(8); _bst.insert(7); _bst.insert(9); _bst.insert(6); let num = 3; _(`Breadth First Search for ${num}: `, _bst.breadthFirstSearch(num)); ================================================ FILE: data_structures/binary_search_tree/javascript/depth_first_search.js ================================================ import { _, BST } from './binary_tree'; // Create Stack Class let Stack = () => { let _data = []; return { Top() { return _data[_data.length - 1]; }, Pop() { return _data.splice(_data.length - 1, 1)[0]; }, Push(val) { _data.push(val); }, isEmpty() { return _data.length === 0; }, }; }; // Test Stack Class // let stack = Stack(); // stack.Push(1); // stack.Push(2); // stack.Push(3); // stack.Push(4); // _(stack.Pop()); // _(stack.Pop()); // _(stack.Pop()); // _(stack.Pop()); BST.prototype.depthFirstLog = function(callback) { function recurse(bst) { callback.call(bst, bst.value); if (bst.left !== undefined) { recurse(bst.left); } if (bst.right !== undefined) { recurse(bst.right); } } recurse(this); }; BST.prototype.depthFirstSearch = function(searchVal) { let stack = Stack(); let it = 0; let returnVal = null; function recurse(bst) { it++; if (bst.value === searchVal) { returnVal = { bst, it }; } else { if (bst.left !== undefined) { stack.Push(bst.left); } if (bst.right !== undefined) { stack.Push(bst.right); } if (!stack.isEmpty()) { recurse(stack.Pop()); } } } recurse(this); if (returnVal === null) { returnVal = { bst: null, it }; } return returnVal; }; BST.prototype.depthFirstSearchIterative = function(searchVal) { let bst = this; let stack = Stack(); let it = 0; do { it++; if (bst.value === searchVal) { return { bst, it }; } else { if (bst.left !== undefined) { stack.Push(bst.left); } if (bst.right !== undefined) { stack.Push(bst.right); } bst = stack.Pop(); } } while (!stack.isEmpty() || bst !== undefined); return { bst: null, it }; }; let _bst = BST(5); _bst.insert(3); _bst.insert(4); _bst.insert(1); _bst.insert(2); _bst.insert(0); _bst.insert(8); _bst.insert(7); _bst.insert(9); _bst.insert(6); let num = 3; _(`Depth First Search for ${num}: `, _bst.depthFirstSearch(num)); ================================================ FILE: data_structures/binary_search_tree/python/bst.py ================================================ """ Defining a TreeNode class """ class TreeNode: def __init__(self,k=None): self.parent=None self.key=k self.left=None self.right=None def isleft(self): if self.parent is None: print("Root") if self.parent.left==self: return True return False def isright(self): if self.parent is None: print("Root") if self.parent.right==self: return True return False def isleaf(self): if self.right is None and self.left is None: return True else: return False """ Binary Search Tree Implementation. Methods : isEmpty() insert() delete() precdecessor() maximum() minimum() successor() search() """ class BST: def __init__(self): self.root=None def isEmpty(self): if self.root is None: return True return False def insert(self,key1): temp=TreeNode(key1) if self.isEmpty(): self.root=temp else: current=self.root while current is not None: if key1 > current.key: if current.right is None: current.right=temp temp.parent=current break else: current=current.right else: if current.left is None: current.left=temp temp.parent=current break else: current=current.left def maximum(self): if self.isEmpty(): return "Empty Tree" else: current=self.root while current is not None: if current.right is None: return current.key else: current=current.right def minimum(self): if self.isEmpty(): return "Empty Tree" else: current=self.root while current is not None: if current.left is None: return current.key else: current=current.left def successor(self,node): if node.key ==self.maximum(): return node.key else: if node.right is not None: tempt=BST() tempt.root=node.right return tempt.minimum() else: ch=node p=node.parent while ch is not None: if ch.isleft(): return p.key else: ch=p p=p.parent def predecessor(self,node): if node.key ==self.minimum(): return node.key else: if node.left is not None: tempt=BST() tempt.root=node.left return tempt.maximum() else: ch=node p=node.parent while ch is not None: if ch.isright(): return p.key else: ch=p p=p.parent def search(self,key): current=self.root while current is not None: if current.key==key: return current elif current.key= data: q.append(n.right) if n.left == None: pass else:q.append(n.left) if n.right == None: passs else:q.append(n.right) def insertR(root,data): if root.data == None: root.data = data return if data < root.data: if root.left != None: BST.insertR(root.left,data) else: root.left = Node(data) else: if root.right != None: BST.insertR(root.right,data) else: root.right = Node(data) def inOrder(root,lamb=None): if root.left != None: BST.inOrder(root.left,lamb) if root.data != None: if lamb == None: print(root.data,end=' ') else: lamb(root.data) if root.right != None: BST.inOrder(root.right,lamb) def _search(root,data): if root.left != None: return BST._search(root.left,data) if root.data != None: if root.data == data: return root.data if root.right != None: return BST._search(root.right,data) def search(self,data): return BST._search(self.root,data) def _path(root,data): if root.left != None: res = BST._path(root.left,data) if res!=None: print(root.data) return res if root.data != None: if root.data == data: print(root.data) return root.data if root.right != None: res = BST._path(root.right,data) if res!=None: print(root.data) return res def path(self,data): BST._path(self.root,data) def _del(root,data): if root.left != None: BST._del(root.left,data) if root.data != None: if root.data == data: pass # root. if root.right != None: BST._del(root.right,data) def dele(self,data): BST._del(self.root,data) ================================================ FILE: data_structures/binary_tree/c/diameterBT.c ================================================ #include #include struct node { int data; struct node* left, *right; }; /* function to create a new node of tree and returns pointer */ struct node* newNode(int data); /* returns max of two integers */ int max(int a, int b); /* function to Compute height of a tree. */ int height(struct node* node); /* Function to get diameter of a binary tree */ int diameter(struct node * tree) { /* base case where tree is empty */ if (tree == NULL) return 0; /* get the height of left and right sub-trees */ int lheight = height(tree->left); int rheight = height(tree->right); /* get the diameter of left and right sub-trees */ int ldiameter = diameter(tree->left); int rdiameter = diameter(tree->right); /* Return max of following three 1) Diameter of left subtree 2) Diameter of right subtree 3) Height of left subtree + height of right subtree + 1 */ return max(lheight + rheight + 1, max(ldiameter, rdiameter)); } /* UTILITY FUNCTIONS TO TEST diameter() FUNCTION */ /* The function Compute the "height" of a tree. Height is the number f nodes along the longest path from the root node down to the farthest leaf node.*/ int height(struct node* node) { /* base case tree is empty */ if(node == NULL) return 0; /* If tree is not empty then height = 1 + max of left height and right heights */ return 1 + max(height(node->left), height(node->right)); } /* Helper function that allocates a new node with the given data and NULL left and right pointers. */ 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); } /* returns maximum of two integers */ int max(int a, int b) { return (a >= b)? a: b; } /* Driver function*/ int main() { /* Constructed binary tree is 1 / \ 2 3 / \ 4 5 */ struct node *root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); printf("Diameter of the given binary tree is %d\n", diameter(root)); getchar(); return 0; } ================================================ FILE: data_structures/binary_tree/cpp/binary_tree.cpp ================================================ #include struct Node { int key; Node *leftnode; Node *rightnode; std::string value; Node(int tkey, const std::string& tvalue) : leftnode(nullptr), rightnode(nullptr), key(tkey), value(tvalue) {} }; Node root_node(1, "Node #1"); std::string query_bst(const int key) { Node *cur_node = &root_node; while (cur_node != nullptr) { if (key == cur_node->key) { return cur_node->value; } if (key < cur_node->key) { cur_node = cur_node->leftnode; } else { cur_node = cur_node->rightnode; } } return ""; } void insert_bst(int key, const std::string& value) { Node *cur_node; Node *next_node = &root_node; while (next_node != nullptr) { cur_node = next_node; if (key < cur_node->key) { next_node = cur_node->leftnode; } else { next_node = cur_node->rightnode; } } if (key < cur_node->key) { cur_node->leftnode = new Node(key, value); } else { cur_node->rightnode = new Node(key, value); } } int main() { insert_bst(2, "Node #2"); insert_bst(3, "Node #3"); std::cout << query_bst(3) << '\n'; } ================================================ FILE: data_structures/binary_tree/cpp/boundaryTraversal.cpp ================================================ /* program for boundary traversal of a binary tree */ #include #include struct node { int data; struct node *left, *right; }; // A simple function to print leaf nodes of a binary tree void printLeaves(struct node* root) { if ( root ) { printLeaves(root->left); // Print it if it is a leaf node if ( !(root->left) && !(root->right) ) printf("%d ", root->data); printLeaves(root->right); } } // A function to print all left boundry nodes, except a leaf node. // Print the nodes in TOP DOWN manner void printBoundaryLeft(struct node* root) { if (root) { if (root->left) { // to ensure top down order, print the node // before calling itself for left subtree printf("%d ", root->data); printBoundaryLeft(root->left); } else if( root->right ) { printf("%d ", root->data); printBoundaryLeft(root->right); } // do nothing if it is a leaf node, this way we avoid // duplicates in output } } // A function to print all right boundry nodes, except a leaf node // Print the nodes in BOTTOM UP manner void printBoundaryRight(struct node* root) { if (root) { if ( root->right ) { // to ensure bottom up order, first call for right // subtree, then print this node printBoundaryRight(root->right); printf("%d ", root->data); } else if ( root->left ) { printBoundaryRight(root->left); printf("%d ", root->data); } // do nothing if it is a leaf node, this way we avoid // duplicates in output } } // A function to do boundary traversal of a given binary tree void printBoundary (struct node* root) { if (root) { printf("%d ",root->data); // Print the left boundary in top-down manner. printBoundaryLeft(root->left); // Print all leaf nodes printLeaves(root->left); printLeaves(root->right); // Print the right boundary in bottom-up manner printBoundaryRight(root->right); } } // Create a node struct node* newNode( int data ) { struct node* temp = (struct node *) malloc( sizeof(struct node) ); temp->data = data; temp->left = temp->right = NULL; return temp; } // Driver program int main() { struct node *root = newNode(20); root->left = newNode(8); root->left->left = newNode(4); root->left->right = newNode(12); root->left->right->left = newNode(10); root->left->right->right = newNode(14); root->right = newNode(22); root->right->right = newNode(25); printBoundary( root ); return 0; } ================================================ FILE: data_structures/binary_tree/csharp/BinaryTree.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DataStructures { class BinaryTree { public class TreeObject { TreeObject key; TreeObject leftchild = null; TreeObject rightchild = null; public TreeObject(TreeObject newitem) { key = newitem; } public TreeObject getRoot() { return key; } public TreeObject getLeftChild() { return leftchild; } public TreeObject getRightChild() { return rightchild; } public void setRoot(TreeObject newItem) { key = newItem; } public void setLeftChild(TreeObject newItem) { leftchild = newItem; } public void setRightChild(TreeObject newItem) { rightchild = newItem; } } public TreeObject init(TreeObject newitem) { return new TreeObject(newitem); } public void insertRight(TreeObject self, TreeObject newNode) { if (self.getRightChild() == null) { self.setRightChild(newNode); } else { TreeObject obj = new TreeObject(newNode); obj.setRightChild(self.getRightChild()); self.setRightChild(obj); } } public void insertLeft(TreeObject self, TreeObject newNode) { if (self.getLeftChild() == null) { self.setLeftChild(newNode); } else { TreeObject obj = new TreeObject(newNode); obj.setLeftChild(self.getLeftChild()); self.setLeftChild(obj); } } } } ================================================ FILE: data_structures/binary_tree/java/binary_tree_bfs.java ================================================ package shubham; //Breadth first search to search the element and print the path. import java.util.LinkedList; import java.util.Queue; public class bfs { public void levelOrderQueue(Node root) { Queue q = new LinkedList(); if (root == null) return; q.add(root); while (!q.isEmpty()) { Node n = (Node) q.remove(); int goal=11; int c=0; if (n.left != null) q.add(n.left); c+=1; if (n.right != null) q.add(n.right); c+=1; System.out.print(" " + n.data); if(n.data==goal) break; } } public static void main(String[] args) throws java.lang.Exception { Node root = new Node(1); root.left = new Node(2); root.right = new Node(3); root.left.left = new Node(4); root.left.right = new Node(5); root.right.left = new Node(6); root.right.right = new Node(7); root.left.left.left= new Node(8); root.left.left.right= new Node(9); root.left.right.left=new Node(10); root.left.right.right=new Node(11); root.right.left.left=new Node(12); root.right.left.right=new Node(13); root.right.left.right= new Node(14); root.right.right.right= new Node(15); bfs i = new bfs(); System.out.println("Breadth First Search : "); i.levelOrderQueue(root); } } class Node { int data; Node left; Node right; public Node(int data) { this.data = data; this.left = null; this.right = null; } } ================================================ FILE: data_structures/binary_tree/java/binary_tree_dfs.java ================================================ import java.util.*; class Node{ int data; Node left,right; public Node(int item){ data = item; left = right = null; } } class BinaryTree{ Node root; BinaryTree(){ root = null; } public void preorder_rec(Node node){ if(node == null) return; System.out.println(node.data); preorder_rec(node.left); preorder_rec(node.right); } public void inorder_rec(Node node){ if(node == null) return; inorder_rec(node.left); System.out.println(node.data); inorder_rec(node.right); } public void postorder(Node node){ if(node == null) return; postorder(node.left); postorder(node.right); System.out.println(node.data); } public static void main(String[] args){ BinaryTree bt = new BinaryTree(); bt.root = new Node(1); bt.root.left = new Node(2); bt.root.right = new Node(3); bt.root.left.left = new Node(4); bt.root.left.right = new Node(5); bt.root.right.right = new Node(7); bt.root.right.left = new Node(6); bt.queue.add(bt.root); System.out.println("Preorder Recursive"); bt.preorder_rec(bt.root); System.out.println("Inorder Recursive"); bt.inorder_rec(bt.root); System.out.println("Postorder"); bt.postorder(bt.root); } } ================================================ FILE: data_structures/binary_tree/python/binary_tree.py ================================================ class BinaryTree: def __init__(self,rootObj): self.key = rootObj self.leftChild = None self.rightChild = None def insertLeft(self,newNode): if self.leftChild == None: self.leftChild = BinaryTree(newNode) else: t = BinaryTree(newNode) t.leftChild = self.leftChild self.leftChild = t def insertRight(self,newNode): if self.rightChild == None: self.rightChild = BinaryTree(newNode) else: t = BinaryTree(newNode) t.rightChild = self.rightChild self.rightChild = t def getRightChild(self): return self.rightChild def getLeftChild(self): return self.leftChild def setRootVal(self,obj): self.key = obj def getRootVal(self): return self.key ================================================ FILE: data_structures/bloom_filter/python/bloom_filter.py ================================================ # A simple bloom filter in Python 3 # Author: Flora Rosenkreuz (reindeer-cafe) import math class BloomFilter: # very simple string encode def SimpleStringEncode(self, data): hash = 0 for x in data: hash += (ord(x)) return hash % 20 # implementation of the fnv hash def FNV(self, data): hash = 2166136261 b = bytes(data, 'utf-8') for byte in b: hash = hash ^ byte hash = hash * 16777619 return hash % 20 # add a string to the filter def Add(self, data): h1 = self.SimpleStringEncode(data) h2 = self.FNV(data) self.Vector[h1] = 1 self.Vector[h2] = 1 # false positives are possible in a bloom filter hence is "possibly" in def IsPossiblyIn(self, data): #m num b h1 = self.SimpleStringEncode(data) h2 = self.FNV(data) return True if (self.Vector[h1] and self.Vector[h2]) else False # computes the approximate false positive rate def ComputeCollisionRate(self): n = 0 for b in self.Vector: n += 1 if b else 0 return math.pow((1 - (math.pow(math.e, (((-1 * 2) * n) / 20)))), 2) def __init__(self): self.Vector = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0] ================================================ FILE: data_structures/circular_queue/circular_queue.md ================================================ ## ELI5 CIRCULAR QUEUE is a queue in which last position is connected back to first position,i.e. after last location of the list we visit the first location.Forms a circle. ### Pros: * Fast operations of adding and removing elements. * Utilizes memory efficiently. ### Cons: * May become a never-ending loop. ## TECHNICAL EXPLAINATION A FIFO data structure ,also called ‘Ring Buffer’,where last element points back to the first element to make a circle. * Operations on Circular Queue:. *enqueue(element): This function is used to insert an element into the circular queue. The new element is always inserted at Rear position. Steps: Check whether queue is Full – Check ((REAR == SIZE && FRONT == 1) || (REAR == FRONT-1)) If TRUE,queue is full. If queue is not full then insert element. *dequeue(): This function is used to delete an element from the circular queue.The element is always deleted from FRONT position. eg. CQueue = 1,2,3,4,_ enqueue(5) gives CQueue=1,2,3,4,5 dequeue() gives CQueue= _,2,3,4,5 enqueue(6) gives CQueue=6,2,3,4,5 ### Pros: * Time complexity of enqueue(), dequeue() operation is O(1). * Prevents wastage of space of Simple Queue. ### Cons: * A circular queue might cause an an infinite loop, impairing processing - if not implemented properly or in a multi-threaded environment. * Complex to code. ================================================ FILE: data_structures/circular_queue/cpp/circular queue.cpp ================================================ #include #include using namespace std; class queue1 { int n=8,front1=-1,rear=-1,a=0; public: int arr[8]; void element() { cout<<"enter element"; cin>>a; } void inqueue() { if((front1>=0&&rear==n-1)||(front1==rear+1)) { //overflow cout<<"queue overflow"<>ch; switch(ch) { case 1: { q.element(); q.inqueue(); break; } case 2: { q.dequeue(); break; } case 3: { q.display(); break; } case 4: { c=0; break; } } } } //seraching n traversing in lkd list ================================================ FILE: data_structures/circular_queue/java/circular_queue.java ================================================ //circular queue import java.util.*; interface queue1 { void insert(); void delete(); void display(); } class myqueue1 implements queue1 { int arr[]=new int[3]; int front=0,rear=0; Scanner s1 = new Scanner(System.in); public void insert() { int a; System.out.println("enter element:"); a=s1.nextInt(); arr[rear]=a; rear++; if(rear==3) rear=0; } public void delete() { if (rear==front) System.out.println("queue is empty"); else { int a; a=arr[front]; front++; System.out.println("element deleted : "+a ); if(front==3) front=0; } } public void display() { System.out.println("elements are"); for(int i=front;i=self.head: return (self.tail-self.head) return (self.maxSize - (self.head-self.tail)) ================================================ FILE: data_structures/d_heap/c/d_heap.c ================================================ #include #include #include #include HEAP *init(int d){ HEAP *heap = (HEAP *) malloc(sizeof(HEAP)); heap->d = d; heap->size = 0; heap->items = NULL; return heap; } int parent_index(int n, int d){ return (n-1)/d; } int child_index(int n, int d, int i){ return n*d+i+1; } void push(HEAP *heap, int value){ int i; heap->size++; heap->items = (int *) realloc(heap->items, sizeof(int)*heap->size); i = heap->size - 1; heap->items[i] = 0; while(i >= 1 && heap->items[parent_index(i, heap->d)] > value){ heap->items[i] = heap->items[parent_index(i, heap->d)]; i = parent_index(i, heap->d); } heap->items[i] = value; } void min_heapify(int n, HEAP *heap){ int i, current, aux, smallest; smallest = n; for(i = 0; i < heap->d; i++){ current = child_index(n, heap->d, i); if(current <= heap->size && heap->items[current] < heap->items[smallest]){ smallest = current; } } if(smallest != n){ aux = heap->items[n]; heap->items[n] = heap->items[smallest]; heap->items[smallest] = aux; min_heapify(smallest, heap); } } int pop(HEAP *heap){ int removed; if(heap->size == 0) return -1; else{ removed = heap->items[0]; heap->items[0] = heap->items[heap->size -1]; heap->size--; min_heapify(0, heap); return removed; } } void short_print(HEAP *heap){ int i; for(i = 0; i < heap->size; i++){ printf("%d ", heap->items[i]); } } void print(HEAP *heap){ int i, j; printf("size = %d\n", heap->size); for(i = 0; i < heap->size; i++){ printf("Index = %d Elemento = %d\n", i, heap->items[i]); printf("Pai = %d\n", parent_index(i, heap->d)); for(j = 0; j < heap->d; j++){ printf("Filho %d = %d\n", j+1, child_index(i, heap->d, j)); } printf("\n"); } printf("\n\n"); } void destroy(HEAP *heap){ if(heap->items != NULL){ free(heap->items); } free(heap); } ================================================ FILE: data_structures/dimaeter_of_a_tree/cpp/Diameter.cpp ================================================ //WAP to find diameter of a BST. #include #include using namespace std; struct tree{ int data; struct tree *left,*right; }; typedef struct tree node; node *current=NULL,*root=NULL,*parent=NULL,*temp=NULL; void newnode(int n) { current = (node*)malloc(sizeof(node)); current->data = n; current->left = NULL; current->right = NULL; if(root==NULL) { root=current; } else { temp=root; parent=NULL; while(1) { parent = temp; if(ndata) { temp = temp->left; if(temp==NULL) { parent->left= current; return; } } else { temp = temp->right; if(temp==NULL) { parent->right= current; return; } } } } } int max(int a,int b) { if(a>b) return a; else return b; } int height(node* temp) { if(temp==NULL) return 0; return 1+max(height(temp->left),height(temp->right));} int diameter(node* temp) { int dia=0,maxDia; if(temp ==NULL) return 0; int lheight,rheight,ldiameter,rdiameter; lheight = height(temp->left); rheight = height(temp->right); dia = 1 + lheight + rheight; ldiameter = diameter(temp->left); rdiameter = diameter(temp->right); maxDia = max(dia,max(ldiameter,rdiameter)); return maxDia; } int main() { int i,an; int x[]={41,27,83,45,65,80,40,55}; /* 41 / \ 27 83 \ / 40 45 \ 65 / \ 55 80 */ for(i=0;i<=7;i++) newnode(x[i]); an=diameter(root); cout<<"\nDiameter of tree:"< using namespace std; void FindLocation(int); struct student{ int data; student* next; student* prev; } *loc,*head,*tail,*ptr; void insertion_begin(int y){ student* temp=new student(); if(head==NULL){ temp->next=NULL; temp->prev=NULL; head=temp; tail=temp; temp->data=y; } else{ temp->next=head; temp->prev=NULL; head->prev=temp; head=temp; temp->data=y; } } void insertion_end(int y){ student* temp=new student(); if(head==NULL){ temp->next=head; temp->prev=head; head=temp; tail=temp; temp->data=y; } else{ temp->next=NULL; temp->prev=tail; tail->next=temp; tail=temp; temp->data=y; } } void insertion_after(int y1){ student* temp=new student(); int k3; cout<<"enter the element after which data to be inserted "; cin>>k3; FindLocation(k3); if(loc==NULL) insertion_end(y1); else{ temp->next=loc->next; temp->prev=loc; loc->next->prev=temp; loc->next=temp; temp->data=y1; } } void insertion_before(int y2){ student* temp=new student(); int k1; cout<<"enter the element before which data to be inserted "; cin>>k1; FindLocation(k1); if(loc==NULL) insertion_begin(y2); else{ temp->next=loc; temp->prev=loc->prev; loc->prev->next=temp; loc->prev=temp; temp->data=y2; } } void FindLocation(int k2){ student* p=head; while(p!=NULL){ if(p->data==k2){ loc=p; return; } else p=p->next; } loc=NULL; } void display() { student* q=head; while(q!=NULL){ cout<data<<" "; q=q->next; } cout<>n; while(1){ cout<<"select from the following: "<>k; switch(k) { case 1: cout<<"enter the number:"; for(i=0;i>x; insertion_begin(x); } break; case 2: cout<<"enter the number:"; for(i=0;i>x; insertion_end(x); } break; case 3: cout<<"enter the element to be inserted: "; cin>>m; insertion_after(m); break; case 4: cout<<"enter the element to be inserted: "; cin>>a; insertion_before(a); break; case 5: display(); break; case 6: return(0); default: cout<<"incorrect choice"<"); ptr = ptr.getNextLink(); } System.out.print(ptr.getData()); } // Traversing data from right to lest public void showDataFromRight() { Node ptr = end ; while(ptr.getPrevLink()!=null) { System.out.print(ptr.getData() + "-->"); ptr = ptr.getPrevLink(); } System.out.print(ptr.getData()); } } public class DoublyLinkedList { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int data = 0 ; LinkList ll = new LinkList(); System.out.println("Choose : \n1. Insert at Start \n2. Insert At End "); switch (sc.nextInt()) { case 1: // Get data from user again and again and add them to linked list do { System.out.print("Enter the data : "); data = sc.nextInt(); ll.addAtStart(data); System.out.print("Do you want to add more (y/n) : "); }while(sc.next().equals("y")); System.out.println("From left to right : "); ll.showDataFromLeft(); // show data from left to right of linked list System.out.println("\nFrom right to left : "); ll.showDataFromRight(); // show data from right to left of linked list break; case 2: do { System.out.print("Enter the data : "); data = sc.nextInt(); ll.addAtEnd(data); System.out.print("Do you want to add more (y/n) : "); }while(sc.next().equals("y")); System.out.println("From left to right : "); ll.showDataFromLeft(); System.out.println("\nFrom right to left : "); ll.showDataFromRight(); break; default: break; } System.out.println("\nChoose : \n1. Insert At Middle \n2. Insert After A Data \n3. Delete A Node"); switch (sc.nextInt()) { case 1: System.out.print("Enter the data : "); data = sc.nextInt(); int pos = 0 ; if(ll.size%2 == 0) { pos = ll.size/2 ; }else { pos = (ll.size - 1)/2 ; } ll.addAtMiddle(data , pos); // Calculating middle position System.out.println("From left to right : "); ll.showDataFromLeft(); System.out.println("\nFrom right to left : "); ll.showDataFromRight(); break; case 2: System.out.print("Enter the data : "); data = sc.nextInt(); System.out.print("Enter the data after which you want to add new data : "); ll.addAfterData(data , sc.nextInt()); System.out.println("From left to right : "); ll.showDataFromLeft(); System.out.println("\nFrom right to left : "); ll.showDataFromRight(); break; case 3: System.out.print("Enter the data to be deleted : "); data = sc.nextInt(); ll.deleteNode(data); // Delete node System.out.println("From left to right : "); ll.showDataFromLeft(); System.out.println("\nFrom right to left : "); ll.showDataFromRight(); break; default: break; } } } ================================================ FILE: data_structures/doubly_linked_list/python/DoublyLinkedList.py ================================================ class Li2st: def __init__(self,data = None): self.head = self.tail = node(data) self.size = 0 if data == None else 1 def __str__(self): p = self.head while p.nexts != None: print(p.data,end=' ') p = p.nexts print(p.data) return '' def isEmpty(self): return self.size == 0 def append(self,data): p = node(data) if self.head.data == None: self.head = p self.tail = self.head self.tail.nexts = p self.tail = p self.size += 1 def addHead(self,data): p = node(data,self.head) self.head = p self.size +=1 def isIn(self,data): t = self.head while t.nexts != None: if t.data == data: return True t = t.nexts if t.data == data: return True return False def before(self,data): before = None i = self.head while i.nexts != None: if i.data == data: return before before = i i = i.nexts if i.data == data: return before return None # def remove(self,data): # if not self.isIn(data) or self.before(data) == None: # print('Failed to remove') # return # self.before(data).nexts = self.before(data).nexts.nexts def remove(self,index): currentNode = self.get(index-1) currentNode.nexts= self.get(index+1) def removeTail(self): t = self.before(self.tail.data) t.nexts = None self.tail = t def removeHead(self): self.head = self.head.nexts def get(self,index): if index > self.size: raise IndexError t = self.head for i in range(index): t = t.nexts if t != None: return t def insert(self,node,index): currentNode = self.get(index) nextNode = currentNode.nexts currentNode.nexts = node node.nexts = nextNode ================================================ FILE: data_structures/generic_tree/java/gt.java ================================================ package practiceds; import java.util.ArrayList; import java.util.LinkedList; import java.util.Queue; import java.util.Scanner; import java.util.Stack; public class generictree { private class node { private int data; private ArrayList children; public node(int data) { this.data = data; this.children = new ArrayList<>(); } } private node root; private int size; public generictree() { Scanner scn = new Scanner(System.in); this.root = this.takeinput(scn, null, 0); } private node takeinput(Scanner scn, node parent, int ithchild) { if (parent == null) { System.out.println("Enter data for parent node "); } else { System.out.println("enter data for " + ithchild + "th child of "+parent.data); } int childdata = scn.nextInt(); node child = new node(childdata); this.size++; System.out.println("Enter the number of children for " + childdata); int numgranchild = scn.nextInt(); for (int i = 0; i < numgranchild; i++) { node grandchild = takeinput(scn, child, i + 1); child.children.add(grandchild); } return child; } public int size() { return this.size; } public boolean isempty() { return this.size == 0; } public void display() { System.out.println(this); } @Override public String toString() { return this.toString(this.root); } private String toString(node node) { String retval = ""; retval = retval + node.data + " => "; for (int i = 0; i < node.children.size(); i++) { retval = retval + node.children.get(i).data + " , "; } retval = retval + " end\n"; for (int i = 0; i < node.children.size(); i++) { retval = retval + this.toString(node.children.get(i)); } return retval; } public int max (){ return this.max (this.root); } private int max (node Node){ int max=Node.data; for (int i=0;imax){ max = maxofchild; } } return max; } public boolean find(int data){ return this.find(data,this.root); } private boolean find(int data,node Node){ if (Node.data==data){ return true; } for (int i=0;iheight){ height = childheight; } } height = height +1; return height; } } ================================================ FILE: data_structures/graph/cpp/graph.cpp ================================================ //Graph C++ #include #include using namespace std; //class for graph , easily customisable class graph { int vertices; int edges; vector *v; public: //constructors graph() { vertices=0; edges=0; v=NULL; } graph(int ver,int e) { vertices=ver; edges=e; v=new vector[ver+2]; } //0 for undirected //1 for directed void addedge(int a,int b,int dir) { if(a>vertices || a<0 || b>vertices || b<0) return; v[a].push_back(b); if(dir==0) v[b].push_back(a); } void printedges() { vector::iterator it; for(int i=0;i<=vertices;i++) { for(it=v[i].begin();it!=v[i].end();it++) { cout< #include #include #include template class HashTable // AKA Symbol Table or HashMap or Dictionary { public: // constructor HashTable(size_t size = 13) { length = size; table = new std::list>[length]; } // destructor ~HashTable() { delete[] table; } // insert val w/ specified key void insert(Key key, T val) { size_t i = hash(key); for (auto it = table[i].begin(); it != table[i].end(); ++it) { if (std::get<0>(*it) == key) { (*it) = std::make_pair(key, val); return; } } table[i].push_front(std::make_pair(key, val)); used++; } // delete key and value void remove(Key key) { size_t i = hash(key); if (!table[i].empty()) for (auto it = table[i].begin(); it != table[i].end(); ++it) { if (std::get<0>(*it) == key) { it = table[i].erase(it); used--; } } } // search for a val w/ given key T get(Key key) { size_t i = hash(key); for (auto it = table[i].begin(); it != table[i].end(); ++it) { if (std::get<0>(*it) == key) { return std::get<1>(*it); } } return nullptr; } void printTable() { std::cout << "[\n"; for (size_t i = 0; i < length; i++) { if (!table[i].empty()) { for (auto it = table[i].begin(); it != table[i].end(); ++it) { std::cout << '\t' << std::get<0>(*it) << "\t:\t" << std::get<1>(*it) << '\n'; } } } std::cout << "]\n"; } // returns true if hashtable is empty inline bool isEmpty() { return used == 0; } // returns true if hashtable // contains specific key bool contains(Key key) { return !(get(key) == nullptr); } // returns size of hashtable inline int size() { return used; } private: std::hash prehash; size_t length; size_t used; std::list>* table; size_t hash(Key key) { return (prehash(key) & 0x7fffffff) % length; } }; #endif // HASHTABLE_H ================================================ FILE: data_structures/hash_table/csharp/hash_table.cs ================================================ using System; using System.Collections; // namespace for hashtable using System.Linq; using System.Text; using System.Threading.Tasks; /* * The Hashtable class represents a collection of key-and-value pairs that are organized * based on the hash code of the key. It uses the key to access the elements in the collection. * */ namespace hashtables { sealed class hTable // a class { static int key; // key of the hastable public bool uniqueness { get; set; } // setting to check if allow uniqueness or not Hashtable hashtable = new Hashtable(); internal void add(string value) { if(uniqueness) { if(hashtable.ContainsValue(value)) { Console.WriteLine("Entry exists"); } else { hashtable.Add(++key,value); } } else { hashtable.Add(++key, value); } } internal void delete(int key) { if (hashtable.ContainsKey(key)) { Console.WriteLine("Deleted value : " + hashtable[key].ToString()); hashtable.Remove(key); } else { Console.WriteLine("Key not found"); } } internal void show() { foreach(var key in hashtable.Keys) { Console.WriteLine(key.ToString() + " : " + hashtable[key]); } } } class Program { static void Main(string[] args) { hTable obj = new hTable(); // i want uniqueness therefore making property true obj.uniqueness = true; // adding 3 values Console.WriteLine("ADDING EXAMPLE"); obj.add("terabyte"); obj.add("sandysingh"); obj.add("hacktoberfest"); // adding terabyte again to see the exists message Console.WriteLine("ADDING 'terabyte' AGAIN"); obj.add("terabyte"); // showing all original Console.WriteLine("Original Table"); obj.show(); // removing value at key = 2 Console.WriteLine("Deleting value"); obj.delete(2); // showing all new Console.WriteLine("New Table"); obj.show(); Console.ReadKey(); // in ordr to pause the program } } } ================================================ FILE: data_structures/hash_table/java/Hash_table.java ================================================ package lecture18; public class HashTable { private class HTPair { K key; V value; public HTPair(K key, V value) { this.key = key; this.value = value; } public boolean equals(Object other) { HTPair op = (HTPair) other; return this.key.equals(op.key); } public String toString() { return "{" + this.key + "->" + this.value + "}"; } } private LinkedList[] bucketArray; private int size; public static final int DEFAULT_CAPACITY = 5; public HashTable() { this(DEFAULT_CAPACITY); } public HashTable(int capacity) { this.bucketArray = (LinkedList[]) new LinkedList[capacity]; this.size = 0; } public int size() { return this.size; } private int HashFunction(K key) { int hc = key.hashCode(); hc = Math.abs(hc); int bi = hc % this.bucketArray.length; return bi; } public void put(K key, V value) throws Exception { int bi = HashFunction(key); HTPair data = new HTPair(key, value); if (this.bucketArray[bi] == null) { LinkedList bucket = new LinkedList<>(); bucket.addLast(data); this.size++; this.bucketArray[bi] = bucket; } else { int foundAt = this.bucketArray[bi].find(data); if (foundAt == -1) { this.bucketArray[bi].addLast(data); this.size++; } else { HTPair obj = this.bucketArray[bi].getAt(foundAt); obj.value = value; this.size++; } } double lambda = (this.size) * 1.0; lambda = this.size / this.bucketArray.length; if (lambda > 0.75) { rehash(); } } public void display() { for (LinkedList list : this.bucketArray) { if (list != null && !list.isEmpty()) { list.display(); } else { System.out.println("NULL"); } } } public V get(K key) throws Exception { int index = this.HashFunction(key); LinkedList list = this.bucketArray[index]; HTPair ptf = new HTPair(key, null); if (list == null) { return null; } else { int findAt = list.find(ptf); if (findAt == -1) { return null; } else { HTPair pair = list.getAt(findAt); return pair.value; } } } public V remove(K key) throws Exception { int index = this.HashFunction(key); LinkedList list = this.bucketArray[index]; HTPair ptf = new HTPair(key, null); if (list == null) { return null; } else { int findAt = list.find(ptf); if (findAt == -1) { return null; } else { HTPair pair = list.getAt(findAt); list.removeAt(findAt); this.size--; return pair.value; } } } public void rehash() throws Exception { LinkedList[] oba = this.bucketArray; this.bucketArray = (LinkedList[]) new LinkedList[2 * oba.length]; this.size = 0; for (LinkedList ob : oba) { while (ob != null && !ob.isEmpty()) { HTPair pair = ob.removeFirst(); this.put(pair.key, pair.value); } } } } ================================================ FILE: data_structures/hash_table/python/hashTable.py ================================================ class hashTable: def __init__(self): self.size = 13 # hash table with size of 13 to be consistent with cpp code self.slots = [None] * self.size self.data = [None] * self.size def hashfunction(self, key, size): # remainder used to define slots return key % size def rehash(self, oldhash, size): # just a simple linear probing function for rehashing return ( oldhash + 1 ) % size def insert(self, key, data): hash_val = self.hashfunction(key, len(self.slots)) if self.slots[hash_val] == None: self.slots[hash_val] = key self.data[hash_val] = data else: new_slot = self.rehash(hash_val,len(self.slots)) while self.slots[new_slot] != None and self.slots[new_slot] != key: new_slot = self.rehash(new_slot,len(self.slots)) if self.slots[new_slot] == None: self.slots[new_slot] = key self.data[new_slot] = data def get(self, key): first_slot = self.hashfunction(key, len(self.slots)) data = None stop = False found = False position = first_slot while self.slots[position] != None and not found and not stop: if self.slots[position] == key: found = True data = self.data[position] else: position=self.rehash(position,len(self.slots)) if position == first_slot: stop = True return data def __getitem__(self,key): return self.get(key) def __setitem__(self,key,data): self.insert(key,data) ================================================ FILE: data_structures/hashmap/java/hashmap.java ================================================ import java.util.*; class hashmap { public static void main(String args[]) { // Create a hash map HashMap hm = new HashMap(); // Put elements to the map hm.put(1, "one"); hm.put(2, "two"); hm.put(3,"three"); hm.put(1,"ONE"); hm.put(4,"four"); //storing values in key-value pairs with unorder of keys, by eliminating duplicate keys System.out.println(hm);//1-ONE,2-two,3-three,4-four } } ================================================ FILE: data_structures/hashset/java/hashset.java ================================================ import java.util.*; class hashset { public static void main(String args[]) { // Create a tree set HashSet hs = new HashSet(); // Add elements to the tree set hs.add(3); hs.add(2); hs.add(3); hs.add(2); hs.add(1); hs.add(4); //HashSet is very helpful datastructure for avoid duplicatses and access elements in o(1) time completexity. In this datastructure order is not preserved. System.out.println(hs);// output will be {2,3,1,4} } } ================================================ FILE: data_structures/heap/cpp/MinHeap.h ================================================ #include #include using std::vector; class MinHeap { public: MinHeap(); MinHeap(vector); void push(int); int pop(); int size() { return heap.size(); } private: int left(int); int right(int); int parent(int); void siftUp(int); void siftDown(int); vector heap; }; MinHeap::MinHeap() { } MinHeap::MinHeap(vector nums) { heap = nums; for (int i = nums.size() / 2 - 1; i >= 0; i--) siftDown(i); } void MinHeap::push(int element) { heap.push_back(element); siftUp(heap.size() - 1); } int MinHeap::pop() { int top = heap.front(); heap[0] = heap.at(heap.size() - 1); heap.pop_back(); siftDown(0); return top; } void MinHeap::siftUp(int index) { while ((index > 0) && (parent(index) >= 0) && (heap[parent(index)] > heap[index])) { int tmp = heap[parent(index)]; heap[parent(index)] = heap[index]; heap[index] = tmp; index = parent(index); } } void MinHeap::siftDown(int index) { int child = left(index); if ((child > 0) && (right(index) > 0) && (heap[child] > heap[right(index)])) { child = right(index); } if (child > 0) { int tmp = heap[index]; heap[index] = heap[child]; heap[child] = tmp; siftDown(child); } } int MinHeap::left(int parent) { int i = (parent * 2) + 1; return (i < heap.size()) ? i : -1; } int MinHeap::right(int parent) { int i = (parent * 2) + 2; return (i < heap.size()) ? i : -1; } int MinHeap::parent(int child) { if (child != 0) { int i = (child - 1) / 2; return i; } return -1; } ================================================ FILE: data_structures/heap/java/Heap.java ================================================ package lecture19; import java.util.ArrayList; public class Heap> { boolean isMin; ArrayList data; public Heap(){ this(false); } public Heap(boolean isMin){ this.isMin=isMin; this.data=new ArrayList<>(); } public Heap(T[] arr,boolean isMin){ this(isMin); for(T value:arr){ this.data.add(value); } for(int i=this.data.size()/2-1;i>=0;i--){ this.downheapify(i); } } public int size(){ return this.data.size(); } public T getHP(){ return this.data.get(0); } public void add(T item){ this.data.add(item); this.upheapify(this.size()-1); } private void upheapify(int ci){ if(ci==0){ return; } int pi=(ci-1)/2; if(this.isLarger(pi,ci)==true){ return; }else{ this.swap(pi,ci); this.upheapify(pi); } } private void swap(int i,int j){ T temp=this.data.get(i); this.data.set(i,this.data.get(j)); this.data.set(j, temp); } private boolean isLarger(int i,int j){ T ithitem=this.data.get(i); T jthitem=this.data.get(j); if(isMin==true){ return ithitem.compareTo(jthitem)<0; }else{ return ithitem.compareTo(jthitem)>0; } } public T remove(){ T rv=this.data.get(0); this.swap(0, this.data.size()-1); this.data.remove(this.size()-1); this.downheapify(0); return rv; } private void downheapify(int pi){ int lci=(2*pi)+1; int rci=(2*pi)+2; int mi=pi; if(lci"; }else{ str=str+"END=>"; } str=str+node; if(rci, v> { private class node implements Comparable { k score; v value; node(k score, v value) { this.score = score; this.value = value; } public String toString() { return "{" + this.score + ":" + this.value + "}"; } @Override public int compareTo(heaps.node o) { if (ismin) { return -1 * this.score.compareTo(o.score); } else { return this.score.compareTo(o.score); } } } private ArrayList nodes; private boolean ismin; public heaps() { this(false); } public heaps(boolean ismin) { this.ismin = ismin; this.nodes = new ArrayList<>(); } public int size() { return this.nodes.size(); } public boolean isempty() { return this.nodes.size() == 0; } public void add(k score, v value) { node ntba = new node(score, value); this.nodes.add(ntba); this.upheapify(this.nodes.size() - 1); } private void upheapify(int ci) { if (ci == 0) return; int pi = (ci - 1) / 2; node parent = this.nodes.get(pi); node child = this.nodes.get(ci); if (parent.compareTo(child) < 0) { swap(pi, ci); upheapify(pi); } } public v removehp() { v rv = this.nodes.get(0).value; this.swap(0, this.nodes.size() - 1); this.nodes.remove(this.nodes.size() - 1); this.downheapify(0); return rv; } private void downheapify(int pi) { int lci = 2 * pi + 1; int rci = 2 * pi + 2; int maxi = pi; if (lci < this.nodes.size() && this.nodes.get(lci).compareTo(this.nodes.get(maxi)) > 0) maxi = lci; if (rci < this.nodes.size() && this.nodes.get(rci).compareTo(this.nodes.get(maxi)) > 0) maxi = rci; if (maxi != pi) { this.swap(maxi, pi); this.downheapify(maxi); } } public v gethp() { return this.nodes.get(0).value; } public void display() { System.out.println(this); } public String toString() { return this.nodes.toString(); } public void displaytree() { String ts = this.treestring(0); System.out.println(ts); } private String treestring(int pi) { String rv = ""; int lci = 2 * pi + 1; int rci = 2 * pi + 2; if (lci < this.nodes.size()) { rv += this.nodes.get(lci) + "=>"; } else { rv += "end =>"; } rv += this.nodes.get(pi); if (rci < this.nodes.size()) { rv += "<=" + this.nodes.get(rci); } else { rv += "<= end"; } rv += "\n"; if (lci < this.nodes.size()) rv += treestring(lci); if (rci < this.nodes.size()) rv += treestring(rci); return rv; } private void swap(int i, int j) { node temp = this.nodes.get(i); this.nodes.set(i, this.nodes.get(j)); this.nodes.set(j, temp); } } ================================================ FILE: data_structures/heap/python/minheap.py ================================================ import heapq class Heap(object): def __init__(self): self._heap = [] def push(self, priority, item): assert priority >= 0 heapq.heappush(self._heap, (priority, item)) def pop(self): item = heapq.heappop(self._heap)[1] return item def __len__(self): return len(self._heap) def __iter__(self): return self def next(self): try: return self.pop() except IndexError: raise StopIteration ================================================ FILE: data_structures/heap/ruby/heap.rb ================================================ class Heap def initialize @store = Array.new end def push(data) @store.push(data) tear_up(size - 1) end def top @store.first end def pop data = top if size > 1 @store[0] = @store.pop tear_down(0) else @store.pop end return data end def size @store.size end private def tear_up(pos) return if pos == 0 parent = (pos - 1) / 2 if @store[parent] < @store[pos] @store[parent], @store[pos] = @store[pos], @store[parent] tear_up(parent) end end def tear_down(pos) return if pos >= size left = pos * 2 + 1 right = pos * 2 + 2 max_leaf = -1 if left >= size max_leaf = -1 elsif right >= size max_leaf = left else if @store[right] > @store[left] max_leaf = right else max_leaf = left end end if max_leaf != -1 @store[max_leaf], @store[pos] = @store[pos], @store[max_leaf] tear_down(max_leaf) end end end # Usage H = Heap.new H.push(5) H.push(3) H.push(9) H.push(10) H.push(1) H.push(4) # 10 puts H.top() # 10 9 5 4 3 1 while H.size() > 0 do puts H.pop() end ================================================ FILE: data_structures/heapify_insert_extract_min/cpp/max-heap_functions.cpp ================================================ #include #include #include void heapify(int k,int arr[]); void insert(int t,int arr[]); int extract_max(int arr[]); int n; int size; int flag; int max; int temp; int temp1; int xx; int h; int main() { int N; int i,T; int query; int j; scanf("%d",&N); int array[N]; int array1[N]; size=N; int element; for(i=0;i0 && arr[n]>arr[(int)floor((double)(n-1)/2.0)]) { temp=arr[n]; arr[n]=arr[(int)floor((double)(n-1)/2.0)]; arr[(int)floor((double)(n-1)/2.0)]=temp; n=(int)floor((double)(n-1)/2.0); } } int extract_max(int arr[]) { n=size-1; temp=arr[0]; arr[0]=arr[n]; arr[n]=temp; //printf("arr[0],arr[n]:- %d %d\n",arr[0],arr[n]); size-=1; //printf("%d",size); heapify(0,arr); return temp; } ================================================ FILE: data_structures/left_learning_red_black_tree/c/llrb_tree.c ================================================ #include #include #include // Data structures struct treenode { int data; bool is_red; struct treenode *left; struct treenode *right; }; // Type definitions typedef struct treenode TREENODE; typedef TREENODE *TREE; // Function prototypes TREE make_tree(int data, TREE left, TREE right); int is_empty(TREE t); TREE left_subtree(TREE t); TREE right_subtree(TREE t); size_t size(TREE t); size_t height(TREE t); void preorder(TREE t); void inorder(TREE t); void postorder(TREE t); void print_leaf(TREE t); void insert_RB(TREE *t, int data); int search_RB(TREE t, int key); int main() { TREE t; int i; t = NULL; // let's start with an empty tree for (i = 1; i < 10; i++) insert_RB(&t, i); printf("Tree Size: %u / %u\n", size(t), height(t)); printf("Pre-order traversal: "); preorder(t); printf("\n"); printf("In-order traversal: "); inorder(t); printf("\n"); printf("Post-order traversal: "); postorder(t); printf("\n"); printf("Leaf Node: "); print_leaf(t); printf("\n"); // ***** END OF EXAMPLE ***** // exit(EXIT_SUCCESS); } TREE make_tree(int data, TREE left, TREE right) { TREE t; t = (TREE) malloc(sizeof(TREENODE)); t->data = data; t->left = left; t->right = right; t->is_red = true; return t; } bool is_red(TREE t) { if (t == NULL) return false; else return t->is_red; } int is_empty(TREE t) { return (t == NULL); } TREE left_subtree(TREE t) { return t->left; } TREE right_subtree(TREE t) { return t->right; } size_t size(TREE t) { // Basis: return 0 if tree is empty if (is_empty(t)) return 0; // Recursive: Count the root and accumulate size of left and right subtrees else return 1 + size(left_subtree(t)) + size(right_subtree(t)); } size_t max(size_t x, size_t y) { if (x > y) return x; else return y; } size_t height(TREE t) { // Basis: return 0 if tree is empty if (is_empty(t)) return 0; // Recursive: +1 Current layer and find maximum height of both left and right return 1 + max(height(left_subtree(t)), height(right_subtree(t))); } void preorder(TREE t) { if (!is_empty(t)) { printf("%d ", t->data); preorder(left_subtree(t)); preorder(right_subtree(t)); } } void inorder(TREE t) { if (!is_empty(t)) { inorder(left_subtree(t)); printf("%d ", t->data); inorder(right_subtree(t)); } } void postorder(TREE t) { if (!is_empty(t)) { postorder(left_subtree(t)); postorder(right_subtree(t)); printf("%d ", t->data); } } void print_leaf(TREE t) { if (!is_empty(t)) { print_leaf(left_subtree(t)); // The leaf has no children if ((left_subtree(t) == NULL) && (right_subtree(t) == NULL)) printf("%d ", t->data); print_leaf(right_subtree(t)); } } void rotate_left(TREE *t) { TREE old_root, new_root; old_root = *t; new_root = (*t)->right; old_root->right = new_root->left; new_root->left = old_root; new_root->is_red = old_root->is_red; old_root->is_red = true; *t = new_root; } void rotate_right(TREE *t) { TREE old_root, new_root; old_root = *t; new_root = (*t)->left; old_root->left = new_root->right; new_root->right = old_root; new_root->is_red = old_root->is_red; old_root->is_red = true; *t = new_root; } void flip_color(TREE *t) { (*t)->is_red = !(*t)->is_red; (*t)->left->is_red = !(*t)->left->is_red; (*t)->right->is_red = !(*t)->right->is_red; } void insert_RB(TREE *t, int data) { if (is_empty(*t)) *t = make_tree(data, NULL, NULL); else if ((*t)->data > data) insert_RB(&((*t)->left), data); else if ((*t)->data < data) insert_RB(&((*t)->right), data); else ; // No duplicates !! // Red node should be on left if (is_red((*t)->right) && !is_red((*t)->left)) rotate_left(t); // Consecutive red nodes must be rotated to be double red children and flipped if (is_red((*t)->left) && is_red((*t)->left->left)) rotate_right(t); // No double red children, flip color !! if (is_red((*t)->left) && is_red((*t)->right)) flip_color(t); } int search_RB(TREE t, int key) { // Basis 1: there is no data if tree is empty if (is_empty(t)) return 0; // Basis 2: if the root node is the key, we found it else if (t->data == key) return 1; // Recursive 1: if the root is greather, the key should be on the left of BST else if (t->data > key) return search_RB(left_subtree(t), key); // Recursive 2: the key should be on the right subtree otherwise else return search_RB(right_subtree(t), key); } ================================================ FILE: data_structures/left_learning_red_black_tree/java/left_leaning_red_black_tree.java ================================================ // Simplest Java Implementation of Left leaning Red Black Trees. public class left_leaning_red_black_tree, Value> { private static final boolean RED = true; private static final boolean BLACK = false; private Node root; private class Node { private Key key; private Value val; private Node left, right; private boolean color; Node(Key key, Value val) { this.key = key; this.val = val; this.color = RED; } } public Value search(Key key) { Node x = root; while (x != null) { int cmp = key.compareTo(x.key); if (cmp == 0) return x.val; else if (cmp < 0) x = x.left; else if (cmp > 0) x = x.right; } return null; } public void insert(Key key, Value value) { root = insert(root, key, value); root.color = BLACK; } private Node insert(Node h, Key key, Value value) { if (h == null) return new Node(key, value); if (isRed(h.left) && isRed(h.right)) colorFlip(h); int cmp = key.compareTo(h.key); if (cmp == 0) h.val = value; else if (cmp < 0) h.left = insert(h.left, key, value); else h.right = insert(h.right, key, value); if (isRed(h.right) && !isRed(h.left)) h = rotateLeft(h); if (isRed(h.left) && isRed(h.left.left)) h = rotateRight(h); return h; } private boolean isRed(Node h) { if(h == null) return false; return h.color; } void colorFlip(Node h) { h.color = !h.color; h.left.color = !h.left.color; h.right.color = !h.right.color; } private Node rotateLeft(Node h) { Node x = h.right; h.right = x.left; x.left = h; x.color = h.color; h.color = RED; return x; } private Node rotateRight(Node h) { Node x = h.left; h.left= x.right; x.right= h; x.color = h.color; h.color = RED; return x; } public void preorder() { preorder(root); } private void preorder(Node root) { if(root == null) return; System.out.println(root.key); preorder(root.left); preorder(root.right); } public void inorder() { inorder(root); } private void inorder(Node root) { if(root == null) return; inorder(root.left); System.out.println(root.key); inorder(root.right); } public void postorder() { postorder(root); } private void postorder(Node root) { if(root == null) return; postorder(root.left); postorder(root.right); System.out.println(root.key); } public static void main(String[] args) { left_leaning_red_black_tree l1 = new left_leaning_red_black_tree<>(); l1.insert(1, 10); l1.insert(2, 20); l1.insert(4, 30); l1.insert(6, 75); l1.insert(12, 89); l1.insert(19, 134); l1.insert(38, 12); l1.preorder(); } } ================================================ FILE: data_structures/linked_list/c/linked_list.c ================================================ #include #include #include struct node { int info; struct node *next; }*start=NULL; int main() { int n; char ch; do { printf("enter choice\n"); printf("1.creation\n2.insertion\n3.deletion\n4.search\n5.display\n"); scanf("%d",&n); switch(n) { case '1' : create(); break; case '2' : insert(); break; case '3' : delete(); break; case '4' : search(); break; case '5' : display(); break; default:printf("wrong choice\n"); break; } printf("\nwant to continue\n"); scanf("%s",&ch); }while(ch!='n'); return 0; } void create() { struct node *temp,*new; char ch; do { temp=(struct node *)malloc(sizeof(struct node)); printf("\nenter data\n"); scanf("%d",&temp->info); if(start==NULL) { start=temp; temp->next=NULL; new=temp; } else { new->next=temp; temp->next=NULL; new=temp; } printf("want to enter more\n"); ch=getche(); printf("\n"); }while(ch!='n'); } void insert() { int n; struct node *ptr,*temp; printf("enter choice\n"); printf("1.insertion at beginning\n2.insertion in the middle\n3.insertion at end\n"); scanf("%d",&n); if(n==1) { printf("enter the data to be inserted at the beginning\n"); temp=(struct node*)malloc(sizeof(struct node)); scanf("%d",&temp->info); temp->next=start; start=temp; } else if(n==2) { int i,pos; ptr=start; printf("insert data after the position\n"); scanf("%d",&pos); for(i=0;inext; temp=(struct node*)malloc(sizeof(struct node)); printf("enter data to be entered\n"); scanf("%d",&temp->info); temp->next=ptr->next; ptr->next=temp; } else if(n==3) { printf("enter data to be inserted at the end\n"); ptr=start; while(ptr->next!=NULL) ptr=ptr->next; temp=(struct node*)malloc(sizeof(struct node)); scanf("%d",&temp->info); temp->next=NULL; ptr->next=temp; } } void delete() { int n; struct node *ptr,*temp; ptr=start; printf("enter choice\n"); printf("1.deletion at the beginning\n2.deletion in the middle\n3.deletion at the end\n"); scanf("%d",&n); if(n==1) { start=ptr->next; free(ptr); } else if(n==2) { int pos,i; printf("enter the node number to be deleted\n"); scanf("%d",&pos); for(i=0;inext; temp=ptr->next; ptr->next=temp->next; free(temp); } else if(n==3) { int count=0,i; while(ptr->next!=NULL) { ptr=ptr->next; count++; } ptr=start; for(i=0;inext; ptr->next=NULL; } } void search() { struct node *ptr; ptr=start; int data,f=0,count=0; printf("enter data to be searched\n"); scanf("%d",&data); while(ptr!=NULL) { if(ptr->info==data) { f=1; break; } else { ptr=ptr->next; count++; } } if(f==1) printf("element %d found at node %d",data,count+1); else printf("element %d not found",data); } void display() { int count=0,i; struct node *ptr; printf("List is\n"); ptr=start; if(ptr==NULL) printf("List empty\n"); do { printf("%d->",ptr->info); ptr=ptr->next; }while(ptr!=NULL); printf("NULL\n"); } ================================================ FILE: data_structures/linked_list/cpp/LinkedList.cpp ================================================ /* * C++ Program to Implement Singly Linked List */ #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"< namespace std{ class Node{ private: int _data; Node *_next; public: Node(){} // setters void setData(int Data){ _data = Data;} void setNext(Node *Next){ if(Next == NULL){ _next = NULL; }else{ _next = Next; } } int Data(){return _data;} Node *Next(){return _next;} }; class LinkedList{ private: Node *head; public: LinkedList(){ head = NULL;} void insert_Back(int data); void insert_front(int data); bool isEmpty(); void init_list(int data); void print_List(); int size(); }; void LinkedList::print_List(){ Node *tmp = head; //Checking the list if there is a node or not. if(tmp == NULL){ cout << "List is empty\n"; return; } //Checking only one node situation. if(tmp->Next() == NULL){ cout << "Starting: " <Data() <<"Next Value > NULL\n"; }else{ while(tmp!=NULL){ cout << tmp->Data() << " > "; //incrementing the pointer; tmp = tmp->Next(); } } } /*inserting a value infront of the */ void LinkedList::insert_Back(int data){ //Creating a node Node *newNode = new Node(); newNode->setData(data); newNode->setNext(NULL); //Creating a temporary pointer. Node *tmp = head; if (tmp != NULL){ while(tmp->Next() != NULL){ tmp = tmp->Next(); } tmp->setNext(newNode); }else{ head = newNode; } } /*Inserting a value in front of the head node.*/ void LinkedList::insert_front(int data){ // creating a new node. Node *newNode = new Node(); newNode->setData(data); newNode->setNext(NULL); newNode->setNext(head); head = newNode; } /*Initializing the list with a value.*/ void LinkedList::init_list(int data){ //creating a node Node *newNode = new Node(); newNode->setData(data); newNode->setNext(NULL); if(head != NULL){ head = NULL; } head = newNode; } /*It returns to Linked Lists size.*/ int LinkedList::size(){ //counter variable int ctr = 0; Node *tmp = head; while(tmp!=NULL){ ctr++; tmp = tmp->Next(); } return ctr; } bool LinkedList::isEmpty(){ return (head == NULL) ? true:false; } } int main(){ //Creating a list std::LinkedList list; //Initilizing it with 5 list.init_list(5); list.insert_Back(6); list.insert_front(4); list.print_List(); } ================================================ FILE: data_structures/linked_list/csharp/LinkedList.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DataStructures { /* * Implementing methods from https://www.cs.cmu.edu/~adamchik/15-121/lectures/Linked%20Lists/linked%20lists.html */ class LinkedList { LinkedListNode head = null; public class LinkedListNode { object data; LinkedListNode next = null; public LinkedListNode(object newitem) { data = newitem; } public LinkedListNode(object newitem, LinkedListNode next) { data = newitem; this.next = next; } public object getData() { return data; } public LinkedListNode getNextNode() { return next; } public void setNextNode(LinkedListNode next) { this.next = next; } } public LinkedList(object data) { head = new LinkedListNode(data); } public void addFirst(object data) { head = new LinkedListNode(data, head); } public void addLast(object data) { if (head == null) { addFirst(data); } else { LinkedListNode temp = head; while (temp.getNextNode() != null) { temp = temp.getNextNode(); } temp.setNextNode(new LinkedListNode(data)); } } public void insertAfter(object data, object newData) { LinkedListNode temp = head; while ((temp != null) && (temp.getData() != data)) { temp = temp.getNextNode(); } if (temp != null) { temp.setNextNode(new LinkedListNode(newData, temp)); } } public void insertBefore(object data, object newData) { if (head == null) { return; } if (head.getData() == data) { addFirst(newData); return; } LinkedListNode prev = null; LinkedListNode curr = head; while ((curr != null) && (curr.getData() != data)) { prev = curr; curr = curr.getNextNode(); } if (curr != null) { prev.setNextNode(new LinkedListNode(newData, curr)); } } public void remove(object data) { if (head == null) { throw new Exception("List is empty, cannot delete."); } if (head.getData() == data) { head = head.getNextNode(); return; } LinkedListNode prev = null; LinkedListNode curr = head; while ((curr != null) && (curr.getData() != data)) { prev = curr; curr = curr.getNextNode(); } if (curr == null) { throw new Exception("Cannot delete."); } prev.setNextNode(curr.getNextNode()); } } } ================================================ FILE: data_structures/linked_list/go/linked_list.go ================================================ package main import "fmt" type Node struct { Value interface{} next *Node } func (n *Node) Next() *Node { return n.next } type LinkedList struct { first *Node last *Node } func (l *LinkedList) Add(v interface{}) { n := new(Node) n.Value = v if l.first == nil { l.first = n l.last = n } else { l.last.next = n l.last = n } } func (l *LinkedList) First() *Node { return l.first } func (l *LinkedList) ToString() string { str := "" if l.first != nil { n := l.first str += n.Value.(string) for n.next != nil { str += "," + n.next.Value.(string) n = n.next } } return str } func main() { list := new(LinkedList) list.Add("a") list.Add("b") list.Add("c") fmt.Printf(list.ToString() + "\n") } ================================================ FILE: data_structures/linked_list/java/LinkedList.java ================================================ * * Java Program to Implement Singly Linked List */ import java.util.Scanner; /* Class Node */ class Node { protected int data; protected Node link; /* Constructor */ public Node() { link = null; data = 0; } /* Constructor */ public Node(int d,Node n) { data = d; link = n; } /* Function to set link to next Node */ public void setLink(Node n) { link = n; } /* Function to set data to current Node */ public void setData(int d) { data = d; } /* Function to get link to next node */ public Node getLink() { return link; } /* Function to get data from current Node */ public int getData() { return data; } } /* Class linkedList */ class linkedList { protected Node start; protected Node end ; public int size ; /* Constructor */ public linkedList() { start = null; end = null; size = 0; } /* Function to check if list is empty */ public boolean isEmpty() { return start == null; } /* Function to get size of list */ public int getSize() { return size; } /* Function to insert an element at begining */ public void insertAtStart(int val) { Node nptr = new Node(val, null); size++ ; if(start == null) { start = nptr; end = start; } else { nptr.setLink(start); start = nptr; } } /* Function to insert an element at end */ public void insertAtEnd(int val) { Node nptr = new Node(val,null); size++ ; if(start == null) { start = nptr; end = start; } else { end.setLink(nptr); end = nptr; } } /* Function to insert an element at position */ public void insertAtPos(int val , int pos) { Node nptr = new Node(val, null); Node ptr = start; pos = pos - 1 ; for (int i = 1; i < size; i++) { if (i == pos) { Node tmp = ptr.getLink() ; ptr.setLink(nptr); nptr.setLink(tmp); break; } ptr = ptr.getLink(); } size++ ; } /* Function to delete an element at position */ public void deleteAtPos(int pos) { if (pos == 1) { start = start.getLink(); size--; return ; } if (pos == size) { Node s = start; Node t = start; while (s != end) { t = s; s = s.getLink(); } end = t; end.setLink(null); size --; return; } Node ptr = start; pos = pos - 1 ; for (int i = 1; i < size - 1; i++) { if (i == pos) { Node tmp = ptr.getLink(); tmp = tmp.getLink(); ptr.setLink(tmp); break; } ptr = ptr.getLink(); } size-- ; } /* Function to display elements */ public void display() { System.out.print("\nSingly Linked List = "); if (size == 0) { System.out.print("empty\n"); return; } if (start.getLink() == null) { System.out.println(start.getData() ); return; } Node ptr = start; System.out.print(start.getData()+ "->"); ptr = start.getLink(); while (ptr.getLink() != null) { System.out.print(ptr.getData()+ "->"); ptr = ptr.getLink(); } System.out.print(ptr.getData()+ "\n"); } } /* Class SinglyLinkedList */ public class SinglyLinkedList { public static void main(String[] args) { Scanner scan = new Scanner(System.in); /* Creating object of class linkedList */ linkedList list = new linkedList(); System.out.println("Singly Linked List Test\n"); char ch; /* Perform list operations */ do { System.out.println("\nSingly Linked List Operations\n"); System.out.println("1. insert at begining"); System.out.println("2. insert at end"); System.out.println("3. insert at position"); System.out.println("4. delete at position"); System.out.println("5. check empty"); System.out.println("6. get size"); int choice = scan.nextInt(); switch (choice) { case 1 : System.out.println("Enter integer element to insert"); list.insertAtStart( scan.nextInt()); break; case 2 : System.out.println("Enter integer element to insert"); list.insertAtEnd( scan.nextInt()); break; case 3 : System.out.println("Enter integer element to insert"); int num = scan.nextInt() ; System.out.println("Enter position"); int pos = scan.nextInt() ; if (pos <= 1 || pos > list.getSize()) System.out.println("Invalid position\n"); else list.insertAtPos(num, pos); break; case 4 : System.out.println("Enter position"); int p = scan.nextInt() ; if (p < 1 || p > list.getSize() ) System.out.println("Invalid position\n"); else list.deleteAtPos(p); break; case 5 : System.out.println("Empty status = "+ list.isEmpty()); break; case 6 : System.out.println("Size = "+ list.getSize() +" \n"); break; default : System.out.println("Wrong Entry \n "); break; } /* Display List */ list.display(); 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/linked_list/java/LinkedListLinkedList.java ================================================ /** * Java LinkedList implementation for Hacktoberfest * @author Prohunt * * @param type of LinkedList */ public class LinkedList { private Node head; private Node tail; private int size; /** * Constructor */ public LinkedList(){ head = null; tail = null; size = 0; } /** * Adds an element to the tail end of the list * @param element * @return success or failure */ public boolean add(E element){ if(null == head){ head = new Node(element); size++; return true; } if(null == tail){ tail = new Node(element); head.next = tail; size++; return true; } if(null != element){ tail.next = new Node(element); tail = new Node(element); size++; return true; } return false; } /** * Removes the given element from the list * @param element to remove * @return success or failure */ public boolean remove(E element){ Node current = head; while(null != current.next){ if(current.next.data.equals(element)){ current.next = current.next.next; size--; return true; } current = current.next; } return false; } /** * Checks if the list contains the element * @param element to check * @return true if it contains it, false otherwise */ public boolean contains(E element) { Node current = head; while (null != current){ if(current.data.equals(element)){ return true; } current = current.next; } return false; } /** * Get the Head of the list * @return */ public E head(){ return head.data; } /** * Gets the tail of the list * @return tail element */ public E tail(){ return tail.data; } /** * Gets the size of the list * @return size */ public int size(){ return size; } /** * Inner Class for storing elements as nodes * Provides a next Node for linking the elements together * @author Prohunt * */ private class Node{ E data; Node next; public Node(E element){ data = element; next = null; } } } ================================================ FILE: data_structures/linked_list/java/LinkedListTest.java ================================================ import static org.junit.Assert.*; import org.junit.Test; /** * Testing LinkedList * @author Prohunt * */ public class LinkedListTest { @Test public void testLinkedList(){ LinkedList intList = new LinkedList(); assertTrue(intList.add(1)); assertTrue(intList.add(2)); assertEquals(new Integer(1), intList.head()); assertEquals(new Integer(2), intList.tail()); assertTrue(intList.add(3)); assertEquals(new Integer(3), intList.tail()); assertEquals(3, intList.size()); assertFalse(intList.add(null)); assertTrue(intList.remove(new Integer(3))); assertFalse(intList.contains(new Integer(3))); assertEquals(2, intList.size()); assertTrue(intList.contains(new Integer(2))); assertFalse(intList.remove(new Integer(3))); } } ================================================ FILE: data_structures/linked_list/kotlin/LinkedList.kt ================================================ import java.util.* /* * Kotlin Program to Implement Singly Linked List */ /* Class Node */ internal class Node { /* Function to get data from current Node */ /* Function to set data to current Node */ var data: Int = 0 /* Function to get link to next node */ /* Function to set link to next Node */ var link: Node? = null /* Constructor */ constructor() { link = null data = 0 } /* Constructor */ constructor(d: Int, n: Node?) { data = d link = n } } /* Class linkedList */ internal class linkedList { private var start: Node? = null private var end: Node? = null /* Function to get size of list */ var size: Int = 0 /* Function to check if list is empty */ val isEmpty: Boolean get() = start == null /* Constructor */ init { start = null end = null size = 0 } /* Function to insert an element at begining */ fun insertAtStart(value: Int) { val nptr = Node(value, null) size++ if (start == null) { start = nptr end = start } else { nptr.link = start start = nptr } } /* Function to insert an element at end */ fun insertAtEnd(value: Int) { val nptr = Node(value, null) size++ if (start == null) { start = nptr end = start } else { end!!.link = nptr end = nptr } } /* Function to insert an element at position */ fun insertAtPos(value: Int, pos: Int) { var pos = pos val nptr = Node(value, null) var ptr = start pos =- 1 for (i in 1 until size) { if (i == pos) { val tmp = ptr!!.link ptr.link = nptr nptr.link = tmp break } ptr = ptr!!.link } size++ } /* Function to delete an element at position */ fun deleteAtPos(pos: Int) { var pos = pos if (pos == 1) { start = start!!.link size-- return } if (pos == size) { var s = start var t = start while (s !== end) { t = s s = s!!.link } end = t end!!.link = null size-- return } var ptr = start pos =- 1 for (i in 1 until size - 1) { if (i == pos) { var tmp = ptr!!.link tmp = tmp!!.link ptr.link = tmp break } ptr = ptr!!.link } size-- } /* Function to display elements */ fun display() { print("\nSingly Linked List = ") if (size == 0) { print("empty\n") return } if (start!!.link == null) { println(start!!.data) return } var ptr = start print(start!!.data.toString() + "->") ptr = start!!.link while (ptr!!.link != null) { print(ptr.data.toString() + "->") ptr = ptr.link } print(ptr.data.toString() + "\n") } } /* Class SinglyLinkedList */ object SinglyLinkedList { fun main(args: Array) { val scan = Scanner(System.`in`) /* Creating object of class linkedList */ val list = linkedList() println("Singly Linked List Test\n") var ch: Char /* Perform list operations */ do { println("\nSingly Linked List Operations\n") println("1. insert at begining") println("2. insert at end") println("3. insert at position") println("4. delete at position") println("5. check empty") println("6. get size") val choice = scan.nextInt() when (choice) { 1 -> { println("Enter integer element to insert") list.insertAtStart(scan.nextInt()) } 2 -> { println("Enter integer element to insert") list.insertAtEnd(scan.nextInt()) } 3 -> { println("Enter integer element to insert") val num = scan.nextInt() println("Enter position") val pos = scan.nextInt() if (pos <= 1 || pos > list.size) println("Invalid position\n") else list.insertAtPos(num, pos) } 4 -> { println("Enter position") val p = scan.nextInt() if (p < 1 || p > list.size) println("Invalid position\n") else list.deleteAtPos(p) } 5 -> println("Empty status = " + list.isEmpty) 6 -> println("Size = " + list.size + " \n") else -> println("Wrong Entry \n ") } /* Display List */ list.display() println("\nDo you want to continue (Type y or n) \n") ch = scan.next()[0] } while (ch == 'Y' || ch == 'y') } } ================================================ FILE: data_structures/linked_list/linked_list.md ================================================ ## ELI5 A linked list is a data structure made up of a bunch of little boxes that each hold a piece of information and directions to the next box. This makes it easy to make changes, because you don't have to move anything to a different box, you just have to give each box new directions. However, if you want the values in a certain box, you have to ask every box before it for directions to get there. ### Pros * It's cheap to add and remove elements from a linked list. ### Cons * It's expensive to get values in a given box. ## Technical Explanation A linked list is defined recursively as being either empty, or containing a node which stores a value and a pointer to a linked list. A linked list commonly starts with a pointer (often named "start" or "head") to the first node, and each subsequent node contains its value and a pointer to the next node. The pointer of the last node points to null, and therefore there are no more nodes and the list ends. Because of the pointer connections between nodes, inserting and removing values from a linked list is efficient, in O(1) time. Whereas contiguous data structures require shifting every piece of data after the edit point to preserve the contiguous structure, one can simply redirect the pointers in a linked list to accomplish the same. Inserting an item requires creating a node with that item, assigning that node's pointer to the address of the item after it (which can be retrieved from the item before it) and then assigning the pointer of the item before it to the newly created node. Deleting/erasing an item simply requires redirecting the pointer of the previous node to the next node. Care must be taken in languages where memory is manually deallocated/freed so as to delete the node before redirecting the pointer that points to it, and without losing the pointer to the next node. The pointer-based nature of list also makes it easier to make greater changes such as reversing the list, as once again no values must be copied to different spots in memory, instead only pointers are reassigned. Accessing the value at a given index in the list is expensive, in O(n) time. One must start at a known pointer and increment through the list one node at a time until the desired location is reached. Because lists are not based on arrays, subscripting in the standard O(1) sense cannot be used to access list values. ### Pros * Adding and removing nodes from the list is cheap O(1) ### Cons * Accessing values in the list is expensive O(n) ================================================ FILE: data_structures/linked_list/python/linked_list.py ================================================ class Node: def __init__(self, data=None, next_node=None): self.data = data self.next = next_node self.prev = None def __repr__(self): return self.data or '' class LinkedList: ''' Implementation of Linked list data structure ''' def __init__(self, data_iterable): self.head = None for data in data_iterable: self.add(data) def add(self, data): node = Node(data) node.next = self.head self.head = node if node.next: node.next.prev = node def search(self, data): node = self.head while node: if node.data == data: return node node = node.next return None def remove(self, node): if node is self.head: self.head = node.next else: node.prev.next = node.next if node.next: node.next.prev = node.prev def __repr__(self): node = self.head data = [] while node: data.append(node.data) node = node.next return ' '.join(data) if __name__ == '__main__': l = LinkedList(['d', 'c', 'b']) assert str(l) == 'b c d' l.add('a') assert str(l) == 'a b c d' l.remove(l.search('a')) l.remove(l.search('c')) assert str(l) == 'b d' ================================================ FILE: data_structures/linked_list/ruby/linked_list.rb ================================================ class Node attr_writer :next attr_reader :next, :data def initialize(data, next_node = nil) @data = data @next = next_node end end class LinkedList def initialize @head = nil @tail = @head end def insertFront(data) node = Node.new(data, @head) @tail = node if @tail == nil @head = node end def insertBack(data) node = Node.new(data) @head = node if @head == nil @tail.next = node if @tail != nil @tail = node end def find(data) current = @head while current != nil do return current if data == current.data current = current.next end return nil end def remove(node) prev = nil current = @head while current != nil do if node.equal? current if current == @head @head = @head.next elsif current == @tail @tail = prev prev.next = nil else prev.next = current.next end break end prev = current current = current.next end end def iterate current = @head while current != nil do yield current.data current = current.next end end end # Usage L = LinkedList.new L.insertBack(3) L.insertBack(4) L.insertFront(2) L.insertFront(1) # 1 2 3 4 L.iterate { |data| puts(data) } node_2 = L.find(4) L.remove(node_2) # 1 3 4 L.iterate { |data| puts(data) } ================================================ FILE: data_structures/linked_list_queue/cpp/queue_linked_list.cpp ================================================ // Simple queue data structure using singly linked list #include // List node template struct QueueNode { // Constructor. Set node value and initialize next node pointer to NULL QueueNode(T _value) { value = _value; pNext = NULL; } T value; // Value stored in node QueueNode *pNext; // Next node in linked list }; // Queue structure template class CQueue { public: // Constructor. Initialize head & tail pointer to NULL. CQueue() { m_pHead = m_pTail = NULL; } // Push a new element into the queue void enqueue(T value) { QueueNode *pNewTail = new QueueNode(value); if (m_pHead == NULL) m_pHead = m_pTail = pNewTail; else { m_pTail->pNext = pNewTail; m_pTail = pNewTail; } } // Pop the head element from the queue T dequeue() { if (m_pHead == NULL) return NULL; T value = m_pHead->value; QueueNode *pNewHead = m_pHead->pNext; delete m_pHead; m_pHead = pNewHead; return value; } // Check if the queue is empty bool isEmpty() { return m_pHead == NULL; } private: QueueNode *m_pHead; // Head node of linked list QueueNode *m_pTail; // Tail node of linked list }; using namespace std; int main() { CQueue queue; queue.enqueue(1); queue.enqueue(2); queue.enqueue(3); queue.enqueue(4); queue.enqueue(5); while (!queue.isEmpty()) cout << queue.dequeue() << ' '; return 0; } ================================================ FILE: data_structures/min_heap/cpp/impl_minHeap.cpp ================================================ // Insert the following numbers into the heap, printing the heap after each insert: // 2 3 7 22 5 21 1 28 4 16 0 17 12 18 20 25 // deleteMin() the numbers in the heap, into a new list (array or vector is fine), printing the heap after each deleteMin() (I want to see how your heap structure changes after each deleteMin). // Print the new sorted list of numbers. #include "minHeap.cpp" #include #include #include #include using std::cout; using std::endl; using std::string; int main(){ int unsortedNums[] = {2, 3, 7, 22, 5, 21, 1, 28, 4, 16, 0, 17, 12, 18, 20, 25}; int sortedNums[16]; MinHeap heap; cout << "Printing unsorted List: \n"; for(int k = 0;k<16;k++){ cout << unsortedNums[k] << ", "; } cout << "\n\n========================================================\nInserting to min heap: \n"; for(int i = 0;i<16;i++){ heap.insert(unsortedNums[i]); heap.printSelf(); cout << endl; } cout << "========================================================\nSorting List: \n"; for(int j = 0;j<16;j++){ int min = heap.deleteMin(); sortedNums[j] = min; heap.printSelf(); cout << endl; } cout << "========================================================\nPrinting Sorted List: \n"; for(int k = 0;k<16;k++){ cout << sortedNums[k] << ", "; } cout << endl; } ================================================ FILE: data_structures/min_heap/cpp/minHeap.cpp ================================================ #include "minHeap.hpp" #include #include #include using std::cout; using std::endl; using std::vector; // Some helpers first // The left child of node in index i is: 2*i+1 // The right child of node in index i is: 2*i+2 // The parent of the node in index i is: (int)((i-1)/2) int getLeftIndex(int x){ return 2*x+1; } int getRightIndex(int x){ return 2*x+2; } int getParentIndex(int x){ return (int)((x-1)/2); } MinHeap::MinHeap(){} MinHeap::~MinHeap(){} void MinHeap::insert(int item){ int length = _heap.size(); _heap.push_back(item); bubbleUp(length); } int MinHeap::deleteMin(){ int length = _heap.size(); if(length == 0){ return -1; } int min = _heap[0]; _heap[0] = _heap[length-1]; _heap.pop_back(); bubbleDown(0); return min; } void MinHeap::printSelf(){ cout << "Heap printing...\n"; if(_heap.size() == 0){ cout << "There is nothing in the heap\n"; return; } for(int i = 0;i < _heap.size();i++){ cout << _heap.at(i) << ", "; } cout << endl; } void MinHeap::bubbleDown(int index){ int length = _heap.size(); int leftChildIndex = getLeftIndex(index); int rightChildIndex = getRightIndex(index); if(leftChildIndex >= length) return; //index is a leaf int minIndex = index; if(_heap[index] > _heap[leftChildIndex]){ minIndex = leftChildIndex; } if((rightChildIndex < length) && (_heap[minIndex] > _heap[rightChildIndex])){ minIndex = rightChildIndex; } if(minIndex != index){ //need to swap int temp = _heap[index]; _heap[index] = _heap[minIndex]; _heap[minIndex] = temp; bubbleDown(minIndex); } } void MinHeap::bubbleUp(int index){ if(index == 0) return; int parentIndex = getParentIndex(index); if(_heap[parentIndex] > _heap[index]){ int temp = _heap[parentIndex]; _heap[parentIndex] = _heap[index]; _heap[index] = temp; bubbleUp(parentIndex); } } ================================================ FILE: data_structures/min_heap/cpp/minHeap.hpp ================================================ #ifndef MINHEAP_H #define MINHEAP_H #include #include #include using std::vector; class MinHeap{ public: MinHeap(); ~MinHeap(); void insert(int item); int deleteMin(); void printSelf(); private: void bubbleUp(int index); void bubbleDown(int index); vector _heap; }; #endif //MINHEAP_H ================================================ FILE: data_structures/mirror_of_a_tree.java/java/Mirror.java ================================================ class Mirror{ Node root = null; Node mRoot = null; public void mirror(Node node){ if(node == null) return ; mirror(node.left); mirror(node.right); Node temp = node.left; node.left = node.right; node.right = temp; } public void printTree(Node node){ if(node == null) return; printTree(node.left); System.out.print(node.data+" "); printTree(node.right); } public static void main(String[] args){ Mirror bt = new Mirror(); bt.root = new Node(1); bt.root.left = new Node(2); bt.root.right = new Node(3); bt.root.left.left = new Node(4); bt.root.left.right = new Node(5); bt.root.right.right = new Node(7); bt.root.right.left = new Node(6); System.out.println("Original Tree\n"); bt.printTree(bt.root); bt.mirror(bt.root); System.out.println(); System.out.println("Mirror Tree\n"); bt.printTree(bt.root); } } ================================================ FILE: data_structures/mirrot_of_a_tree.cpp/mirror.cpp ================================================ #include #include #include using namespace std; typedef struct btree { int data; struct btree *left; struct btree *right; }btree; btree *makeTree(btree *root , int d) { btree *nn = (btree*)malloc(sizeof(btree)); nn->data = d; nn->left = NULL; nn->right = NULL; if(root==NULL) { return nn; } else { queue q; q.push(root); while(!q.empty()) { btree *node = q.front(); q.pop(); if(node->left) q.push(node->left); else { node->left = nn; return root; } if(node->right) q.push(node->right); else { node->right = nn; return root; } } } } btree *mirror(btree *root) { if(root==NULL) return NULL; btree *nn = (btree*)malloc(sizeof(btree)); nn->data = root->data; nn->right = mirror(root->left); nn->left = mirror(root->right); return nn; } void printTreeLevelOrder(btree *root) { queue q; q.push(root); while(!q.empty()) { btree *node = q.front(); q.pop(); cout<data<<" "; if(node->left) q.push(node->left); if(node->right) q.push(node->right); } } int main() { btree *a = NULL; a = makeTree(a,1); a = makeTree(a,2); a = makeTree(a,3); a = makeTree(a,4); a = makeTree(a,5); a = makeTree(a,6); a = makeTree(a,7); btree *b = mirror(a); printTreeLevelOrder(b); cout< #include // Number of vertices in the graph #define V 5 // A utility function to find the vertex with minimum key value, from // the set of vertices not yet included in MST int minKey(int key[], bool mstSet[]) { // Initialize min value int min = INT_MAX, min_index; for (int v = 0; v < V; v++) if (mstSet[v] == false && key[v] < min) min = key[v], min_index = v; return min_index; } // A utility function to print the constructed MST stored in parent[] int printMST(int parent[], int n, int graph[V][V]) { printf("Edge Weight\n"); for (int i = 1; i < V; i++) printf("%d - %d %d \n", parent[i], i, graph[i][parent[i]]); } // Function to construct and print MST for a graph represented using adjacency // matrix representation void primMST(int graph[V][V]) { int parent[V]; // Array to store constructed MST int key[V]; // Key values used to pick minimum weight edge in cut bool mstSet[V]; // To represent set of vertices not yet included in MST // Initialize all keys as INFINITE for (int i = 0; i < V; i++) key[i] = INT_MAX, mstSet[i] = false; // Always include first 1st vertex in MST. key[0] = 0; // Make key 0 so that this vertex is picked as first vertex parent[0] = -1; // First node is always root of MST // The MST will have V vertices for (int count = 0; count < V-1; count++) { // Pick the minimum key vertex from the set of vertices // not yet included in MST int u = minKey(key, mstSet); // Add the picked vertex to the MST Set mstSet[u] = true; // Update key value and parent index of the adjacent vertices of // the picked vertex. Consider only those vertices which are not yet // included in MST for (int v = 0; v < V; v++) // graph[u][v] is non zero only for adjacent vertices of m // mstSet[v] is false for vertices not yet included in MST // Update the key only if graph[u][v] is smaller than key[v] if (graph[u][v] && mstSet[v] == false && graph[u][v] < key[v]) parent[v] = u, key[v] = graph[u][v]; } // print the constructed MST printMST(parent, V, graph); } // driver program to test above function int main() { /* Let us create the following graph 2 3 (0)--(1)--(2) | / \ | 6| 8/ \5 |7 | / \ | (3)-------(4) 9 */ int graph[V][V] = {{0, 2, 0, 6, 0}, {2, 0, 3, 8, 5}, {0, 3, 0, 0, 7}, {6, 8, 0, 0, 9}, {0, 5, 7, 9, 0}, }; // Print the solution primMST(graph); return 0; } ================================================ FILE: data_structures/mst/java/prims.java ================================================ public class PrimMST { private static final double FLOATING_POINT_EPSILON = 1E-12; private Edge[] edgeTo; // edgeTo[v] = shortest edge from tree vertex to non-tree vertex private double[] distTo; // distTo[v] = weight of shortest such edge private boolean[] marked; // marked[v] = true if v on tree, false otherwise private IndexMinPQ pq; /** * Compute a minimum spanning tree (or forest) of an edge-weighted graph. * @param G the edge-weighted graph */ public PrimMST(EdgeWeightedGraph G) { edgeTo = new Edge[G.V()]; distTo = new double[G.V()]; marked = new boolean[G.V()]; pq = new IndexMinPQ(G.V()); for (int v = 0; v < G.V(); v++) distTo[v] = Double.POSITIVE_INFINITY; for (int v = 0; v < G.V(); v++) // run from each vertex to find if (!marked[v]) prim(G, v); // minimum spanning forest // check optimality conditions assert check(G); } // run Prim's algorithm in graph G, starting from vertex s private void prim(EdgeWeightedGraph G, int s) { distTo[s] = 0.0; pq.insert(s, distTo[s]); while (!pq.isEmpty()) { int v = pq.delMin(); scan(G, v); } } // scan vertex v private void scan(EdgeWeightedGraph G, int v) { marked[v] = true; for (Edge e : G.adj(v)) { int w = e.other(v); if (marked[w]) continue; // v-w is obsolete edge if (e.weight() < distTo[w]) { distTo[w] = e.weight(); edgeTo[w] = e; if (pq.contains(w)) pq.decreaseKey(w, distTo[w]); else pq.insert(w, distTo[w]); } } } /** * Returns the edges in a minimum spanning tree (or forest). * @return the edges in a minimum spanning tree (or forest) as * an iterable of edges */ public Iterable edges() { Queue mst = new Queue(); for (int v = 0; v < edgeTo.length; v++) { Edge e = edgeTo[v]; if (e != null) { mst.enqueue(e); } } return mst; } /** * Returns the sum of the edge weights in a minimum spanning tree (or forest). * @return the sum of the edge weights in a minimum spanning tree (or forest) */ public double weight() { double weight = 0.0; for (Edge e : edges()) weight += e.weight(); return weight; } // check optimality conditions (takes time proportional to E V lg* V) private boolean check(EdgeWeightedGraph G) { // check weight double totalWeight = 0.0; for (Edge e : edges()) { totalWeight += e.weight(); } if (Math.abs(totalWeight - weight()) > FLOATING_POINT_EPSILON) { System.err.printf("Weight of edges does not equal weight(): %f vs. %f\n", totalWeight, weight()); return false; } // check that it is acyclic UF uf = new UF(G.V()); for (Edge e : edges()) { int v = e.either(), w = e.other(v); if (uf.connected(v, w)) { System.err.println("Not a forest"); return false; } uf.union(v, w); } // check that it is a spanning forest for (Edge e : G.edges()) { int v = e.either(), w = e.other(v); if (!uf.connected(v, w)) { System.err.println("Not a spanning forest"); return false; } } // check that it is a minimal spanning forest (cut optimality conditions) for (Edge e : edges()) { // all edges in MST except e uf = new UF(G.V()); for (Edge f : edges()) { int x = f.either(), y = f.other(x); if (f != e) uf.union(x, y); } // check that e is min weight edge in crossing cut for (Edge f : G.edges()) { int x = f.either(), y = f.other(x); if (!uf.connected(x, y)) { if (f.weight() < e.weight()) { System.err.println("Edge " + f + " violates cut optimality conditions"); return false; } } } } return true; } /** * Unit tests the {@code PrimMST} data type. * * @param args the command-line arguments */ public static void main(String[] args) { In in = new In(args[0]); EdgeWeightedGraph G = new EdgeWeightedGraph(in); PrimMST mst = new PrimMST(G); for (Edge e : mst.edges()) { StdOut.println(e); } StdOut.printf("%.5f\n", mst.weight()); } } ================================================ FILE: data_structures/priority_queue/c/priority_queue.cpp ================================================ #include #include struct node{ int data,priority; struct node* next; }; struct node *header=NULL; void enque(int data,int priority) { struct node* ptr2; ptr2=(struct node*)malloc(sizeof(struct node)); ptr2->data=data; ptr2->priority=priority; ptr2->next=header; header=ptr2; } void deque() { struct node *ptr,*min,*prev; prev=NULL; ptr=header; min=ptr; ptr=ptr->next; if(ptr==NULL) { printf("empty\n"); return; } while(ptr!=NULL) { if(min->priority>ptr->priority) { prev=min; min=ptr; } ptr=ptr->next; } printf("dequeued element: %d\tpriority: %d\n",min->data,min->priority); prev->next=min->next; free(min); } void display() { struct node *ptr; ptr=header; if(ptr==NULL) { printf("empty\n"); return; } while(ptr!=NULL) { printf("%d,%d\t",ptr->data,ptr->priority); ptr=ptr->next; } printf("\n"); } int main() { int c,x,p; while(1) { printf("1.enque\n2.deque\n3.display\n4.exit\n"); scanf("%d",&c); switch(c) { case 1: printf("enter element and priority: "); scanf("%d%d",&x,&p); enque(x,p); break; case 2: deque(); break; case 3: display(); break; case 4: goto end; } } end:; } ================================================ FILE: data_structures/queue/c/queue.c ================================================ #include #include # define max 5 int queue[max]; int f=0,r=-1; int count=0; int main() { int n; do { printf("\nEnter choice:\n1.Push\n2.POP\n3.Display\n4.Exit\n"); scanf("%d",&n); switch(n) { case 1: push(); break; case 2: pop(); break; case 3: display(); break; case 4: exit(0); break; } }while(n!=4); return 0; } void push() { int data; printf("\n"); if((f==0 && r==max-1) || (f>0 && r==f-1)) printf("queue overflow\n"); else if((r==-1 && f==0) || (f==0 && r0 && r!=f)) { r=(r+1)%max; printf("Enter element\n"); scanf("%d",&queue[r]); count++; } printf("\n\n"); } void pop() { if(r==-1 || (f>0 && f==(r+1)%max)) printf("\nUnderflow\n"); else { printf("\nElement %d is popped out\n",queue[f]); f=(f+1)%max; count--; } printf("\n\n"); } void display() { printf("\n"); int i; printf("\nElements present are\n"); for(i=0;i Queue::Queue() { tail = head = nullptr; sz = 0; } template Queue::Queue(T value, int intial_size) { sz = intial_size; if(intial_size > 0) { Node* temp = new Node(value, nullptr); tail = head = temp; intial_size--; }else{ tail = head = nullptr; } while(intial_size > 0) { Node* temp = new Node(value, nullptr); tail->prev = temp; tail = temp; intial_size--; } } template T* Queue::Front() { try{ if(head != nullptr) return &(head->value); throw(0); catch(...){ cout << "EmptyQueue" << endl; } } template void Queue::Pop() { if(head == nullptr) return; sz--; Node* temp = head; head = head->prev; delete temp; } template void Queue::Push(T value) { Node* temp = new Node(value, NULL); if(tail == nullptr) { tail = head = temp; sz++; return; } tail->prev = temp; tail = temp; sz++; } template int Queue::Size() { return sz; } template void Queue::Print() { Node* temp = head; while(temp != nullptr) { cout << temp->value << " "; temp = temp->prev; } } template Queue::~Queue() { Node* temp = head; while(temp != nullptr) { temp = head; head = head->prev; delete temp; } } ================================================ FILE: data_structures/queue/cpp/Queue.h ================================================ #ifndef QUEUE_H #define QUEUE_H #include using namespace std; template class Queue { struct Node { Node(T v, Node* pre){value = v; prev = pre;} T value; Node* prev; }; public: Queue(); Queue(T value, int intial_size); T* Front(); void Pop(); void Push(T value); int Size(); void Print(); virtual ~Queue(); protected: private: Node* tail; Node* head; int sz; }; #endif // QUEUE_H ================================================ FILE: data_structures/queue/csharp/Queue.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DataStructures { class Queue { private List queue = new List(); public Object dequeue() { if (queue.Count > 0) { Object temp = queue[0]; queue.RemoveAt(0); return temp; } else { return null; } } public Object peek() { if (queue.Count > 0) { return queue[0]; } else { return null; } } public void enqueue(Object newItem) { queue.Add(newItem); } public bool isEmpty() { return (queue.Count == 0); } } } ================================================ FILE: data_structures/queue/go/queue.go ================================================ package main import "fmt" type queue struct { data []interface{} } func NewQueue() queue { return queue{nil} } func (q *queue) Enqueue(value interface{}) { q.data = append(q.data, value) } func (q *queue) Dequeue() (interface{}) { value := q.data[0] q.data = q.data[1: len(q.data)] return value } func main() { q := NewQueue() q.Enqueue(10) q.Enqueue("Hello") q.Enqueue(20) q.Enqueue(10) q.Enqueue("Hello") q.Enqueue(20) q.Enqueue(10) q.Enqueue("Hello") q.Enqueue(20) q.Enqueue(10) q.Enqueue("Hello") q.Enqueue(20) q.Enqueue(10) q.Enqueue("Hello") q.Enqueue(20) q.Enqueue(10) q.Enqueue("Hello") q.Enqueue(20) fmt.Println(q) fmt.Println(q.Dequeue()) fmt.Println(q.Dequeue()) fmt.Println(q) } ================================================ FILE: data_structures/queue/java/IterableQueue.java ================================================ import java.util.Iterator; import java.util.NoSuchElementException; public class IterableQueue implements Iterable { private Node first; // beginning of queue private Node last; // end of queue private int n; // number of elements on queue // helper linked list class private static class Node { private E element; private Node next; } /** * Initializes an empty queue. */ public IterableQueue() { first = null; last = null; n = 0; } /** * Returns true if this queue is empty. * * @return {@code true} if this queue is empty; {@code false} otherwise */ public boolean isEmpty() { return first == null; } /** * Returns the number of items in this queue. * * @return the number of items in this queue */ public int size() { return n; } /** * Returns the element least recently added to this queue. * * @return the element least recently added to this queue * @throws NoSuchElementException if this queue is empty */ public E peek() { if (isEmpty()) throw new NoSuchElementException("Queue underflow"); return first.element; } /** * Adds the element to this queue. * * @param element the element to add */ public void enqueue(E element) { Node oldLast = last; last = new Node(); last.element = element; last.next = null; if (isEmpty()) first = last; else oldLast.next = last; n++; } /** * Removes and returns the element on this queue that was least recently added. * * @return the element on this queue that was least recently added * @throws NoSuchElementException if this queue is empty */ public E dequeue() { if (isEmpty()) throw new NoSuchElementException("Queue underflow"); E element = first.element; first = first.next; n--; if (isEmpty()) last = null; // to avoid loitering return element; } /** * Returns a string representation of this queue. * * @return the sequence of items in FIFO order, separated by spaces */ public String toString() { StringBuilder s = new StringBuilder(); for (E element : this) { s.append(element); s.append(' '); } return s.toString(); } /** * Returns an iterator that iterates over the items in this queue in FIFO order. * * @return an iterator that iterates over the items in this queue in FIFO order */ public Iterator iterator() { return new ListIterator(first); } // an iterator, doesn't implement remove() since it's optional private class ListIterator implements Iterator { private Node current; public ListIterator(Node first) { current = first; } public boolean hasNext() { return current != null; } public void remove() { throw new UnsupportedOperationException(); } public Item next() { if (!hasNext()) throw new NoSuchElementException(); Item item = current.element; current = current.next; return item; } } } ================================================ FILE: data_structures/queue/javascript/queue_ES5.js ================================================ function Queue() { this._oldestIndex = 1; this._newestIndex = 1; this._storage = {}; } Queue.prototype.size = function() { return this._newestIndex - this._oldestIndex; }; Queue.prototype.enqueue = function(data) { this._storage[this._newestIndex] = data; this._newestIndex++; }; Queue.prototype.dequeue = function() { var oldestIndex = this._oldestIndex, newestIndex = this._newestIndex, deletedData; if (oldestIndex !== newestIndex) { deletedData = this._storage[oldestIndex]; delete this._storage[oldestIndex]; this._oldestIndex++; return deletedData; } }; ================================================ FILE: data_structures/queue/javascript/queue_ES6.js ================================================ class Queue { constructor() { this._oldestIndex = 1; this._newestIndex = 1; this._storage = {}; } size() { return this._newestIndex - this._oldestIndex; } enqueue(data) { this._storage[this._newestIndex] = data; this._newestIndex++; } dequeue() { let oldestIndex = this._oldestIndex; let newestIndex = this._newestIndex; let deletedData; if (oldestIndex !== newestIndex) { deletedData = this._storage.oldestIndex; delete this._storage.oldestIndex; this._oldestIndex++; return deletedData; } } } ================================================ FILE: data_structures/queue/kotlin/IterableQueue.kt ================================================ import java.util.NoSuchElementException class IterableQueue : Iterable { private var first: Node? = null // beginning of queue private var last: Node? = null // end of queue private var n: Int = 0 // number of elements on queue // helper linked list class private class Node { internal var element: E? = null internal var next: Node? = null } /** * Initializes an empty queue. */ init { first = null last = null n = 0 } /** * Returns true if this queue is empty. * @return `true` if this queue is empty; `false` otherwise */ val isEmpty: Boolean get() = first == null /** * Returns the number of items in this queue. * @return the number of items in this queue */ fun size(): Int { return n } /** * Returns the element least recently added to this queue. * @return the element least recently added to this queue * * * @throws NoSuchElementException if this queue is empty */ fun peek(): E { if (isEmpty) throw NoSuchElementException("Queue underflow") return first!!.element!! } /** * Adds the element to this queue. * @param element the element to add */ fun enqueue(element: E) { val oldLast = last last = Node() last!!.element = element last!!.next = null if (isEmpty) first = last else oldLast!!.next = last n++ } /** * Removes and returns the element on this queue that was least recently added. * @return the element on this queue that was least recently added * * * @throws NoSuchElementException if this queue is empty */ fun dequeue(): E { if (isEmpty) throw NoSuchElementException("Queue underflow") val element = first!!.element first = first!!.next n-- if (isEmpty) last = null // to avoid loitering return element!! } /** * Returns a string representation of this queue. * @return the sequence of items in FIFO order, separated by spaces */ override fun toString(): String { val s = StringBuilder() for (element in this) { s.append(element) s.append(' ') } return s.toString() } /** * Returns an iterator that iterates over the items in this queue in FIFO order. * @return an iterator that iterates over the items in this queue in FIFO order */ override fun iterator(): Iterator { return ListIterator(first) } // an iterator, doesn't implement remove() since it's optional private inner class ListIterator(private var current: Node?) : Iterator { override fun hasNext(): Boolean { return current != null } override fun next(): Item { if (!hasNext()) throw NoSuchElementException() val item = current!!.element current = current!!.next return item!! } } } ================================================ FILE: data_structures/queue/php/queue.php ================================================ enqueue($item); } } } /** * @return int */ public function size(){ return count($this->_data); } /** * @param $item */ public function enqueue($item){ $this->_data[] = $item; } /** * @return mixed * @throws Exception */ public function dequeue(){ if($this->size() > 0){ return array_shift($this->_data); } else { throw new Exception('Can\'t dequeue an empty queue!'); } } } $queue = new Queue(['1','2','3','4']); $queue->dequeue(); //1 $queue->enqueue('5'); //2,3,4,5 ?> ================================================ FILE: data_structures/queue/python/queue_two_stacks.py ================================================ def get_command(): parts = input().strip().split(' ') command = int(parts[0]) if len(parts) == 1: return (command, None) try: arg = int(parts[1]) except ValueError: arg = parts[1] return command, arg class Stack: def __init__(self): self._l = [] def __len__(self): return len(self._l) def push(self, data): self._l.append(data) def pop(self): return self._l.pop() def top(self): if self._l: return self._l[-1] return None class Queue: def __init__(self): self._head = Stack() self._tail = Stack() def enqueue(self, data): self._tail.push(data) def dequeue(self): if self._head: return self._head.pop() return self._tail_to_head().pop() def peek(self): if self._head: return self._head.top() return self._tail_to_head().top() def _tail_to_head(self): while self._tail: self._head.push(self._tail.pop()) return self._head def main(): queue = Queue() command_no = int(input().strip()) for _ in range(command_no): command, arg = get_command() if command == ENQUEUE: queue.enqueue(arg) elif command == DEQUEUE: queue.dequeue() elif command == PRINT: print(queue.peek()) if __name__ == '__main__': main() ================================================ FILE: data_structures/queue/ruby/queue.rb ================================================ class Queue def initialize @store = Array.new end def enqueue(data) @store.push(data) end def dequeue() raise Exception if size == 0 @store.shift end def front() raise Exception if size == 0 @store.first end def back() @store.last end def size() @store.size end end # Usage Q = Queue.new Q.enqueue(1) Q.enqueue(2) Q.enqueue(3) puts Q.front() puts Q.back() puts Q.dequeue() puts Q.dequeue() ================================================ FILE: data_structures/simple_queue/java/QueueImplementation.java ================================================ import java.util.Scanner; /* Class QueueImplement */ public class QueueImplementation { public static void main(String[] args) { Scanner scan = new Scanner(System.in); System.out.println("Array Queue Test\n"); System.out.println("Enter Size of Integer Queue "); int n = scan.nextInt(); /* creating object of class arrayQueue */ arrayQueue q = new arrayQueue(n); /* Perform Queue Operations */ char ch; do{ System.out.println("\nQueue Operations"); System.out.println("1. insert"); System.out.println("2. remove"); System.out.println("3. peek"); System.out.println("4. check empty"); System.out.println("5. check full"); System.out.println("6. size"); int choice = scan.nextInt(); switch (choice) { case 1 : System.out.println("Enter integer element to insert"); try { q.insert( scan.nextInt() ); } catch(Exception e) { System.out.println("Error : " +e.getMessage()); } break; case 2 : try { System.out.println("Removed Element = "+q.remove()); } catch(Exception e) { System.out.println("Error : " +e.getMessage()); } break; case 3 : try { System.out.println("Peek Element = "+q.peek()); } catch(Exception e) { System.out.println("Error : "+e.getMessage()); } break; case 4 : System.out.println("Empty status = "+q.isEmpty()); break; case 5 : System.out.println("Full status = "+q.isFull()); break; case 6 : System.out.println("Size = "+ q.getSize()); break; default : System.out.println("Wrong Entry \n "); break; } /* display Queue */ q.display(); 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/simple_queue/java/arrayQueue.java ================================================ /* * Java Program to Implement Queue */ import java.util.*; /* Class arrayQueue */ class arrayQueue { protected int Queue[] ; protected int front, rear, size, len; /* Constructor */ public arrayQueue(int n) { size = n; len = 0; Queue = new int[size]; front = -1; rear = -1; } /* Function to check if queue is empty */ public boolean isEmpty() { return front == -1; } /* Function to check if queue is full */ public boolean isFull() { return front==0 && rear == size -1 ; } /* Function to get the size of the queue */ public int getSize() { return len ; } /* Function to check the front element of the queue */ public int peek() { if (isEmpty()) throw new NoSuchElementException("Underflow Exception"); return Queue[front]; } /* Function to insert an element to the queue */ public void insert(int i) { if (rear == -1) { front = 0; rear = 0; Queue[rear] = i; } else if (rear + 1 >= size) throw new IndexOutOfBoundsException("Overflow Exception"); else if ( rear + 1 < size) Queue[++rear] = i; len++ ; } /* Function to remove front element from the queue */ public int remove() { if (isEmpty()) throw new NoSuchElementException("Underflow Exception"); else { len-- ; int ele = Queue[front]; if ( front == rear) { front = -1; rear = -1; } else front++; return ele; } } /* Function to display the status of the queue */ public void display() { System.out.print("\nQueue = "); if (len == 0) { System.out.print("Empty\n"); return ; } for (int i = front; i <= rear; i++) System.out.print(Queue[i]+" "); System.out.println(); } } ================================================ FILE: data_structures/simple_queue/java/queue.java ================================================ import java.util.*; interface queue { void insert(); void delete(); void display(); } class myqueue implements queue { int arr[]=new int[10]; int front=0,rear=0; Scanner s1 = new Scanner(System.in); public void insert() { if (rear>10) System.out.println("queue overflow"); else { int a; System.out.println("enter element:"); a=s1.nextInt(); arr[rear]=a; rear++; } } public void delete() { if (rear==front) System.out.println("queue is empty"); else { int a; a=arr[front]; front++; System.out.println("element deleted : "+a ); } } public void display() { System.out.println("elements are"); for(int i=front;i #include struct node{ int data; struct node* next; }; struct node* head; void insertatthebegin(int x) { struct node* temp=(struct node*)malloc(sizeof(struct node)); temp->data=x; temp->next=head; head=temp; } void print() { struct node* temp=head; if(temp== NULL) printf("empty list\n"); else{ while(temp!=NULL) { printf("%d ",temp->data); temp=temp->next; } } printf("\n"); } void reverse() { struct node* prev, *current , *next; prev=NULL; current=head; while(current !=NULL) { next=current->next; current->next=prev; prev=current; current=next; } head=prev; } int main() { int i,j,n,k,l,x; head=NULL; printf("enter the number of elements\n"); scanf("%d",&n); printf("enter the elements and the position\n"); for(i=0;i stack = new Stack(); stack.Push(1); stack.Push(3); Console.WriteLine(stack.Top()); stack.Pop(); Console.WriteLine(stack.Top()); } } } ================================================ FILE: data_structures/stack/c#/stack.cs ================================================ using System; using System.Collections.Generic; namespace Stack{ public class Stack { private List _array; // Storage for stack elements private int _size; private int _top; // Number of items in the stack. static List _emptyArray = new List(); public Stack(){ _array = _emptyArray; _size = 0; _top = -1; } public void Push(t data){ _array.Add(data); _size++; _top++; } public void Pop(){ _array.RemoveAt(_top--); } public t Top(){ return _array[_top]; } } } ================================================ FILE: data_structures/stack/cpp/celement.h ================================================ #ifndef CELEMENT_H #define CELEMENT_H /** * An element of a CStack : contains a char value and a pointer to the element just below in the stack */ struct CElement { CElement *_element_below; //Next element in the stack char _val; }; #endif // CELEMENT_H included ================================================ FILE: data_structures/stack/cpp/cstack.cpp ================================================ // Implementation File #include "cstack.h" using namespace std; // Default Constructor to allow for no params being passed CStack::CStack() { // Init top to be nullptr, stack is empty _top = nullptr; }; // Destructor to free memory CStack::~CStack() { while (!IsEmpty()) { Pop (); } } // Removes value from the top of the stack void CStack::Pop() { // Check if the array isnt empty, then pop off top stack value if (!IsEmpty()) { CElement *new_top = _top->_element_below; delete _top; //Do not forget to free memory _top = new_top; } } // Pushes new value to the top of the stack void CStack::Push(char val) { CElement *new_top = new CElement(); //Allocate memory for the new top element new_top->_element_below = _top; new_top->_val = val; _top = new_top; } // Returns value at top of the stack char CStack::Top() { // If array is empty, return null character if (IsEmpty()) { return '\0'; // Else return top Stack value } else { return _top->_val; } } // Checks whether the stack is empty, returns bool bool CStack::IsEmpty() { return _top == nullptr; } ================================================ FILE: data_structures/stack/cpp/cstack.h ================================================ #ifndef CSTACK_H #define CSTACK_H #include "celement.h" // Header File class CStack { public: CStack(const CStack&) = delete; //Forbid usage of Copy Constructor because we use raw pointers CStack& operator=(const CStack&) = delete; //Forbid usage of copy assignment for the same reason CStack(); ~CStack(); char Top(); void Pop(); void Push(char); bool IsEmpty(); private: CElement *_top; }; #endif ================================================ FILE: data_structures/stack/cpp/cstack.test.cpp ================================================ #include #include "cstack.h" using namespace std; int main() { char input; CStack stack; // Prompt user for expression cout << "Please Enter an expression (must end with the EOF character) : "; //EOF is CTRL^D (Linux) or CTRL^Z (Windows) // Fill stack with char values while(cin >> input) { stack.Push(input); } // Show LIFO cout << endl; while(!stack.IsEmpty()){ cout << stack.Top(); stack.Pop(); } cout << endl; return 0; } ================================================ FILE: data_structures/stack/cpp/stack_balanced_paranthesis.cpp ================================================ #include #include using namespace std; int main() { int t; cout<<"Enter no of test cases"; cin>>t; string s=" "; while(t--) { stack st; cout<<"\nEnter the string\n"; cin>>s; int flag=0; for(int i=0;i #include #include "Stack.hpp" /* * Main is only used to test different * methods on my stack * */ int main(void) { Stack s; std::cout << "Initializing stack" << std::endl; for (int i = 0; i < 10; ++i) s.push(i); std::cout << "Done!" << std::endl; while ( !s.empty() ) { std::cout << s.top() << std::endl; s.pop(); } std::cout << "Popping off another (inexistant) element" << std::endl; try { s.pop(); } catch (std::exception& e) { std::cerr << "[ERR] " << e.what() << std::endl; } return 0; } ================================================ FILE: data_structures/stack/cpp/templated_stack.hpp ================================================ #ifndef STACK_H #define STACK_H #include /* * Templated class declaration and definition * in a single file for portability * */ template class Stack { private: class Node { friend Stack; private: Node * next; Object data; public: Node(const Object & d, Node * n): data(d), next(n) { } }; int length {0}; Node * head {nullptr}; public: // Default ctor but clear on destruction Stack() { }; ~Stack() { clear(); }; // Returns the number of elements in the stack int size() { return length; } // Adds an element on top of the stack void push(const Object & value) { head = new Node(value, head); ++length; } // Returns top element form the stack Object top() { if ( head != nullptr ) return head->data; throw std::logic_error("Cannot return top from an empty stack"); } // Removes top element from the stack void pop() { if ( head != nullptr ) { Node * tmp {head}; head = head->next; --length; delete tmp; } else throw std::logic_error("Cannot remove top from an empty stack"); } // Tests wether or not the stack is empty bool empty() { return length == 0; } // Removes all element from the stack void clear() { while ( !empty() ) pop(); } }; #endif ================================================ FILE: data_structures/stack/crystal/stack.cr ================================================ class Stack(T) @size : Int32 def initialize(@stack : Array(T)) @size = @stack.size end # Returns size (Implicit return) def push(item : T) @stack << item @size += 1 end # Returns size (Implicit return) def pop() @stack.pop @size -= 1 end def peek() @stack.last end def size() @size end end # Union together Types you might need since crystal is type-checked at compile time # You'll get an error if you try and push a type that isn't in the union stack = Stack.new([] of Int32|String) puts stack.size() # ==> 0 stack.push(30) # ==> [30] stack.push("Hello") # ==> [30, "hello"] stack.pop() # ==> 1 puts stack.peek() # ==> 30 ================================================ FILE: data_structures/stack/csharp/Stack.cs ================================================ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DataStructures { class Stack { private List items = new List(); public Object pop() { if (items.Count > 0) { int lastPos = items.Count - 1; Object temp = items[lastPos]; items.RemoveAt(lastPos); return temp; } else { throw new Exception("Underflow: Stack is empty"); } } public void push(Object newItem) { items.Add(newItem); } public bool isEmpty() { return (items.Count == 0); } } } ================================================ FILE: data_structures/stack/go/stack.go ================================================ package main type stack struct { data []interface{} } func (s *stack) Push(value interface{}) { s.data = append(s.data, value) } func (s *stack) Pop() interface{} { //get last item value := s.data[len(s.data)-1] //shrink array s.data = s.data[0 : len(s.data)-1] return value } ================================================ FILE: data_structures/stack/java/Node.java ================================================ import java.util.*; public class Node{ private T data; private Node nextNode; private Node previewNode; private int index; public Node(T data){ this.data = data; this.nextNode = null; this.previewNode = null; this.index = 0; } public Node(){ this.data = null; this.nextNode = null; this.previewNode = null; this.index = 0; } public T getData(){ return this.data; } public void setData(T data){ this.data = data; } public int getIndex(){ return this.index; } public void setNext(Node node){ this.nextNode = node; } public Node getNext(){ return this.nextNode; } public void setPreview(Node node){ this.previewNode = node; } public Node getPreview(){ return this.previewNode; } } ================================================ FILE: data_structures/stack/java/Stack.java ================================================ import java.util.*; public class Stack{ private Node topNode; private int size; public Stack(){ this.topNode = null; this.size = 0; } public boolean isEmpty(){ return this.size == 0; } public void push(T data){ Node node = new Node(); node.setData(data); if(!isEmpty()){ node.setPreview(this.topNode); this.topNode.setNext(node); this.topNode = node; }else{ this.topNode = node; } this.size++; } public T top(){ if(!isEmpty()){ return (T) this.topNode; } return null; } public void pop(){ if(!isEmpty()){ if(this.size == 1){ this.topNode = null; }else{ Node a = this.topNode.getPreview(); a.setNext(null); this.topNode = a; } this.size--; }else{ System.out.println("There is no object on the stack!"); } } public void viewStack(){ if(!isEmpty()){ Node node = this.topNode; while(node != null){ System.out.println(node.getData()); node = node.getPreview(); } }else{ System.out.println("Stack is Empty!"); } } public static void main(String[] args) { Stack s = new Stack<>(); s.push("a"); s.push("aa"); s.push("aaa"); s.push("aaaa"); s.viewStack(); System.out.println("-------------------------"); s.pop(); s.viewStack(); System.out.println("-------------------------"); s.pop(); s.viewStack(); System.out.println("-------------------------"); s.pop(); s.viewStack(); System.out.println("-------------------------"); s.pop(); s.viewStack(); System.out.println("-------------------------"); } } ================================================ FILE: data_structures/stack/java/integer_stack.java ================================================ import java.util.ArrayList; import java.util.List; public class Stack { private List _data = new ArrayList(); private int _top = -1; public Stack(){ } public void Push(int val){ _top++; _data.add(val); } public void Pop(){ if(!isEmpty()) _data.remove(_top--); else System.out.println("Queue Is Empty"); } public int Top(){ return _data.get(_top); } private boolean isEmpty(){ return _top == -1; } } ================================================ FILE: data_structures/stack/javascript/stack.js ================================================ 'use strict'; export default function Stack(maxSize = null) { // Private variables let _data = []; let _top = -1; // Helper function to check if the stack is empty function _checkEmpty() { return _top === -1; } // Helper function to check if the stack is full function _checkFull() { return maxSize === null ? false : _top >= maxSize - 1; } // Error Helper Function to help display // when Stack is empty or full function throwError(message) { throw new Error(message); return true; } // Return Object let _Stack = { // Returns Top Data Top: () => { return _data[_top] !== undefined ? _data[_top] : null; }, // Void, adds new Data Push: data => { !_checkFull() ? (_data[++_top] = data) : throwError('Stack is full'); }, // Void, removes Data Pop: () => { !_checkEmpty() ? _data.splice(_top--, 1) : throwError('Stack is empty'); }, // Void, logs Top Data Log: () => { console.log(this.Top()); }, // Void , logs all Data LogAll: () => { for (let i = 0; i < _top; i++) { console.log(_data[i]); } }, }; return _Stack; } // Test the Code // let _ = data => { // console.log(data); // }; // let stack = new Stack(); // try { // stack.Push(1); // _(stack.Top()); // stack.Push(0b11); // _(stack.Top()); // stack.Pop(); // _(stack.Top()); // } catch (e) { // _(e.message); // } ================================================ FILE: data_structures/stack/javascript/usingstack.js ================================================ import Stack from './stack'; import readline from 'readline'; (async function RunMe(){ let stack = Stack(); let input; const cin = readline.createInterface({ input: process.stdin, output: process.stdout }); cin.question('Test the stack class, type something it will output it backwards. Aka LIFO: ', (answer) => { input = answer; cin.close(); for(let char of input){ stack.Push(char); } while(stack.Top()!==null){ console.log(stack.Top()); stack.Pop(); } }); })(); ================================================ FILE: data_structures/stack/lisp/Stack.bak ================================================ (define (make-stack) (define arr '()) (define length 0) (define temp '()) (define (size) length) (define (pop) (set! temp (car arr)) (set! arr (cons arr)) temp) (define (dispatch method) (cond ((eq? method 'size) size) ((eq? method 'pop) pop) (else (lambda() (display "Unknown Stack Request")(display method)(newline))))) dispatch) ================================================ FILE: data_structures/stack/lisp/Stack.rkt ================================================ (define (make-stack) ;backing structure (define arr '()) (define length 0) (define temp '()) ;size method (define (size) length) ;print method (define (print) (display arr)) ;receiving mpair violation instead of exiting procedure call ;pop method: removes the head and returns it (define (pop) (if (eqv? length 0) (display "Can't Pop")) (set! length (- length 1)) (set! temp (cdr arr)) (set! arr (cdr arr)) temp) ;push method: puts x at the head (define (push x) (set! length (+ length 1)) (set! arr (cons x arr))) ;method to get method from user (define (dispatch method) (cond ((eq? method 'size) size) ((eq? method 'pop) pop) ((eq? method 'print) print) ((eq? method 'push) push) (else (lambda() (display "Unknown Stack Request")(display method)(newline))))) dispatch) ;how to use (define (testing) (define stack (make-stack)) ((stack 'push) 0) ((stack 'push) 1) ((stack 'push) 2) ((stack 'print))(newline) ((stack 'pop)) ((stack 'print))(newline) ((stack 'pop)) ((stack 'print))(newline) ((stack 'pop)) ;((stack 'pop)) ) (testing) ================================================ FILE: data_structures/stack/php/stack.php ================================================ _top == -1){ throw new Exception("Stack is empty"); }else{ $this->_top--; } } public function Push($data) { $this->_top++; array_push($this->_data,$data); } public function Top(){ return $this->_data[$this->_top]; } } $stack = new Stack(); $stack->Push("First Input"); $stack->Push("Second Input"); echo $stack->Top(); $stack->Pop(); echo $stack->Top(); ?> ================================================ FILE: data_structures/stack/python/stack.py ================================================ class Stack: def __init__(self): self.data = [] def push(self, item): self.data.append(item) def pop(self): return self.data.pop() def peek(self): return self.data[-1] ================================================ FILE: data_structures/stack/ruby/stack.rb ================================================ class Stack def initialize @store = Array.new end def push(data) @store.push(data) end def pop() raise Exception if size == 0 @store.pop end def top() raise Exception if size == 0 @store.last end def size() @store.size end end # Usage S = Stack.new S.push(1) S.push(2) S.push(3) puts S.top() puts S.size() puts S.pop() puts S.pop() ================================================ FILE: data_structures/treemap/java/treemap.java ================================================ import java.util.*; class treemap { public static void main(String args[]) { // Create a hash map TreeMap tm = new TreeMap(); // Put elements to the map tm.put(1, "one"); tm.put(2, "two"); tm.put(3,"three"); tm.put(1,"ONE"); tm.put(4,"four"); //storing values in key-value pairs with sorted order of keys, by eliminating duplicate keys System.out.println(tm);//1-ONE,2-two,3-three,4-four } } ================================================ FILE: data_structures/treeset/java/treeset.java ================================================ import java.util.*; class treeset { public static void main(String args[]) { // Create a tree set TreeSet ts = new TreeSet(); // Add elements to the tree set ts.add(3); ts.add(2); ts.add(3); ts.add(2); ts.add(1); ts.add(4); //Treeset is very helpful datastructure for avoid duplicatses and maintain the values in sorted order System.out.println(ts);// output will be {1,2,3,4} } } ================================================ FILE: data_structures/trie/Trie.md ================================================ ## ELI5 Trie is an information re'trie'val data container.It's a tree useful in searching strings. USES:Autocomplete in text messages etc. ### Pros * Searching is easier and faster. ### Cons * Storage takes more space. ## Technical Explaination A Trie, also called a digital tree or prefix tree, is a search tree that is used to store a dynamic set or associative array.The keys of a Trie are mostly strings.The postition of node in tree defines its key. All the descendants of a node have a common prefix of the string associated with that node, and the root is associated with the empty string. Each brach of tree represents a character. * isEndOfWord : It is the last node of a word. ### Pros * Search in trie is O(M) where M is length of the key. Faster than BST. ### Cons * Tries can be slower in some cases than hash tables for looking up data * Require more space. ================================================ FILE: data_structures/trie/java/Trie.java ================================================ import java.util.ArrayList; public class Trie { public class TrieNode { TrieNode[] characters; Boolean isEnd = false; public TrieNode() { characters = new TrieNode[26]; } } public static void main(String[] args) { new Trie().demo(); } private void demo() { TrieNode trie = new TrieNode(); ArrayList values = new ArrayList() {{ add("MY"); add("MANY"); add("LIE"); add("A"); add("AS"); }}; for (String s : values) { add(trie, s); } displayTree(trie); } private void displayTree(TrieNode trie) { for (int i = 0; i < trie.characters.length; i++) { if (trie.characters[i] != null) { DFS(trie.characters[i], new StringBuilder(), i); } } } private void DFS(TrieNode n, StringBuilder sb, int index) { if (n == null) { return; } sb.append(getCharacter(index)); for (int i = 0; i < n.characters.length; i++) { if (n.characters[i] != null ) { DFS(n.characters[i], new StringBuilder(sb), i); } } if (sb.length() != 0 && n.isEnd) { System.out.println(sb.toString()); } } private void add(TrieNode trie, String s) { char[] chars = s.toCharArray(); TrieNode currentTrie = trie; for (Character c : chars) { if (currentTrie.characters[getIndex(c)] == null) { currentTrie.characters[getIndex(c)] = new TrieNode(); } currentTrie = currentTrie.characters[getIndex(c)]; } currentTrie.isEnd = true; } public Character getCharacter(int index) { return (char) (index + 65); } public Integer getIndex(Character c) { return c - 65; } } ================================================ FILE: data_structures/trie/javascript/Trie.js ================================================ class Node { constructor(){ this.end = false; this.children = {}; } setEnd(isEnd) { this.end = isEnd; } addChild(value) { if (this.children && this.children.hasOwnProperty(value)) { return this.children[value]; } else { let a = new Node(); this.children[value] = a; return a; } } } class Trie { constructor() { this.root = new Node(); } findPrefix(prefix, parent) { if (!parent) { parent = this.root; } if (prefix !== null) { let letter = prefix.substring(0, 1); let remaining = prefix.substring(1); if (parent.children.hasOwnProperty(letter)) { if (prefix.length === 1) { return true;} let result = this.findPrefix(remaining, parent.children[letter]); return result; } else { return false; } } } addWord(word, parent = this.root) { if (word !== null) { let letter = word.substring(0, 1); let child = parent.addChild(letter); if (word.length > 1) { this.addWord(word.substring(1), child); } else { child.setEnd(true); } } } list(root = this.root, word = [], words = []) { if (root.end) { words.push(word.join("")); } for (let child in root.children) { word.push(child); this.list(root.children[child], word, words); word.pop(); } return words; } } // How to use: // let t = new Trie(); // t.addWord("testing"); // t.addWord("test"); // t.addWord("tesla"); // t.addWord("word"); // t.addWord("work"); // let allwords = t.list(); // console.info(JSON.stringify(t.root)); // console.info(allwords); // console.info("Prefix test :", t.findPrefix("tes")); // console.info("Prefix testi :", t.findPrefix("testi")); // console.info("Prefix word :", t.findPrefix("word")); // console.info("Prefix war :", t.findPrefix("war")); // console.info("Prefix c :", t.findPrefix("c")); // console.info("Prefix testingg :", t.findPrefix("testingg")); // console.info("Prefix testing2 :", t.findPrefix("testing2")); ================================================ FILE: data_structures/union_find/cpp/UnionFind.cpp ================================================ #include using namespace std; class UnionFind{ vector parent; vector size; int components; // Finds the root of p, which is the identifier of its component int root(int p){ while(p != parent[p]){ parent[p] = parent[parent[p]]; p = parent[p]; } return p; } // Creates the Union-Find data structure // N = number of components public: UnionFind(int N){ components = N; for(int i=0; i (http://brettreinhard.com)", "license": "GPL-3.0", "bugs": { "url": "https://github.com/bareinhard/Hacktoberfest-Data-Structure-and-Algorithms/issues" }, "homepage": "https://github.com/bareinhard/Hacktoberfest-Data-Structure-and-Algorithms#readme", "devDependencies": { "babel-cli": "^6.26.0", "babel-preset-env": "^1.6.0" } }