mirror of
https://github.com/TheAlgorithms/Ruby
synced 2024-12-25 21:58:57 +01:00
Clean up
This commit is contained in:
parent
3bde29dd55
commit
e21120857d
34 changed files with 344 additions and 348 deletions
|
@ -3,46 +3,40 @@
|
|||
# Time Complexity: O(√n)
|
||||
|
||||
def jump_search(arr, x)
|
||||
n = arr.length;
|
||||
n = arr.length
|
||||
|
||||
# Finding block size to be jumped
|
||||
step = Math.sqrt(n);
|
||||
prev = 0;
|
||||
# Finding block size to be jumped
|
||||
step = Math.sqrt(n)
|
||||
prev = 0
|
||||
|
||||
# Finding the block where element is
|
||||
# present (if it is present)
|
||||
while (arr[[step, n].min - 1] < x) do
|
||||
prev = step;
|
||||
step += Math.sqrt(n);
|
||||
if (prev >= n)
|
||||
return -1;
|
||||
end
|
||||
# Finding the block where element is
|
||||
# present (if it is present)
|
||||
while arr[[step, n].min - 1] < x
|
||||
prev = step
|
||||
step += Math.sqrt(n)
|
||||
return -1 if prev >= n
|
||||
end
|
||||
|
||||
# Doing a linear search for x in block
|
||||
# beginning with prev.
|
||||
while (arr[prev] < x) do
|
||||
prev = prev + 1;
|
||||
# If we reached next block or end of
|
||||
# array, element is not present.
|
||||
if (prev == [step, n].min)
|
||||
return -1;
|
||||
end
|
||||
# Doing a linear search for x in block
|
||||
# beginning with prev.
|
||||
while arr[prev] < x
|
||||
prev += 1
|
||||
# If we reached next block or end of
|
||||
# array, element is not present.
|
||||
return -1 if prev == [step, n].min
|
||||
end
|
||||
|
||||
# If element is found
|
||||
if (arr[prev] == x)
|
||||
return prev;
|
||||
end
|
||||
return prev if arr[prev] == x
|
||||
|
||||
return -1;
|
||||
-1
|
||||
end
|
||||
|
||||
puts "Enter a sorted space-separated list:"
|
||||
puts 'Enter a sorted space-separated list:'
|
||||
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
|
||||
|
||||
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}"
|
||||
|
|
|
@ -1,64 +1,65 @@
|
|||
require'openssl';
|
||||
require 'openssl'
|
||||
|
||||
class MerkleHellman
|
||||
SMALLEST_KNAPSACK_ITEM = 2**32
|
||||
STEP = 2**32
|
||||
|
||||
def initialize size
|
||||
@size = size;
|
||||
sum = SMALLEST_KNAPSACK_ITEM;
|
||||
@easy_knapsack = size.times.map do |k|
|
||||
x = sum + rand(STEP);
|
||||
sum += x;
|
||||
x;
|
||||
def initialize(size)
|
||||
@size = size
|
||||
sum = SMALLEST_KNAPSACK_ITEM
|
||||
@easy_knapsack = size.times.map do |_k|
|
||||
x = sum + rand(STEP)
|
||||
sum += x
|
||||
x
|
||||
end
|
||||
@n = sum + rand(STEP);
|
||||
@n = sum + rand(STEP)
|
||||
|
||||
loop do
|
||||
@a = rand(0..@n);
|
||||
break if @a.gcd(@n) == 1;
|
||||
@a = rand(0..@n)
|
||||
break if @a.gcd(@n) == 1
|
||||
end
|
||||
|
||||
@hard_knapsack = @easy_knapsack.map do |x|
|
||||
(@a * x) % @n;
|
||||
(@a * x) % @n
|
||||
end
|
||||
end
|
||||
|
||||
def encrypt msg
|
||||
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|
|
||||
7.downto(0) do|j|
|
||||
wj = ch.>>(j).& 1;
|
||||
c += wj * @hard_knapsack[i*8+7-j]
|
||||
def encrypt(msg)
|
||||
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|
|
||||
7.downto(0) do |j|
|
||||
wj = ch.>>(j).& 1
|
||||
c += wj * @hard_knapsack[i * 8 + 7 - j]
|
||||
end
|
||||
end
|
||||
c;
|
||||
c
|
||||
end
|
||||
|
||||
def decrypt c
|
||||
p = @a.to_bn.mod_inverse(@n).mod_mul(c,@n).to_i;
|
||||
byte = 0;
|
||||
msg = [ ];
|
||||
@easy_knapsack.reverse_each.with_index do |x,i|
|
||||
bit = 0;
|
||||
def decrypt(c)
|
||||
p = @a.to_bn.mod_inverse(@n).mod_mul(c, @n).to_i
|
||||
byte = 0
|
||||
msg = []
|
||||
@easy_knapsack.reverse_each.with_index do |x, i|
|
||||
bit = 0
|
||||
if p >= x
|
||||
p -= x;
|
||||
bit = 1;
|
||||
p -= x
|
||||
bit = 1
|
||||
end
|
||||
byte |= (bit << (i%8));
|
||||
byte |= (bit << (i % 8))
|
||||
if i % 8 == 7
|
||||
msg << byte.chr;
|
||||
byte = 0;
|
||||
msg << byte.chr
|
||||
byte = 0
|
||||
end
|
||||
end
|
||||
msg.join;
|
||||
msg.join
|
||||
end
|
||||
attr_accessor :hard_knapsack;
|
||||
attr_accessor :hard_knapsack
|
||||
end
|
||||
|
||||
str = "Hello there, this is my plaintext";
|
||||
mh = MerkleHellman.new(str.length*8)
|
||||
str = 'Hello there, this is my plaintext'
|
||||
mh = MerkleHellman.new(str.length * 8)
|
||||
puts "[*] Encrypting \"#{str}\""
|
||||
|
||||
c = mh.encrypt(str)
|
||||
|
|
|
@ -11,11 +11,9 @@
|
|||
def calculate_products_of_all_other_elements(nums)
|
||||
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|
|
||||
if (i != j)
|
||||
product_of_other_elements[i] = product_of_other_elements[i] * num2
|
||||
end
|
||||
product_of_other_elements[i] = product_of_other_elements[i] * num2 if i != j
|
||||
end
|
||||
end
|
||||
|
||||
|
@ -34,14 +32,14 @@ def build_prefix_products(nums)
|
|||
prefix_products = []
|
||||
|
||||
nums.each do |num|
|
||||
if prefix_products.count > 0
|
||||
prefix_products << (prefix_products.last * num)
|
||||
else
|
||||
prefix_products << num
|
||||
end
|
||||
prefix_products << if prefix_products.count > 0
|
||||
(prefix_products.last * num)
|
||||
else
|
||||
num
|
||||
end
|
||||
end
|
||||
|
||||
return prefix_products
|
||||
prefix_products
|
||||
end
|
||||
|
||||
# Generates suffix products
|
||||
|
@ -49,31 +47,31 @@ def build_suffix_products(nums)
|
|||
suffix_products = []
|
||||
|
||||
nums.reverse.each do |num|
|
||||
if suffix_products.count > 0
|
||||
suffix_products << (suffix_products.last * num)
|
||||
else
|
||||
suffix_products << num
|
||||
end
|
||||
suffix_products << if suffix_products.count > 0
|
||||
(suffix_products.last * num)
|
||||
else
|
||||
num
|
||||
end
|
||||
end
|
||||
|
||||
return suffix_products
|
||||
suffix_products
|
||||
end
|
||||
|
||||
# Builds output
|
||||
def output(prefix_products, suffix_products, nums)
|
||||
result = []
|
||||
|
||||
nums.reverse.each_with_index do |num, index|
|
||||
if index == 0
|
||||
result << suffix_products[index + 1]
|
||||
elsif index == nums.length - 1
|
||||
result << prefix_products[index - 1]
|
||||
else
|
||||
result << (prefix_products[index - 1] * suffix_products[index + 1])
|
||||
end
|
||||
nums.reverse.each_with_index do |_num, index|
|
||||
result << if index == 0
|
||||
suffix_products[index + 1]
|
||||
elsif index == nums.length - 1
|
||||
prefix_products[index - 1]
|
||||
else
|
||||
(prefix_products[index - 1] * suffix_products[index + 1])
|
||||
end
|
||||
end
|
||||
|
||||
return result
|
||||
result
|
||||
end
|
||||
|
||||
# Generate result from the product of prefixes and suffixes
|
||||
|
@ -82,7 +80,7 @@ def products(nums)
|
|||
suffix_products = build_suffix_products(nums)
|
||||
suffix_products = suffix_products.reverse
|
||||
|
||||
return output(prefix_products, suffix_products, nums)
|
||||
output(prefix_products, suffix_products, nums)
|
||||
end
|
||||
|
||||
puts(products([1, 2, 3]))
|
||||
|
|
|
@ -12,12 +12,12 @@
|
|||
def inorder_traversal(root)
|
||||
ans = []
|
||||
def traverse(node, ans)
|
||||
if node != nil
|
||||
unless node.nil?
|
||||
traverse(node.left, ans)
|
||||
ans.push(node.val)
|
||||
traverse(node.right, ans)
|
||||
end
|
||||
end
|
||||
traverse(root, ans)
|
||||
return ans
|
||||
end
|
||||
ans
|
||||
end
|
||||
|
|
|
@ -10,11 +10,10 @@
|
|||
# @param {TreeNode} root
|
||||
# @return {TreeNode}
|
||||
def invert_tree(root)
|
||||
if root == nil
|
||||
return nil
|
||||
end
|
||||
return nil if root.nil?
|
||||
|
||||
temp = root.left
|
||||
root.left = invert_tree(root.right)
|
||||
root.right = invert_tree(temp)
|
||||
return root
|
||||
end
|
||||
root
|
||||
end
|
||||
|
|
|
@ -12,12 +12,12 @@
|
|||
def postorder_traversal(root)
|
||||
ans = []
|
||||
def traverse(node, ans)
|
||||
if node != nil
|
||||
unless node.nil?
|
||||
traverse(node.left, ans)
|
||||
traverse(node.right, ans)
|
||||
ans.push(node.val)
|
||||
end
|
||||
end
|
||||
traverse(root, ans)
|
||||
return ans
|
||||
end
|
||||
ans
|
||||
end
|
||||
|
|
|
@ -12,12 +12,12 @@
|
|||
def preorder_traversal(root)
|
||||
ans = []
|
||||
def traverse(node, ans)
|
||||
if node != nil
|
||||
unless node.nil?
|
||||
ans.push(node.val)
|
||||
traverse(node.left, ans)
|
||||
traverse(node.right, ans)
|
||||
end
|
||||
end
|
||||
traverse(root, ans)
|
||||
return ans
|
||||
end
|
||||
ans
|
||||
end
|
||||
|
|
|
@ -1,6 +1,7 @@
|
|||
# Define a node in the list
|
||||
class Node
|
||||
attr_accessor :value, :next, :prev
|
||||
|
||||
def initialize(value)
|
||||
@value = value
|
||||
@next = nil
|
||||
|
@ -12,6 +13,7 @@ end
|
|||
class DoubleList
|
||||
include Enumerable
|
||||
attr_accessor :head, :tail
|
||||
|
||||
def initialize
|
||||
@head = nil
|
||||
@tail = nil
|
||||
|
@ -67,7 +69,7 @@ class DoubleList
|
|||
|
||||
def print_list
|
||||
# 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
|
||||
|
||||
def empty?
|
||||
|
|
|
@ -1,6 +1,7 @@
|
|||
# Define a node in the list
|
||||
class Node
|
||||
attr_accessor :value, :next
|
||||
|
||||
def initialize(value)
|
||||
@value = value
|
||||
@next = nil
|
||||
|
@ -12,6 +13,7 @@ end
|
|||
class SingleList
|
||||
include Enumerable
|
||||
attr_accessor :head
|
||||
|
||||
def initialize
|
||||
@head = nil
|
||||
end
|
||||
|
@ -48,7 +50,7 @@ class SingleList
|
|||
end
|
||||
|
||||
def print_list
|
||||
puts '[' + self.to_a.join(', ') + ']'
|
||||
puts '[' + to_a.join(', ') + ']'
|
||||
end
|
||||
|
||||
def delete_head
|
||||
|
|
|
@ -1,4 +1,4 @@
|
|||
#https://en.wikipedia.org/wiki/Euclidean_algorithm
|
||||
# https://en.wikipedia.org/wiki/Euclidean_algorithm
|
||||
|
||||
def euclidean_gcd(a, b)
|
||||
while b != 0
|
||||
|
@ -6,9 +6,9 @@ def euclidean_gcd(a, b)
|
|||
b = a % b
|
||||
a = t
|
||||
end
|
||||
return a
|
||||
a
|
||||
end
|
||||
|
||||
puts "GCD(3, 5) = " + euclidean_gcd(3, 5).to_s
|
||||
puts "GCD(3, 6) = " + euclidean_gcd(3, 6).to_s
|
||||
puts "GCD(6, 3) = " + euclidean_gcd(6, 3).to_s
|
||||
puts 'GCD(3, 5) = ' + euclidean_gcd(3, 5).to_s
|
||||
puts 'GCD(3, 6) = ' + euclidean_gcd(3, 6).to_s
|
||||
puts 'GCD(6, 3) = ' + euclidean_gcd(6, 3).to_s
|
||||
|
|
|
@ -1,31 +1,30 @@
|
|||
# https://en.wikipedia.org/wiki/Extended_Euclidean_algorithm
|
||||
|
||||
def extended_euclidean_gcd(a, b)
|
||||
|
||||
x0, x1 = a, b
|
||||
s, t = 1, 0
|
||||
x0 = a
|
||||
x1 = b
|
||||
s = 1
|
||||
t = 0
|
||||
until x1.zero?
|
||||
q, x2 = x0.divmod(x1)
|
||||
x0, x1 = x1, x2
|
||||
x0 = x1
|
||||
x1 = x2
|
||||
s, t = t, s - q * t
|
||||
end
|
||||
gcd = x0
|
||||
return gcd
|
||||
x0
|
||||
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
|
||||
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
|
||||
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
|
||||
|
||||
=begin
|
||||
|
||||
Dynamic driver code:
|
||||
|
||||
a = gets.to_i
|
||||
b = gets.to_i
|
||||
puts "GCD (#{a}, #{b} ) = #{extended_euclidean_gcd(a, b)}"
|
||||
|
||||
=end
|
||||
#
|
||||
# Dynamic driver code:
|
||||
#
|
||||
# a = gets.to_i
|
||||
# b = gets.to_i
|
||||
# puts "GCD (#{a}, #{b} ) = #{extended_euclidean_gcd(a, b)}"
|
||||
#
|
||||
|
|
|
@ -1,23 +1,23 @@
|
|||
# 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
|
||||
|
||||
p "Enter second number"
|
||||
p 'Enter second number'
|
||||
value_two = gets.chomp.to_i
|
||||
|
||||
def gcd(first, second)
|
||||
if second != 0
|
||||
gcd(second, first%second)
|
||||
gcd(second, first % second)
|
||||
else
|
||||
first
|
||||
end
|
||||
end
|
||||
|
||||
def lcm(first, second)
|
||||
(first * second)/gcd(first, second)
|
||||
(first * second) / gcd(first, second)
|
||||
end
|
||||
|
||||
p "Least Common Multiple is: #{lcm(value_one, value_two)}"
|
||||
p "Least Common Multiple is: #{lcm(value_one, value_two)}"
|
||||
|
|
|
@ -1,26 +1,24 @@
|
|||
=begin
|
||||
|
||||
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):
|
||||
decimal = d0×2^0 + d1×2^1 + d2×2^2 + ...
|
||||
|
||||
=end
|
||||
#
|
||||
# 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):
|
||||
# decimal = d0×2^0 + d1×2^1 + d2×2^2 + ...
|
||||
#
|
||||
|
||||
def binary_to_decimal(n)
|
||||
decimal = 0
|
||||
base = 1
|
||||
until n.zero?
|
||||
x = n % 10
|
||||
n /= 10
|
||||
decimal += x * base
|
||||
base *= 2
|
||||
end
|
||||
return decimal
|
||||
decimal = 0
|
||||
base = 1
|
||||
until n.zero?
|
||||
x = n % 10
|
||||
n /= 10
|
||||
decimal += x * base
|
||||
base *= 2
|
||||
end
|
||||
decimal
|
||||
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
|
||||
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
|
||||
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
|
||||
|
|
|
@ -1,24 +1,22 @@
|
|||
# Given a number, find number of digits in it.
|
||||
|
||||
def count_digits(n)
|
||||
count = 0
|
||||
temp = n
|
||||
|
||||
if (n == 0)
|
||||
return 1
|
||||
end
|
||||
|
||||
until temp.zero?
|
||||
count += 1
|
||||
temp /= 10
|
||||
end
|
||||
|
||||
return count
|
||||
count = 0
|
||||
temp = n
|
||||
|
||||
return 1 if n == 0
|
||||
|
||||
until temp.zero?
|
||||
count += 1
|
||||
temp /= 10
|
||||
end
|
||||
|
||||
count
|
||||
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
|
||||
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
|
||||
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
|
||||
|
|
|
@ -1,18 +1,19 @@
|
|||
# Given a number, find sum of its digits.
|
||||
|
||||
def digits_sum(n)
|
||||
a, sum = 0, 0
|
||||
a = 0
|
||||
sum = 0
|
||||
until n.zero?
|
||||
a = n % 10
|
||||
sum += a
|
||||
n /= 10
|
||||
end
|
||||
return sum
|
||||
sum
|
||||
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
|
||||
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
|
||||
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
|
||||
|
|
|
@ -1,12 +1,12 @@
|
|||
# Fisher and Yates Shuffle is one of the simplest and most popular shuffling algorithm
|
||||
def fisher_yates_shuffle(array)
|
||||
n = array.length
|
||||
while n > 0
|
||||
i = rand(n-=1)
|
||||
while n > 0
|
||||
i = rand(n -= 1)
|
||||
array[i], array[n] = array[n], array[i]
|
||||
end
|
||||
return array
|
||||
array
|
||||
end
|
||||
|
||||
arr = [1, 2, 40, 30, 20, 15, 323, 12, 3, 4]
|
||||
puts fisher_yates_shuffle(arr)
|
||||
puts fisher_yates_shuffle(arr)
|
||||
|
|
|
@ -8,7 +8,7 @@ even_fib_sum = 0
|
|||
fib_first = 1
|
||||
fib_second = 2
|
||||
|
||||
while fib_second < 4000000
|
||||
while fib_second < 4_000_000
|
||||
even_fib_sum += fib_second if fib_second.even?
|
||||
fib_second += fib_first
|
||||
fib_first = fib_second - fib_first
|
||||
|
|
|
@ -26,4 +26,4 @@ def largest_prime_factor(number)
|
|||
prime_factors.max
|
||||
end
|
||||
|
||||
puts largest_prime_factor(600851475143)
|
||||
puts largest_prime_factor(600_851_475_143)
|
||||
|
|
|
@ -15,4 +15,4 @@ def solution(n)
|
|||
prime.to_i
|
||||
end
|
||||
|
||||
puts solution(600851475143)
|
||||
puts solution(600_851_475_143)
|
||||
|
|
|
@ -8,4 +8,4 @@ answer = 0
|
|||
answer = i * j if (t.to_s == t.to_s.reverse) && (t > answer) && (t > answer)
|
||||
end
|
||||
end
|
||||
puts answer
|
||||
puts answer
|
||||
|
|
|
@ -3,7 +3,6 @@
|
|||
# What is the smallest positive number that is evenly
|
||||
# divisible by all of the numbers from 1 to 20?
|
||||
|
||||
|
||||
# Euclid's algorithm for the greatest common divisor
|
||||
def gcd(a, b)
|
||||
b.zero? ? a : gcd(b, a % b)
|
||||
|
@ -20,4 +19,4 @@ result = 1
|
|||
result = lcm(result, i + 1)
|
||||
end
|
||||
|
||||
p result
|
||||
p result
|
||||
|
|
|
@ -1,15 +1,17 @@
|
|||
=begin
|
||||
Searches through a list for a value in O(log(n)) time.
|
||||
The list must be sorted.
|
||||
=end
|
||||
# Searches through a list for a value in O(log(n)) time.
|
||||
# The list must be sorted.
|
||||
def binary_search(array, key)
|
||||
front = 0
|
||||
back = array.length - 1
|
||||
while front <= back
|
||||
middle = (front + back) / 2
|
||||
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
|
||||
nil
|
||||
end
|
||||
|
@ -18,6 +20,8 @@ puts "Enter a sorted space-separated list:"
|
|||
arr = gets.chomp.split(' ').map(&:to_i)
|
||||
puts "Enter the value to be searched:"
|
||||
value = gets.chomp.to_i
|
||||
puts binary_search(arr, value) != nil ?
|
||||
"Found at index #{binary_search(arr, value)}" :
|
||||
puts if binary_search(arr, value) != nil
|
||||
"Found at index #{binary_search(arr, value)}"
|
||||
else
|
||||
"Not found"
|
||||
end
|
||||
|
|
|
@ -8,6 +8,7 @@ def dfs(start, target, adjacency_list)
|
|||
stack = [start]
|
||||
loop do
|
||||
break if stack.empty?
|
||||
|
||||
current_node = stack.pop
|
||||
is_visited[current_node] = true
|
||||
|
||||
|
@ -15,6 +16,7 @@ def dfs(start, target, adjacency_list)
|
|||
|
||||
adjacency_list[current_node].each do |neighbor|
|
||||
next if is_visited[neighbor]
|
||||
|
||||
stack << neighbor
|
||||
is_visited[neighbor] = true
|
||||
parent[neighbor] = current_node
|
||||
|
@ -38,12 +40,12 @@ end
|
|||
|
||||
def main
|
||||
adjacency_list = [
|
||||
[1, 2], #0
|
||||
[0, 3], #1
|
||||
[0, 3], #2
|
||||
[1, 2, 4], #3
|
||||
[3, 5], #4
|
||||
[4] #5
|
||||
[1, 2], # 0
|
||||
[0, 3], # 1
|
||||
[0, 3], # 2
|
||||
[1, 2, 4], # 3
|
||||
[3, 5], # 4
|
||||
[4] # 5
|
||||
]
|
||||
p dfs(0, 5, adjacency_list)
|
||||
end
|
||||
|
|
|
@ -1,18 +1,18 @@
|
|||
=begin
|
||||
Looks through array for a value in O(n) time.
|
||||
Array does not need to be sorted.
|
||||
=end
|
||||
# Looks through array for a value in O(n) time.
|
||||
# Array does not need to be sorted.
|
||||
def linear_search(array, key)
|
||||
array.each_with_index do |current, index|
|
||||
return index if current == key
|
||||
end
|
||||
return nil
|
||||
nil
|
||||
end
|
||||
|
||||
puts "Enter a space-separated list:"
|
||||
arr = gets.chomp.split(' ').map(&:to_i)
|
||||
puts "Enter a value to be searched:"
|
||||
key = gets.chomp.to_i
|
||||
puts linear_search(arr, key) != nil ?
|
||||
"Found at index #{linear_search(arr, key)}" :
|
||||
puts if linear_search(arr, key) != nil
|
||||
"Found at index #{linear_search(arr, key)}"
|
||||
else
|
||||
"Not found"
|
||||
end
|
||||
|
|
|
@ -1,43 +1,43 @@
|
|||
=begin
|
||||
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 divide-and-conquer algorithm.
|
||||
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.
|
||||
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)
|
||||
Space Complexity: O(1)
|
||||
=end
|
||||
# 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 divide-and-conquer algorithm.
|
||||
# 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.
|
||||
# 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)
|
||||
# Space Complexity: O(1)
|
||||
|
||||
def ternary_search(l, r, key, arr)
|
||||
#l is the starting index and r is the ending index of the array/sub-array.
|
||||
if (r >= l)
|
||||
#find mid1 and mid2
|
||||
mid1 = l + (r - l) / 3
|
||||
mid2 = r - (r - l) / 3
|
||||
#check if key is equal to mid1
|
||||
if arr[mid1] == key
|
||||
mid1
|
||||
#check if key is equal to mid2
|
||||
elsif arr[mid2] == key
|
||||
mid2
|
||||
#Since key is not present at mid, check in which region it is present
|
||||
#then repeat the Search operation in that region
|
||||
elsif key < arr[mid1]
|
||||
ternary_search(l, mid1 - 1, key, arr)
|
||||
elsif (key > arr[mid2])
|
||||
ternary_search(mid2 + 1, r, key, arr)
|
||||
else
|
||||
ternary_search(mid1 + 1, mid2 - 1, key, arr)
|
||||
end
|
||||
end
|
||||
# l is the starting index and r is the ending index of the array/sub-array.
|
||||
if r >= l
|
||||
# find mid1 and mid2
|
||||
mid1 = l + (r - l) / 3
|
||||
mid2 = r - (r - l) / 3
|
||||
# check if key is equal to mid1
|
||||
if arr[mid1] == key
|
||||
mid1
|
||||
# check if key is equal to mid2
|
||||
elsif arr[mid2] == key
|
||||
mid2
|
||||
# Since key is not present at mid, check in which region it is present
|
||||
# then repeat the Search operation in that region
|
||||
elsif key < arr[mid1]
|
||||
ternary_search(l, mid1 - 1, key, arr)
|
||||
elsif key > arr[mid2]
|
||||
ternary_search(mid2 + 1, r, key, arr)
|
||||
else
|
||||
ternary_search(mid1 + 1, mid2 - 1, key, arr)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
puts "Enter a space-separated list:"
|
||||
arr = gets.chomp.split(' ').map(&:to_i)
|
||||
puts "Enter a value to be searched:"
|
||||
key = gets.chomp.to_i
|
||||
puts ternary_search(0, arr.length - 1, key, arr) != nil ?
|
||||
"Found at index #{ternary_search(0, arr.length - 1, key, arr)}" :
|
||||
puts if ternary_search(0, arr.length - 1, key, arr) != nil
|
||||
"Found at index #{ternary_search(0, arr.length - 1, key, arr)}"
|
||||
else
|
||||
"Not found"
|
||||
end
|
||||
|
|
|
@ -1,20 +1,21 @@
|
|||
class Array
|
||||
def sorted?
|
||||
### goes thru array and checks if all elements are in order
|
||||
for i in 1...self.length
|
||||
return false if self[i-1] > self[i]
|
||||
(1...length).each do |i|
|
||||
return false if self[i - 1] > self[i]
|
||||
end
|
||||
return true
|
||||
true
|
||||
end
|
||||
|
||||
def bogosort
|
||||
### randomly shuffles until sorted
|
||||
self.shuffle! until self.sorted?
|
||||
return self #return sorted array
|
||||
shuffle! until sorted?
|
||||
self # return sorted array
|
||||
end
|
||||
end
|
||||
|
||||
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('')
|
||||
puts str.bogosort.join('')
|
||||
end
|
||||
|
|
|
@ -1,22 +1,22 @@
|
|||
def bubble_sort(array)
|
||||
n = array.length
|
||||
loop do
|
||||
swapped = false
|
||||
|
||||
(n-1).times do |i|
|
||||
if array[i] > array[i+1]
|
||||
array[i], array[i+1] = array[i+1], array[i]
|
||||
swapped = true
|
||||
end
|
||||
end
|
||||
|
||||
break if not swapped
|
||||
end
|
||||
|
||||
array
|
||||
end
|
||||
puts "Enter a list of numbers separated by space"
|
||||
|
||||
list = gets
|
||||
bubble_sort(list)
|
||||
print list
|
||||
def bubble_sort(array)
|
||||
n = array.length
|
||||
loop do
|
||||
swapped = false
|
||||
|
||||
(n - 1).times do |i|
|
||||
if array[i] > array[i + 1]
|
||||
array[i], array[i + 1] = array[i + 1], array[i]
|
||||
swapped = true
|
||||
end
|
||||
end
|
||||
|
||||
break unless swapped
|
||||
end
|
||||
|
||||
array
|
||||
end
|
||||
puts 'Enter a list of numbers separated by space'
|
||||
|
||||
list = gets
|
||||
bubble_sort(list)
|
||||
print list
|
||||
|
|
|
@ -1,30 +1,29 @@
|
|||
|
||||
DEFAULT_BUCKET_SIZE = 5
|
||||
|
||||
def bucket_sort(input, bucket_size = DEFAULT_BUCKET_SIZE)
|
||||
print 'Array is empty' if input.empty?
|
||||
|
||||
array = input.split(' ').map(&:to_i)
|
||||
|
||||
bucket_count = ((array.max - array.min) / bucket_size).floor + 1
|
||||
|
||||
# create buckets
|
||||
buckets = []
|
||||
bucket_count.times { buckets.push [] }
|
||||
|
||||
# fill buckets
|
||||
array.each do |item|
|
||||
buckets[((item - array.min) / bucket_size).floor].push(item)
|
||||
end
|
||||
|
||||
# sort buckets
|
||||
buckets.each do |bucket|
|
||||
bucket.sort!
|
||||
end
|
||||
|
||||
buckets.flatten.join(' ')
|
||||
end
|
||||
puts "Enter a list of numbers separated by space"
|
||||
|
||||
list = gets
|
||||
print bucket_sort(list)
|
||||
DEFAULT_BUCKET_SIZE = 5
|
||||
|
||||
def bucket_sort(input, bucket_size = DEFAULT_BUCKET_SIZE)
|
||||
print 'Array is empty' if input.empty?
|
||||
|
||||
array = input.split(' ').map(&:to_i)
|
||||
|
||||
bucket_count = ((array.max - array.min) / bucket_size).floor + 1
|
||||
|
||||
# create buckets
|
||||
buckets = []
|
||||
bucket_count.times { buckets.push [] }
|
||||
|
||||
# fill buckets
|
||||
array.each do |item|
|
||||
buckets[((item - array.min) / bucket_size).floor].push(item)
|
||||
end
|
||||
|
||||
# sort buckets
|
||||
buckets.each do |bucket|
|
||||
bucket.sort!
|
||||
end
|
||||
|
||||
buckets.flatten.join(' ')
|
||||
end
|
||||
puts 'Enter a list of numbers separated by space'
|
||||
|
||||
list = gets
|
||||
print bucket_sort(list)
|
||||
|
|
|
@ -7,25 +7,26 @@ def heap_sort(array)
|
|||
adjusted_down(adjusted_array, i, array_size)
|
||||
end
|
||||
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
|
||||
adjusted_down(adjusted_array, 1, array_size)
|
||||
end
|
||||
adjusted_array.drop(1)
|
||||
end
|
||||
|
||||
#Method to adjust heap in downward manner
|
||||
# Method to adjust heap in downward manner
|
||||
def adjusted_down(adjusted_array, parent, limit)
|
||||
top = adjusted_array[parent]
|
||||
while (child = 2 * parent) <= limit
|
||||
child += 1 if child < limit and adjusted_array[child] < adjusted_array[child + 1]
|
||||
break if top >= adjusted_array[child]
|
||||
child += 1 if (child < limit) && (adjusted_array[child] < adjusted_array[child + 1])
|
||||
break if top >= adjusted_array[child]
|
||||
|
||||
adjusted_array[parent] = adjusted_array[child]
|
||||
parent = child
|
||||
end
|
||||
adjusted_array[parent] = top
|
||||
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
|
||||
print heap_sort(array)
|
||||
print heap_sort(array)
|
||||
|
|
|
@ -1,17 +1,17 @@
|
|||
def insertion_sort(array)
|
||||
0.upto(array.length - 1).each do |index|
|
||||
element = array[index]
|
||||
position = index
|
||||
while element < array[position - 1] && position > 0
|
||||
array[position] = array[position - 1]
|
||||
array[position - 1] = element
|
||||
position -= 1
|
||||
end
|
||||
end
|
||||
array
|
||||
end
|
||||
puts "Enter a list of numbers separated by space"
|
||||
|
||||
list = gets
|
||||
insertion_sort(list)
|
||||
print list
|
||||
def insertion_sort(array)
|
||||
0.upto(array.length - 1).each do |index|
|
||||
element = array[index]
|
||||
position = index
|
||||
while element < array[position - 1] && position > 0
|
||||
array[position] = array[position - 1]
|
||||
array[position - 1] = element
|
||||
position -= 1
|
||||
end
|
||||
end
|
||||
array
|
||||
end
|
||||
puts 'Enter a list of numbers separated by space'
|
||||
|
||||
list = gets
|
||||
insertion_sort(list)
|
||||
print list
|
||||
|
|
|
@ -1,5 +1,6 @@
|
|||
def merge_sort(array)
|
||||
return array if array.length <= 1
|
||||
|
||||
mid = array.length / 2
|
||||
first_array = array.slice(0..mid - 1)
|
||||
second_array = array.slice(mid..-1)
|
||||
|
@ -9,7 +10,7 @@ def merge_sort(array)
|
|||
|
||||
# merge
|
||||
result = []
|
||||
until first_array.empty? and second_array.empty?
|
||||
until first_array.empty? && second_array.empty?
|
||||
if first_array.empty?
|
||||
result.concat(second_array)
|
||||
second_array.clear
|
||||
|
@ -17,16 +18,16 @@ def merge_sort(array)
|
|||
result.concat(first_array)
|
||||
first_array.clear
|
||||
else
|
||||
if first_array.first < second_array.first
|
||||
result << first_array.shift
|
||||
else
|
||||
result << second_array.shift
|
||||
end
|
||||
result << if first_array.first < second_array.first
|
||||
first_array.shift
|
||||
else
|
||||
second_array.shift
|
||||
end
|
||||
end
|
||||
end
|
||||
result
|
||||
end
|
||||
|
||||
puts "Enter a list of numbers separated by space"
|
||||
puts 'Enter a list of numbers separated by space'
|
||||
list = gets
|
||||
print merge_sort list.split(" ").map(&:to_i)
|
||||
print merge_sort list.split(' ').map(&:to_i)
|
||||
|
|
|
@ -8,7 +8,7 @@ def quicksort(arr)
|
|||
left, right = arr.partition(&pivot.method(:>))
|
||||
|
||||
# recursively calling the quicksort method on itself
|
||||
return *quicksort(left), pivot, *quicksort(right)
|
||||
[*quicksort(left), pivot, *quicksort(right)]
|
||||
end
|
||||
|
||||
arr = [34, 2, 1, 5, 3]
|
||||
|
|
|
@ -13,6 +13,6 @@ def selection_sort(array)
|
|||
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)
|
||||
puts "Sorted array is: #{arr.inspect}"
|
||||
|
|
|
@ -1,27 +1,24 @@
|
|||
def shell_sort(a)
|
||||
n=a.length
|
||||
h=1
|
||||
n = a.length
|
||||
h = 1
|
||||
|
||||
while (h<n/3) #for computing increment factor "h"
|
||||
h= (3*h)+1
|
||||
end
|
||||
h = (3 * h) + 1 while h < n / 3
|
||||
|
||||
while h>=1
|
||||
while h >= 1
|
||||
# Logic of insertion sort with inrement steps of "h"
|
||||
for i in h...n
|
||||
j=i
|
||||
while j>=h
|
||||
if a[j-h]>a[j]
|
||||
temp=a[j]
|
||||
a[j]=a[j-h]
|
||||
a[j-h]=temp
|
||||
(h...n).each do |i|
|
||||
j = i
|
||||
while j >= h
|
||||
if a[j - h] > a[j]
|
||||
temp = a[j]
|
||||
a[j] = a[j - h]
|
||||
a[j - h] = temp
|
||||
end
|
||||
j-=h
|
||||
j -= h
|
||||
end
|
||||
end
|
||||
h/=3
|
||||
h /= 3
|
||||
end
|
||||
|
||||
return a
|
||||
|
||||
a
|
||||
end
|
||||
|
|
Loading…
Reference in a new issue