### Quicksort Example Source: https://github.com/kanwei/algorithms/blob/master/_autodocs/MANIFEST.md Shows an example of the quicksort algorithm, a highly efficient sorting algorithm that uses a divide-and-conquer approach. It has an average-case time complexity of O(n log n). ```ruby Algorithms::Sort.quicksort([3, 1, 4, 1, 5, 9, 2, 6]) #=> [1, 1, 2, 3, 4, 5, 6, 9] ``` -------------------------------- ### Example: Get Queue Size Source: https://github.com/kanwei/algorithms/blob/master/_autodocs/api-reference/priority-queue.md Demonstrates retrieving the number of elements in the queue using the `size` method. ```ruby queue = Containers::PriorityQueue.new queue.push("Alaska", 50) queue.push("Delaware", 30) puts queue.size #=> 2 ``` -------------------------------- ### MinHeap Example Source: https://github.com/kanwei/algorithms/blob/master/_autodocs/QUICKSTART.md Demonstrates retrieving the smallest item from a MinHeap. Initialize the heap with an array of numbers. ```ruby require 'algorithms' include Containers # MinHeap: "Give me the smallest item" smallest = MinHeap.new([5, 2, 8]) smallest.pop #=> 2 ``` -------------------------------- ### Selection Sort Example Source: https://github.com/kanwei/algorithms/blob/master/_autodocs/MANIFEST.md Shows an example of the selection sort algorithm, which repeatedly finds the minimum element from the unsorted part and puts it at the beginning. ```ruby Algorithms::Sort.selection_sort([3, 1, 4, 1, 5, 9, 2, 6]) #=> [1, 1, 2, 3, 4, 5, 6, 9] ``` -------------------------------- ### Sorting Algorithms Examples Source: https://github.com/kanwei/algorithms/blob/master/_autodocs/types.md Examples of in-place and functional sorting algorithms. All sorting algorithms return the container. ```ruby # In-place sorts return the modified container sorted = Algorithms::Sort.bubble_sort([3, 1, 2]) #=> [1, 2, 3] # Functional sorts return new array sorted = Algorithms::Sort.mergesort([3, 1, 2]) #=> [1, 2, 3] sorted = Algorithms::Sort.heapsort([3, 1, 2]) #=> [1, 2, 3] ``` -------------------------------- ### Example Usage of RBTreeMap Get and Bracket Access Source: https://github.com/kanwei/algorithms/blob/master/_autodocs/api-reference/tree-maps.md Shows how to retrieve values from an RBTreeMap using both `get` and bracket access, including cases where the key does not exist. ```ruby map = Containers::RBTreeMap.new map["CA"] = "California" puts map["CA"] #=> "California" puts map["TX"] #=> nil ``` -------------------------------- ### MaxHeap Example Source: https://github.com/kanwei/algorithms/blob/master/_autodocs/QUICKSTART.md Demonstrates retrieving the largest item from a MaxHeap. Initialize the heap with an array of numbers. ```ruby require 'algorithms' include Containers # MaxHeap: "Give me the largest item" largest = MaxHeap.new([5, 2, 8]) largest.pop #=> 8 ``` -------------------------------- ### Dictionary with Wildcard Search Example Source: https://github.com/kanwei/algorithms/blob/master/_autodocs/api-reference/trie.md Demonstrates using a Trie to store a dictionary and perform wildcard searches to find words matching a pattern. The example adds words and then uses the `wildcard` method to find matches. ```ruby require 'algorithms' include Containers dictionary = Trie.new %w[cat car card care careful can].each { |w| dictionary[w] = w.upcase } # Find all words matching pattern puts dictionary.wildcard("ca*").inspect ``` -------------------------------- ### Queue Example (FIFO) Source: https://github.com/kanwei/algorithms/blob/master/_autodocs/QUICKSTART.md Demonstrates the First-In, First-Out (FIFO) behavior of a Queue. Items are added to the queue and removed in the order they were added. ```ruby require 'algorithms' include Containers # Queue: "First in, first out" line = Queue.new line.push("Person A") line.push("Person B") line.pop #=> "Person A" ``` -------------------------------- ### Example: Pop All Elements Source: https://github.com/kanwei/algorithms/blob/master/_autodocs/api-reference/priority-queue.md Shows how to sequentially remove and print all elements from the priority queue using `pop` until it is empty. ```ruby queue = Containers::PriorityQueue.new queue.push("Alaska", 50) queue.push("Delaware", 30) queue.push("Georgia", 35) puts queue.pop #=> "Alaska" puts queue.pop #=> "Georgia" puts queue.pop #=> "Delaware" puts queue.pop #=> nil ``` -------------------------------- ### Trie Get Example Source: https://github.com/kanwei/algorithms/blob/master/_autodocs/MANIFEST.md Shows retrieving a value from a Trie using its key. This operation is efficient for exact matches. ```ruby trie = Containers::Trie.new trie.push("apple", 1) trie.get("apple") #=> 1 ``` -------------------------------- ### Install Algorithms Gem Source: https://github.com/kanwei/algorithms/blob/master/_autodocs/README.md Install the algorithms gem using RubyGems. This command fetches and installs the gem and its dependencies. ```bash gem install algorithms ``` -------------------------------- ### Example: Push and Next Element Source: https://github.com/kanwei/algorithms/blob/master/_autodocs/api-reference/priority-queue.md Demonstrates adding elements with priorities and retrieving the highest priority element using `next`. ```ruby require 'algorithms' include Containers queue = PriorityQueue.new queue.push("Alaska", 50) queue.push("Delaware", 30) queue.push("Georgia", 35) item = queue.next puts item #=> "Alaska" (highest priority) ``` -------------------------------- ### Example Usage of RBTreeMap each Source: https://github.com/kanwei/algorithms/blob/master/_autodocs/api-reference/tree-maps.md Demonstrates iterating over an RBTreeMap and printing each key-value pair. ```ruby map = Containers::RBTreeMap.new map["Z"] = 26 map["A"] = 1 map["M"] = 13 map.each { |k, v| puts "#{k}: #{v}" } # Output: # A: 1 # M: 13 # Z: 26 ``` -------------------------------- ### Heap Comparison Function Examples Source: https://github.com/kanwei/algorithms/blob/master/_autodocs/configuration.md Examples of comparison blocks for Heap and other ordered structures. The block takes two items and returns true if the first item has higher priority. ```ruby # Min-heap comparison { |x, y| (x <=> y) == -1 } # Max-heap comparison { |x, y| (x <=> y) == 1 } # For objects, compare by attribute { |a, b| a.priority > b.priority } # Reverse alphabetical order { |a, b| a.to_s > b.to_s } ``` -------------------------------- ### Example Usage of RBTreeMap size Source: https://github.com/kanwei/algorithms/blob/master/_autodocs/api-reference/tree-maps.md Demonstrates getting the number of elements in an RBTreeMap. ```ruby map = Containers::RBTreeMap.new map["CA"] = "California" map["TX"] = "Texas" puts map.size #=> 2 ``` -------------------------------- ### KDTree Example (Nearest Neighbors) Source: https://github.com/kanwei/algorithms/blob/master/_autodocs/QUICKSTART.md Shows how to use a KDTree for finding nearest neighbors in a multi-dimensional space. The tree is initialized with a hash of points. ```ruby require 'algorithms' include Containers # KDTree: "Find nearest neighbors in space" points = {0 => [1, 2], 1 => [3, 4], 2 => [10, 10]} tree = KDTree.new(points) tree.find_nearest([2, 3], 1) #=> [[distance², id]] ``` -------------------------------- ### KMP Search Example Source: https://github.com/kanwei/algorithms/blob/master/_autodocs/types.md Demonstrates the usage of kmp_search. Returns the integer index if found, nil otherwise. ```ruby # Returns integer index if found, nil otherwise Algorithms::Search.kmp_search("hello", "ll") #=> 2 Algorithms::Search.kmp_search("hello", "xyz") #=> nil ``` -------------------------------- ### PriorityQueue Example Source: https://github.com/kanwei/algorithms/blob/master/_autodocs/QUICKSTART.md Shows how to use a PriorityQueue to retrieve the highest-priority item. Items are pushed with a value and a priority level. ```ruby require 'algorithms' include Containers # PriorityQueue: "Give me the highest-priority item" todo = PriorityQueue.new todo.push("Task A", 1) todo.push("Task B", 10) todo.pop #=> Task B (highest priority) ``` -------------------------------- ### Example: Clear Queue Source: https://github.com/kanwei/algorithms/blob/master/_autodocs/api-reference/priority-queue.md Demonstrates clearing all elements from the queue and verifying that it is empty and has a size of 0. ```ruby queue = Containers::PriorityQueue.new queue.push("Alaska", 50) queue.push("Delaware", 30) queue.clear puts queue.size #=> 0 puts queue.empty? #=> true ``` -------------------------------- ### Example: Check Priority Existence Source: https://github.com/kanwei/algorithms/blob/master/_autodocs/api-reference/priority-queue.md Shows how to use `has_priority?` to check for the presence of specific priorities within the queue. ```ruby queue = Containers::PriorityQueue.new queue.push("Alaska", 50) queue.push("Delaware", 30) puts queue.has_priority?(50) #=> true puts queue.has_priority?(30) #=> true puts queue.has_priority?(100) #=> false ``` -------------------------------- ### MinHeap Example Source: https://github.com/kanwei/algorithms/blob/master/_autodocs/MANIFEST.md Shows how to use the MinHeap, a priority queue implementation where the smallest element has the highest priority. Useful for algorithms like Dijkstra's. ```ruby heap = Containers::MinHeap.new heap.push(5) heap.push(2) heap.pop #=> 2 ``` -------------------------------- ### Heap Comparison Block Example Source: https://github.com/kanwei/algorithms/blob/master/_autodocs/types.md Demonstrates how to initialize a Heap with a custom comparison block for ordering. The block should return true if the first item has higher priority. ```ruby heap = Containers::Heap.new { |x, y| (x <=> y) == -1 } ``` -------------------------------- ### Bubble Sort Example Source: https://github.com/kanwei/algorithms/blob/master/_autodocs/MANIFEST.md Provides an example of the bubble sort algorithm, a simple sorting algorithm that repeatedly steps through the list, compares adjacent elements and swaps them if they are in the wrong order. ```ruby Algorithms::Sort.bubble_sort([3, 1, 4, 1, 5, 9, 2, 6]) #=> [1, 1, 2, 3, 4, 5, 6, 9] ``` -------------------------------- ### Insertion Sort Example Source: https://github.com/kanwei/algorithms/blob/master/_autodocs/MANIFEST.md Provides an example of the insertion sort algorithm, which builds the final sorted array one item at a time. It is much less efficient on large lists than more advanced algorithms. ```ruby Algorithms::Sort.insertion_sort([3, 1, 4, 1, 5, 9, 2, 6]) #=> [1, 1, 2, 3, 4, 5, 6, 9] ``` -------------------------------- ### Example: Peek Next Element Source: https://github.com/kanwei/algorithms/blob/master/_autodocs/api-reference/priority-queue.md Demonstrates using `next` to view the highest priority element without altering the queue's size. ```ruby queue = Containers::PriorityQueue.new queue.push("Alaska", 50) queue.push("Delaware", 30) puts queue.next #=> "Alaska" puts queue.size #=> 2 (unchanged) ``` -------------------------------- ### Trie Example (Autocomplete) Source: https://github.com/kanwei/algorithms/blob/master/_autodocs/QUICKSTART.md Illustrates using a Trie for efficient pattern matching and prefix queries, suitable for autocomplete functionality. Requires the 'algorithms' gem. ```ruby require 'algorithms' include Containers # Trie: "Pattern matching and prefix queries" words = Trie.new words["cat"] = true words["catch"] = true words.wildcard("ca*") #=> ["cat", "catch"] ``` -------------------------------- ### Deque Push Front Example Source: https://github.com/kanwei/algorithms/blob/master/_autodocs/MANIFEST.md Demonstrates adding an element to the front of a Deque (Double-Ended Queue). This allows for efficient insertion at the beginning. ```ruby deque = Containers::Deque.new deque.push_front(1) deque.push_front(2) ``` -------------------------------- ### Stack Example (LIFO) Source: https://github.com/kanwei/algorithms/blob/master/_autodocs/QUICKSTART.md Illustrates the Last-In, First-Out (LIFO) behavior of a Stack. Items are pushed onto the stack and popped off in reverse order. ```ruby require 'algorithms' include Containers # Stack: "Last in, first out" history = Stack.new history.push("Action 1") history.push("Action 2") history.pop #=> "Action 2" ``` -------------------------------- ### Example Usage of RBTreeMap min_key Source: https://github.com/kanwei/algorithms/blob/master/_autodocs/api-reference/tree-maps.md Demonstrates finding the minimum key in an RBTreeMap. ```ruby map = Containers::RBTreeMap.new map["Z"] = 26 map["A"] = 1 puts map.min_key #=> "A" ``` -------------------------------- ### Example Usage of SplayTreeMap Push and Assignment Source: https://github.com/kanwei/algorithms/blob/master/_autodocs/api-reference/tree-maps.md Demonstrates adding elements to a SplayTreeMap using both `push` and bracket assignment, and retrieving a value. ```ruby require 'algorithms' include Containers map = SplayTreeMap.new map.push("MA", "Massachusetts") map["GA"] = "Georgia" puts map["MA"] #=> "Massachusetts" ``` -------------------------------- ### Example: Check if Empty Source: https://github.com/kanwei/algorithms/blob/master/_autodocs/api-reference/priority-queue.md Illustrates checking the empty status of a priority queue before and after adding elements. ```ruby queue = Containers::PriorityQueue.new puts queue.empty? #=> true queue.push("Alaska", 50) puts queue.empty? #=> false ``` -------------------------------- ### Queue Push Example Source: https://github.com/kanwei/algorithms/blob/master/_autodocs/MANIFEST.md Demonstrates adding an element to the end of a Queue (FIFO - First-In, First-Out). This is a fundamental operation for queue data structures. ```ruby queue = Containers::Queue.new queue.push(1) queue.push(2) ``` -------------------------------- ### Queue Pop Example Source: https://github.com/kanwei/algorithms/blob/master/_autodocs/MANIFEST.md Shows how to remove and return the element from the front of a Queue. This operation follows the FIFO principle. ```ruby queue = Containers::Queue.new queue.push(1) queue.push(2) queue.pop #=> 1 ``` -------------------------------- ### Initialize a Trie Source: https://github.com/kanwei/algorithms/blob/master/_autodocs/api-reference/trie.md Creates a new, empty Trie instance. No setup is required beyond including the Containers module. ```ruby Containers::Trie.new ``` -------------------------------- ### Suffix Array Creation Example Source: https://github.com/kanwei/algorithms/blob/master/_autodocs/api-reference/suffix-array.md Illustrates the internal process of creating a SuffixArray for the string 'abra'. It shows the generation of all suffixes and their subsequent sorting. ```text For string "abra": - Suffixes: ["abra", "bra", "ra", "a"] - Sorted: ["a", "abra", "bra", "ra"] ``` -------------------------------- ### Trie Push Example Source: https://github.com/kanwei/algorithms/blob/master/_autodocs/MANIFEST.md Demonstrates adding a key-value pair to a Trie (Ternary Search Tree). Tries are efficient for prefix-based lookups. ```ruby trie = Containers::Trie.new trie.push("apple", 1) trie.push("apricot", 2) ``` -------------------------------- ### Deque Example (Access Both Ends) Source: https://github.com/kanwei/algorithms/blob/master/_autodocs/QUICKSTART.md Shows how a Deque can be used for efficient access to both ends. Elements can be added to the front or back and removed from either end. ```ruby require 'algorithms' include Containers # Deque: "Access both ends" passengers = Deque.new passengers.push_back("Alice") passengers.push_front("Bob") passengers.pop_front #=> "Bob" ``` -------------------------------- ### Deque Push Back Example Source: https://github.com/kanwei/algorithms/blob/master/_autodocs/MANIFEST.md Demonstrates adding an element to the back of a Deque. This allows for efficient insertion at the end. ```ruby deque = Containers::Deque.new deque.push_back(1) deque.push_back(2) ``` -------------------------------- ### Heap Sort Example Source: https://github.com/kanwei/algorithms/blob/master/_autodocs/api-reference/sort.md Demonstrates how to use the heapsort method. This method returns a new sorted array and does not mutate the original. ```ruby require 'algorithms' arr = [5, 4, 3, 1, 2] sorted = Algorithms::Sort.heapsort(arr) puts sorted.inspect #=> [1, 2, 3, 4, 5] puts arr.inspect #=> [5, 4, 3, 1, 2] (original unchanged) ``` -------------------------------- ### Selection Sort Example Source: https://github.com/kanwei/algorithms/blob/master/_autodocs/api-reference/sort.md Demonstrates how to use the selection_sort method. This method mutates the input array in place. ```ruby arr = [5, 4, 3, 1, 2] result = Algorithms::Sort.selection_sort(arr) puts result.inspect #=> [1, 2, 3, 4, 5] ``` -------------------------------- ### Shell Sort Example Source: https://github.com/kanwei/algorithms/blob/master/_autodocs/api-reference/sort.md Demonstrates how to use the shell_sort method. This method mutates the input array in place. ```ruby arr = [5, 4, 3, 1, 2] result = Algorithms::Sort.shell_sort(arr) puts result.inspect #=> [1, 2, 3, 4, 5] ``` -------------------------------- ### Binary Search Example Source: https://github.com/kanwei/algorithms/blob/master/_autodocs/MANIFEST.md Demonstrates the usage of the binary_search method for efficient searching in a sorted array. Assumes the array is already sorted. ```ruby Algorithms::Search.binary_search([1, 2, 3, 4, 5], 3) #=> 2 ``` -------------------------------- ### Example Usage of RBTreeMap Push and Assignment Source: https://github.com/kanwei/algorithms/blob/master/_autodocs/api-reference/tree-maps.md Demonstrates how to add elements to an RBTreeMap using both `push` and bracket assignment, and how to retrieve a value. ```ruby require 'algorithms' include Containers map = RBTreeMap.new map.push("MA", "Massachusetts") map.push("GA", "Georgia") map["NH"] = "New Hampshire" puts map.get("MA") #=> "Massachusetts" ``` -------------------------------- ### Mergesort Example Source: https://github.com/kanwei/algorithms/blob/master/_autodocs/MANIFEST.md Illustrates the mergesort algorithm, a stable, comparison-based sorting algorithm with a guaranteed worst-case time complexity of O(n log n). ```ruby Algorithms::Sort.mergesort([3, 1, 4, 1, 5, 9, 2, 6]) #=> [1, 1, 2, 3, 4, 5, 6, 9] ``` -------------------------------- ### Stack Pop Example Source: https://github.com/kanwei/algorithms/blob/master/_autodocs/MANIFEST.md Shows how to remove and return the element from the top of a Stack. This operation follows the LIFO principle. ```ruby stack = Containers::Stack.new stack.push(1) stack.push(2) stack.pop #=> 2 ``` -------------------------------- ### Example: Delete Element Source: https://github.com/kanwei/algorithms/blob/master/_autodocs/api-reference/priority-queue.md Illustrates deleting an element with a specific priority and verifying the queue's updated size. ```ruby queue = Containers::PriorityQueue.new queue.push("Alaska", 50) queue.push("Delaware", 30) queue.push("Georgia", 35) item = queue.delete(35) puts item #=> "Georgia" puts queue.size #=> 2 ``` -------------------------------- ### Basic Substring Search Example Source: https://github.com/kanwei/algorithms/blob/master/_autodocs/api-reference/suffix-array.md Demonstrates how to initialize a SuffixArray and check for the presence of various substrings within the text 'abracadabra'. ```ruby require 'algorithms' include Containers sa = SuffixArray.new("abracadabra") puts sa.has_substring?("abra") #=> true puts sa.has_substring?("cadabra") #=> true puts sa.has_substring?("xyz") #=> false puts sa["bra"] #=> true ``` -------------------------------- ### Insertion Sort Example Source: https://github.com/kanwei/algorithms/blob/master/_autodocs/api-reference/sort.md Demonstrates how to use the insertion_sort method. This method mutates the input array in place. ```ruby arr = [5, 4, 3, 1, 2] result = Algorithms::Sort.insertion_sort(arr) puts result.inspect #=> [1, 2, 3, 4, 5] ``` -------------------------------- ### Comb Sort Example Source: https://github.com/kanwei/algorithms/blob/master/_autodocs/api-reference/sort.md Demonstrates how to use the comb_sort method. This method mutates the input array in place. ```ruby arr = [5, 4, 3, 1, 2] result = Algorithms::Sort.comb_sort(arr) puts result.inspect #=> [1, 2, 3, 4, 5] ``` -------------------------------- ### Deque Pop Front Example Source: https://github.com/kanwei/algorithms/blob/master/_autodocs/MANIFEST.md Shows how to remove and return an element from the front of a Deque. This operation is efficient for accessing the beginning of the deque. ```ruby deque = Containers::Deque.new deque.push_front(1) deque.push_front(2) deque.pop_front #=> 2 ``` -------------------------------- ### MaxHeap Example Source: https://github.com/kanwei/algorithms/blob/master/_autodocs/MANIFEST.md Illustrates the use of the MaxHeap, a priority queue implementation where the largest element has the highest priority. Suitable for algorithms like Prim's. ```ruby heap = Containers::MaxHeap.new heap.push(5) heap.push(2) heap.pop #=> 5 ``` -------------------------------- ### PriorityQueue Comparison Block Example Source: https://github.com/kanwei/algorithms/blob/master/_autodocs/types.md Shows how to initialize a PriorityQueue with a custom comparison block. The block returns true if x has higher priority than y. ```ruby queue = Containers::PriorityQueue.new { |x, y| (x <=> y) == 1 } ``` -------------------------------- ### Bubble Sort Example Source: https://github.com/kanwei/algorithms/blob/master/_autodocs/api-reference/sort.md Demonstrates how to use the bubble_sort method. This method mutates the input array in place. ```ruby require 'algorithms' arr = [5, 4, 3, 1, 2] result = Algorithms::Sort.bubble_sort(arr) puts result.inspect #=> [1, 2, 3, 4, 5] ``` -------------------------------- ### Initialize Heap Source: https://github.com/kanwei/algorithms/blob/master/_autodocs/configuration.md Demonstrates various ways to initialize a Heap, including with no arguments, an array of values, or a custom comparison function. ```ruby # Basic initialization with no arguments heap = Containers::Heap.new # Initialize with array of values heap = Containers::MinHeap.new([5, 3, 7, 1]) # Initialize with custom comparison function heap = Containers::Heap.new { |x, y| (x <=> y) == 1 } # Max-heap # With both array and comparison heap = Containers::Heap.new([5, 3, 7]) { |x, y| (x <=> y) == -1 } ``` -------------------------------- ### Stack Push Example Source: https://github.com/kanwei/algorithms/blob/master/_autodocs/MANIFEST.md Demonstrates adding an element to the top of a Stack (LIFO - Last-In, First-Out). This is a basic operation for stack data structures. ```ruby stack = Containers::Stack.new stack.push(1) stack.push(2) ``` -------------------------------- ### Comb Sort Example Source: https://github.com/kanwei/algorithms/blob/master/_autodocs/MANIFEST.md Demonstrates the comb sort algorithm, an improvement over bubble sort that addresses the problem of small gaps. ```ruby Algorithms::Sort.comb_sort([3, 1, 4, 1, 5, 9, 2, 6]) #=> [1, 1, 2, 3, 4, 5, 6, 9] ``` -------------------------------- ### Heap Sort Example Source: https://github.com/kanwei/algorithms/blob/master/_autodocs/MANIFEST.md Illustrates the heapsort algorithm, a comparison-based sorting technique based on binary heaps. It has a worst-case, average-case, and best-case complexity of O(n log n). ```ruby Algorithms::Sort.heapsort([3, 1, 4, 1, 5, 9, 2, 6]) #=> [1, 1, 2, 3, 4, 5, 6, 9] ``` -------------------------------- ### Deque Pop Back Example Source: https://github.com/kanwei/algorithms/blob/master/_autodocs/MANIFEST.md Shows how to remove and return an element from the back of a Deque. This operation is efficient for accessing the end of the deque. ```ruby deque = Containers::Deque.new deque.push_back(1) deque.push_back(2) deque.pop_back #=> 2 ``` -------------------------------- ### KMP Search Example Source: https://github.com/kanwei/algorithms/blob/master/_autodocs/MANIFEST.md Illustrates the Knuth-Morris-Pratt (KMP) algorithm for pattern matching within a text. This method is efficient for finding occurrences of a pattern. ```ruby Algorithms::Search.kmp_search("ababa", "aba") #=> [0, 2] ``` -------------------------------- ### SplayTreeMap Insertion Example Source: https://github.com/kanwei/algorithms/blob/master/_autodocs/MANIFEST.md Shows inserting a key-value pair into a Splay Tree Map. This structure offers O(log n) amortized time complexity for operations. ```ruby spt = Containers::SplayTreeMap.new spt[:key1] = "value1" spt[:key2] = "value2" ``` -------------------------------- ### 2D Nearest Neighbor Search Example Source: https://github.com/kanwei/algorithms/blob/master/_autodocs/api-reference/kd-tree.md Demonstrates finding the nearest cities to a given geographical coordinate using KDTree. Requires the 'algorithms' gem and inclusion of the Containers module. The output shows city names and their distances. ```ruby require 'algorithms' include Containers # City locations cities = { "NYC" => [40.7128, -74.0060], "LA" => [34.0522, -118.2437], "Chicago" => [41.8781, -87.6298], "Houston" => [29.7604, -95.3698], "Phoenix" => [33.4484, -112.0742] } kdtree = KDTree.new(cities) # Find 2 nearest cities to a location target = [35.0, -100.0] nearest = kdtree.find_nearest(target, 2) nearest.each do |distance, city_name| sqrt_distance = Math.sqrt(distance) puts "#{city_name}: #{sqrt_distance.round(2)} units away" end # Output varies based on calculations ``` -------------------------------- ### Get Value by Key in RBTreeMap Source: https://github.com/kanwei/algorithms/blob/master/_autodocs/api-reference/tree-maps.md Retrieves the value associated with a given key using `get` or bracket notation. Returns nil if the key is not found. ```ruby tmap.get(key) tmap[key] ``` -------------------------------- ### Initialize Trie Source: https://github.com/kanwei/algorithms/blob/master/_autodocs/configuration.md Shows how to initialize an empty Trie. Tries do not support bulk initialization and must have items added individually. ```ruby # Empty trie trie = Containers::Trie.new # No bulk initialization; add items individually trie["hello"] = "world" trie["test"] = 123 ``` -------------------------------- ### Initialize and Use Data Structures Source: https://github.com/kanwei/algorithms/blob/master/_autodocs/configuration.md Demonstrates the complete workflow for initializing and using various data structures provided by the algorithms gem, including PriorityQueue, RBTreeMap, Deque, and Trie. ```ruby require 'algorithms' include Containers # Create a priority queue for tasks task_queue = PriorityQueue.new task_queue.push("Urgent task", 10) task_queue.push("Normal task", 5) task_queue.push("Low priority", 1) # Create a tree for sorted access id_map = RBTreeMap.new id_map[1] = "Alice" id_map[2] = "Bob" id_map[3] = "Charlie" # Create a deque for buffering buffer = Deque.new buffer.push_back("item1") buffer.push_back("item2") # Create a trie for pattern matching dictionary = Trie.new dictionary["apple"] = :fruit dictionary["application"] = :software dictionary["apply"] = :verb ``` -------------------------------- ### RBTreeMap Insertion Example Source: https://github.com/kanwei/algorithms/blob/master/_autodocs/MANIFEST.md Illustrates inserting a key-value pair into a Red-Black Tree Map. This data structure guarantees O(log n) for insertions and deletions. ```ruby rbt = Containers::RBTreeMap.new rbt[:key1] = "value1" rbt[:key2] = "value2" ``` -------------------------------- ### Custom Heap Configuration Source: https://github.com/kanwei/algorithms/blob/master/_autodocs/api-reference/heap.md Demonstrates creating custom max-heaps and min-heaps using a block for comparison logic, and using custom objects with a heap. ```ruby require 'algorithms' # Create a max-heap explicitly max_heap = Containers::Heap.new { |x, y| (x <=> y) == 1 } max_heap.push(5) max_heap.push(3) max_heap.push(7) puts max_heap.pop #=> 7 # Create a min-heap (default if no block) min_heap = Containers::Heap.new { |x, y| (x <=> y) == -1 } min_heap.push(5) min_heap.push(3) min_heap.push(7) puts min_heap.pop #=> 3 # Use with custom objects Person = Struct.new(:name, :age) people = [ Person.new("Alice", 25), Person.new("Bob", 30), Person.new("Charlie", 20) ] age_heap = Containers::Heap.new(people) { |a, b| a.age > b.age } oldest = age_heap.pop puts oldest.name #=> "Bob" ``` -------------------------------- ### Autocomplete System using Trie Source: https://github.com/kanwei/algorithms/blob/master/_autodocs/api-reference/trie.md An example of building an autocomplete system using a Trie. It adds words with associated scores and provides suggestions based on a given prefix, returning the top 'count' suggestions sorted by score. ```ruby require 'algorithms' include Containers class Autocomplete def initialize @trie = Trie.new end def add_word(word, score = 1) @trie[word] = score end def suggestions(prefix, count = 5) # Find all words starting with prefix results = [] @trie.wildcard("#{prefix}*").each do |word| results << [word, @trie[word]] end results.sort_by { |w, s| -s }.take(count) end end ac = Autocomplete.new ac.add_word("apple", 100) ac.add_word("app", 50) ac.add_word("application", 75) ac.add_word("apply", 60) puts ac.suggestions("app").inspect # => [["apple", 100], ["application", 75], ["apply", 60], ["app", 50]] ``` -------------------------------- ### Use Search Algorithms Source: https://github.com/kanwei/algorithms/blob/master/_autodocs/configuration.md Demonstrates using binary search and KMP search algorithms from the Algorithms::Search module. KMP search can also be included as an instance method on the String class. ```ruby require 'algorithms' # Binary search (requires sorted array) result = Algorithms::Search.binary_search([1, 2, 3, 4, 5], 3) # KMP search index = Algorithms::Search.kmp_search("hello world", "world") # As instance method on String class String include Algorithms::Search end index = "hello world".kmp_search("world") ``` -------------------------------- ### Example Usage of RBTreeMap max_key Source: https://github.com/kanwei/algorithms/blob/master/_autodocs/api-reference/tree-maps.md Shows how to find the maximum key in an RBTreeMap. ```ruby map = Containers::RBTreeMap.new map["Z"] = 26 map["A"] = 1 puts map.max_key #=> "Z" ``` -------------------------------- ### Mergesort and Dual-Pivot Quicksort Source: https://github.com/kanwei/algorithms/blob/master/_autodocs/QUICKSTART.md Demonstrates how to use Mergesort for guaranteed O(n log n) performance and Dual-Pivot Quicksort for average performance on a dataset. ```ruby sorted = Algorithms::Sort.mergesort(data.dup) # Or use dual-pivot quicksort for average performance sorted = Algorithms::Sort.dualpivotquicksort(data.dup) puts sorted.first #=> 1 puts sorted.last #=> 10000 ``` -------------------------------- ### Example Usage of RBTreeMap has_key? Source: https://github.com/kanwei/algorithms/blob/master/_autodocs/api-reference/tree-maps.md Demonstrates checking for the presence of keys in an RBTreeMap. ```ruby map = Containers::RBTreeMap.new map["CA"] = "California" puts map.has_key?("CA") #=> true puts map.has_key?("TX") #=> false ``` -------------------------------- ### Example Usage of RBTreeMap empty? Source: https://github.com/kanwei/algorithms/blob/master/_autodocs/api-reference/tree-maps.md Illustrates checking if an RBTreeMap is empty before and after adding an element. ```ruby map = Containers::RBTreeMap.new puts map.empty? #=> true map["A"] = 1 puts map.empty? #=> false ``` -------------------------------- ### Initialize KDTree Source: https://github.com/kanwei/algorithms/blob/master/_autodocs/configuration.md Shows how to initialize a KDTree with a hash of points, where keys are IDs and values are coordinate arrays. All points must have the same dimensionality. ```ruby # Must pass hash of id => [coordinates] pairs points = { 0 => [1.0, 2.0], 1 => [3.0, 4.0], 2 => [-1.0, -2.0] } kdtree = Containers::KDTree.new(points) # 3D points points_3d = { 0 => [1.0, 2.0, 3.0], 1 => [4.0, 5.0, 6.0] } kdtree = Containers::KDTree.new(points_3d) ``` -------------------------------- ### Example Usage of RBTreeMap height Source: https://github.com/kanwei/algorithms/blob/master/_autodocs/api-reference/tree-maps.md Shows how to retrieve the height of the Red-Black Tree map. ```ruby map = Containers::RBTreeMap.new (1..10).each { |i| map[i] = i } puts map.height #=> 4 ``` -------------------------------- ### Example Usage of RBTreeMap delete Source: https://github.com/kanwei/algorithms/blob/master/_autodocs/api-reference/tree-maps.md Illustrates deleting an element from an RBTreeMap and verifying its removal. ```ruby map = Containers::RBTreeMap.new map["CA"] = "California" value = map.delete("CA") puts value #=> "California" puts map.has_key?("CA") #=> false ``` -------------------------------- ### Get Height of RBTreeMap Source: https://github.com/kanwei/algorithms/blob/master/_autodocs/api-reference/tree-maps.md Returns the height of the Red-Black Tree structure. This operation is O(1). ```ruby tmap.height ``` -------------------------------- ### Get Size of PriorityQueue Source: https://github.com/kanwei/algorithms/blob/master/_autodocs/api-reference/priority-queue.md Returns the total number of elements currently stored in the queue. ```ruby queue.size -> integer ``` ```ruby queue.length -> integer ``` -------------------------------- ### Get the size of the Queue Source: https://github.com/kanwei/algorithms/blob/master/_autodocs/api-reference/stack-and-queue.md Returns the number of elements currently in the queue. Alias for `length`. ```Ruby queue.size -> integer queue.length -> integer ``` ```Ruby queue = Containers::Queue.new([1, 2, 3]) puts queue.size #=> 3 ``` -------------------------------- ### Get the size of the Stack Source: https://github.com/kanwei/algorithms/blob/master/_autodocs/api-reference/stack-and-queue.md Returns the number of elements currently in the stack. Alias for `length`. ```Ruby stack.size -> integer stack.length -> integer ``` ```Ruby stack = Containers::Stack.new([1, 2, 3]) puts stack.size #=> 3 ``` -------------------------------- ### Example Usage of RBTreeMap delete_max Source: https://github.com/kanwei/algorithms/blob/master/_autodocs/api-reference/tree-maps.md Illustrates deleting and retrieving the value of the largest element from an RBTreeMap. ```ruby map = Containers::RBTreeMap.new map["Z"] = 26 map["A"] = 1 value = map.delete_max puts value #=> 26 ``` -------------------------------- ### Example Usage of RBTreeMap delete_min Source: https://github.com/kanwei/algorithms/blob/master/_autodocs/api-reference/tree-maps.md Shows how to remove and retrieve the value of the smallest element from an RBTreeMap. ```ruby map = Containers::RBTreeMap.new map["Z"] = 26 map["A"] = 1 value = map.delete_min puts value #=> 1 ``` -------------------------------- ### get / [] Source: https://github.com/kanwei/algorithms/blob/master/_autodocs/api-reference/trie.md Retrieves the value associated with a given key from the Trie. Returns nil if the key is not found. ```APIDOC ## get / [] ### Description Retrieves the value associated with a key. Returns nil if the key is not found in the Trie. ### Method `get(key)` or `trie[key]` ### Endpoint N/A (Instance Method) ### Parameters - **key**: (String or other convertible type) - The key to look up. ### Request Example ```ruby trie = Containers::Trie.new trie["hello"] = "world" puts trie.get("hello") #=> "world" puts trie["goodbye"] #=> nil ``` ### Response - **value**: The value associated with the key, or `nil` if the key is not present. ``` -------------------------------- ### Task Scheduling with Priority Queue Source: https://github.com/kanwei/algorithms/blob/master/_autodocs/api-reference/priority-queue.md Demonstrates how to use the Priority Queue to manage tasks based on their deadlines. Tasks with earlier deadlines are given higher priority. Requires the 'algorithms' gem. ```ruby require 'algorithms' Task = Struct.new(:name, :deadline) task_queue = Containers::PriorityQueue.new # Add tasks with deadlines (earlier deadlines = higher priority) task_queue.push(Task.new("Report due", 1), 1) # urgency 1 task_queue.push(Task.new("Meeting prep", 5), 5) # urgency 5 task_queue.push(Task.new("Email response", 2), 2) # urgency 2 # Process tasks in order of urgency while !task_queue.empty? task = task_queue.pop puts "Handling: #{task.name}" end # Output: # Handling: Report due # Handling: Email response # Handling: Meeting prep ``` -------------------------------- ### Initialize a MinHeap with elements Source: https://github.com/kanwei/algorithms/blob/master/_autodocs/api-reference/heap.md Creates a new MinHeap and initializes it with an array of elements. The heap property is maintained by default for minimum values. ```ruby minheap = Containers::MinHeap.new([1, 2, 3]) puts minheap.size #=> 3 ``` -------------------------------- ### Use Sort Algorithms Source: https://github.com/kanwei/algorithms/blob/master/_autodocs/configuration.md Shows how to use various sorting algorithms like bubble sort, quicksort, and mergesort from the Algorithms::Sort module. These algorithms accept an array and may either mutate it in-place or return a new sorted array. ```ruby require 'algorithms' # All sorting algorithms accept array parameter arr = [5, 3, 4, 1, 2] sorted = Algorithms::Sort.bubble_sort(arr) sorted = Algorithms::Sort.quicksort(arr) sorted = Algorithms::Sort.mergesort(arr) # Some mutate in-place, others return new array # See individual algorithm documentation for details ``` -------------------------------- ### Get Height of SplayTreeMap Source: https://github.com/kanwei/algorithms/blob/master/_autodocs/api-reference/tree-maps.md Returns the height of the SplayTreeMap's internal tree structure. The complexity is O(log n). ```ruby stmap.height -> integer ``` ```ruby map = Containers::SplayTreeMap.new (1..100).each { |i| map[i] = i } puts map.height #=> varies based on access pattern ``` -------------------------------- ### Performance Tip: Use Heap for Priority Processing Source: https://github.com/kanwei/algorithms/blob/master/_autodocs/QUICKSTART.md Compares inefficient sorting for priority retrieval with the efficient O(log n) retrieval using a MinHeap. The heap approach is recommended for frequent priority-based operations. ```ruby # Bad: Sorting every time items = [...] items.sort_by(&:priority) # O(n log n) every time # Good: Use Heap heap = Containers::MinHeap.new items.each { |i| heap.push(i.priority, i) } heap.pop # O(log n) ``` -------------------------------- ### Get Size of SplayTreeMap Source: https://github.com/kanwei/algorithms/blob/master/_autodocs/api-reference/tree-maps.md Returns the number of key-value pairs currently stored in the SplayTreeMap. This operation is typically O(1). ```ruby stmap.size -> integer ``` ```ruby map = Containers::SplayTreeMap.new map["A"] = 1 map["B"] = 2 puts map.size #=> 2 ``` -------------------------------- ### Get Size of Deque Source: https://github.com/kanwei/algorithms/blob/master/_autodocs/api-reference/deque.md Returns the number of items currently in the deque. Both `size` and `length` methods provide this functionality. ```ruby deque = Containers::Deque.new([1, 2, 3]) puts deque.size #=> 3 ``` -------------------------------- ### PriorityQueue Delete Example Source: https://github.com/kanwei/algorithms/blob/master/_autodocs/MANIFEST.md Illustrates removing an element from the PriorityQueue based on its priority. This can be useful for managing tasks or events dynamically. ```ruby pq = Containers::PriorityQueue.new pq.push(:task1, 10) pq.push(:task2, 5) pq.delete(10) # Removes :task1 ``` -------------------------------- ### Performance Tip: Use Trie for Autocomplete Source: https://github.com/kanwei/algorithms/blob/master/_autodocs/QUICKSTART.md Highlights the performance difference between linear search for prefix matching and using a Trie. Tries offer significantly faster prefix queries (O(m)) compared to linear scans (O(n*m)). ```ruby # Bad: Check every word words = [...] pattern = "app" words.select { |w| w.start_with?(pattern) } # O(n*m) # Good: Trie structure trie = Containers::Trie.new trie.wildcard("#{pattern}*") # O(m) ``` -------------------------------- ### Containers::KDTree Initialization Source: https://github.com/kanwei/algorithms/blob/master/_autodocs/api-reference/kd-tree.md Initializes a new KDTree instance with a hash of points. All points must have the same dimensionality. ```APIDOC ## Containers::KDTree.new ### Description Initializes a KDTree with a hash mapping IDs to coordinate arrays. All points must have the same dimensionality. ### Parameters #### Request Body - **points_hash** (Hash) - Required - Hash mapping IDs to coordinate arrays; all points must have same dimensionality. Format: `{id => [coord1, coord2, ...], ...}` ### Request Example ```ruby require 'algorithms' include Containers points = { 0 => [4, 3], 1 => [3, 4], 2 => [-1, 2], 3 => [6, 4], 4 => [3, -5], 5 => [-2, -5] } kdtree = KDTree.new(points) ``` ``` -------------------------------- ### Initialize KDTree with 2D Points Source: https://github.com/kanwei/algorithms/blob/master/_autodocs/api-reference/kd-tree.md Initializes a KDTree with a hash of points. The hash maps IDs to coordinate arrays. All points must have the same dimensionality. Ensure the 'algorithms' gem is required and the Containers module is included. ```ruby require 'algorithms' include Containers # 2D points points = { 0 => [4, 3], 1 => [3, 4], 2 => [-1, 2], 3 => [6, 4], 4 => [3, -5], 5 => [-2, -5] } kdtree = KDTree.new(points) ``` -------------------------------- ### Stack for Postfix Expression Evaluation Source: https://github.com/kanwei/algorithms/blob/master/_autodocs/api-reference/stack-and-queue.md Demonstrates using a stack to evaluate postfix mathematical expressions. Requires the 'algorithms' gem and inclusion of the Containers module. ```Ruby require 'algorithms' include Containers # Simple postfix evaluation def evaluate_postfix(tokens) stack = Stack.new tokens.each do |token| if token.is_a?(Integer) stack.push(token) else b = stack.pop a = stack.pop case token when '+' stack.push(a + b) when '-' stack.push(a - b) when '*' stack.push(a * b) when '/' stack.push(a / b) end end end stack.pop end result = evaluate_postfix([5, 3, '+', 2, '*']) puts result #=> 16 ((5 + 3) * 2) ``` -------------------------------- ### PriorityQueue Pop Example Source: https://github.com/kanwei/algorithms/blob/master/_autodocs/MANIFEST.md Shows how to remove and return the element with the highest priority from the PriorityQueue. This operation is fundamental for processing tasks in order. ```ruby pq = Containers::PriorityQueue.new pq.push(:task1, 10) pq.push(:task2, 5) pq.pop #=> :task2 ``` -------------------------------- ### Containers::MinHeap Initialization Source: https://github.com/kanwei/algorithms/blob/master/_autodocs/api-reference/heap.md Initializes a new MinHeap instance, which is a subclass of Heap configured to prioritize the smallest items. ```APIDOC ## Containers::MinHeap.new ### Description Initializes a new MinHeap instance, which is a subclass of Heap configured to return the smallest items first (min-heap property). Items with smaller keys are parent nodes. ### Parameters #### Parameters - **optional_array** (Array) - Optional - Default: [] - Array of items to insert. ### Returns - **MinHeap** - A new MinHeap instance. ``` -------------------------------- ### get / [] Source: https://github.com/kanwei/algorithms/blob/master/_autodocs/api-reference/tree-maps.md Retrieves the value associated with a given key. Returns nil if the key is not found. This operation has an amortized complexity of O(log n). ```APIDOC ## get / [] ### Description Retrieves the value for a key. Returns nil if not found. ### Method `stmap.get(key)` or `stmap[key]` ### Parameters #### Path Parameters - **key** (any comparable type) - Required - The key to look up. ### Response #### Success Response - **value** (any type) - The value associated with the key, or nil if the key is not found. ### Complexity O(log n) amortized ``` -------------------------------- ### Initialize Queue with an Array Source: https://github.com/kanwei/algorithms/blob/master/_autodocs/api-reference/stack-and-queue.md Creates a new queue and initializes it with elements from an optional array. Defaults to an empty queue if no array is provided. ```Ruby Containers::Queue.new(optional_array=[]) -> Queue ``` -------------------------------- ### Get Size of RBTreeMap Source: https://github.com/kanwei/algorithms/blob/master/_autodocs/api-reference/tree-maps.md Returns the total number of key-value pairs stored in the Red-Black Tree map using the `size` method. ```ruby tmap.size ```