├── src └── .gitkeep ├── .github ├── issue-template.md ├── pull-request-template.md ├── contributing.md └── code-of-conduct.md ├── algorithms ├── math │ ├── greatest_common_denominator.rb │ ├── catalan.rb │ ├── lucas.rb │ ├── factorial.rb │ ├── fibonacci.rb │ ├── gcd.rb │ ├── geometric_progression.rb │ ├── square_root_integer.rb │ ├── lcm.rb │ └── subset_sum.rb ├── others │ ├── fizzbuzz.rb │ ├── sieve-of-eratosthenes.rb │ ├── minesweeper.rb │ ├── levenshtein_distance.rb │ ├── thread_jruby.rb │ ├── jokenpo.rb │ └── knapsack.rb ├── ciphers │ ├── caesar.rb │ ├── encryptor.rb │ ├── baconian.rb │ └── playfair.rb ├── leap_year.rb ├── sorting │ ├── selection_sort.rb │ ├── bogo_sort.rb │ ├── insertion_sort.rb │ ├── bubble_sort.rb │ ├── shell_sort.rb │ ├── quick_sort.rb │ └── merge_sort.rb ├── searches │ └── binary_search.rb ├── data-structures │ ├── stack.rb │ ├── queue.rb │ ├── is_binary_tree_bst.rb │ ├── linked_list.rb │ ├── trie.rb │ ├── binary_tree.rb │ └── djikstra.rb ├── strings │ ├── palindrome.rb │ └── anagram_search.rb ├── dynamic-programming │ └── longest_common_subsquence.rb ├── searching │ └── binary_search_tree.rb ├── cryptography │ └── ed25519.rb ├── cellular-automaton │ └── conways_game_of_life.rb └── graphs │ └── bfs.rb ├── license └── readme.md /src/.gitkeep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /.github/issue-template.md: -------------------------------------------------------------------------------- 1 | I am creating an issue because... 2 | -------------------------------------------------------------------------------- /algorithms/math/greatest_common_denominator.rb: -------------------------------------------------------------------------------- 1 | def gcd(num1, num2) 2 | num1 == 0 ? num2 : gdc(num2%num1, num1) 3 | end 4 | 5 | puts "GCD(10,15) = #{gcd(10,15)}" -------------------------------------------------------------------------------- /algorithms/math/catalan.rb: -------------------------------------------------------------------------------- 1 | def catalan(n) 2 | return 1 if n == 0 3 | 2*(2*n - 1) * catalan(n-1) / (n+1) 4 | end 5 | 6 | for j in 0..10 7 | puts "#{catalan(j)} " 8 | end 9 | -------------------------------------------------------------------------------- /.github/pull-request-template.md: -------------------------------------------------------------------------------- 1 | I am creating a pull request for... 2 | 3 | - [ ] New algorithm 4 | - [ ] Update to an algorithm 5 | - [ ] Fix an error 6 | - [ ] Other - *Describe below* -------------------------------------------------------------------------------- /.github/contributing.md: -------------------------------------------------------------------------------- 1 | ## Contributing 2 | 3 | > Please note that this project is released with a [Contributor Code of Conduct](code-of-conduct.md). By participating in this project you agree to abide by its terms. -------------------------------------------------------------------------------- /algorithms/math/lucas.rb: -------------------------------------------------------------------------------- 1 | number = gets.chomp.to_i 2 | 3 | def lucas(number) 4 | case number 5 | when 1 then 2 6 | when 2 then 1 7 | else lucas(number - 1) + lucas(number - 2) 8 | end 9 | end 10 | 11 | puts lucas(number) 12 | -------------------------------------------------------------------------------- /algorithms/math/factorial.rb: -------------------------------------------------------------------------------- 1 | def factorial(n) 2 | (1..n).reduce(:*) || 1 3 | end 4 | 5 | puts "factorial(0): #{factorial(0)}" 6 | puts "factorial(1): #{factorial(1)}" 7 | puts "factorial(2): #{factorial(2)}" 8 | puts "factorial(5): #{factorial(5)}" -------------------------------------------------------------------------------- /algorithms/math/fibonacci.rb: -------------------------------------------------------------------------------- 1 | def fibonacci(n) 2 | n <= 1 ? n : fibonacci(n - 1) + fibonacci(n - 2) 3 | end 4 | 5 | puts "fibonacci(0): #{fibonacci(0)}" 6 | puts "fibonacci(1): #{fibonacci(1)}" 7 | puts "fibonacci(4): #{fibonacci(4)}" 8 | puts "fibonacci(6): #{fibonacci(6)}" -------------------------------------------------------------------------------- /algorithms/others/fizzbuzz.rb: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby -w 2 | 3 | 1.upto(100) do |i| 4 | if i % 5 == 0 and i % 3 == 0 5 | puts "FizzBuzz" 6 | elsif i % 5 == 0 7 | puts "Buzz" 8 | elsif i % 3 == 0 9 | puts "Fizz" 10 | else 11 | puts i 12 | end 13 | end 14 | -------------------------------------------------------------------------------- /algorithms/ciphers/caesar.rb: -------------------------------------------------------------------------------- 1 | def caesar_cipher(string) 2 | alphabet = Array('a'..'z') 3 | encrypter = Hash[alphabet.zip(alphabet.rotate(1))] 4 | string.chars.map { |c| encrypter.fetch(c, " ") } 5 | end 6 | 7 | p 'Enter the word you want to be encrypted:' 8 | p caesar_cipher(gets.chomp).join 9 | -------------------------------------------------------------------------------- /algorithms/math/gcd.rb: -------------------------------------------------------------------------------- 1 | value_one = gets.chomp.to_i 2 | value_two = gets.chomp.to_i 3 | 4 | def gcd(first, second) 5 | if second != 0 6 | gcd(second, first%second) 7 | else 8 | first 9 | end 10 | end 11 | 12 | puts "The greatest common divisor is #{gcd(value_one, value_two)}" 13 | -------------------------------------------------------------------------------- /algorithms/math/geometric_progression.rb: -------------------------------------------------------------------------------- 1 | def geometric_progression initial, ratio, numbers 2 | (numbers - 1).times.inject([initial]){|array| array << array.last * ratio} 3 | end 4 | 5 | puts "geometric_progression(2, 2, 10): #{geometric_progression(2, 2, 10)}" 6 | puts "geometric_progression(2, 0.5, 10): #{geometric_progression(2, 0.5, 10)}" 7 | -------------------------------------------------------------------------------- /algorithms/leap_year.rb: -------------------------------------------------------------------------------- 1 | system('clear') 2 | 3 | p "Qual o ano que deseja saber ?" 4 | ano = gets.chomp.to_i 5 | 6 | 7 | a1 = (ano % 400).to_i 8 | a2 = (ano % 4).to_i 9 | a3 = (ano % 100).to_i 10 | system('clear') 11 | 12 | 13 | 14 | if a1 == 0 || a2 == 0 15 | p 'É um ano bissexto' 16 | else 17 | p 'Não é um ano bissexto' 18 | end 19 | -------------------------------------------------------------------------------- /algorithms/sorting/selection_sort.rb: -------------------------------------------------------------------------------- 1 | def selection_sort(arr) 2 | for j in 0..arr.count - 2 do 3 | i_min = j 4 | for i in j..arr.count - 1 do 5 | if arr[i] < arr[i_min] 6 | i_min = i 7 | end 8 | end 9 | if i_min != j 10 | arr[j], arr[i_min] = arr[i_min], arr[j] 11 | end 12 | end 13 | arr 14 | end 15 | -------------------------------------------------------------------------------- /algorithms/searches/binary_search.rb: -------------------------------------------------------------------------------- 1 | def binary_search(element, arr) 2 | middle = arr[arr.length / 2] 3 | 4 | if middle == element 5 | return true 6 | elsif middle < element 7 | beg = middle 8 | last = arr.length - 1 9 | middle = beg + last / 2 10 | else 11 | beg = 0 12 | last = middle 13 | middle = beg + last / 2 14 | end 15 | end -------------------------------------------------------------------------------- /algorithms/math/square_root_integer.rb: -------------------------------------------------------------------------------- 1 | # Find the square root of an integer 2 | 3 | def rounded_sqrt(number) 4 | return number if number == 0 || number == 1 5 | 6 | result = 1 7 | counter = 1 8 | while result <= number 9 | counter += 1 10 | result = counter ** 2 11 | end 12 | 13 | return counter - 1 14 | end 15 | 16 | puts rounded_sqrt(4) 17 | puts rounded_sqrt(16) 18 | puts rounded_sqrt(121) 19 | -------------------------------------------------------------------------------- /algorithms/sorting/bogo_sort.rb: -------------------------------------------------------------------------------- 1 | # Ruby implementation of bogo sort 2 | # 3 | # Author: Matthias Kranzer 4 | def bogoSort(array) 5 | array.shuffle! until sorted(array) 6 | array 7 | end 8 | 9 | def sorted(array) 10 | (0..array.length-2).all? {|i| array[i] <= array[i+1]} 11 | end 12 | 13 | # Test 14 | arr = [46, 24, 33, 10, 2, 81, -50] 15 | puts("Unsorted array") 16 | p arr 17 | 18 | puts("Sorted array") 19 | p bogoSort(arr) -------------------------------------------------------------------------------- /algorithms/sorting/insertion_sort.rb: -------------------------------------------------------------------------------- 1 | def insertion_sort(array) 2 | result = [array.shift] 3 | for n in array 4 | index = 0 5 | while index < result.length 6 | if n <= result[index] 7 | result.insert(index, n) 8 | break 9 | elsif index == result.length - 1 10 | result.insert(index + 1, n) 11 | break 12 | end 13 | index+=1 14 | end 15 | end 16 | result 17 | end 18 | -------------------------------------------------------------------------------- /algorithms/math/lcm.rb: -------------------------------------------------------------------------------- 1 | # LCM (Least Common Multiple) of two numbers is the smallest number which can be divided by both numbers. 2 | 3 | value_one = gets.chomp.to_i 4 | value_two = gets.chomp.to_i 5 | 6 | def gcd(first, second) 7 | if second != 0 8 | gcd(second, first%second) 9 | else 10 | first 11 | end 12 | end 13 | 14 | def lcm(first, second) 15 | (first * second)/gcd(first, second) 16 | end 17 | 18 | puts lcm(value_one, value_two) 19 | -------------------------------------------------------------------------------- /algorithms/math/subset_sum.rb: -------------------------------------------------------------------------------- 1 | # Given a set of non negative numbers and a value, sum, 2 | # find if there is a subset with sum equal to the sum given 3 | def subset_sum(set, set_length, sum) 4 | return true if sum == 0 5 | return false if set_length == 0 && sum != 0 6 | 7 | if(set[set_length - 1] > sum) 8 | return subset_sum(set, set_length - 1, sum) 9 | end 10 | 11 | return subset_sum(set, set_length - 1, sum) || subset_sum(set, set_length - 1, sum - set[set_length - 1]) 12 | end 13 | 14 | -------------------------------------------------------------------------------- /algorithms/ciphers/encryptor.rb: -------------------------------------------------------------------------------- 1 | CIPHER_MAP = 2 | {'a' => 'n', 'b' => 'o', 'c' => 'p', 'd' => 'q', 3 | 'e' => 'r', 'f' => 's', 'g' => 't', 'h' => 'u', 4 | 'i' => 'v', 'j' => 'w', 'k' => 'x', 'l' => 'y', 5 | 'm' => 'z', 'n' => 'a', 'o' => 'b', 'p' => 'c', 6 | 'q' => 'd', 'r' => 'e', 's' => 'f', 't' => 'g', 7 | 'u' => 'h', 'v' => 'i', 'w' => 'j', 'x' => 'k', 8 | 'y' => 'l', 'z' => 'm'} 9 | 10 | puts gets 11 | .chomp 12 | .chars 13 | .map { |letter| CIPHER_MAP[letter.downcase] }.join 14 | -------------------------------------------------------------------------------- /algorithms/others/sieve-of-eratosthenes.rb: -------------------------------------------------------------------------------- 1 | class Prime 2 | def sieves(n) 3 | primes = Array.new(n+1,true) 4 | primes[0] = primes[1] = false 5 | (0..n).each do |i| 6 | if primes[i] 7 | l = i * 2 8 | (l..n).step(i).each do |k| 9 | primes[k] = false 10 | end 11 | end 12 | end 13 | primes.collect.with_index{|prime,i| prime ? i : nil}.compact 14 | end 15 | end 16 | 17 | Prime.new.sieves(10) 18 | Prime.new.sieves(20) 19 | Prime.new.sieves(10000000) 20 | -------------------------------------------------------------------------------- /algorithms/sorting/bubble_sort.rb: -------------------------------------------------------------------------------- 1 | # Ruby implementation of bubble sort 2 | # 3 | # Author: Carlos Abraham Hernandez 4 | 5 | def bubbleSort(array) 6 | swapped = true 7 | while swapped do 8 | swapped = false 9 | (array.length - 1).times do |i| 10 | if array[i] > array[i + 1] 11 | array[i], array[i + 1] = array[i + 1], array[i] 12 | swapped = true 13 | end 14 | end 15 | end 16 | array 17 | end 18 | 19 | # Test 20 | arr = [46, 24, 33, 10, 2, 81, 50] 21 | puts "Unsorted array" 22 | p arr 23 | 24 | puts "Sorted array" 25 | p bubbleSort(arr) 26 | -------------------------------------------------------------------------------- /algorithms/sorting/shell_sort.rb: -------------------------------------------------------------------------------- 1 | # Ruby implementation of shell sort 2 | # 3 | # See: http://www.codecodex.com/wiki/Shell_sort 4 | 5 | def shellSort(array) 6 | inc = array.size / 2 7 | while inc > 0 8 | inc.upto(array.size - 1) { |i| 9 | j = i 10 | temp = array[i] 11 | while j >= inc and array[j - inc] > temp 12 | array[j] = array[j - inc] 13 | j -= inc 14 | end 15 | array[j] = temp 16 | } 17 | inc = (inc == 2 ? 1 : inc * 10 / 22) 18 | end 19 | array 20 | end 21 | 22 | # Test 23 | arr = [46, 24, 33, 10, 2, 81, -50] 24 | puts("Unsorted array") 25 | p arr 26 | 27 | puts("Sorted array") 28 | p shellSort(arr) -------------------------------------------------------------------------------- /algorithms/others/minesweeper.rb: -------------------------------------------------------------------------------- 1 | def minefield(field, cell) 2 | queue = [] 3 | row, col = cell 4 | 5 | if field[row][col] == 0 6 | queue << cell 7 | elsif field[row][col] == -1 8 | return "Boom!!" 9 | else 10 | return field 11 | end 12 | 13 | while queue.size > 0 14 | current_i, current_j = queue.shift 15 | (current_i - 1).upto(current_i + 1) do |i| 16 | (current_j - 1).upto(current_j + 1) do |j| 17 | if i >= 0 && i < field.size && j >= 0 && j < field[0].size 18 | if field[i][j] == 0 19 | queue << [i,j] 20 | field[i][j] = -2 21 | end 22 | end 23 | end 24 | end 25 | end 26 | field 27 | end -------------------------------------------------------------------------------- /algorithms/sorting/quick_sort.rb: -------------------------------------------------------------------------------- 1 | # Author: Murilo Ferreira 2 | 3 | 4 | # Swap two elements of an array 5 | def swap(arr, x, y) 6 | aux = arr[x] 7 | arr[x] = arr[y] 8 | arr[y] = aux 9 | nil 10 | end 11 | 12 | def partition(arr, a, b, x) 13 | m = a - 1 14 | for k in a..b do 15 | if arr[k] <= x 16 | m += 1 17 | swap(arr, m, k) 18 | end 19 | end 20 | m 21 | end 22 | 23 | def quick_sort(arr, a, b) 24 | return arr if a >= b 25 | pivot = partition arr, a, b, arr[b] 26 | quick_sort arr, a, pivot-1 27 | quick_sort arr, pivot+1, b 28 | arr 29 | end 30 | 31 | 32 | test_array = [3,1,-10,8,10,4] 33 | quick_sort test_array, 0, test_array.size-1 34 | puts test_array -------------------------------------------------------------------------------- /algorithms/data-structures/stack.rb: -------------------------------------------------------------------------------- 1 | class Stack 2 | 3 | class Store 4 | attr_accessor :next, :data 5 | 6 | def initialize(data) 7 | @data = data 8 | end 9 | end 10 | 11 | def pop 12 | unless @top.nil? 13 | @top = @top.next 14 | @top.data if @top 15 | end 16 | end 17 | 18 | def push(obj) 19 | if @top.nil? 20 | @top = Store.new(obj) 21 | else 22 | old_top = @top 23 | @top = Store.new(obj) 24 | @top.next = old_top 25 | end 26 | end 27 | 28 | def peek 29 | @top.data if @top 30 | end 31 | 32 | end 33 | 34 | stack = Stack.new 35 | stack.push 1 36 | puts stack.inspect 37 | 38 | stack.push 2 39 | puts stack.inspect 40 | 41 | stack.pop 42 | puts stack.inspect 43 | 44 | puts stack.peek 45 | -------------------------------------------------------------------------------- /algorithms/strings/palindrome.rb: -------------------------------------------------------------------------------- 1 | def is_palindrome?(word, first_half = '', second_half = '') 2 | if word.length == 0 || word.length == 1 3 | return first_half == second_half 4 | end 5 | 6 | first_half += word.slice!(0) 7 | second_half += word.slice!(-1) 8 | 9 | is_palindrome?(word, first_half, second_half) 10 | end 11 | 12 | # palindromes 13 | raise 'This is a palindrome' unless is_palindrome?('a') 14 | raise 'this is a palindrome' unless is_palindrome?('racecar') 15 | raise 'this is a palindrome' unless is_palindrome?('abcddcba') 16 | 17 | # not palindromes 18 | raise 'this is not a palindrome' if is_palindrome?('abdcd') 19 | raise 'this is not a palindrome' if is_palindrome?('aalflkjad') 20 | raise 'this is not a palindrome' if is_palindrome?('abcdefdcba') 21 | -------------------------------------------------------------------------------- /algorithms/strings/anagram_search.rb: -------------------------------------------------------------------------------- 1 | FIRST_TWENTY_SIX_PRIMES = [ 2 | 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 3 | 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 4 | 79, 83, 89, 97, 101 ].freeze 5 | 6 | def anagram_number(word) 7 | word.downcase.chars.map do |letter| 8 | letter.ord - 'a'.ord 9 | end.reject do |index| 10 | index < 0 || index >= FIRST_TWENTY_SIX_PRIMES.size 11 | end.map do |index| 12 | FIRST_TWENTY_SIX_PRIMES[index] 13 | end.inject(:*) 14 | end 15 | 16 | def anagrams?(first_word, second_word) 17 | anagram_number(first_word) == anagram_number(second_word) 18 | end 19 | 20 | anagrams?('anagram', 'nag a ram') # true 21 | anagrams?('William Shakespeare', 'I am a weakish speller') # true 22 | anagrams?('Madam Curie', 'Radium came') # true 23 | anagrams?('notagram', 'notaflam') # false 24 | -------------------------------------------------------------------------------- /algorithms/dynamic-programming/longest_common_subsquence.rb: -------------------------------------------------------------------------------- 1 | require 'matrix' 2 | 3 | def max arg1, arg2 4 | arg1 > arg2 ? arg1 : arg2 5 | end 6 | # Dp using a hash 7 | def lcs str1, str2, ptr1, ptr2, hash 8 | if (ptr1 < 0 || ptr2 < 0) 9 | return 0 10 | end 11 | if hash[[ptr1, ptr2]] == -1 12 | result = -1 13 | if str1[ptr1] == str2[ptr2] 14 | result = 1 + lcs(str1, str2, ptr1 - 1, ptr2 - 1, hash) 15 | else 16 | result = max(lcs(str1, str2, ptr1 - 1, ptr2, hash), lcs(str1, str2, ptr1, ptr2 - 1, hash)) 17 | end 18 | hash[[ptr1, ptr2]] = result 19 | else 20 | result = hash[[ptr1, ptr2]] 21 | end 22 | return result 23 | end 24 | 25 | print "Enter The Two Strings\n" 26 | 27 | str1 = gets.chomp 28 | str2 = gets.chomp 29 | hash = Hash.new(-1) 30 | puts lcs(str1, str2, str1.length - 1, str2.length - 1, hash) 31 | -------------------------------------------------------------------------------- /algorithms/ciphers/baconian.rb: -------------------------------------------------------------------------------- 1 | BACONIAN_CODE = { 2 | 'a' => 'AAAAA', 'b' => 'AAAAB', 'c' => 'AAABA', 3 | 'd' => 'AAABB', 'e' => 'AABAA', 'f' => 'AABAB', 4 | 'g' => 'AABBA', 'h' => 'AABBB', 'i' => 'ABAAA', 5 | 'j' => 'BBBAA', 'k' => 'ABAAB', 'l' => 'ABABA', 6 | 'm' => 'ABABB', 'n' => 'ABBAA', 'o' => 'ABBAB', 7 | 'p' => 'ABBBA', 'q' => 'ABBBB', 'r' => 'BAAAA', 8 | 's' => 'BAAAB', 't' => 'BAABA', 'u' => 'BAABB', 9 | 'v' => 'BBBAB', 'w' => 'BABAA', 'x' => 'BABAB', 10 | 'y' => 'BABBA', 'z' => 'BABBB' 11 | }.freeze 12 | 13 | def encode(string) 14 | text = string.downcase.split('') 15 | encoded_text = [] 16 | 17 | text.each do |c| 18 | bac_char = BACONIAN_CODE[c] 19 | encoded_text.push(bac_char) 20 | end 21 | 22 | encoded_text.join('') 23 | end 24 | 25 | puts encode('Hello World') 26 | # => AABBBAABAAABABAABABAABBABBABAAABBABBAAAAABABAAAABB 27 | -------------------------------------------------------------------------------- /algorithms/data-structures/queue.rb: -------------------------------------------------------------------------------- 1 | class Queue 2 | 3 | class Node 4 | attr_accessor :next, :data 5 | 6 | def initialize(data) 7 | @data = data 8 | end 9 | end 10 | 11 | def enqueue(o) 12 | if @first.nil? 13 | @last = Node.new(o) 14 | @first = @last 15 | else 16 | @last.next = Node.new(o) 17 | @last = @last.next 18 | end 19 | end 20 | 21 | def dequeue 22 | unless @first.nil? 23 | node = @first 24 | @first = @first.next 25 | @last = nil if @first.nil? 26 | node.data 27 | end 28 | end 29 | 30 | end 31 | 32 | queue = Queue.new 33 | queue.enqueue("Test string") 34 | queue.enqueue(:test_symbol) 35 | queue.enqueue([1, 2, 3]) 36 | string = queue.dequeue 37 | symbol = queue.dequeue 38 | list = queue.dequeue 39 | 40 | puts "String #{string}" 41 | puts "Symbol #{symbol}" 42 | puts "List: #{list}" -------------------------------------------------------------------------------- /algorithms/sorting/merge_sort.rb: -------------------------------------------------------------------------------- 1 | # Ruby implementation of merge sort 2 | # 3 | # Author: Tae Noppakun Wongsrinoppakun 4 | 5 | def merge(left, right) 6 | result = [] 7 | left_index, right_index = 0, 0 8 | while (left_index < left.length && right_index < right.length) 9 | left_element = left[left_index] 10 | right_element = right[right_index] 11 | 12 | if left_element <= right_element 13 | result << left_element 14 | left_index += 1 15 | else 16 | result << right_element 17 | right_index += 1 18 | end 19 | end 20 | 21 | # add whatever is left from the left or right to the result 22 | if left 23 | result += left[left_index..-1] 24 | end 25 | if right 26 | result += right[right_index..-1] 27 | end 28 | 29 | return result 30 | end 31 | 32 | def merge_sort(m) 33 | if m.length <= 1 34 | return m 35 | end 36 | 37 | middle = m.length / 2 38 | left = m[0...middle] 39 | right = m[middle..-1] 40 | left = merge_sort(left) 41 | right = merge_sort(right) 42 | return merge(left, right) 43 | end -------------------------------------------------------------------------------- /algorithms/data-structures/is_binary_tree_bst.rb: -------------------------------------------------------------------------------- 1 | # A binary search tree (BST) is a node based binary tree data structure 2 | # Keys of the left subtree of a node should be less than the node key. 3 | # Keys of the right subtree of a node should be greater than the node key. 4 | # Both the left and right subtrees must also be binary search trees. 5 | # 6 | class Node 7 | attr_accessor :value, :left, :right 8 | 9 | def initialize(value) 10 | @value = value 11 | @left = nil 12 | @right = nil 13 | end 14 | end 15 | 16 | def bst?(node, lower_limit = nil, upper_limit = nil) 17 | return true if node.nil? 18 | return false if !upper_limit.nil? && upper_limit < node.value 19 | return false if !lower_limit.nil? && lower_limit > node.value 20 | 21 | is_left_bst = is_bst(node.left, lower_limit, node.value) 22 | is_right_bst = is_bst(node.right, node.value, upper_limit) 23 | 24 | is_left_bst && is_right_bst 25 | end 26 | 27 | root = Node.new(4) 28 | root.left = Node.new(3) 29 | root.right = Node.new(5) 30 | root.left.left = Node.new(1) 31 | root.left.right = Node.new(2) 32 | 33 | p is_bst(root) 34 | -------------------------------------------------------------------------------- /license: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2018 All Algorithms and its contributors (allalgorithms.com) 4 | Copyright (c) 2018 Carlos Abraham (abranhe.com) 5 | 6 | Permission is hereby granted, free of charge, to any person obtaining a copy 7 | of this software and associated documentation files (the "Software"), to deal 8 | in the Software without restriction, including without limitation the rights 9 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | copies of the Software, and to permit persons to whom the Software is 11 | furnished to do so, subject to the following conditions: 12 | 13 | The above copyright notice and this permission notice shall be included in all 14 | copies or substantial portions of the Software. 15 | 16 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 22 | SOFTWARE. -------------------------------------------------------------------------------- /algorithms/others/levenshtein_distance.rb: -------------------------------------------------------------------------------- 1 | # Source: https://devnull.absolventa.de/2015/11/24/exploring-levenshtein-algorithm-with-ruby/ 2 | # https://rosettacode.org/wiki/Levenshtein_distance#Ruby 3 | # In information theory, linguistics and computer science, the Levenshtein distance is a string 4 | # metric for measuring the difference between two sequences. Informally, the Levenshtein distance 5 | # between two words is the minimum number of single-character edits (insertions, deletions or substitutions) 6 | # required to change one word into the other. It is named after the Soviet mathematician Vladimir Levenshtein, 7 | # who considered this distance in 1965. source: https://en.wikipedia.org/wiki/Levenshtein_distance 8 | module Levenshtein 9 | def self.distance(a, b) 10 | a, b = a.downcase, b.downcase 11 | costs = Array(0..b.length) # i == 0 12 | (1..a.length).each do |i| 13 | costs[0], nw = i, i - 1 # j == 0; nw is lev(i-1, j) 14 | (1..b.length).each do |j| 15 | costs[j], nw = [costs[j] + 1, costs[j-1] + 1, a[i-1] == b[j-1] ? nw : nw + 1].min, costs[j] 16 | end 17 | end 18 | costs[b.length] 19 | end 20 | end 21 | 22 | # Example: 23 | # Just copy the code above into your irb console 24 | # Levenshtein.distance("hello", "hallo") #=> 1 25 | # Levenshtein.distance("aabb", "aaaa") #=> 2 26 | -------------------------------------------------------------------------------- /algorithms/data-structures/linked_list.rb: -------------------------------------------------------------------------------- 1 | class Node 2 | attr_accessor :data, :next 3 | 4 | def initialize(data) 5 | @data = data 6 | @next = nil 7 | end 8 | end 9 | 10 | class LinkedList 11 | attr_accessor :head 12 | 13 | def initialize 14 | @head = nil 15 | end 16 | 17 | # Inserts the element at the front of the list. 18 | def push(node) 19 | new_node = Node.new(node) 20 | new_node.next = @head 21 | @head = new_node 22 | end 23 | 24 | # Removes and returns the first element of the list. 25 | def pop 26 | temp = @head 27 | return nil if temp.nil? 28 | @head = temp.next 29 | temp.data 30 | end 31 | 32 | def remove(node) 33 | # Store head node 34 | temp = @head 35 | 36 | # If head node itself holds the key to be deleted 37 | unless temp.nil? 38 | if temp.data == node 39 | @head = temp.next 40 | return 41 | end 42 | end 43 | 44 | # Search for the key to be deleted, keep track of the 45 | # previous node as we need to change 'prev.next' 46 | until temp.nil? 47 | break if temp.data == node 48 | prev = temp 49 | temp = temp.next 50 | end 51 | 52 | # if key was not present in linked list 53 | return if temp.nil? 54 | 55 | # Unlink the node from linked list 56 | prev.next = temp.next 57 | end 58 | end 59 | 60 | list = LinkedList.new 61 | list.push(12) 62 | list.push(15) 63 | list.push(10) 64 | list.push(11) 65 | list.push(5) 66 | list.push(6) 67 | list.push(2) 68 | list.push(3) 69 | p list 70 | list.pop 71 | p list 72 | -------------------------------------------------------------------------------- /algorithms/others/thread_jruby.rb: -------------------------------------------------------------------------------- 1 | # used to call java code 2 | require 'java' 3 | 4 | # 'java_import' is used to import java classes 5 | java_import 'java.util.concurrent.Callable' 6 | java_import 'java.util.concurrent.FutureTask' 7 | java_import 'java.util.concurrent.LinkedBlockingQueue' 8 | java_import 'java.util.concurrent.ThreadPoolExecutor' 9 | java_import 'java.util.concurrent.TimeUnit' 10 | 11 | # Implement a callable class 12 | class CountMillion 13 | include Callable 14 | def call 15 | count = 0 16 | 1000000.times do 17 | count += 1 18 | end 19 | end 20 | end 21 | 22 | # Create a thread pool 23 | executor = ThreadPoolExecutor.new(4, # core_pool_treads 24 | 4, # max_pool_threads 25 | 60, # keep_alive_time 26 | TimeUnit::SECONDS, 27 | LinkedBlockingQueue.new) 28 | 29 | # Try counting to 1 million on 4 separate threads 20 times 30 | num_tests = 20 31 | num_threads = 4 32 | total_time = 0.0 33 | 34 | num_tests.times do |i| 35 | tasks = [] 36 | 37 | t_0 = Time.now 38 | num_threads.times do 39 | task = FutureTask.new(CountMillion.new) 40 | executor.execute(task) 41 | tasks << task 42 | end 43 | 44 | # Wait for all threads to complete 45 | tasks.each do |t| 46 | t.get 47 | end 48 | t_1 = Time.now 49 | 50 | time_ms = (t_1-t_0) * 1000.0 51 | puts "TEST #{i}: Time elapsed = #{time_ms}ms" 52 | total_time += time_ms 53 | end 54 | executor.shutdown() 55 | 56 | puts "Average completion time: #{total_time/num_tests}" 57 | -------------------------------------------------------------------------------- /algorithms/data-structures/trie.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | class Trie 4 | # root of the trie 5 | @@root = { 6 | ending: 0, # counter to keep track of how many strings are ending at that poing 7 | nodes: {} # hash of containing nodes 8 | } 9 | 10 | # method to insert string in the trie 11 | def insert(string) 12 | temp = @@root 13 | 14 | # traverse string char by char because order matters in trie 15 | string.each_char do |char| 16 | # if node is not present in trie then create a new node for that char otherwise juse do nothing 17 | if temp[:nodes][char].nil? 18 | temp[:nodes][char] = { 19 | ending: 0, 20 | nodes: {} 21 | } 22 | end 23 | # update the node to next node 24 | temp = temp[:nodes][char] 25 | end 26 | # finally make the ending +1 with means this string ending here 27 | temp[:ending] += 1 28 | end 29 | 30 | def search(string) 31 | temp = @@root 32 | 33 | # traverse string char by char because order matters in trie 34 | string.each_char do |char| 35 | # return false if any of sequential char isn't present 36 | return false if temp[:nodes][char].nil? 37 | 38 | temp = temp[:nodes][char] 39 | end 40 | 41 | # if ending is > 0 which means string is ending here, which mean string present in trie 42 | (temp[:ending]).positive? 43 | end 44 | 45 | def show 46 | puts @@root 47 | end 48 | end 49 | 50 | t = Trie.new 51 | t.insert('Hello World!') 52 | # will print the whole trie structure 53 | t.show 54 | t.search('Hello World!') 55 | t.search('Hello') 56 | t.insert('Hell') 57 | t.search('Hello') 58 | -------------------------------------------------------------------------------- /algorithms/others/jokenpo.rb: -------------------------------------------------------------------------------- 1 | def jokenpo(times) 2 | options = ['rock', 'paper', 'scissors'] 3 | one = 0 4 | two = 0 5 | 6 | while times > 0 7 | player_one = options.sample 8 | player_two = options.sample 9 | 10 | if player_one == player_two 11 | puts "Both chose #{player_one}. That's a tie, try again" 12 | elsif player_one == 'rock' && player_two == 'paper' 13 | two += 1 14 | puts "Player one chose: #{player_one} and Player Two chose: #{player_two}. Player Two Wins!" 15 | elsif player_one == 'rock' && player_two == 'scissors' 16 | one += 1 17 | puts "Player one chose: #{player_one} and Player Two chose: #{player_two}. Player One Wins!" 18 | elsif player_one == 'paper' && player_two == 'scissors' 19 | two += 1 20 | puts "Player one chose: #{player_one} and Player Two chose: #{player_two}. Player Two Wins!" 21 | elsif player_one == 'paper' && player_two == 'rock' 22 | one += 1 23 | puts "Player one chose: #{player_one} and Player Two chose: #{player_two}. Player One Wins!" 24 | elsif player_one == 'scissors' && player_two == 'rock' 25 | two += 1 26 | puts "Player one chose: #{player_one} and Player Two chose: #{player_two}. Player Two Wins!" 27 | else player_one == 'scissors' && player_two == 'paper' 28 | one += 1 29 | puts "Player one chose: #{player_one} and Player Two chose: #{player_two}. Player One Wins!" 30 | end 31 | 32 | times -= 1 33 | end 34 | 35 | if one > two 36 | puts 'Player One is the winner!' 37 | elsif two > one 38 | puts 'Player Two is the winner!' 39 | elsif two == one 40 | puts 'A boring tie' 41 | end 42 | end 43 | 44 | puts 'Enter the number of matches: ' 45 | 46 | times = gets.chomp.to_i 47 | 48 | jokenpo(times) 49 | -------------------------------------------------------------------------------- /algorithms/data-structures/binary_tree.rb: -------------------------------------------------------------------------------- 1 | class Node 2 | attr_accessor :value, :left, :right 3 | 4 | def initialize(data) 5 | @value = data 6 | @left = nil 7 | @right = nil 8 | end 9 | end 10 | 11 | class BinaryTree 12 | attr_accessor :root 13 | 14 | def initialize 15 | @root = nil 16 | end 17 | 18 | ## smaller value goes left, bigger value goes right, equal goes right 19 | def push_node(node, value) 20 | new_node = Node.new(value) 21 | if node 22 | if(value > node.value) 23 | if(node.right) 24 | push_node(node.right, value) 25 | else 26 | node.right = new_node 27 | end 28 | else 29 | if(node.left) 30 | push_node(node.left, value) 31 | else 32 | node.left = new_node 33 | end 34 | end 35 | else 36 | @root = new_node 37 | end 38 | end 39 | 40 | def traverse_left(node) 41 | if(node == nil) 42 | return 43 | end 44 | if(node.left) 45 | traverse_left(node.left) 46 | end 47 | p node.value 48 | if(node.right) 49 | traverse_left(node.right) 50 | end 51 | end 52 | 53 | def traverse_right(node) 54 | if(node == nil) 55 | return 56 | end 57 | if(node.right) 58 | traverse_right(node.right) 59 | end 60 | p node.value 61 | if(node.left) 62 | traverse_right(node.left) 63 | end 64 | end 65 | 66 | def traverse_in(node) 67 | if(node == nil) 68 | return 69 | end 70 | p node.value 71 | if(node.left) 72 | traverse_in(node.left) 73 | end 74 | if(node.right) 75 | traverse_in(node.right) 76 | end 77 | end 78 | 79 | end 80 | 81 | arr = [5,6,2,4,1,8,7,9,3]; 82 | btree = BinaryTree.new() 83 | arr.each{|e| btree.push_node(btree.root, e) } 84 | 85 | puts "In order Traversal" 86 | btree.traverse_in(btree.root) 87 | puts "Left order Traversal" 88 | btree.traverse_left(btree.root) 89 | puts "Right order Traversal" 90 | btree.traverse_right(btree.root) 91 | 92 | -------------------------------------------------------------------------------- /algorithms/searching/binary_search_tree.rb: -------------------------------------------------------------------------------- 1 | class BinarySearchTree 2 | class Node 3 | attr_reader :key, :left, :right 4 | 5 | def initialize( key ) 6 | @key = key 7 | @left = nil 8 | @right = nil 9 | end 10 | 11 | def insert( new_key ) 12 | if new_key <= @key 13 | @left.nil? ? @left = Node.new( new_key ) : @left.insert( new_key ) 14 | elsif new_key > @key 15 | @right.nil? ? @right = Node.new( new_key ) : @right.insert( new_key ) 16 | end 17 | end 18 | end 19 | 20 | def insert( key ) 21 | if @root.nil? 22 | @root = Node.new( key ) 23 | else 24 | @root.insert( key ) 25 | end 26 | end 27 | 28 | def pre_order(node=@root, &block) 29 | return if node.nil? 30 | yield node 31 | in_order(node.left, &block) 32 | in_order(node.right, &block) 33 | end 34 | 35 | def search( key, node=@root ) 36 | return nil if node.nil? 37 | if key < node.key 38 | search( key, node.left ) 39 | elsif key > node.key 40 | search( key, node.right ) 41 | else 42 | return node 43 | end 44 | end 45 | 46 | def check_height(node) 47 | return 0 if node.nil? 48 | 49 | leftHeight = check_height(node.left) 50 | return -1 if leftHeight == -1 51 | 52 | rightHeight = check_height(node.right) 53 | return -1 if rightHeight == -1 54 | 55 | diff = leftHeight - rightHeight 56 | if diff.abs > 1 57 | -1 58 | else 59 | [leftHeight, rightHeight].max + 1 60 | end 61 | end 62 | 63 | def is_balanced?(node=@root) 64 | check_height(node) == -1 ? false : true 65 | end 66 | 67 | end 68 | 69 | tree = BinarySearchTree.new 70 | tree.insert(50) 71 | tree.insert(25) 72 | tree.insert(75) 73 | tree.insert(12) 74 | tree.insert(37) 75 | tree.insert(87) 76 | tree.insert(63) 77 | puts tree.inspect 78 | puts "tree.is_balanced?" 79 | puts tree.is_balanced? 80 | 81 | puts "pre_order" 82 | tree.pre_order do |node| 83 | puts node.key 84 | end 85 | 86 | puts "in_order" 87 | tree.in_order do |node| 88 | puts node.key 89 | end 90 | 91 | puts "post_order" 92 | tree.post_order do |node| 93 | puts node.key 94 | end 95 | 96 | -------------------------------------------------------------------------------- /.github/code-of-conduct.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation. 6 | 7 | ## Our Standards 8 | 9 | Examples of behavior that contributes to creating a positive environment include: 10 | 11 | * Using welcoming and inclusive language 12 | * Being respectful of differing viewpoints and experiences 13 | * Gracefully accepting constructive criticism 14 | * Focusing on what is best for the community 15 | * Showing empathy towards other community members 16 | 17 | Examples of unacceptable behavior by participants include: 18 | 19 | * The use of sexualized language or imagery and unwelcome sexual attention or advances 20 | * Trolling, insulting/derogatory comments, and personal or political attacks 21 | * Public or private harassment 22 | * Publishing others' private information, such as a physical or electronic address, without explicit permission 23 | * Other conduct which could reasonably be considered inappropriate in a professional setting 24 | 25 | ## Our Responsibilities 26 | 27 | Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior. 28 | 29 | Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful. 30 | 31 | ## Scope 32 | 33 | This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers. 34 | 35 | ## Attribution 36 | 37 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [http://contributor-covenant.org/version/1/4][version] 38 | 39 | [homepage]: http://contributor-covenant.org 40 | [version]: http://contributor-covenant.org/version/1/4/ 41 | -------------------------------------------------------------------------------- /algorithms/others/knapsack.rb: -------------------------------------------------------------------------------- 1 | KnapsackItem = Struct.new(:name, :weight, :value) 2 | 3 | def dynamic_programming_knapsack(items, max_weight) 4 | num_items = items.size 5 | cost_matrix = Array.new(num_items){Array.new(max_weight+1, 0)} 6 | 7 | num_items.times do |i| 8 | (max_weight + 1).times do |j| 9 | if(items[i].weight > j) 10 | cost_matrix[i][j] = cost_matrix[i-1][j] 11 | else 12 | cost_matrix[i][j] = [cost_matrix[i-1][j], items[i].value + cost_matrix[i-1][j-items[i].weight]].max 13 | end 14 | end 15 | end 16 | used_items = get_used_items(items, cost_matrix) 17 | [get_list_of_used_items_names(items, used_items), # used items names 18 | items.zip(used_items).map{|item,used| item.weight*used}.inject(:+), # total weight 19 | cost_matrix.last.last] # total value 20 | end 21 | 22 | def get_used_items(items, cost_matrix) 23 | i = cost_matrix.size - 1 24 | currentCost = cost_matrix[0].size - 1 25 | marked = cost_matrix.map{0} 26 | 27 | while(i >= 0 && currentCost >= 0) 28 | if(i == 0 && cost_matrix[i][currentCost] > 0 ) || (cost_matrix[i][currentCost] != cost_matrix[i-1][currentCost]) 29 | marked[i] = 1 30 | currentCost -= items[i].weight 31 | end 32 | i -= 1 33 | end 34 | marked 35 | end 36 | 37 | def get_list_of_used_items_names(items, used_items) 38 | items.zip(used_items).map{|item,used| item.name if used>0}.compact.join(', ') 39 | end 40 | 41 | if $0 == __FILE__ 42 | items = [ 43 | KnapsackItem['map' , 9, 150], KnapsackItem['compass' , 13, 35], 44 | KnapsackItem['water' , 153, 200], KnapsackItem['sandwich' , 50, 160], 45 | KnapsackItem['glucose' , 15, 60], KnapsackItem['tin' , 68, 45], 46 | KnapsackItem['banana' , 27, 60], KnapsackItem['apple' , 39, 40], 47 | KnapsackItem['cheese' , 23, 30], KnapsackItem['beer' , 52, 10], 48 | KnapsackItem['suntan cream' , 11, 70], KnapsackItem['camera' , 32, 30], 49 | KnapsackItem['t-shirt' , 24, 15], KnapsackItem['trousers' , 48, 10], 50 | KnapsackItem['umbrella' , 73, 40], KnapsackItem['waterproof trousers', 42, 70], 51 | KnapsackItem['waterproof overclothes', 43, 75], KnapsackItem['note-case' , 22, 80], 52 | KnapsackItem['sunglasses' , 7, 20], KnapsackItem['towel' , 18, 12], 53 | KnapsackItem['socks' , 4, 50], KnapsackItem['book' , 30, 10] 54 | ] 55 | 56 | names, weight, value = dynamic_programming_knapsack(items, 400) 57 | puts 58 | puts 'Dynamic Programming:' 59 | puts 60 | puts "Found solution: #{names}" 61 | puts "total weight: #{weight}" 62 | puts "total value: #{value}" 63 | end -------------------------------------------------------------------------------- /algorithms/data-structures/djikstra.rb: -------------------------------------------------------------------------------- 1 | class Edge 2 | attr_accessor :src, :dst, :length 3 | 4 | def initialize(src, dst, length = 1) 5 | @src = src 6 | @dst = dst 7 | @length = length 8 | end 9 | end 10 | 11 | class Graph < Array 12 | attr_reader :edges 13 | 14 | def initialize 15 | @edges = [] 16 | end 17 | 18 | def connect(src, dst, length = 1) 19 | unless self.include?(src) 20 | raise ArgumentException, "No such vertex: #{src}" 21 | end 22 | unless self.include?(dst) 23 | raise ArgumentException, "No such vertex: #{dst}" 24 | end 25 | @edges.push Edge.new(src, dst, length) 26 | end 27 | 28 | def connect_mutually(vertex1, vertex2, length = 1) 29 | self.connect vertex1, vertex2, length 30 | self.connect vertex2, vertex1, length 31 | end 32 | 33 | def neighbors(vertex) 34 | neighbors = [] 35 | @edges.each do |edge| 36 | neighbors.push edge.dst if edge.src == vertex 37 | end 38 | return neighbors.uniq 39 | end 40 | 41 | def length_between(src, dst) 42 | @edges.each do |edge| 43 | return edge.length if edge.src == src and edge.dst == dst 44 | end 45 | nil 46 | end 47 | 48 | def dijkstra(src, dst = nil) 49 | distances = {} 50 | previouses = {} 51 | self.each do |vertex| 52 | distances[vertex] = nil # Infinity 53 | previouses[vertex] = nil 54 | end 55 | distances[src] = 0 56 | vertices = self.clone 57 | until vertices.empty? 58 | nearest_vertex = vertices.inject do |a, b| 59 | next b unless distances[a] 60 | next a unless distances[b] 61 | next a if distances[a] < distances[b] 62 | b 63 | end 64 | break unless distances[nearest_vertex] # Infinity 65 | if dst and nearest_vertex == dst 66 | return distances[dst] 67 | end 68 | neighbors = vertices.neighbors(nearest_vertex) 69 | neighbors.each do |vertex| 70 | alt = distances[nearest_vertex] + vertices.length_between(nearest_vertex, vertex) 71 | if distances[vertex].nil? or alt < distances[vertex] 72 | distances[vertex] = alt 73 | previouses[vertices] = nearest_vertex 74 | # decrease-key v in Q # ??? 75 | end 76 | end 77 | p nearest_vertex 78 | vertices.delete nearest_vertex 79 | end 80 | if dst 81 | return nil 82 | else 83 | return distances 84 | end 85 | end 86 | end 87 | 88 | graph = Graph.new 89 | (1..6).each {|node| graph.push node } 90 | graph.connect_mutually 1, 2, 7 91 | graph.connect_mutually 1, 3, 9 92 | graph.connect_mutually 1, 6, 14 93 | graph.connect_mutually 2, 3, 10 94 | graph.connect_mutually 2, 4, 15 95 | graph.connect_mutually 3, 4, 11 96 | graph.connect_mutually 3, 6, 2 97 | graph.connect_mutually 4, 5, 6 98 | graph.connect_mutually 5, 6, 9 99 | 100 | p graph 101 | p graph.length_between(2, 1) 102 | p graph.neighbors(1) 103 | p graph.dijkstra(1, 5) 104 | -------------------------------------------------------------------------------- /algorithms/cryptography/ed25519.rb: -------------------------------------------------------------------------------- 1 | require 'openssl' 2 | 3 | # Port of http://ed25519.cr.yp.to/python/ed25519.py 4 | 5 | @b = 256 6 | @q = 2**255 - 19 7 | @l = 2**252 + 27742317777372353535851937790883648493 8 | 9 | def H(m) 10 | OpenSSL::Digest::SHA512.digest(m) 11 | end 12 | 13 | def expmod(b,e,m) 14 | return 1 if e == 0 15 | t = expmod(b,e/2,m)**2 % m 16 | t = (t*b) % m if e & 1 != 0 17 | return t 18 | end 19 | 20 | def inv(x) 21 | expmod(x,@q-2,@q) 22 | end 23 | 24 | @d = -121665 * inv(121666) 25 | @I = expmod(2,(@q-1)/4,@q) 26 | 27 | def xrecover(y) 28 | xx = (y*y-1) * inv(@d*y*y+1) 29 | x = expmod(xx,(@q+3)/8,@q) 30 | x = (x*@I) % @q if (x*x - xx) % @q != 0 31 | x = @q-x if x % 2 != 0 32 | x 33 | end 34 | 35 | @By = 4 * inv(5) 36 | @Bx = xrecover(@By) 37 | @B = [@Bx % @q,@By % @q] 38 | 39 | def edwards(_P,_Q) 40 | x1 = _P[0] 41 | y1 = _P[1] 42 | x2 = _Q[0] 43 | y2 = _Q[1] 44 | x3 = (x1*y2+x2*y1) * inv(1+@d*x1*x2*y1*y2) 45 | y3 = (y1*y2+x1*x2) * inv(1-@d*x1*x2*y1*y2) 46 | return [x3 % @q,y3 % @q] 47 | end 48 | 49 | def scalarmult(_P,e) 50 | return [0,1] if e == 0 51 | _Q = scalarmult(_P,e/2) 52 | _Q = edwards(_Q,_Q) 53 | _Q = edwards(_Q,_P) if e & 1 != 0 54 | return _Q 55 | end 56 | 57 | def encodeint(y) 58 | bits = (0...@b).map{ |i| (y >> i) & 1} 59 | (0...@b/8).map{ |i|(0...8).map { |j| bits[i * 8 + j] << j}.sum.chr }.join 60 | end 61 | 62 | def encodepoint(_P) 63 | x = _P[0] 64 | y = _P[1] 65 | bits = (0...@b-1).map{|i| (y >> i ) & 1}.concat([x & 1]) 66 | (0...@b/8).map {|i|(0...8).map {|j| bits[i * 8 + j] << j}.sum.chr }.join 67 | end 68 | 69 | def bit(h,i) 70 | ((h[i/8]).ord >> (i%8)) & 1 71 | end 72 | 73 | def publickey(sk) 74 | h = H(sk) 75 | a = 2**(@b-2) + (3...@b-2).map{|i| 2**i * bit(h,i)}.sum 76 | _A = scalarmult(@B,a) 77 | encodepoint(_A) 78 | end 79 | 80 | def Hint(m) 81 | h = H(m) 82 | (0...2*@b).map {|i| 2**i * bit(h,i)}.sum 83 | end 84 | 85 | def signature(m,sk,pk) 86 | h = H(sk) 87 | a = 2**(@b-2) + (3...@b-2).map{|i| 2**i * bit(h,i)}.sum 88 | r = Hint((@b/8...@b/4).map { |i| h[i]}.join + m) 89 | _R = scalarmult(@B,r) 90 | _S = (r + Hint(encodepoint(_R) + pk + m) * a) % @l 91 | encodepoint(_R) + encodeint(_S) 92 | end 93 | 94 | def isoncurve(_P) 95 | x = _P[0] 96 | y = _P[1] 97 | (-x*x + y*y - 1 - @d*x*x*y*y) % @q == 0 98 | end 99 | 100 | def decodeint(s) 101 | (0...@b).map{|i| 2**i * bit(s,i)}.sum 102 | end 103 | 104 | def decodepoint(s) 105 | y = (0...@b-1).map{|i| 2**i * bit(s,i)}.sum 106 | x = xrecover(y) 107 | x = @q - x if x & 1 != bit(s,@b-1) 108 | _P = [x,y] 109 | raise ArgumentError, "decoding point that is not on curve" unless isoncurve(_P) 110 | _P 111 | end 112 | 113 | def checkvalid(s,m,pk) 114 | raise ArgumentError, "signature length is wrong" if s.length != @b/4 115 | raise ArgumentError, "public-key length is wrong "if pk.length != @b/8 116 | _R = decodepoint(s[0..@b/8]) 117 | _A = decodepoint(pk) 118 | _S = decodeint(s[@b/8..@b/4]) 119 | h = Hint(encodepoint(_R) + pk + m) 120 | raise "Signature does not pass verifiction" if scalarmult(@B,_S) != edwards(_R,scalarmult(_A,h)) 121 | end 122 | -------------------------------------------------------------------------------- /algorithms/cellular-automaton/conways_game_of_life.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | # Conway's Game of Life 3 | # 4 | # Author: Sebastian Sangervasi 5 | 6 | class GameOfLife 7 | def self.from_str(string) 8 | non_empty_lines = 9 | string 10 | .split("\n") 11 | .lazy 12 | .map(&:strip) 13 | .reject(&:empty?) 14 | 15 | parsed_grid = non_empty_lines.lazy.map do |line| 16 | lazy_line = line.split('').lazy.map do |char| 17 | Cell.from_str(char) 18 | end 19 | lazy_line.to_a 20 | end 21 | 22 | new(grid: parsed_grid.to_a) 23 | end 24 | 25 | def initialize(grid:) 26 | @grid = grid 27 | end 28 | 29 | attr_reader :grid 30 | 31 | def height 32 | grid.size 33 | end 34 | 35 | def width 36 | grid.first&.size || 0 37 | end 38 | 39 | def to_s 40 | str_rows = grid.map do |row| 41 | row.map(&:to_s).join 42 | end 43 | str_rows.join("\n") 44 | end 45 | 46 | def next_generation 47 | lazy_grid = grid_with_live_neighbor_counts.map do |row| 48 | lazy_row = row.map do |cell, neighbor_count| 49 | cell.next_state(neighbor_count) 50 | end 51 | lazy_row.to_a 52 | end 53 | 54 | self.class.new(grid: lazy_grid.to_a) 55 | end 56 | 57 | private 58 | 59 | def grid_with_live_neighbor_counts 60 | grid.lazy.each_with_index.map do |row, row_index| 61 | row.lazy.each_with_index.map do |cell, cell_index| 62 | [cell, count_live_neighbors(row_index, cell_index)] 63 | end 64 | end 65 | end 66 | 67 | def count_live_neighbors(row, col) 68 | neighbor_coords = neighbor_directions.map do |d_row, d_col| 69 | [row + d_row, col + d_col] 70 | end 71 | neighbors = neighbor_coords.lazy.map do |row, col| 72 | get_cell(row, col, default: Dead.new) 73 | end 74 | neighbors.map { |cell| cell.alive? ? 1 : 0 }.sum 75 | end 76 | 77 | def neighbor_directions 78 | @neighbor_directions ||= begin 79 | directions_1D = [-1, 0, 1] 80 | directions_1D 81 | .product(directions_1D) 82 | .reject { |pair| pair == [0, 0] } 83 | end 84 | end 85 | 86 | def get_cell(row, col, default: nil) 87 | is_within_rows = (0...height).cover?(row) 88 | is_within_cols = (0...width).cover?(col) 89 | return grid[row][col] if is_within_rows && is_within_cols 90 | 91 | default 92 | end 93 | end 94 | 95 | class Cell 96 | def self.from_str(string) 97 | return Live.new if string == Live::STRING_FORM 98 | Dead.new 99 | end 100 | 101 | def to_s 102 | self.class::STRING_FORM 103 | end 104 | end 105 | 106 | class Dead < Cell 107 | STRING_FORM = '·' 108 | 109 | def alive? 110 | false 111 | end 112 | 113 | def next_state(neighbor_count) 114 | return Live.new if neighbor_count == 3 115 | Dead.new 116 | end 117 | end 118 | 119 | class Live < Cell 120 | STRING_FORM = '0' 121 | 122 | def alive? 123 | true 124 | end 125 | 126 | def next_state(neighbor_count) 127 | return Live.new if (2..3).cover?(neighbor_count) 128 | Dead.new 129 | end 130 | end 131 | 132 | def glider_example 133 | seed_str = <<~GLIDER 134 | ··0···· 135 | 0·0···· 136 | ·00···· 137 | ······· 138 | ······· 139 | ······· 140 | GLIDER 141 | seed_game = GameOfLife.from_str(seed_str) 142 | num_gens = 15 143 | puts <<~HEADER 144 | ========================= 145 | | Conway's Game of Life | 146 | ========================= 147 | Starting with seed: "Glider" 148 | Running for #{num_gens} generations. 149 | HEADER 150 | latest_generation = seed_game 151 | (1..num_gens).map do |gen_num| 152 | puts "Generation #{gen_num}:" 153 | puts latest_generation 154 | latest_generation = latest_generation.next_generation 155 | end 156 | end 157 | 158 | if __FILE__ == $0 159 | glider_example 160 | end 161 | -------------------------------------------------------------------------------- /algorithms/graphs/bfs.rb: -------------------------------------------------------------------------------- 1 | # This class represents a node in a graph. 2 | # It has a NAME and an ID and each node knows which nodes it is connected to. 3 | class GraphNode 4 | require 'set' 5 | @@id = 0 6 | 7 | attr_reader :name, :id, :connections 8 | 9 | def initialize(name) 10 | @name = name 11 | @id = (@@id += 1) 12 | @connections = Set.new 13 | end 14 | 15 | def connect(node) 16 | return false unless node.is_a? GraphNode 17 | @connections << node 18 | end 19 | 20 | def equal?(other) 21 | return false unless other.is_a? GraphNode 22 | @name == other.name && @id == other.id 23 | end 24 | 25 | def to_s 26 | "" 27 | end 28 | 29 | def to_str 30 | to_s 31 | end 32 | end 33 | 34 | # A simple function as a default function performed for each node in bfs() 35 | def goalNode?(node) 36 | node.name == 'Goal' 37 | end 38 | 39 | # Given a start node and a function or code block this performs a bread first search and will exit upon function or code block returning true, or returns :goal_node_not_found when it has visited the whole graph. 40 | # 41 | # visited is a set containing all nodes that has been checked. 42 | # frontier is a queue were new nodes are appended, making this a breadth first search. 43 | def bfs(start, goal = :goalNode?) 44 | require 'set' 45 | visited = Set.new 46 | frontier = [] 47 | frontier << start 48 | 49 | until frontier.empty? 50 | current = frontier.shift 51 | 52 | next if visited.include? current 53 | visited << current 54 | 55 | found = false 56 | found = if block_given? 57 | yield(current) 58 | else 59 | send(goal, current) 60 | end 61 | 62 | if !found 63 | current.connections.each do |node| 64 | frontier << node 65 | end 66 | else 67 | return current 68 | end 69 | end 70 | :goal_node_not_found 71 | end 72 | 73 | # A small test that will use bfs() for root node First, then for the Second node. 74 | # The bfs accepts a code block, and here we just print each visited node and will never find the goal-node. 75 | # 76 | # The tests output: 77 | # Testing from root node 'First' 78 | # 79 | # 80 | # 81 | # 82 | # 83 | # 84 | # 85 | # goal_node_not_found 86 | # Testing from second node 'Second' 87 | # 88 | # 89 | # 90 | # 91 | # 92 | # 93 | # 94 | # goal_node_not_found 95 | def test 96 | puts 'Building Graph for tests...' 97 | # Simple graph 98 | # 99 | # First 100 | # / \ 101 | # second third 102 | # / | | \ 103 | # fourth fifth goal sixth 104 | # 105 | # Construct graph 106 | first = GraphNode.new 'First' 107 | second = GraphNode.new 'Second' 108 | third = GraphNode.new 'Third' 109 | fourth = GraphNode.new 'Fourth' 110 | fifth = GraphNode.new 'Fifth' 111 | sixth = GraphNode.new 'Sixth' 112 | goal = GraphNode.new 'Goal' 113 | 114 | first.connect second 115 | first.connect third 116 | 117 | second.connect first 118 | second.connect fourth 119 | second.connect fifth 120 | 121 | third.connect first 122 | third.connect goal 123 | third.connect sixth 124 | 125 | fourth.connect second 126 | fifth.connect second 127 | 128 | goal.connect third 129 | sixth.connect third 130 | 131 | # Perform tests 132 | puts "Testing from root node 'First'" 133 | puts(bfs(first) { |node| puts ' ' + node }) 134 | 135 | puts "Testing from second node 'Second'" 136 | puts(bfs(second) { |node| puts ' ' + node }) 137 | end 138 | 139 | test if $PROGRAM_NAME == __FILE__ 140 | -------------------------------------------------------------------------------- /algorithms/ciphers/playfair.rb: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | 3 | alphabet = "abcdefghijlmnopqrstuvwxyz".upcase 4 | 5 | def vetorize(text) 6 | listText = [] 7 | text.each_char{|c| listText << c} 8 | return listText 9 | end 10 | 11 | def normalizeMessage(text) 12 | newText = [] 13 | text = text.upcase 14 | text = text.gsub(" ", "") 15 | text = text.gsub(".", "") 16 | text = text.gsub(",", "") 17 | pos = 0 18 | while pos < text.length - 1 19 | firstLetter = text[pos] 20 | secondLetter = text[pos + 1] 21 | if firstLetter == secondLetter 22 | if firstLetter == "X" 23 | newText << firstLetter 24 | newText << "Z" 25 | pos += 1 26 | else 27 | newText << firstLetter 28 | newText << "X" 29 | pos += 1 30 | end 31 | else 32 | newText << firstLetter 33 | newText << secondLetter 34 | pos += 2 35 | end 36 | end 37 | if pos < text.length 38 | if text[-1] == "X" 39 | newText << text[pos] 40 | newText << "Z" 41 | else 42 | newText << text[pos] 43 | newText << "X" 44 | end 45 | end 46 | return newText 47 | end 48 | 49 | def createMatrix() 50 | matrix = [] 51 | 5.times do 52 | matrix << [] 53 | end 54 | return matrix 55 | end 56 | 57 | def mountGrid(matrix, key, alphabet) 58 | alphabet = vetorize(alphabet) 59 | line, column, pos = 0, 0, 0 60 | key.split("").each do |letter| 61 | line = pos / 5 62 | column = pos % 5 63 | if alphabet.include?(letter) 64 | alphabet.remove(letter) 65 | matrix[line][column] = letter 66 | pos += 1 67 | end 68 | end 69 | while alphabet.length > 0 70 | line = pos / 5 71 | column = pos % 5 72 | matrix[line][column] = alphabet.shift 73 | pos += 1 74 | end 75 | return matrix 76 | end 77 | 78 | def getIndex(letter, matrix) 79 | for i in (0...5) 80 | for j in (0...5) 81 | if matrix[i][j] == letter 82 | return [i, j] 83 | end 84 | end 85 | end 86 | end 87 | 88 | def encrypt(message, key, alphabet) 89 | message = message.upcase 90 | matrix = mountGrid(createMatrix(), key, alphabet) 91 | message = normalizeMessage(message) 92 | messageEncrypted = "" 93 | pos, line, column = 0, 0, 1 94 | while pos < message.length - 1 95 | firstLetter = message[pos] 96 | secondLetter = message[pos + 1] 97 | indexFirstLetter = getIndex(firstLetter, matrix) 98 | indexSecondLetter = getIndex(secondLetter, matrix) 99 | if indexFirstLetter[line] == indexSecondLetter[line] 100 | messageEncrypted += matrix[indexFirstLetter[line]][(indexFirstLetter[column] + 1) % 5] 101 | messageEncrypted += matrix[indexSecondLetter[line]][(indexSecondLetter[column] + 1) % 5] 102 | elsif indexFirstLetter[column] == indexSecondLetter[column] 103 | messageEncrypted += matrix[(indexFirstLetter[line] + 1) % 5][indexFirstLetter[column]] 104 | messageEncrypted += matrix[(indexSecondLetter[line] + 1) % 5][indexSecondLetter[column]] 105 | else 106 | messageEncrypted += matrix[indexFirstLetter[line]][indexSecondLetter[column]] 107 | messageEncrypted += matrix[indexSecondLetter[line]][indexFirstLetter[column]] 108 | end 109 | pos += 2 110 | end 111 | return messageEncrypted 112 | end 113 | 114 | def decrypt(messageEncrypted, key, alphabet) 115 | messageEncrypted = messageEncrypted.upcase 116 | matrix = mountGrid(createMatrix(), key, alphabet) 117 | messageDecrypted = "" 118 | pos, line, column = 0, 0, 1 119 | while pos < messageEncrypted.length 120 | firstLetter = messageEncrypted[pos] 121 | secondLetter = messageEncrypted[pos + 1] 122 | indexFirstLetter = getIndex(firstLetter, matrix) 123 | indexSecondLetter = getIndex(secondLetter, matrix) 124 | if indexFirstLetter[line] == indexSecondLetter[line] 125 | messageDecrypted += matrix[indexFirstLetter[line]][(indexFirstLetter[column] - 1) % 5] 126 | messageDecrypted += matrix[indexSecondLetter[line]][(indexSecondLetter[column] - 1) % 5] 127 | elsif indexFirstLetter[column] == indexSecondLetter[column] 128 | messageDecrypted += matrix[(indexFirstLetter[line] - 1) % 5][indexFirstLetter[column]] 129 | messageDecrypted += matrix[(indexSecondLetter[line] - 1) % 5][indexSecondLetter[column]] 130 | else 131 | messageDecrypted += matrix[indexFirstLetter[line]][indexSecondLetter[column]] 132 | messageDecrypted += matrix[indexSecondLetter[line]][indexFirstLetter[column]] 133 | end 134 | pos += 2 135 | end 136 | return messageDecrypted 137 | end 138 | 139 | alphabet = "abcdefghijlmnopqrstuvwxyz".upcase 140 | puts encrypt("insert your text", "test", alphabet) 141 | puts decrypt("insert your text", "test", alphabet) -------------------------------------------------------------------------------- /readme.md: -------------------------------------------------------------------------------- 1 | We are accepting all pull requests. [Read More](https://github.com/AllAlgorithms/algorithms/issues/40) 2 | 3 |
4 |
5 |
6 |
7 |
8 | Algorithms Logo 9 |
10 |
11 |
12 |
13 |
14 |
15 | 16 |

17 | What is an algorithm?    18 | Contributing    19 | Stickers & T-Shirts 20 |

21 | 22 | 23 |

24 | 25 | Twitter 26 |     27 | 28 | Instagram 29 |     30 | 31 | Github 32 |     33 |

34 | 35 |
36 |

37 | Huge collection of All ▲lgorithms implemented in multiple languages 38 |

39 |
40 | 41 | 42 | 43 | 44 | 45 | 46 |
47 | 48 | ## See 49 | 50 | - [What is an algorithm](#what-is-an-algorithm) 51 | - [Contributing](https://github.com/AllAlgorithms/algorithms/blob/master/.github/contributing.md) 52 | - [Code of Conduct](https://github.com/AllAlgorithms/algorithms/blob/master/.github/code-of-conduct.md) 53 | - [Stickers and T-Shirts](https://www.redbubble.com/people/abranhe/works/34285088) 54 | - [Twitter](https://twitter.com/AllAlgorithms) 55 | - [Instagram](https://instagram.com/AllAlgorithms) 56 | - [Algorithms Categories](#categories) 57 | - [Maintainers](#maintainers) 58 | - [License](#license) 59 | 60 | 61 | ## What is an algorithm? 62 | 63 | Informally, an algorithm is any well-defined computational procedure that takes 64 | some value, or set of values, as input and produces some value, or set of values, as 65 | output. An algorithm is thus a sequence of computational steps that transform the 66 | input into the output. 67 | 68 | An algorithm should have three important characteristics to be considered valid: 69 | 70 | - **It should be finite**: If your algorithm never ends trying to solve the problem 71 | it was designed to solve then it is useless 72 | - **It should have well defined instructions**: Each step of the algorithm has to 73 | be precisely defined; the instructions should be unambiguously specified for each case. 74 | - **It should be effective**: The algorithm should solve the problem it was designed 75 | to solve. And it should be possible to demonstrate that the algorithm converges with 76 | just a paper and pencil. 77 | 78 | ## Categories 79 | 80 | > Structure of The All ▲lgoritms project 81 | 82 | - [Artificial Intelligence](#artificial-intelligence) 83 | - [Backtracking](#backtracking) 84 | - [Bit Manipulation](#bit-manipulation) 85 | - [Cellular Automaton](#cellular-automaton) 86 | - [Ciphers](#ciphers) 87 | - [Computational Geometry](#computational-geometry) 88 | - [Cryptography](#cryptography) 89 | - [Data Structures](#data-structures) 90 | - [Divide and conquer](#divide-and-conquer) 91 | - [Dynamic Programming](#dynamic-programming) 92 | - [Gaming Theory](#gaming-theory) 93 | - [Graphs](#graphs) 94 | - [Greedy Algorithms](#greedy-algorithms) 95 | - [Math](#math) 96 | - [Networking](#networking) 97 | - [Numerical Analysis](#numerical-analysis) 98 | - [Operating system](#operating-system) 99 | - [Randomized Algorithms](#randomized-algorithms) 100 | - [Searches](#searches) 101 | - [Selections Algorithms](#selections-algorithms) 102 | - [Sorting](#sorting) 103 | - [Strings](#strings) 104 | - [Online Challenges](#online-challenges) 105 | - [Others](#others) 106 | 107 | ## [Artificial Intelligence](artificial-intelligence) 108 | 109 | - [Density-based spatial clustering of applications with noise (DBSCAN Clustering)](https://allalgorithms.com/docs/dbscan) 110 | - [Interactive Self-Organizing Data Analysis Technique yAy! (ISODATA Clustering)](https://allalgorithms.com/docs/isodata) 111 | - [Linear Regression](https://allalgorithms.com/docs/linear-regression) 112 | - [Logistic Regression](https://allalgorithms.com/docs/logistic-regression) 113 | - [Neutral Style Transfer](https://allalgorithms.com/docs/neutral-style-transfer) 114 | - [SATisfiable (SAT)](https://allalgorithms.com/docs/sat) 115 | - [Travelling salesman problem (TSP)](https://allalgorithms.com/docs/tsp) 116 | - [A* (A Star)](https://allalgorithms.com/docs/a-star) 117 | - [Artificial Neutral Network](https://allalgorithms.com/docs/artificial-neutral-network) 118 | - [Convolutional Neutral Network](https://allalgorithms.com/docs/convolutional-neutral-network) 119 | - [Decision Tree](https://allalgorithms.com/docs/decision-tree) 120 | - [Factorization Machines](https://allalgorithms.com/docs/factorization-machines) 121 | - [Gaussian Mixture Model](https://allalgorithms.com/docs/gaussian-mixtrue-model) 122 | - [Gradient Boosting Trees](https://allalgorithms.com/docs/gradient-boostring-trees) 123 | - [Hierachical Clustering](https://allalgorithms.com/docs/hierachical-clustering) 124 | - [Image Processing](https://allalgorithms.com/docs/image-processing) 125 | - [K Nearest Neighbors](https://allalgorithms.com/docs/k-nearest-neighbors) 126 | - [K Means](https://allalgorithms.com/docs/k-means) 127 | - [Minimax](https://allalgorithms.com/docs/minimax) 128 | - [Native Bayes](https://allalgorithms.com/docs/native-bayes) 129 | - [Nearest Sequence Memory](https://allalgorithms.com/docs/nearest-sequence-memory) 130 | - [Neutral Network](https://allalgorithms.com/docs/neutral-network) 131 | - [Perceptron](https://allalgorithms.com/docs/perceptron) 132 | - [Principal Component Analysis](https://allalgorithms.com/docs/principal-component-analysis) 133 | - [Q Learing](https://allalgorithms.com/docs/q-learning) 134 | - [Random Forests](https://allalgorithms.com/docs/random-forest) 135 | - [Restricted Boltzman Machine](https://allalgorithms.com/docs/restricted-boltzman-machine) 136 | 137 | ## [Backtracking](backtracking) 138 | 139 | - [Algorithm X](backtracking/algorithm-x) 140 | - [Crossword Puzzle](backtracking/crossword-Puzzle) 141 | - [Knight Tour](backtracking/knight-tour) 142 | - [M Coloring Problem](backtracking/m-coloring-problem) 143 | - [N Queen](backtracking/n-queen) 144 | - [Number of ways in Maze](backtracking/number-of-ways-in-maze) 145 | - [Partitions of set](backtracking/partitions-of-set) 146 | - [Permutation of Strings](backtracking/permutation-of-strings) 147 | - [Powerset](backtracking/powerset) 148 | - [Rat in maze](backtracking/rat-in-maze) 149 | - [Subset Sum](backtracking/subset-sum) 150 | - [Sudoku Solve](backtracking/sudoku-solve) 151 | 152 | ## [Bit Manipulation](bit-manipulation) 153 | 154 | - [Addition using bits](bit-manipulation/adding-using-bits) 155 | - [Bit divisor](bit-manipulation/bit-divisor) 156 | - [Byte swapper](bit-manipulation/byte-swapper) 157 | - [Convert numbers to binary](bit-manipulation/convert-numbers-to-binary) 158 | - [Count set bits](bit-manipulation/count-set-bits) 159 | - [Flip bits](bit-manipulation/flip-bits) 160 | - [Hamming distance](bit-manipulation/hamming-distace) 161 | - [Invert bit](bit-manipulation/invert-bit) 162 | - [Lonely integer](bit-manipulation/lonely-integer) 163 | - [Magic Number](bit-manipulation/magic-number) 164 | - [Maximum XOR Value](bit-manipulation/maximun-xor-value) 165 | - [Power of 2](bit-manipulation/power-of-2) 166 | - [Subset Generation](bit-manipulation/subset-generation) 167 | - [Sum binary numbers](bit-manipulation/sum-binary-numbers) 168 | - [Sum equals XOR](bit-manipulation/sum-equals-xor) 169 | - [Thrice unique number](bit-manipulation/thrice-unique-number) 170 | - [Twice unique number](bit-manipulation/twice-unique-number) 171 | - [XOR Swap](bit-manipulation/xor-swap) 172 | 173 | ## [Cellular Automaton](cellular-automaton) 174 | 175 | - [Brians Brain](cellular-automaton/brians-brain) 176 | - [Conways Game of life](cellular-automaton/conways-game-of-life) 177 | - [Elementary Cellular Automata](cellular-automaton/elementary-cellular-automata) 178 | - [Generic Algorithm](cellular-automaton/generic-algorithm) 179 | - [Langtons Ant](cellular-automaton/langtons-ant) 180 | - [Nobili Cellular Automata](cellular-automaton/nobili-cellular-automata) 181 | - [Von Neoumann Cellular Automata](cellular-automaton/von-neoumann-cellular-automata) 182 | 183 | ## [Computational Geometry](computational-geometry) 184 | 185 | - [2D Line intersection](computational-geometry/) 186 | - [2D Separating Axis test](computational-geometry/) 187 | - [Area of polygon](computational-geometry/) 188 | - [Area of triangle](computational-geometry/) 189 | - [Axis aligned bounding box collision](computational-geometry/) 190 | - [Bresenham Line](computational-geometry/) 191 | - [Chans Algorithm](computational-geometry/) 192 | - [Cohen Sutherland Lineclip](computational-geometry/) 193 | - [Distance between points](computational-geometry/) 194 | - [Graham Scan](computational-geometry/) 195 | - [Halfplane intersection](computational-geometry/) 196 | - [Jarvis March](computational-geometry/) 197 | - [Quickull](computational-geometry/) 198 | - [Sphere tetrahedron intersection](computational-geometry/) 199 | - [Sutherland Hodgeman clipping](computational-geometry/) 200 | 201 | ## [Cryptography](cryptography) 202 | 203 | - [Affine Cipher](cryptography/) 204 | - [Atbash Cipher](cryptography/) 205 | - [Autokey Cipher](cryptography/) 206 | - [Baconian Cipher](cryptography/) 207 | - [Caesar Cipher](cryptography/) 208 | - [Colummnar Cipher](cryptography/) 209 | - [Vigenere Cipher](cryptography/) 210 | 211 | ## [Data Structures](data-structures) 212 | 213 | - [Bag](data-structures/bag/) 214 | - [Hashes](data-structures/hashes/) 215 | - [Linked List](data-structures/linked-list/) 216 | - [List](data-structures/list/) 217 | - [Queue](data-structures/queue/) 218 | - [Stack](data-structures/stack/) 219 | - [Tree](data-structures/tree/) 220 | 221 | ## [Divide and conquer](divide-and-conquer) 222 | 223 | - [Strassen Matrix Manipulation](divide-and-conquer/) 224 | - [Closest Pair of Point](divide-and-conquer/) 225 | - [Inversion Count](divide-and-conquer/) 226 | - [Karatsuba Multiplication](divide-and-conquer/) 227 | - [Maximum Contiguous subsequence sum](divide-and-conquer/) 228 | - [Merge Sort using divide and conquer](divide-and-conquer/) 229 | - [Quick Sort using divide and conquer](divide-and-conquer/) 230 | - [Tournament Method to find min max](divide-and-conquer/) 231 | - [Warnock Algorithm](divide-and-conquer/) 232 | - [X Power Y](divide-and-conquer/) 233 | 234 | ## [Dynamic Programming](dynamic-programming) 235 | 236 | - [Array Median](dynamic-programming) 237 | - [Optima Binary Search Tree](dynamic-programming) 238 | - [Binomial Coefficient](dynamic-programming) 239 | 240 | ## [Gaming Theory](gaming-theory) 241 | 242 | - [Nim Next Best Move Game](gaming-theory/) 243 | - [Nim Win Loss Game](gaming-theory/) 244 | - [Grundy Numbers Kayle Game](gaming-theory/) 245 | 246 | ## [Graphs](graphs) 247 | 248 | - [Bipartite Check](graphs/) 249 | - [Adjacency Lists graphs representation](graphs/) 250 | - [A* (A Star)](https://allalgorithms.com/docs/a-star) 251 | 252 | ## [Greedy Algorithms](greedy-algorithms) 253 | 254 | - [Activity Selection](greedy-algorithms) 255 | - [Dijkstra Shortest Path](greedy-algorithms) 256 | - [Egyptian Fraction](greedy-algorithms) 257 | 258 | ## [Math](math) 259 | 260 | - [2 Sum](math/) 261 | - [Add Polynomials](math/) 262 | - [Amicable Numbers](math/) 263 | - [Armstrong Numbers](math/) 264 | - [Automorphic Numbers](math/) 265 | - [Average Stream Numbers](math/) 266 | - [Babylonian Method](math/) 267 | - [Binomial Coefficient](math/) 268 | - [Catalan Number](math/) 269 | - [Check is Square](math/) 270 | - [Convolution](math/) 271 | - [Coprime Numbers](math/) 272 | - [Count Digits](math/) 273 | - [Count Trailing Zeroes](math/) 274 | - [Decoding of String](math/) 275 | - [Delannoy Number](math/) 276 | - [Derangements](math/) 277 | - [DFA Division](math/) 278 | - [Diophantine](math/) 279 | - [Divided Differences](math/) 280 | - [Euler Totient](math/) 281 | - [Exponentiation Power](math/) 282 | - [Factorial](math/factorial) 283 | - [Fast Fourier transform](math/) 284 | - [Fast inverse (sqrt) Square Root](math/) 285 | 286 | ## [Networking](networking) 287 | 288 | - [Packet Sniffer](networking/) 289 | - [Determine Endianess](networking/) 290 | - [Validate IP](networking/) 291 | 292 | ## [Numerical Analysis](numerical-analysis) 293 | 294 | - [Integral](numerical-analysis/integral) 295 | - [Monte Carlo](numerical-analysis/monte-carlo) 296 | - [Runge Kutt](numerical-analysis/runge-kutt) 297 | 298 | ## [Operating system](operating-system) 299 | 300 | - [Currency](operating-system/) 301 | - [Deadlocks](operating-system/) 302 | - [Memory Management](operating-system/) 303 | - [Scheduling](operating-system/) 304 | - [Shell](operating-system/) 305 | 306 | ## [Randomized Algorithms](randomized-algorithms) 307 | 308 | - [Birthday Paradox](randomized-algorithms) 309 | - [Karger Minimum Cut Algorithm](randomized-algorithms) 310 | - [Kth Smallest Element Algorithm](randomized-algorithms) 311 | - [Random from Stream](randomized-algorithms) 312 | - [Random Node Linked list](randomized-algorithms) 313 | - [Randomized Quicksort](randomized-algorithms) 314 | - [Reservoir Sampling](randomized-algorithms) 315 | - [Shuffle an Array](randomized-algorithms) 316 | 317 | ## [Searches](searches) 318 | 319 | - [Binary Search](searches) 320 | - [Exponential Search](searches) 321 | - [Fibonacci Search](searches) 322 | - [Fuzzy Search](searches) 323 | - [Interpolation Search](searches) 324 | - [Jump Search](searches) 325 | - [Linear Search](searches) 326 | - [Ternay Search](searches) 327 | 328 | ## [Selections Algorithms](selections-algorithms) 329 | 330 | - [Median of Medians](selections-algorithms) 331 | - [Quick Select](selections-algorithms) 332 | 333 | ## [Sorting](sorting) 334 | 335 | - [Bead Sort](sorting/) 336 | - [Bogo Sort](sorting/) 337 | - [Bubble Sort](sorting/) 338 | - [Bucket Sort](sorting/) 339 | - [Circle Sort](sorting/) 340 | - [Comb Sort](sorting/) 341 | - [Counting Sort](sorting/) 342 | - [Cycle Sort](sorting/) 343 | - [Flash Sort](sorting/) 344 | - [Gnome Sort](sorting/) 345 | - [Heap Sort](sorting/) 346 | - [Insertion Sort](sorting/) 347 | - [Intro Sort](sorting/) 348 | - [Median Sort](sorting/) 349 | - [Merge Sort](sorting/) 350 | - [Pipeonhole Sort](sorting/) 351 | - [Quick Sort](sorting/) 352 | - [Radix Sort](sorting/) 353 | - [Selection Sort](sorting/) 354 | - [Shaker Sort](sorting/) 355 | - [Shell Sort](sorting/) 356 | - [Sleep Sort](sorting/) 357 | - [Stooge Sort](sorting/) 358 | - [Topological Sort](sorting/) 359 | - [Tree Sort](sorting/) 360 | 361 | ## [Strings](strings) 362 | 363 | - [Aho Corasick Algorithm](strings) 364 | - [Anagram Search](strings) 365 | - [Arithmetic on large numbers](strings) 366 | - [Boyer Moore Algorithm](strings) 367 | - [Finite Automata](strings) 368 | - [Kasai Algorithm](strings) 369 | - [Kmp Algorithm](strings) 370 | - [Levenshteing Distance](strings) 371 | - [Lipogram Checker](strings) 372 | 373 | ## [Online Challenges](online-challenges) 374 | 375 | - [Coderbyte](online-challenges/coderbyte) 376 | - [Code Chef](online-challenges/code-chef) 377 | - [Code Eval](online-challenges/code-eval) 378 | - [Hackerearth](online-challenges/hackerearth) 379 | - [Hackerrank](online-challenges/hackerrank) 380 | - [LeetCode](online-challenges/leetcode) 381 | - [Project Euler](online-challenges/project-euler) 382 | - [Rosalind](online-challenges/rosalind) 383 | - [SPOJ](online-challenges/spoj) 384 | - [Top Coder](online-challenges/top-coder)` 385 | 386 | ## [Others](others) 387 | 388 | - [Average](others/) 389 | - [Biggest of n numbers](others/) 390 | - [Biggest Suffix](others/) 391 | - [Fifteen Puzzle](others/) 392 | - [Jaccard Similarity](others/) 393 | - [Jose Phus Problem](others/) 394 | - [Lapindrom Checker](others/) 395 | - [Leap Year](others/) 396 | - [Magic Square](others/) 397 | - [Majority Element](others/) 398 | - [Minimum subarray size with degree](others/) 399 | - [No operator addition](others/) 400 | - [Paint fill](others/) 401 | - [Split list](others/) 402 | - [Tokenizer](others/) 403 | - [Unique number](others/) 404 | 405 | ## License 406 | 407 | This work is released under MIT License. 408 | 409 | To the extent possible under law, [Abraham Hernandez (@abranhe)](https://go.abranhe.com/github) has waived all copyright and related or neighboring rights to this work. 410 | 411 |
412 | 413 | 414 | 415 |
416 |
--------------------------------------------------------------------------------