This commit is contained in:
Vitor Oliveira 2021-02-06 23:05:54 -08:00
parent 3bde29dd55
commit e21120857d
34 changed files with 344 additions and 348 deletions

View file

@ -3,46 +3,40 @@
# Time Complexity: O(√n) # Time Complexity: O(√n)
def jump_search(arr, x) def jump_search(arr, x)
n = arr.length; n = arr.length
# Finding block size to be jumped # Finding block size to be jumped
step = Math.sqrt(n); step = Math.sqrt(n)
prev = 0; prev = 0
# Finding the block where element is # Finding the block where element is
# present (if it is present) # present (if it is present)
while (arr[[step, n].min - 1] < x) do while arr[[step, n].min - 1] < x
prev = step; prev = step
step += Math.sqrt(n); step += Math.sqrt(n)
if (prev >= n) return -1 if prev >= n
return -1;
end
end end
# Doing a linear search for x in block # Doing a linear search for x in block
# beginning with prev. # beginning with prev.
while (arr[prev] < x) do while arr[prev] < x
prev = prev + 1; prev += 1
# If we reached next block or end of # If we reached next block or end of
# array, element is not present. # array, element is not present.
if (prev == [step, n].min) return -1 if prev == [step, n].min
return -1;
end
end end
# If element is found # If element is found
if (arr[prev] == x) return prev if arr[prev] == x
return prev;
end
return -1; -1
end end
puts "Enter a sorted space-separated list:" puts 'Enter a sorted space-separated list:'
arr = gets.chomp.split(' ').map(&:to_i) arr = gets.chomp.split(' ').map(&:to_i)
puts "Enter the value to be searched:" puts 'Enter the value to be searched:'
value = gets.chomp.to_i value = gets.chomp.to_i
index = jump_search(arr, value) index = jump_search(arr, value)
puts index == -1 ? "Element not found" : "Number #{value} is at #{index}" puts index == -1 ? 'Element not found' : "Number #{value} is at #{index}"

View file

@ -1,64 +1,65 @@
require'openssl'; require 'openssl'
class MerkleHellman class MerkleHellman
SMALLEST_KNAPSACK_ITEM = 2**32 SMALLEST_KNAPSACK_ITEM = 2**32
STEP = 2**32 STEP = 2**32
def initialize size def initialize(size)
@size = size; @size = size
sum = SMALLEST_KNAPSACK_ITEM; sum = SMALLEST_KNAPSACK_ITEM
@easy_knapsack = size.times.map do |k| @easy_knapsack = size.times.map do |_k|
x = sum + rand(STEP); x = sum + rand(STEP)
sum += x; sum += x
x; x
end end
@n = sum + rand(STEP); @n = sum + rand(STEP)
loop do loop do
@a = rand(0..@n); @a = rand(0..@n)
break if @a.gcd(@n) == 1; break if @a.gcd(@n) == 1
end end
@hard_knapsack = @easy_knapsack.map do |x| @hard_knapsack = @easy_knapsack.map do |x|
(@a * x) % @n; (@a * x) % @n
end end
end end
def encrypt msg def encrypt(msg)
raise ArgumentError, "max length is #{@size/8} characters" if msg.length * 8 > @size; raise ArgumentError, "max length is #{@size / 8} characters" if msg.length * 8 > @size
c = 0;
msg.each_codepoint.reverse_each.with_index do |ch,i| c = 0
7.downto(0) do|j| msg.each_codepoint.reverse_each.with_index do |ch, i|
wj = ch.>>(j).& 1; 7.downto(0) do |j|
c += wj * @hard_knapsack[i*8+7-j] wj = ch.>>(j).& 1
c += wj * @hard_knapsack[i * 8 + 7 - j]
end end
end end
c; c
end end
def decrypt c def decrypt(c)
p = @a.to_bn.mod_inverse(@n).mod_mul(c,@n).to_i; p = @a.to_bn.mod_inverse(@n).mod_mul(c, @n).to_i
byte = 0; byte = 0
msg = [ ]; msg = []
@easy_knapsack.reverse_each.with_index do |x,i| @easy_knapsack.reverse_each.with_index do |x, i|
bit = 0; bit = 0
if p >= x if p >= x
p -= x; p -= x
bit = 1; bit = 1
end end
byte |= (bit << (i%8)); byte |= (bit << (i % 8))
if i % 8 == 7 if i % 8 == 7
msg << byte.chr; msg << byte.chr
byte = 0; byte = 0
end end
end end
msg.join; msg.join
end end
attr_accessor :hard_knapsack; attr_accessor :hard_knapsack
end end
str = "Hello there, this is my plaintext"; str = 'Hello there, this is my plaintext'
mh = MerkleHellman.new(str.length*8) mh = MerkleHellman.new(str.length * 8)
puts "[*] Encrypting \"#{str}\"" puts "[*] Encrypting \"#{str}\""
c = mh.encrypt(str) c = mh.encrypt(str)

View file

@ -11,11 +11,9 @@
def calculate_products_of_all_other_elements(nums) def calculate_products_of_all_other_elements(nums)
product_of_other_elements = Array.new(nums.length, 1) product_of_other_elements = Array.new(nums.length, 1)
nums.each_with_index do |num1, i| nums.each_with_index do |_num1, i|
nums.each_with_index do |num2, j| nums.each_with_index do |num2, j|
if (i != j) product_of_other_elements[i] = product_of_other_elements[i] * num2 if i != j
product_of_other_elements[i] = product_of_other_elements[i] * num2
end
end end
end end
@ -34,14 +32,14 @@ def build_prefix_products(nums)
prefix_products = [] prefix_products = []
nums.each do |num| nums.each do |num|
if prefix_products.count > 0 prefix_products << if prefix_products.count > 0
prefix_products << (prefix_products.last * num) (prefix_products.last * num)
else else
prefix_products << num num
end end
end end
return prefix_products prefix_products
end end
# Generates suffix products # Generates suffix products
@ -49,31 +47,31 @@ def build_suffix_products(nums)
suffix_products = [] suffix_products = []
nums.reverse.each do |num| nums.reverse.each do |num|
if suffix_products.count > 0 suffix_products << if suffix_products.count > 0
suffix_products << (suffix_products.last * num) (suffix_products.last * num)
else else
suffix_products << num num
end end
end end
return suffix_products suffix_products
end end
# Builds output # Builds output
def output(prefix_products, suffix_products, nums) def output(prefix_products, suffix_products, nums)
result = [] result = []
nums.reverse.each_with_index do |num, index| nums.reverse.each_with_index do |_num, index|
if index == 0 result << if index == 0
result << suffix_products[index + 1] suffix_products[index + 1]
elsif index == nums.length - 1 elsif index == nums.length - 1
result << prefix_products[index - 1] prefix_products[index - 1]
else else
result << (prefix_products[index - 1] * suffix_products[index + 1]) (prefix_products[index - 1] * suffix_products[index + 1])
end end
end end
return result result
end end
# Generate result from the product of prefixes and suffixes # Generate result from the product of prefixes and suffixes
@ -82,7 +80,7 @@ def products(nums)
suffix_products = build_suffix_products(nums) suffix_products = build_suffix_products(nums)
suffix_products = suffix_products.reverse suffix_products = suffix_products.reverse
return output(prefix_products, suffix_products, nums) output(prefix_products, suffix_products, nums)
end end
puts(products([1, 2, 3])) puts(products([1, 2, 3]))

View file

@ -12,12 +12,12 @@
def inorder_traversal(root) def inorder_traversal(root)
ans = [] ans = []
def traverse(node, ans) def traverse(node, ans)
if node != nil unless node.nil?
traverse(node.left, ans) traverse(node.left, ans)
ans.push(node.val) ans.push(node.val)
traverse(node.right, ans) traverse(node.right, ans)
end end
end end
traverse(root, ans) traverse(root, ans)
return ans ans
end end

View file

@ -10,11 +10,10 @@
# @param {TreeNode} root # @param {TreeNode} root
# @return {TreeNode} # @return {TreeNode}
def invert_tree(root) def invert_tree(root)
if root == nil return nil if root.nil?
return nil
end
temp = root.left temp = root.left
root.left = invert_tree(root.right) root.left = invert_tree(root.right)
root.right = invert_tree(temp) root.right = invert_tree(temp)
return root root
end end

View file

@ -12,12 +12,12 @@
def postorder_traversal(root) def postorder_traversal(root)
ans = [] ans = []
def traverse(node, ans) def traverse(node, ans)
if node != nil unless node.nil?
traverse(node.left, ans) traverse(node.left, ans)
traverse(node.right, ans) traverse(node.right, ans)
ans.push(node.val) ans.push(node.val)
end end
end end
traverse(root, ans) traverse(root, ans)
return ans ans
end end

View file

@ -12,12 +12,12 @@
def preorder_traversal(root) def preorder_traversal(root)
ans = [] ans = []
def traverse(node, ans) def traverse(node, ans)
if node != nil unless node.nil?
ans.push(node.val) ans.push(node.val)
traverse(node.left, ans) traverse(node.left, ans)
traverse(node.right, ans) traverse(node.right, ans)
end end
end end
traverse(root, ans) traverse(root, ans)
return ans ans
end end

View file

@ -1,6 +1,7 @@
# Define a node in the list # Define a node in the list
class Node class Node
attr_accessor :value, :next, :prev attr_accessor :value, :next, :prev
def initialize(value) def initialize(value)
@value = value @value = value
@next = nil @next = nil
@ -12,6 +13,7 @@ end
class DoubleList class DoubleList
include Enumerable include Enumerable
attr_accessor :head, :tail attr_accessor :head, :tail
def initialize def initialize
@head = nil @head = nil
@tail = nil @tail = nil
@ -67,7 +69,7 @@ class DoubleList
def print_list def print_list
# the to_a method is from Enumerable, will call each to get the values, and return an array # the to_a method is from Enumerable, will call each to get the values, and return an array
puts '[' + self.to_a.join(', ') + ']' puts '[' + to_a.join(', ') + ']'
end end
def empty? def empty?

View file

@ -1,6 +1,7 @@
# Define a node in the list # Define a node in the list
class Node class Node
attr_accessor :value, :next attr_accessor :value, :next
def initialize(value) def initialize(value)
@value = value @value = value
@next = nil @next = nil
@ -12,6 +13,7 @@ end
class SingleList class SingleList
include Enumerable include Enumerable
attr_accessor :head attr_accessor :head
def initialize def initialize
@head = nil @head = nil
end end
@ -48,7 +50,7 @@ class SingleList
end end
def print_list def print_list
puts '[' + self.to_a.join(', ') + ']' puts '[' + to_a.join(', ') + ']'
end end
def delete_head def delete_head

View file

@ -1,4 +1,4 @@
#https://en.wikipedia.org/wiki/Euclidean_algorithm # https://en.wikipedia.org/wiki/Euclidean_algorithm
def euclidean_gcd(a, b) def euclidean_gcd(a, b)
while b != 0 while b != 0
@ -6,9 +6,9 @@ def euclidean_gcd(a, b)
b = a % b b = a % b
a = t a = t
end end
return a a
end end
puts "GCD(3, 5) = " + euclidean_gcd(3, 5).to_s puts 'GCD(3, 5) = ' + euclidean_gcd(3, 5).to_s
puts "GCD(3, 6) = " + euclidean_gcd(3, 6).to_s puts 'GCD(3, 6) = ' + euclidean_gcd(3, 6).to_s
puts "GCD(6, 3) = " + euclidean_gcd(6, 3).to_s puts 'GCD(6, 3) = ' + euclidean_gcd(6, 3).to_s

View file

@ -1,31 +1,30 @@
# https://en.wikipedia.org/wiki/Extended_Euclidean_algorithm # https://en.wikipedia.org/wiki/Extended_Euclidean_algorithm
def extended_euclidean_gcd(a, b) def extended_euclidean_gcd(a, b)
x0 = a
x0, x1 = a, b x1 = b
s, t = 1, 0 s = 1
t = 0
until x1.zero? until x1.zero?
q, x2 = x0.divmod(x1) q, x2 = x0.divmod(x1)
x0, x1 = x1, x2 x0 = x1
x1 = x2
s, t = t, s - q * t s, t = t, s - q * t
end end
gcd = x0 x0
return gcd
end end
puts "GCD(3, 5) = " + extended_euclidean_gcd(3, 5).to_s puts 'GCD(3, 5) = ' + extended_euclidean_gcd(3, 5).to_s
# GCD(3, 5) = 1 # GCD(3, 5) = 1
puts "GCD(3, 6) = " + extended_euclidean_gcd(3, 6).to_s puts 'GCD(3, 6) = ' + extended_euclidean_gcd(3, 6).to_s
# GCD(3, 6) = 3 # GCD(3, 6) = 3
puts "GCD(6, 3) = " + extended_euclidean_gcd(6, 3).to_s puts 'GCD(6, 3) = ' + extended_euclidean_gcd(6, 3).to_s
# GCD(6, 3) = 3 # GCD(6, 3) = 3
=begin #
# Dynamic driver code:
Dynamic driver code: #
# a = gets.to_i
a = gets.to_i # b = gets.to_i
b = gets.to_i # puts "GCD (#{a}, #{b} ) = #{extended_euclidean_gcd(a, b)}"
puts "GCD (#{a}, #{b} ) = #{extended_euclidean_gcd(a, b)}" #
=end

View file

@ -1,23 +1,23 @@
# LCM (Least Common Multiple) of two numbers is the smallest number which can be divided by both numbers. # LCM (Least Common Multiple) of two numbers is the smallest number which can be divided by both numbers.
p "Least Common Multiple" p 'Least Common Multiple'
p "Enter first number" p 'Enter first number'
value_one = gets.chomp.to_i value_one = gets.chomp.to_i
p "Enter second number" p 'Enter second number'
value_two = gets.chomp.to_i value_two = gets.chomp.to_i
def gcd(first, second) def gcd(first, second)
if second != 0 if second != 0
gcd(second, first%second) gcd(second, first % second)
else else
first first
end end
end end
def lcm(first, second) def lcm(first, second)
(first * second)/gcd(first, second) (first * second) / gcd(first, second)
end end
p "Least Common Multiple is: #{lcm(value_one, value_two)}" p "Least Common Multiple is: #{lcm(value_one, value_two)}"

View file

@ -1,26 +1,24 @@
=begin #
# For any binary number of n digits i.e dn-1 ... d3 d2 d1 d0
For any binary number of n digits i.e dn-1 ... d3 d2 d1 d0 # The equivalent decimal number is equal to the sum of binary digits (dn) times their power of 2 (2n):
The equivalent decimal number is equal to the sum of binary digits (dn) times their power of 2 (2n): # decimal = d0×2^0 + d1×2^1 + d2×2^2 + ...
decimal = d0×2^0 + d1×2^1 + d2×2^2 + ... #
=end
def binary_to_decimal(n) def binary_to_decimal(n)
decimal = 0 decimal = 0
base = 1 base = 1
until n.zero? until n.zero?
x = n % 10 x = n % 10
n /= 10 n /= 10
decimal += x * base decimal += x * base
base *= 2 base *= 2
end end
return decimal decimal
end end
puts "Decimal value of 110011 is " + binary_to_decimal(110011).to_s puts 'Decimal value of 110011 is ' + binary_to_decimal(110_011).to_s
# Decimal value of 110011 is 51 # Decimal value of 110011 is 51
puts "Decimal value of 11110 is " + binary_to_decimal(11110).to_s puts 'Decimal value of 11110 is ' + binary_to_decimal(11_110).to_s
# Decimal value of 11110 is 30 # Decimal value of 11110 is 30
puts "Decimal value of 101 is " + binary_to_decimal(101).to_s puts 'Decimal value of 101 is ' + binary_to_decimal(101).to_s
# Decimal value of 101 is 5 # Decimal value of 101 is 5

View file

@ -1,24 +1,22 @@
# Given a number, find number of digits in it. # Given a number, find number of digits in it.
def count_digits(n) def count_digits(n)
count = 0 count = 0
temp = n temp = n
if (n == 0) return 1 if n == 0
return 1
end until temp.zero?
count += 1
until temp.zero? temp /= 10
count += 1 end
temp /= 10
end count
return count
end end
puts "Number of digits in 8732 is " + count_digits(8732).to_s puts 'Number of digits in 8732 is ' + count_digits(8732).to_s
# Number of digits in 8732 is 4 # Number of digits in 8732 is 4
puts "Number of digits in 112233 is " + count_digits(112233).to_s puts 'Number of digits in 112233 is ' + count_digits(112_233).to_s
# Number of digits in 112233 is 6 # Number of digits in 112233 is 6
puts "Number of digits in 0 is " + count_digits(0).to_s puts 'Number of digits in 0 is ' + count_digits(0).to_s
# Number of digits in 0 is 1 # Number of digits in 0 is 1

View file

@ -1,18 +1,19 @@
# Given a number, find sum of its digits. # Given a number, find sum of its digits.
def digits_sum(n) def digits_sum(n)
a, sum = 0, 0 a = 0
sum = 0
until n.zero? until n.zero?
a = n % 10 a = n % 10
sum += a sum += a
n /= 10 n /= 10
end end
return sum sum
end end
puts "Sum of digits of 3456 is " + digits_sum(3456).to_s puts 'Sum of digits of 3456 is ' + digits_sum(3456).to_s
# Sum of digits of 3456 is 18 # Sum of digits of 3456 is 18
puts "Sum of digits of 1234 is " + digits_sum(1234).to_s puts 'Sum of digits of 1234 is ' + digits_sum(1234).to_s
# Sum of digits of 1234 is 10 # Sum of digits of 1234 is 10
puts "Sum of digits of 9251321 is " + digits_sum(9251321).to_s puts 'Sum of digits of 9251321 is ' + digits_sum(9_251_321).to_s
# Sum of digits of 9251321 is 23 # Sum of digits of 9251321 is 23

View file

@ -1,12 +1,12 @@
# Fisher and Yates Shuffle is one of the simplest and most popular shuffling algorithm # Fisher and Yates Shuffle is one of the simplest and most popular shuffling algorithm
def fisher_yates_shuffle(array) def fisher_yates_shuffle(array)
n = array.length n = array.length
while n > 0 while n > 0
i = rand(n-=1) i = rand(n -= 1)
array[i], array[n] = array[n], array[i] array[i], array[n] = array[n], array[i]
end end
return array array
end end
arr = [1, 2, 40, 30, 20, 15, 323, 12, 3, 4] arr = [1, 2, 40, 30, 20, 15, 323, 12, 3, 4]
puts fisher_yates_shuffle(arr) puts fisher_yates_shuffle(arr)

View file

@ -8,7 +8,7 @@ even_fib_sum = 0
fib_first = 1 fib_first = 1
fib_second = 2 fib_second = 2
while fib_second < 4000000 while fib_second < 4_000_000
even_fib_sum += fib_second if fib_second.even? even_fib_sum += fib_second if fib_second.even?
fib_second += fib_first fib_second += fib_first
fib_first = fib_second - fib_first fib_first = fib_second - fib_first

View file

@ -26,4 +26,4 @@ def largest_prime_factor(number)
prime_factors.max prime_factors.max
end end
puts largest_prime_factor(600851475143) puts largest_prime_factor(600_851_475_143)

View file

@ -15,4 +15,4 @@ def solution(n)
prime.to_i prime.to_i
end end
puts solution(600851475143) puts solution(600_851_475_143)

View file

@ -8,4 +8,4 @@ answer = 0
answer = i * j if (t.to_s == t.to_s.reverse) && (t > answer) && (t > answer) answer = i * j if (t.to_s == t.to_s.reverse) && (t > answer) && (t > answer)
end end
end end
puts answer puts answer

View file

@ -3,7 +3,6 @@
# What is the smallest positive number that is evenly # What is the smallest positive number that is evenly
# divisible by all of the numbers from 1 to 20? # divisible by all of the numbers from 1 to 20?
# Euclid's algorithm for the greatest common divisor # Euclid's algorithm for the greatest common divisor
def gcd(a, b) def gcd(a, b)
b.zero? ? a : gcd(b, a % b) b.zero? ? a : gcd(b, a % b)
@ -20,4 +19,4 @@ result = 1
result = lcm(result, i + 1) result = lcm(result, i + 1)
end end
p result p result

View file

@ -1,15 +1,17 @@
=begin # Searches through a list for a value in O(log(n)) time.
Searches through a list for a value in O(log(n)) time. # The list must be sorted.
The list must be sorted.
=end
def binary_search(array, key) def binary_search(array, key)
front = 0 front = 0
back = array.length - 1 back = array.length - 1
while front <= back while front <= back
middle = (front + back) / 2 middle = (front + back) / 2
return middle if array[middle] == key return middle if array[middle] == key
key < array[middle] ?
back = middle - 1 : front = middle + 1 if key < array[middle]
back = middle - 1
else
front = middle + 1
end
end end
nil nil
end end
@ -18,6 +20,8 @@ puts "Enter a sorted space-separated list:"
arr = gets.chomp.split(' ').map(&:to_i) arr = gets.chomp.split(' ').map(&:to_i)
puts "Enter the value to be searched:" puts "Enter the value to be searched:"
value = gets.chomp.to_i value = gets.chomp.to_i
puts binary_search(arr, value) != nil ? puts if binary_search(arr, value) != nil
"Found at index #{binary_search(arr, value)}" : "Found at index #{binary_search(arr, value)}"
else
"Not found" "Not found"
end

View file

@ -8,6 +8,7 @@ def dfs(start, target, adjacency_list)
stack = [start] stack = [start]
loop do loop do
break if stack.empty? break if stack.empty?
current_node = stack.pop current_node = stack.pop
is_visited[current_node] = true is_visited[current_node] = true
@ -15,6 +16,7 @@ def dfs(start, target, adjacency_list)
adjacency_list[current_node].each do |neighbor| adjacency_list[current_node].each do |neighbor|
next if is_visited[neighbor] next if is_visited[neighbor]
stack << neighbor stack << neighbor
is_visited[neighbor] = true is_visited[neighbor] = true
parent[neighbor] = current_node parent[neighbor] = current_node
@ -38,12 +40,12 @@ end
def main def main
adjacency_list = [ adjacency_list = [
[1, 2], #0 [1, 2], # 0
[0, 3], #1 [0, 3], # 1
[0, 3], #2 [0, 3], # 2
[1, 2, 4], #3 [1, 2, 4], # 3
[3, 5], #4 [3, 5], # 4
[4] #5 [4] # 5
] ]
p dfs(0, 5, adjacency_list) p dfs(0, 5, adjacency_list)
end end

View file

@ -1,18 +1,18 @@
=begin # Looks through array for a value in O(n) time.
Looks through array for a value in O(n) time. # Array does not need to be sorted.
Array does not need to be sorted.
=end
def linear_search(array, key) def linear_search(array, key)
array.each_with_index do |current, index| array.each_with_index do |current, index|
return index if current == key return index if current == key
end end
return nil nil
end end
puts "Enter a space-separated list:" puts "Enter a space-separated list:"
arr = gets.chomp.split(' ').map(&:to_i) arr = gets.chomp.split(' ').map(&:to_i)
puts "Enter a value to be searched:" puts "Enter a value to be searched:"
key = gets.chomp.to_i key = gets.chomp.to_i
puts linear_search(arr, key) != nil ? puts if linear_search(arr, key) != nil
"Found at index #{linear_search(arr, key)}" : "Found at index #{linear_search(arr, key)}"
else
"Not found" "Not found"
end

View file

@ -1,43 +1,43 @@
=begin # Ternary Search
Ternary Search # -------------------------------
------------------------------- # Ternary search is a searching technique that is used to search the position of a specific value in an array.
Ternary search is a searching technique that is used to search the position of a specific value in an array. # Ternary search is a divide-and-conquer algorithm.
Ternary search is a divide-and-conquer algorithm. # It is mandatory for the array to be sorted (in which you will search for an element).
It is mandatory for the array to be sorted (in which you will search for an element). # The array is divided into three parts and then we determine in which part the element exists.
The array is divided into three parts and then we determine in which part the element exists. # In this search, after each iteration it neglects 1/3 part of the array and repeats the same operations on the remaining ⅔.
In this search, after each iteration it neglects 1/3 part of the array and repeats the same operations on the remaining . # Time Complexity: O(log3 n)
Time Complexity: O(log3 n) # Space Complexity: O(1)
Space Complexity: O(1)
=end
def ternary_search(l, r, key, arr) def ternary_search(l, r, key, arr)
#l is the starting index and r is the ending index of the array/sub-array. # l is the starting index and r is the ending index of the array/sub-array.
if (r >= l) if r >= l
#find mid1 and mid2 # find mid1 and mid2
mid1 = l + (r - l) / 3 mid1 = l + (r - l) / 3
mid2 = r - (r - l) / 3 mid2 = r - (r - l) / 3
#check if key is equal to mid1 # check if key is equal to mid1
if arr[mid1] == key if arr[mid1] == key
mid1 mid1
#check if key is equal to mid2 # check if key is equal to mid2
elsif arr[mid2] == key elsif arr[mid2] == key
mid2 mid2
#Since key is not present at mid, check in which region it is present # Since key is not present at mid, check in which region it is present
#then repeat the Search operation in that region # then repeat the Search operation in that region
elsif key < arr[mid1] elsif key < arr[mid1]
ternary_search(l, mid1 - 1, key, arr) ternary_search(l, mid1 - 1, key, arr)
elsif (key > arr[mid2]) elsif key > arr[mid2]
ternary_search(mid2 + 1, r, key, arr) ternary_search(mid2 + 1, r, key, arr)
else else
ternary_search(mid1 + 1, mid2 - 1, key, arr) ternary_search(mid1 + 1, mid2 - 1, key, arr)
end end
end end
end end
puts "Enter a space-separated list:" puts "Enter a space-separated list:"
arr = gets.chomp.split(' ').map(&:to_i) arr = gets.chomp.split(' ').map(&:to_i)
puts "Enter a value to be searched:" puts "Enter a value to be searched:"
key = gets.chomp.to_i key = gets.chomp.to_i
puts ternary_search(0, arr.length - 1, key, arr) != nil ? puts if ternary_search(0, arr.length - 1, key, arr) != nil
"Found at index #{ternary_search(0, arr.length - 1, key, arr)}" : "Found at index #{ternary_search(0, arr.length - 1, key, arr)}"
else
"Not found" "Not found"
end

View file

@ -1,20 +1,21 @@
class Array class Array
def sorted? def sorted?
### goes thru array and checks if all elements are in order ### goes thru array and checks if all elements are in order
for i in 1...self.length (1...length).each do |i|
return false if self[i-1] > self[i] return false if self[i - 1] > self[i]
end end
return true true
end end
def bogosort def bogosort
### randomly shuffles until sorted ### randomly shuffles until sorted
self.shuffle! until self.sorted? shuffle! until sorted?
return self #return sorted array self # return sorted array
end end
end end
if $0 == __FILE__ if $0 == __FILE__
puts "Enter a list of numbers separated by space" puts 'Enter a list of numbers separated by space'
str = gets.chomp.split('') str = gets.chomp.split('')
puts str.bogosort.join('') puts str.bogosort.join('')
end end

View file

@ -1,22 +1,22 @@
def bubble_sort(array) def bubble_sort(array)
n = array.length n = array.length
loop do loop do
swapped = false swapped = false
(n-1).times do |i| (n - 1).times do |i|
if array[i] > array[i+1] if array[i] > array[i + 1]
array[i], array[i+1] = array[i+1], array[i] array[i], array[i + 1] = array[i + 1], array[i]
swapped = true swapped = true
end end
end end
break if not swapped break unless swapped
end end
array array
end end
puts "Enter a list of numbers separated by space" puts 'Enter a list of numbers separated by space'
list = gets list = gets
bubble_sort(list) bubble_sort(list)
print list print list

View file

@ -1,30 +1,29 @@
DEFAULT_BUCKET_SIZE = 5
DEFAULT_BUCKET_SIZE = 5
def bucket_sort(input, bucket_size = DEFAULT_BUCKET_SIZE)
def bucket_sort(input, bucket_size = DEFAULT_BUCKET_SIZE) print 'Array is empty' if input.empty?
print 'Array is empty' if input.empty?
array = input.split(' ').map(&:to_i)
array = input.split(' ').map(&:to_i)
bucket_count = ((array.max - array.min) / bucket_size).floor + 1
bucket_count = ((array.max - array.min) / bucket_size).floor + 1
# create buckets
# create buckets buckets = []
buckets = [] bucket_count.times { buckets.push [] }
bucket_count.times { buckets.push [] }
# fill buckets
# fill buckets array.each do |item|
array.each do |item| buckets[((item - array.min) / bucket_size).floor].push(item)
buckets[((item - array.min) / bucket_size).floor].push(item) end
end
# sort buckets
# sort buckets buckets.each do |bucket|
buckets.each do |bucket| bucket.sort!
bucket.sort! end
end
buckets.flatten.join(' ')
buckets.flatten.join(' ') end
end puts 'Enter a list of numbers separated by space'
puts "Enter a list of numbers separated by space"
list = gets
list = gets print bucket_sort(list)
print bucket_sort(list)

View file

@ -7,25 +7,26 @@ def heap_sort(array)
adjusted_down(adjusted_array, i, array_size) adjusted_down(adjusted_array, i, array_size)
end end
while array_size > 1 while array_size > 1
adjusted_array[1], adjusted_array[array_size] = adjusted_array[array_size], adjusted_array[1] adjusted_array[1], adjusted_array[array_size] = adjusted_array[array_size], adjusted_array[1]
array_size -= 1 array_size -= 1
adjusted_down(adjusted_array, 1, array_size) adjusted_down(adjusted_array, 1, array_size)
end end
adjusted_array.drop(1) adjusted_array.drop(1)
end end
#Method to adjust heap in downward manner # Method to adjust heap in downward manner
def adjusted_down(adjusted_array, parent, limit) def adjusted_down(adjusted_array, parent, limit)
top = adjusted_array[parent] top = adjusted_array[parent]
while (child = 2 * parent) <= limit while (child = 2 * parent) <= limit
child += 1 if child < limit and adjusted_array[child] < adjusted_array[child + 1] child += 1 if (child < limit) && (adjusted_array[child] < adjusted_array[child + 1])
break if top >= adjusted_array[child] break if top >= adjusted_array[child]
adjusted_array[parent] = adjusted_array[child] adjusted_array[parent] = adjusted_array[child]
parent = child parent = child
end end
adjusted_array[parent] = top adjusted_array[parent] = top
end end
#Code for testing heapsort # Code for testing heapsort
array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15].shuffle array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15].shuffle
print heap_sort(array) print heap_sort(array)

View file

@ -1,17 +1,17 @@
def insertion_sort(array) def insertion_sort(array)
0.upto(array.length - 1).each do |index| 0.upto(array.length - 1).each do |index|
element = array[index] element = array[index]
position = index position = index
while element < array[position - 1] && position > 0 while element < array[position - 1] && position > 0
array[position] = array[position - 1] array[position] = array[position - 1]
array[position - 1] = element array[position - 1] = element
position -= 1 position -= 1
end end
end end
array array
end end
puts "Enter a list of numbers separated by space" puts 'Enter a list of numbers separated by space'
list = gets list = gets
insertion_sort(list) insertion_sort(list)
print list print list

View file

@ -1,5 +1,6 @@
def merge_sort(array) def merge_sort(array)
return array if array.length <= 1 return array if array.length <= 1
mid = array.length / 2 mid = array.length / 2
first_array = array.slice(0..mid - 1) first_array = array.slice(0..mid - 1)
second_array = array.slice(mid..-1) second_array = array.slice(mid..-1)
@ -9,7 +10,7 @@ def merge_sort(array)
# merge # merge
result = [] result = []
until first_array.empty? and second_array.empty? until first_array.empty? && second_array.empty?
if first_array.empty? if first_array.empty?
result.concat(second_array) result.concat(second_array)
second_array.clear second_array.clear
@ -17,16 +18,16 @@ def merge_sort(array)
result.concat(first_array) result.concat(first_array)
first_array.clear first_array.clear
else else
if first_array.first < second_array.first result << if first_array.first < second_array.first
result << first_array.shift first_array.shift
else else
result << second_array.shift second_array.shift
end end
end end
end end
result result
end end
puts "Enter a list of numbers separated by space" puts 'Enter a list of numbers separated by space'
list = gets list = gets
print merge_sort list.split(" ").map(&:to_i) print merge_sort list.split(' ').map(&:to_i)

View file

@ -8,7 +8,7 @@ def quicksort(arr)
left, right = arr.partition(&pivot.method(:>)) left, right = arr.partition(&pivot.method(:>))
# recursively calling the quicksort method on itself # recursively calling the quicksort method on itself
return *quicksort(left), pivot, *quicksort(right) [*quicksort(left), pivot, *quicksort(right)]
end end
arr = [34, 2, 1, 5, 3] arr = [34, 2, 1, 5, 3]

View file

@ -13,6 +13,6 @@ def selection_sort(array)
end end
end end
arr = ([9,8,3,1,2,55,68,48].shuffle) #We have taken a rondom example and also shuffling it arr = [9, 8, 3, 1, 2, 55, 68, 48].shuffle # We have taken a rondom example and also shuffling it
selection_sort(arr) selection_sort(arr)
puts "Sorted array is: #{arr.inspect}" puts "Sorted array is: #{arr.inspect}"

View file

@ -1,27 +1,24 @@
def shell_sort(a) def shell_sort(a)
n=a.length n = a.length
h=1 h = 1
while (h<n/3) #for computing increment factor "h" h = (3 * h) + 1 while h < n / 3
h= (3*h)+1
end
while h>=1 while h >= 1
# Logic of insertion sort with inrement steps of "h" # Logic of insertion sort with inrement steps of "h"
for i in h...n (h...n).each do |i|
j=i j = i
while j>=h while j >= h
if a[j-h]>a[j] if a[j - h] > a[j]
temp=a[j] temp = a[j]
a[j]=a[j-h] a[j] = a[j - h]
a[j-h]=temp a[j - h] = temp
end end
j-=h j -= h
end end
end end
h/=3 h /= 3
end end
return a a
end end