mirror of
https://github.com/TheAlgorithms/Ruby
synced 2024-12-25 21:58:57 +01:00
Minor fixes
This commit is contained in:
parent
f3c42a5829
commit
8bb781f790
59 changed files with 471 additions and 501 deletions
0
360
Normal file
0
360
Normal file
|
@ -26,7 +26,7 @@
|
||||||
# brackets.
|
# brackets.
|
||||||
|
|
||||||
# Complexity Analysis
|
# Complexity Analysis
|
||||||
#
|
#
|
||||||
# Time Complexity: O(4^n/sqrt(n)). Each valid sequence has at most n steps during the backtracking procedure.
|
# Time Complexity: O(4^n/sqrt(n)). Each valid sequence has at most n steps during the backtracking procedure.
|
||||||
# Space Complexity: O(4^n/sqrt(n)), as described above, and using O(n) space to store the sequence.
|
# Space Complexity: O(4^n/sqrt(n)), as described above, and using O(n) space to store the sequence.
|
||||||
|
|
||||||
|
@ -37,7 +37,7 @@
|
||||||
# @return {String[]}
|
# @return {String[]}
|
||||||
def generate_parenthesis(n)
|
def generate_parenthesis(n)
|
||||||
parenthesis = []
|
parenthesis = []
|
||||||
backtrack(parenthesis, "", 0, 0, n)
|
backtrack(parenthesis, '', 0, 0, n)
|
||||||
parenthesis
|
parenthesis
|
||||||
end
|
end
|
||||||
|
|
||||||
|
@ -47,13 +47,9 @@ def backtrack(parenthesis, curr, open, close, max)
|
||||||
return
|
return
|
||||||
end
|
end
|
||||||
|
|
||||||
if open < max
|
backtrack(parenthesis, curr + '(', open + 1, close, max) if open < max
|
||||||
backtrack(parenthesis, curr + "(", open + 1, close, max)
|
|
||||||
end
|
|
||||||
|
|
||||||
if close < open
|
backtrack(parenthesis, curr + ')', open, close + 1, max) if close < open
|
||||||
backtrack(parenthesis, curr + ")", open, close + 1, max)
|
|
||||||
end
|
|
||||||
end
|
end
|
||||||
|
|
||||||
n = 3
|
n = 3
|
||||||
|
|
|
@ -1,12 +1,12 @@
|
||||||
def binary_and(x, y)
|
def binary_and(x, y)
|
||||||
raise 'Input must only contain positive integers' if x < 0 or y < 0
|
raise 'Input must only contain positive integers' if (x < 0) || (y < 0)
|
||||||
|
|
||||||
"0b" + (x & y).to_s(2)
|
'0b' + (x & y).to_s(2)
|
||||||
end
|
end
|
||||||
|
|
||||||
begin
|
begin
|
||||||
binary_and(-1, 0)
|
binary_and(-1, 0)
|
||||||
rescue => e
|
rescue StandardError => e
|
||||||
puts e.message
|
puts e.message
|
||||||
end
|
end
|
||||||
# Input must only contain positive integers
|
# Input must only contain positive integers
|
||||||
|
|
|
@ -8,7 +8,7 @@ end
|
||||||
|
|
||||||
begin
|
begin
|
||||||
binary_count_setbits(-1)
|
binary_count_setbits(-1)
|
||||||
rescue => e
|
rescue StandardError => e
|
||||||
puts e.message
|
puts e.message
|
||||||
end
|
end
|
||||||
# Input must be a positive integer
|
# Input must be a positive integer
|
||||||
|
|
|
@ -5,7 +5,7 @@ def binary_count_trailing_zeroes(x)
|
||||||
|
|
||||||
count = 0
|
count = 0
|
||||||
binary.chars.reverse_each do |char|
|
binary.chars.reverse_each do |char|
|
||||||
break if char == "1"
|
break if char == '1'
|
||||||
|
|
||||||
count += 1
|
count += 1
|
||||||
end
|
end
|
||||||
|
@ -15,7 +15,7 @@ end
|
||||||
|
|
||||||
begin
|
begin
|
||||||
binary_count_trailing_zeroes(-1)
|
binary_count_trailing_zeroes(-1)
|
||||||
rescue => e
|
rescue StandardError => e
|
||||||
puts e.message
|
puts e.message
|
||||||
end
|
end
|
||||||
# Input must be a positive integer
|
# Input must be a positive integer
|
||||||
|
@ -32,5 +32,5 @@ puts binary_count_trailing_zeroes(1024)
|
||||||
puts binary_count_trailing_zeroes(54)
|
puts binary_count_trailing_zeroes(54)
|
||||||
# 1
|
# 1
|
||||||
|
|
||||||
puts binary_count_trailing_zeroes(121024)
|
puts binary_count_trailing_zeroes(121_024)
|
||||||
# 6
|
# 6
|
||||||
|
|
|
@ -1,12 +1,12 @@
|
||||||
def binary_or(x, y)
|
def binary_or(x, y)
|
||||||
raise 'Input must only contain positive integers' if x < 0 or y < 0
|
raise 'Input must only contain positive integers' if (x < 0) || (y < 0)
|
||||||
|
|
||||||
"0b" + (x | y).to_s(2)
|
'0b' + (x | y).to_s(2)
|
||||||
end
|
end
|
||||||
|
|
||||||
begin
|
begin
|
||||||
binary_or(-1, 0)
|
binary_or(-1, 0)
|
||||||
rescue => e
|
rescue StandardError => e
|
||||||
puts e.message
|
puts e.message
|
||||||
end
|
end
|
||||||
# Input must only contain positive integers
|
# Input must only contain positive integers
|
||||||
|
@ -21,4 +21,3 @@ puts binary_or(0, 1023)
|
||||||
# 0b1111111111
|
# 0b1111111111
|
||||||
puts binary_or(16, 58)
|
puts binary_or(16, 58)
|
||||||
# 0b110010
|
# 0b110010
|
||||||
|
|
||||||
|
|
|
@ -1,25 +1,25 @@
|
||||||
def binary_xor(x, y)
|
def binary_xor(x, y)
|
||||||
raise 'Input must only contain positive integers' if x < 0 or y < 0
|
raise 'Input must only contain positive integers' if (x < 0) || (y < 0)
|
||||||
|
|
||||||
binary_x = x.to_s(2)
|
binary_x = x.to_s(2)
|
||||||
binary_y = y.to_s(2)
|
binary_y = y.to_s(2)
|
||||||
|
|
||||||
if binary_x.length > binary_y.length
|
if binary_x.length > binary_y.length
|
||||||
prefix = "0" * (binary_x.length - binary_y.length)
|
prefix = '0' * (binary_x.length - binary_y.length)
|
||||||
binary_y = prefix + binary_y
|
binary_y = prefix + binary_y
|
||||||
elsif binary_y.length > binary_x.length
|
elsif binary_y.length > binary_x.length
|
||||||
prefix = "0" * (binary_y.length - binary_x.length)
|
prefix = '0' * (binary_y.length - binary_x.length)
|
||||||
binary_x = prefix + binary_x
|
binary_x = prefix + binary_x
|
||||||
end
|
end
|
||||||
result = "0b"
|
result = '0b'
|
||||||
binary_x.each_char.with_index do |x_char, i|
|
binary_x.each_char.with_index do |x_char, i|
|
||||||
y_char = binary_y[i]
|
y_char = binary_y[i]
|
||||||
|
|
||||||
if (x_char == "1" && y_char != "1") || (x_char != "1" && y_char == "1")
|
result += if (x_char == '1' && y_char != '1') || (x_char != '1' && y_char == '1')
|
||||||
result += "1"
|
'1'
|
||||||
else
|
else
|
||||||
result += "0"
|
'0'
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
result
|
result
|
||||||
|
@ -27,7 +27,7 @@ end
|
||||||
|
|
||||||
begin
|
begin
|
||||||
binary_xor(-1, 0)
|
binary_xor(-1, 0)
|
||||||
rescue => e
|
rescue StandardError => e
|
||||||
puts e.message
|
puts e.message
|
||||||
end
|
end
|
||||||
# Input must only contain positive integers
|
# Input must only contain positive integers
|
||||||
|
|
|
@ -1,5 +1,5 @@
|
||||||
def set_bit(x, position)
|
def set_bit(x, position)
|
||||||
raise "position must be >= 0" if position < 0
|
raise 'position must be >= 0' if position < 0
|
||||||
|
|
||||||
x | (1 << position)
|
x | (1 << position)
|
||||||
end
|
end
|
||||||
|
@ -18,14 +18,13 @@ puts set_bit(8, 4)
|
||||||
|
|
||||||
begin
|
begin
|
||||||
puts set_bit(8, -4)
|
puts set_bit(8, -4)
|
||||||
rescue => e
|
rescue StandardError => e
|
||||||
puts e.message
|
puts e.message
|
||||||
end
|
end
|
||||||
# position must be >= 0
|
# position must be >= 0
|
||||||
|
|
||||||
|
|
||||||
def clear_bit(x, position)
|
def clear_bit(x, position)
|
||||||
raise "position must be > 0" if position < 0
|
raise 'position must be > 0' if position < 0
|
||||||
|
|
||||||
x & ~(1 << position)
|
x & ~(1 << position)
|
||||||
end
|
end
|
||||||
|
@ -44,13 +43,13 @@ puts clear_bit(24, 4)
|
||||||
|
|
||||||
begin
|
begin
|
||||||
puts clear_bit(0, -4)
|
puts clear_bit(0, -4)
|
||||||
rescue => e
|
rescue StandardError => e
|
||||||
puts e.message
|
puts e.message
|
||||||
end
|
end
|
||||||
# position must be > 0
|
# position must be > 0
|
||||||
|
|
||||||
def flip_bit(x, position)
|
def flip_bit(x, position)
|
||||||
raise "position must be > 0" if position < 0
|
raise 'position must be > 0' if position < 0
|
||||||
|
|
||||||
x ^ (1 << position)
|
x ^ (1 << position)
|
||||||
end
|
end
|
||||||
|
@ -69,13 +68,13 @@ puts flip_bit(24, 4)
|
||||||
|
|
||||||
begin
|
begin
|
||||||
puts flip_bit(0, -4)
|
puts flip_bit(0, -4)
|
||||||
rescue => e
|
rescue StandardError => e
|
||||||
puts e.message
|
puts e.message
|
||||||
end
|
end
|
||||||
# position must be > 0
|
# position must be > 0
|
||||||
|
|
||||||
def is_bit_set(x, position)
|
def is_bit_set(x, position)
|
||||||
raise "position must be > 0" if position < 0
|
raise 'position must be > 0' if position < 0
|
||||||
|
|
||||||
((x >> position) & 1) == 1
|
((x >> position) & 1) == 1
|
||||||
end
|
end
|
||||||
|
@ -94,7 +93,7 @@ puts is_bit_set(24, 4)
|
||||||
|
|
||||||
begin
|
begin
|
||||||
puts is_bit_set(0, -4)
|
puts is_bit_set(0, -4)
|
||||||
rescue => e
|
rescue StandardError => e
|
||||||
puts e.message
|
puts e.message
|
||||||
end
|
end
|
||||||
# position must be > 0
|
# position must be > 0
|
||||||
|
|
|
@ -5,48 +5,48 @@ module TemperatureConversion
|
||||||
def self.celsius_to_kelvin(celsius_input)
|
def self.celsius_to_kelvin(celsius_input)
|
||||||
kelvin_output = (celsius_input + 273.15).round(2)
|
kelvin_output = (celsius_input + 273.15).round(2)
|
||||||
puts "#{celsius_input}°C = #{kelvin_output}K"
|
puts "#{celsius_input}°C = #{kelvin_output}K"
|
||||||
rescue
|
rescue StandardError
|
||||||
puts "Error: Please provide number only!"
|
puts 'Error: Please provide number only!'
|
||||||
end
|
end
|
||||||
|
|
||||||
# kelvin -> celsius = vale of kelvin - 273.15 => °C
|
# kelvin -> celsius = vale of kelvin - 273.15 => °C
|
||||||
def self.kelvin_to_celsius(kelvin_input)
|
def self.kelvin_to_celsius(kelvin_input)
|
||||||
celsius_output = (kelvin_input - 273.15).round(2)
|
celsius_output = (kelvin_input - 273.15).round(2)
|
||||||
puts "#{kelvin_input}K = #{celsius_output}°C"
|
puts "#{kelvin_input}K = #{celsius_output}°C"
|
||||||
rescue
|
rescue StandardError
|
||||||
puts "Error: Please provide number only!"
|
puts 'Error: Please provide number only!'
|
||||||
end
|
end
|
||||||
|
|
||||||
# celsius -> fahrenheit = (value of celsius * 9 / 5) + 32 => °F
|
# celsius -> fahrenheit = (value of celsius * 9 / 5) + 32 => °F
|
||||||
def self.celsius_to_fahrenheit(celsius_input)
|
def self.celsius_to_fahrenheit(celsius_input)
|
||||||
fahrenheit_output = ((celsius_input * 9 / 5) + 32).round(2)
|
fahrenheit_output = ((celsius_input * 9 / 5) + 32).round(2)
|
||||||
puts "#{celsius_input}°C = #{fahrenheit_output}°F"
|
puts "#{celsius_input}°C = #{fahrenheit_output}°F"
|
||||||
rescue
|
rescue StandardError
|
||||||
puts "Error: Please provide number only!"
|
puts 'Error: Please provide number only!'
|
||||||
end
|
end
|
||||||
|
|
||||||
# fahrenheit -> celsius = (value of fahrenheit - 32) * 5 / 9 => °C
|
# fahrenheit -> celsius = (value of fahrenheit - 32) * 5 / 9 => °C
|
||||||
def self.fahrenheit_to_celsius(fahrenheit_input)
|
def self.fahrenheit_to_celsius(fahrenheit_input)
|
||||||
celsius_output = ((fahrenheit_input - 32) * 5 / 9).round(2)
|
celsius_output = ((fahrenheit_input - 32) * 5 / 9).round(2)
|
||||||
puts "#{fahrenheit_input}°F = #{celsius_output}°C"
|
puts "#{fahrenheit_input}°F = #{celsius_output}°C"
|
||||||
rescue
|
rescue StandardError
|
||||||
puts "Error: Please provide number only!"
|
puts 'Error: Please provide number only!'
|
||||||
end
|
end
|
||||||
|
|
||||||
# fahrenheit -> kelvin = [(value of fahrenheit - 32) * 5 / 9] + 273.15 => K
|
# fahrenheit -> kelvin = [(value of fahrenheit - 32) * 5 / 9] + 273.15 => K
|
||||||
def self.fahrenheit_to_kelvin(fahrenheit_input)
|
def self.fahrenheit_to_kelvin(fahrenheit_input)
|
||||||
kelvin_output = ((fahrenheit_input - 32) * 5 / 9).round(2).round(2)
|
kelvin_output = ((fahrenheit_input - 32) * 5 / 9).round(2).round(2)
|
||||||
puts "#{fahrenheit_input}°F = #{kelvin_output}K"
|
puts "#{fahrenheit_input}°F = #{kelvin_output}K"
|
||||||
rescue
|
rescue StandardError
|
||||||
puts "Error: Please provide number only!"
|
puts 'Error: Please provide number only!'
|
||||||
end
|
end
|
||||||
|
|
||||||
# kelvin -> fahrenheit = [(value of kelvin - 32) * 5 / 9] + 273.15 => K
|
# kelvin -> fahrenheit = [(value of kelvin - 32) * 5 / 9] + 273.15 => K
|
||||||
def self.kelvin_to_fahrenheit(kelvin_input)
|
def self.kelvin_to_fahrenheit(kelvin_input)
|
||||||
fahrenheit_output = (((kelvin_input - 273.15) * 9 / 5) + 32).round(2).round(2)
|
fahrenheit_output = (((kelvin_input - 273.15) * 9 / 5) + 32).round(2).round(2)
|
||||||
puts "#{kelvin_input}K = #{fahrenheit_output}°F"
|
puts "#{kelvin_input}K = #{fahrenheit_output}°F"
|
||||||
rescue
|
rescue StandardError
|
||||||
puts "Error: Please provide number only!"
|
puts 'Error: Please provide number only!'
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
|
@ -55,18 +55,18 @@ TemperatureConversion.celsius_to_kelvin(20)
|
||||||
TemperatureConversion.kelvin_to_celsius(20)
|
TemperatureConversion.kelvin_to_celsius(20)
|
||||||
|
|
||||||
# Invalid input
|
# Invalid input
|
||||||
TemperatureConversion.kelvin_to_celsius("a")
|
TemperatureConversion.kelvin_to_celsius('a')
|
||||||
|
|
||||||
# celsius <-> fahrenheit
|
# celsius <-> fahrenheit
|
||||||
TemperatureConversion.celsius_to_fahrenheit(-20)
|
TemperatureConversion.celsius_to_fahrenheit(-20)
|
||||||
TemperatureConversion.fahrenheit_to_celsius(68)
|
TemperatureConversion.fahrenheit_to_celsius(68)
|
||||||
|
|
||||||
# Invalid input
|
# Invalid input
|
||||||
TemperatureConversion.celsius_to_fahrenheit("abc")
|
TemperatureConversion.celsius_to_fahrenheit('abc')
|
||||||
|
|
||||||
# fahrenheit <-> kelvin
|
# fahrenheit <-> kelvin
|
||||||
TemperatureConversion.fahrenheit_to_kelvin(60)
|
TemperatureConversion.fahrenheit_to_kelvin(60)
|
||||||
TemperatureConversion.kelvin_to_fahrenheit(-60)
|
TemperatureConversion.kelvin_to_fahrenheit(-60)
|
||||||
|
|
||||||
# Invalid input
|
# Invalid input
|
||||||
TemperatureConversion.fahrenheit_to_kelvin("60")
|
TemperatureConversion.fahrenheit_to_kelvin('60')
|
||||||
|
|
|
@ -3,7 +3,7 @@
|
||||||
module WeightConversion
|
module WeightConversion
|
||||||
# Kilogram -> Gram = (kilogram_value * 1000) grams
|
# Kilogram -> Gram = (kilogram_value * 1000) grams
|
||||||
def self.kilogram_to_gram(kilogram_input)
|
def self.kilogram_to_gram(kilogram_input)
|
||||||
raise StandardError unless Integer === kilogram_input
|
raise StandardError unless kilogram_input.is_a?(Integer)
|
||||||
|
|
||||||
gram = kilogram_input * 1000
|
gram = kilogram_input * 1000
|
||||||
|
|
||||||
|
@ -40,7 +40,7 @@ module WeightConversion
|
||||||
|
|
||||||
# Pound -> Kilogram = (pound_input / 2.205) kg
|
# Pound -> Kilogram = (pound_input / 2.205) kg
|
||||||
def self.pound_to_kilogram(pound_input)
|
def self.pound_to_kilogram(pound_input)
|
||||||
raise StandardError unless Integer === pound_input
|
raise StandardError unless pound_input.is_a?(Integer)
|
||||||
|
|
||||||
kilogram = (pound_input / 2.205).round(2)
|
kilogram = (pound_input / 2.205).round(2)
|
||||||
|
|
||||||
|
@ -48,9 +48,9 @@ module WeightConversion
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
#
|
#
|
||||||
# Valid inputs
|
# Valid inputs
|
||||||
#
|
#
|
||||||
|
|
||||||
puts WeightConversion.kilogram_to_gram(2)
|
puts WeightConversion.kilogram_to_gram(2)
|
||||||
# 2 kg = 2000 g
|
# 2 kg = 2000 g
|
||||||
|
@ -65,42 +65,42 @@ puts WeightConversion.kilogram_to_pound(1)
|
||||||
puts WeightConversion.pound_to_kilogram(100)
|
puts WeightConversion.pound_to_kilogram(100)
|
||||||
# 100 lb = 45.35 kg
|
# 100 lb = 45.35 kg
|
||||||
|
|
||||||
#
|
#
|
||||||
# Invalid inputs
|
# Invalid inputs
|
||||||
#
|
#
|
||||||
|
|
||||||
begin
|
begin
|
||||||
puts WeightConversion.kilogram_to_gram("a")
|
puts WeightConversion.kilogram_to_gram('a')
|
||||||
rescue StandardError
|
rescue StandardError
|
||||||
puts "Error: Please provide number only!"
|
puts 'Error: Please provide number only!'
|
||||||
end
|
end
|
||||||
|
|
||||||
begin
|
begin
|
||||||
puts WeightConversion.kilogram_to_gram("3000")
|
puts WeightConversion.kilogram_to_gram('3000')
|
||||||
rescue StandardError
|
rescue StandardError
|
||||||
puts "Error: Please provide number only!"
|
puts 'Error: Please provide number only!'
|
||||||
end
|
end
|
||||||
|
|
||||||
begin
|
begin
|
||||||
puts WeightConversion.kilogram_to_gram("16")
|
puts WeightConversion.kilogram_to_gram('16')
|
||||||
rescue StandardError
|
rescue StandardError
|
||||||
puts "Error: Please provide number only!"
|
puts 'Error: Please provide number only!'
|
||||||
end
|
end
|
||||||
|
|
||||||
begin
|
begin
|
||||||
puts WeightConversion.kilogram_to_gram("x ")
|
puts WeightConversion.kilogram_to_gram('x ')
|
||||||
rescue StandardError
|
rescue StandardError
|
||||||
puts "Error: Please provide number only!"
|
puts 'Error: Please provide number only!'
|
||||||
end
|
end
|
||||||
|
|
||||||
begin
|
begin
|
||||||
puts WeightConversion.kilogram_to_gram("weight")
|
puts WeightConversion.kilogram_to_gram('weight')
|
||||||
rescue StandardError
|
rescue StandardError
|
||||||
puts "Error: Please provide number only!"
|
puts 'Error: Please provide number only!'
|
||||||
end
|
end
|
||||||
|
|
||||||
begin
|
begin
|
||||||
puts WeightConversion.kilogram_to_gram("100")
|
puts WeightConversion.kilogram_to_gram('100')
|
||||||
rescue StandardError
|
rescue StandardError
|
||||||
puts "Error: Please provide number only!"
|
puts 'Error: Please provide number only!'
|
||||||
end
|
end
|
||||||
|
|
|
@ -20,9 +20,7 @@
|
||||||
# Time complexity: O(n)
|
# Time complexity: O(n)
|
||||||
#
|
#
|
||||||
def add_digits(num)
|
def add_digits(num)
|
||||||
if num.to_s.length < 2
|
return num if num.to_s.length < 2
|
||||||
return num
|
|
||||||
end
|
|
||||||
|
|
||||||
digits_to_sum = num.to_s.split('')
|
digits_to_sum = num.to_s.split('')
|
||||||
sum = 0
|
sum = 0
|
||||||
|
|
|
@ -19,9 +19,8 @@ def num_identical_pairs(nums)
|
||||||
target = num
|
target = num
|
||||||
nums.each_with_index do |num, j|
|
nums.each_with_index do |num, j|
|
||||||
next if i >= j
|
next if i >= j
|
||||||
if num == target
|
|
||||||
count += 1
|
count += 1 if num == target
|
||||||
end
|
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
count
|
count
|
||||||
|
|
|
@ -25,6 +25,7 @@ def intersect(arr1, arr2)
|
||||||
shorter.each do |matcher|
|
shorter.each do |matcher|
|
||||||
longer.each do |number|
|
longer.each do |number|
|
||||||
next if number != matcher
|
next if number != matcher
|
||||||
|
|
||||||
result.push(number)
|
result.push(number)
|
||||||
break
|
break
|
||||||
end
|
end
|
||||||
|
@ -60,7 +61,7 @@ def intersect(arr1, arr2)
|
||||||
|
|
||||||
hash = Hash.new(0)
|
hash = Hash.new(0)
|
||||||
|
|
||||||
arr2.each {|num| hash[num] += 1 }
|
arr2.each { |num| hash[num] += 1 }
|
||||||
|
|
||||||
arr1.each do |num|
|
arr1.each do |num|
|
||||||
if hash.has_key?(num)
|
if hash.has_key?(num)
|
||||||
|
@ -107,7 +108,7 @@ def intersect(nums1, nums2)
|
||||||
p2 += 1
|
p2 += 1
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
result
|
result
|
||||||
end
|
end
|
||||||
nums1 = [1, 2, 2, 1]
|
nums1 = [1, 2, 2, 1]
|
||||||
|
|
|
@ -1,6 +1,6 @@
|
||||||
# Challenge name: Maximum 69 number
|
# Challenge name: Maximum 69 number
|
||||||
#
|
#
|
||||||
# Given a positive integer num consisting only of digits 6 and 9.
|
# Given a positive integer num consisting only of digits 6 and 9.
|
||||||
# Return the maximum number you can get by changing at most one digit (6 becomes 9, and 9 becomes 6).
|
# Return the maximum number you can get by changing at most one digit (6 becomes 9, and 9 becomes 6).
|
||||||
#
|
#
|
||||||
# Example 1:
|
# Example 1:
|
||||||
|
@ -37,4 +37,4 @@ puts max_number(9669)
|
||||||
# => 9969
|
# => 9969
|
||||||
|
|
||||||
puts max_number(9996)
|
puts max_number(9996)
|
||||||
# => 9999
|
# => 9999
|
||||||
|
|
|
@ -23,12 +23,12 @@
|
||||||
# For number 2 in the first array, the next greater number for it in the second array is 3.
|
# For number 2 in the first array, the next greater number for it in the second array is 3.
|
||||||
# For number 4 in the first array, there is no next greater number for it in the second array, so output -1.
|
# For number 4 in the first array, there is no next greater number for it in the second array, so output -1.
|
||||||
|
|
||||||
#
|
#
|
||||||
# Approach: Brute Force
|
# Approach: Brute Force
|
||||||
#
|
#
|
||||||
|
|
||||||
# Complexity Analysis
|
# Complexity Analysis
|
||||||
#
|
#
|
||||||
# Time complexity: O(m*n). The complete nums1 array (of size n) needs to be scanned for all the m elements of nums2 in the worst case.
|
# Time complexity: O(m*n). The complete nums1 array (of size n) needs to be scanned for all the m elements of nums2 in the worst case.
|
||||||
# Space complexity: O(1). No additional space since we're swapping elements in nums1 and returning the input array.
|
# Space complexity: O(1). No additional space since we're swapping elements in nums1 and returning the input array.
|
||||||
|
|
||||||
|
|
|
@ -19,13 +19,13 @@
|
||||||
# Time complexity: O(n)
|
# Time complexity: O(n)
|
||||||
#
|
#
|
||||||
def remove_elements(nums, val)
|
def remove_elements(nums, val)
|
||||||
nums.delete_if{ |num| num == val }
|
nums.delete_if { |num| num == val }
|
||||||
nums.length
|
nums.length
|
||||||
end
|
end
|
||||||
|
|
||||||
puts remove_elements([3,2,2,3], 3)
|
puts remove_elements([3, 2, 2, 3], 3)
|
||||||
# => 2
|
# => 2
|
||||||
puts remove_elements([0,1,2,2,3,0,4,2], 2)
|
puts remove_elements([0, 1, 2, 2, 3, 0, 4, 2], 2)
|
||||||
# => 5
|
# => 5
|
||||||
|
|
||||||
#
|
#
|
||||||
|
@ -37,20 +37,20 @@ def remove_elements(nums, val)
|
||||||
result_length = nums.length
|
result_length = nums.length
|
||||||
shift_length = 0
|
shift_length = 0
|
||||||
nums.each_with_index do |num, i|
|
nums.each_with_index do |num, i|
|
||||||
if num == val
|
next unless num == val
|
||||||
nums.delete_at(i)
|
|
||||||
nums.unshift('removed')
|
nums.delete_at(i)
|
||||||
result_length -=1
|
nums.unshift('removed')
|
||||||
shift_length += 1
|
result_length -= 1
|
||||||
end
|
shift_length += 1
|
||||||
end
|
end
|
||||||
nums.shift(shift_length)
|
nums.shift(shift_length)
|
||||||
result_length
|
result_length
|
||||||
end
|
end
|
||||||
|
|
||||||
puts remove_elements([3,2,2,3], 3)
|
puts remove_elements([3, 2, 2, 3], 3)
|
||||||
# => 2
|
# => 2
|
||||||
puts remove_elements([0,1,2,2,3,0,4,2], 2)
|
puts remove_elements([0, 1, 2, 2, 3, 0, 4, 2], 2)
|
||||||
# => 5
|
# => 5
|
||||||
|
|
||||||
#
|
#
|
||||||
|
@ -78,9 +78,9 @@ def remove_element(nums, val)
|
||||||
pointer1
|
pointer1
|
||||||
end
|
end
|
||||||
|
|
||||||
puts remove_elements([3,2,2,3], 3)
|
puts remove_elements([3, 2, 2, 3], 3)
|
||||||
# => 2
|
# => 2
|
||||||
puts remove_elements([0,1,2,2,3,0,4,2], 2)
|
puts remove_elements([0, 1, 2, 2, 3, 0, 4, 2], 2)
|
||||||
# => 5
|
# => 5
|
||||||
|
|
||||||
#
|
#
|
||||||
|
@ -111,7 +111,7 @@ def remove_element(nums, val)
|
||||||
pointer1
|
pointer1
|
||||||
end
|
end
|
||||||
|
|
||||||
puts remove_elements([3,2,2,3], 3)
|
puts remove_elements([3, 2, 2, 3], 3)
|
||||||
# => 2
|
# => 2
|
||||||
puts remove_elements([0,1,2,2,3,0,4,2], 2)
|
puts remove_elements([0, 1, 2, 2, 3, 0, 4, 2], 2)
|
||||||
# => 5
|
# => 5
|
||||||
|
|
|
@ -45,12 +45,12 @@ def find_richest_customer_wealth(accounts)
|
||||||
summed_accounts.push(summed)
|
summed_accounts.push(summed)
|
||||||
end
|
end
|
||||||
|
|
||||||
summed_accounts.sort.pop()
|
summed_accounts.sort.pop
|
||||||
end
|
end
|
||||||
|
|
||||||
puts find_richest_customer_wealth([[1,2,3],[3,2,1]])
|
puts find_richest_customer_wealth([[1, 2, 3], [3, 2, 1]])
|
||||||
# => 6
|
# => 6
|
||||||
puts find_richest_customer_wealth([[1,5],[7,3],[3,5]])
|
puts find_richest_customer_wealth([[1, 5], [7, 3], [3, 5]])
|
||||||
# => 10
|
# => 10
|
||||||
puts find_richest_customer_wealth([[2,8,7],[7,1,3],[1,9,5]])
|
puts find_richest_customer_wealth([[2, 8, 7], [7, 1, 3], [1, 9, 5]])
|
||||||
# => 17
|
# => 17
|
||||||
|
|
|
@ -28,8 +28,8 @@
|
||||||
#
|
#
|
||||||
def shuffle(nums, n)
|
def shuffle(nums, n)
|
||||||
result = []
|
result = []
|
||||||
(0..n-1).count do |i|
|
(0..n - 1).count do |i|
|
||||||
result.push(nums[i], nums[i+n])
|
result.push(nums[i], nums[i + n])
|
||||||
end
|
end
|
||||||
result
|
result
|
||||||
end
|
end
|
||||||
|
@ -55,7 +55,7 @@ print(shuffle(nums, n))
|
||||||
|
|
||||||
def shuffle(nums, n)
|
def shuffle(nums, n)
|
||||||
current_index = 1
|
current_index = 1
|
||||||
(0..n-1).each do |i|
|
(0..n - 1).each do |i|
|
||||||
nums.insert(current_index, nums.delete_at(i + n))
|
nums.insert(current_index, nums.delete_at(i + n))
|
||||||
current_index += 2
|
current_index += 2
|
||||||
end
|
end
|
||||||
|
@ -88,8 +88,8 @@ def shuffle(nums, n)
|
||||||
|
|
||||||
while p1 < n
|
while p1 < n
|
||||||
result.push(nums[p1], nums[p2])
|
result.push(nums[p1], nums[p2])
|
||||||
p1 +=1
|
p1 += 1
|
||||||
p2 +=1
|
p2 += 1
|
||||||
end
|
end
|
||||||
|
|
||||||
result
|
result
|
||||||
|
@ -106,4 +106,4 @@ print(shuffle(nums, n))
|
||||||
nums = [1, 1, 2, 2]
|
nums = [1, 1, 2, 2]
|
||||||
n = 2
|
n = 2
|
||||||
print(shuffle(nums, n))
|
print(shuffle(nums, n))
|
||||||
# Output: [1,2,1,2]
|
# Output: [1,2,1,2]
|
||||||
|
|
|
@ -9,7 +9,7 @@
|
||||||
# @param {Integer[]} nums
|
# @param {Integer[]} nums
|
||||||
# @return {Integer}
|
# @return {Integer}
|
||||||
|
|
||||||
#
|
#
|
||||||
# Approach 1: Hash map
|
# Approach 1: Hash map
|
||||||
#
|
#
|
||||||
# Time Complexity: O(n)
|
# Time Complexity: O(n)
|
||||||
|
@ -18,7 +18,7 @@ def single_number(nums)
|
||||||
result_hash = {}
|
result_hash = {}
|
||||||
nums.each do |num|
|
nums.each do |num|
|
||||||
if result_hash[num]
|
if result_hash[num]
|
||||||
result_hash[num] +=1
|
result_hash[num] += 1
|
||||||
else
|
else
|
||||||
result_hash[num] = 1
|
result_hash[num] = 1
|
||||||
end
|
end
|
||||||
|
@ -58,4 +58,4 @@ puts(single_number(nums))
|
||||||
# Output: 4
|
# Output: 4
|
||||||
nums = [1]
|
nums = [1]
|
||||||
puts(single_number(nums))
|
puts(single_number(nums))
|
||||||
# Output: 1
|
# Output: 1
|
||||||
|
|
|
@ -28,16 +28,14 @@
|
||||||
# Time Complexity: O(n)
|
# Time Complexity: O(n)
|
||||||
# Space Complexity: O(1)
|
# Space Complexity: O(1)
|
||||||
|
|
||||||
|
|
||||||
def almost_palindrome_checker(string)
|
def almost_palindrome_checker(string)
|
||||||
p1 = 0
|
p1 = 0
|
||||||
p2 = string.length - 1
|
p2 = string.length - 1
|
||||||
array = string.split('')
|
array = string.split('')
|
||||||
|
|
||||||
while p1 < p2
|
while p1 < p2
|
||||||
if array[p1] != array[p2]
|
return palindrome_checker(array, p1, p2 - 1) || palindrome_checker(array, p1 + 1, p2) if array[p1] != array[p2]
|
||||||
return palindrome_checker(array, p1, p2 - 1) || palindrome_checker(array, p1 + 1, p2)
|
|
||||||
end
|
|
||||||
p1 += 1
|
p1 += 1
|
||||||
p2 -= 1
|
p2 -= 1
|
||||||
end
|
end
|
||||||
|
@ -47,9 +45,8 @@ end
|
||||||
|
|
||||||
def palindrome_checker(array, p1, p2)
|
def palindrome_checker(array, p1, p2)
|
||||||
while p1 < p2
|
while p1 < p2
|
||||||
if array[p1] != array[p2]
|
return false if array[p1] != array[p2]
|
||||||
return false
|
|
||||||
end
|
|
||||||
p1 += 1
|
p1 += 1
|
||||||
p2 -= 1
|
p2 -= 1
|
||||||
end
|
end
|
||||||
|
|
|
@ -30,23 +30,21 @@
|
||||||
# Time Complexity: O(n^2)
|
# Time Complexity: O(n^2)
|
||||||
#
|
#
|
||||||
|
|
||||||
def find_jewels(jewels, stones)
|
def find_jewels(jewels, stones)
|
||||||
jewels_array = jewels.split('')
|
jewels_array = jewels.split('')
|
||||||
stones_array = stones.split('')
|
stones_array = stones.split('')
|
||||||
result = 0
|
result = 0
|
||||||
jewels_array.each do |jewel|
|
jewels_array.each do |jewel|
|
||||||
stones_array.each do |stone|
|
stones_array.each do |stone|
|
||||||
if jewel == stone
|
result += 1 if jewel == stone
|
||||||
result += 1
|
|
||||||
end
|
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
result
|
result
|
||||||
end
|
end
|
||||||
|
|
||||||
puts find_jewels("aA", "aAAbbbb")
|
puts find_jewels('aA', 'aAAbbbb')
|
||||||
# => 3
|
# => 3
|
||||||
puts find_jewels("z", "ZZ")
|
puts find_jewels('z', 'ZZ')
|
||||||
# => 0
|
# => 0
|
||||||
|
|
||||||
#
|
#
|
||||||
|
@ -62,7 +60,7 @@ def find_jewels(jewels, stones)
|
||||||
result = 0
|
result = 0
|
||||||
|
|
||||||
stones_array.each do |stone|
|
stones_array.each do |stone|
|
||||||
if result_hash[stone]
|
if result_hash[stone]
|
||||||
result_hash[stone] += 1
|
result_hash[stone] += 1
|
||||||
else
|
else
|
||||||
result_hash[stone] = 1
|
result_hash[stone] = 1
|
||||||
|
@ -80,7 +78,7 @@ def find_jewels(jewels, stones)
|
||||||
result
|
result
|
||||||
end
|
end
|
||||||
|
|
||||||
puts find_jewels("aA", "aAAbbbb")
|
puts find_jewels('aA', 'aAAbbbb')
|
||||||
# => 3
|
# => 3
|
||||||
puts find_jewels("z", "ZZ")
|
puts find_jewels('z', 'ZZ')
|
||||||
# => 0
|
# => 0
|
||||||
|
|
|
@ -52,8 +52,8 @@ puts is_palindrome(s)
|
||||||
# Time Complexity: O(n), in length n of the string.
|
# Time Complexity: O(n), in length n of the string.
|
||||||
#
|
#
|
||||||
# We need to iterate through the string: When we filter out non-alphanumeric characters and convert the remaining
|
# We need to iterate through the string: When we filter out non-alphanumeric characters and convert the remaining
|
||||||
# characters to lower-case. When we reverse the string. When we compare the original and the reversed strings.
|
# characters to lower-case. When we reverse the string. When we compare the original and the reversed strings.
|
||||||
# Each iteration runs linearly in time (since each character operation completes in constant time).
|
# Each iteration runs linearly in time (since each character operation completes in constant time).
|
||||||
# Thus, the effective run-time complexity is linear.
|
# Thus, the effective run-time complexity is linear.
|
||||||
#
|
#
|
||||||
# Space Complexity: O(n), in length n of the string. We need O(n) additional
|
# Space Complexity: O(n), in length n of the string. We need O(n) additional
|
||||||
|
|
|
@ -26,9 +26,7 @@ def remove_vowels(s)
|
||||||
start_array = s.split('')
|
start_array = s.split('')
|
||||||
|
|
||||||
start_array.each do |letter|
|
start_array.each do |letter|
|
||||||
if letter != 'a' && letter != 'e' && letter != 'i' && letter != 'o' && letter != 'u'
|
result_array.push(letter) if letter != 'a' && letter != 'e' && letter != 'i' && letter != 'o' && letter != 'u'
|
||||||
result_array.push(letter)
|
|
||||||
end
|
|
||||||
end
|
end
|
||||||
|
|
||||||
result_array.join('')
|
result_array.join('')
|
||||||
|
|
|
@ -20,7 +20,8 @@ def is_valid_sudoku(board)
|
||||||
board.each do |row|
|
board.each do |row|
|
||||||
row_hash = Hash.new(0)
|
row_hash = Hash.new(0)
|
||||||
row.each do |num|
|
row.each do |num|
|
||||||
next if num == "."
|
next if num == '.'
|
||||||
|
|
||||||
row_hash[num] += 1
|
row_hash[num] += 1
|
||||||
end
|
end
|
||||||
rows << row_hash
|
rows << row_hash
|
||||||
|
@ -28,10 +29,8 @@ def is_valid_sudoku(board)
|
||||||
|
|
||||||
# check each row hash for duplicated value
|
# check each row hash for duplicated value
|
||||||
rows.each do |row|
|
rows.each do |row|
|
||||||
row.each do |k, v|
|
row.each do |_k, v|
|
||||||
if v > 1
|
return false if v > 1
|
||||||
return false
|
|
||||||
end
|
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
|
@ -39,7 +38,8 @@ def is_valid_sudoku(board)
|
||||||
(0..8).each do |i|
|
(0..8).each do |i|
|
||||||
column_hash = Hash.new(0)
|
column_hash = Hash.new(0)
|
||||||
board.each do |row|
|
board.each do |row|
|
||||||
next if row[i] == "."
|
next if row[i] == '.'
|
||||||
|
|
||||||
column_hash[row[i]] += 1
|
column_hash[row[i]] += 1
|
||||||
columns << column_hash
|
columns << column_hash
|
||||||
end
|
end
|
||||||
|
@ -47,10 +47,8 @@ def is_valid_sudoku(board)
|
||||||
|
|
||||||
# check each column hash for duplicated value
|
# check each column hash for duplicated value
|
||||||
columns.each do |column|
|
columns.each do |column|
|
||||||
column.each do |k, v|
|
column.each do |_k, v|
|
||||||
if v > 1
|
return false if v > 1
|
||||||
return false
|
|
||||||
end
|
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
|
@ -58,17 +56,20 @@ def is_valid_sudoku(board)
|
||||||
(0..2).each do |i|
|
(0..2).each do |i|
|
||||||
grid_hash = Hash.new(0)
|
grid_hash = Hash.new(0)
|
||||||
board.first(3).each do |row|
|
board.first(3).each do |row|
|
||||||
next if row[i] == "."
|
next if row[i] == '.'
|
||||||
|
|
||||||
grid_hash[row[i]] += 1
|
grid_hash[row[i]] += 1
|
||||||
grids << grid_hash
|
grids << grid_hash
|
||||||
end
|
end
|
||||||
board[3..5].each do |row|
|
board[3..5].each do |row|
|
||||||
next if row[i] == "."
|
next if row[i] == '.'
|
||||||
|
|
||||||
grid_hash[row[i]] += 1
|
grid_hash[row[i]] += 1
|
||||||
grids << grid_hash
|
grids << grid_hash
|
||||||
end
|
end
|
||||||
board.each do |row|
|
board.each do |row|
|
||||||
next if row[i] == "."
|
next if row[i] == '.'
|
||||||
|
|
||||||
grid_hash[row[i]] += 1
|
grid_hash[row[i]] += 1
|
||||||
grids << grid_hash
|
grids << grid_hash
|
||||||
end
|
end
|
||||||
|
@ -76,17 +77,20 @@ def is_valid_sudoku(board)
|
||||||
(3..5).each do |i|
|
(3..5).each do |i|
|
||||||
grid_hash = Hash.new(0)
|
grid_hash = Hash.new(0)
|
||||||
board.first(3).each do |row|
|
board.first(3).each do |row|
|
||||||
next if row[i] == "."
|
next if row[i] == '.'
|
||||||
|
|
||||||
grid_hash[row[i]] += 1
|
grid_hash[row[i]] += 1
|
||||||
grids << grid_hash
|
grids << grid_hash
|
||||||
end
|
end
|
||||||
board[3..5].each do |row|
|
board[3..5].each do |row|
|
||||||
next if row[i] == "."
|
next if row[i] == '.'
|
||||||
|
|
||||||
grid_hash[row[i]] += 1
|
grid_hash[row[i]] += 1
|
||||||
grids << grid_hash
|
grids << grid_hash
|
||||||
end
|
end
|
||||||
board.each do |row|
|
board.each do |row|
|
||||||
next if row[i] == "."
|
next if row[i] == '.'
|
||||||
|
|
||||||
grid_hash[row[i]] += 1
|
grid_hash[row[i]] += 1
|
||||||
grids << grid_hash
|
grids << grid_hash
|
||||||
end
|
end
|
||||||
|
@ -94,17 +98,20 @@ def is_valid_sudoku(board)
|
||||||
(6..8).last(3).each do |i|
|
(6..8).last(3).each do |i|
|
||||||
grid_hash = Hash.new(0)
|
grid_hash = Hash.new(0)
|
||||||
board.first(3).each do |row|
|
board.first(3).each do |row|
|
||||||
next if row[i] == "."
|
next if row[i] == '.'
|
||||||
|
|
||||||
grid_hash[row[i]] += 1
|
grid_hash[row[i]] += 1
|
||||||
grids << grid_hash
|
grids << grid_hash
|
||||||
end
|
end
|
||||||
board[3..5].each do |row|
|
board[3..5].each do |row|
|
||||||
next if row[i] == "."
|
next if row[i] == '.'
|
||||||
|
|
||||||
grid_hash[row[i]] += 1
|
grid_hash[row[i]] += 1
|
||||||
grids << grid_hash
|
grids << grid_hash
|
||||||
end
|
end
|
||||||
board.each do |row|
|
board.each do |row|
|
||||||
next if row[i] == "."
|
next if row[i] == '.'
|
||||||
|
|
||||||
grid_hash[row[i]] += 1
|
grid_hash[row[i]] += 1
|
||||||
grids << grid_hash
|
grids << grid_hash
|
||||||
end
|
end
|
||||||
|
@ -112,63 +119,61 @@ def is_valid_sudoku(board)
|
||||||
|
|
||||||
# check each grid hash for duplicated value
|
# check each grid hash for duplicated value
|
||||||
grids.each do |grid|
|
grids.each do |grid|
|
||||||
grid.each do |k, v|
|
grid.each do |_k, v|
|
||||||
if v > 1
|
return false if v > 1
|
||||||
return false
|
|
||||||
end
|
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
true
|
true
|
||||||
end
|
end
|
||||||
|
|
||||||
board = [["5","3",".",".","7",".",".",".","."],
|
board = [['5', '3', '.', '.', '7', '.', '.', '.', '.'],
|
||||||
["6",".",".","1","9","5",".",".","."],
|
['6', '.', '.', '1', '9', '5', '.', '.', '.'],
|
||||||
[".","9","8",".",".",".",".","6","."],
|
['.', '9', '8', '.', '.', '.', '.', '6', '.'],
|
||||||
["8",".",".",".","6",".",".",".","3"],
|
['8', '.', '.', '.', '6', '.', '.', '.', '3'],
|
||||||
["4",".",".","8",".","3",".",".","1"],
|
['4', '.', '.', '8', '.', '3', '.', '.', '1'],
|
||||||
["7",".",".",".","2",".",".",".","6"],
|
['7', '.', '.', '.', '2', '.', '.', '.', '6'],
|
||||||
[".","6",".",".",".",".","2","8","."],
|
['.', '6', '.', '.', '.', '.', '2', '8', '.'],
|
||||||
[".",".",".","4","1","9",".",".","5"],
|
['.', '.', '.', '4', '1', '9', '.', '.', '5'],
|
||||||
[".",".",".",".","8",".",".","7","9"]]
|
['.', '.', '.', '.', '8', '.', '.', '7', '9']]
|
||||||
print(is_valid_sudoku(board))
|
print(is_valid_sudoku(board))
|
||||||
# => true
|
# => true
|
||||||
|
|
||||||
board = [["8","3",".",".","7",".",".",".","."],
|
board = [['8', '3', '.', '.', '7', '.', '.', '.', '.'],
|
||||||
["6",".",".","1","9","5",".",".","."],
|
['6', '.', '.', '1', '9', '5', '.', '.', '.'],
|
||||||
[".","9","8",".",".",".",".","6","."],
|
['.', '9', '8', '.', '.', '.', '.', '6', '.'],
|
||||||
["8",".",".",".","6",".",".",".","3"],
|
['8', '.', '.', '.', '6', '.', '.', '.', '3'],
|
||||||
["4",".",".","8",".","3",".",".","1"],
|
['4', '.', '.', '8', '.', '3', '.', '.', '1'],
|
||||||
["7",".",".",".","2",".",".",".","6"],
|
['7', '.', '.', '.', '2', '.', '.', '.', '6'],
|
||||||
[".","6",".",".",".",".","2","8","."],
|
['.', '6', '.', '.', '.', '.', '2', '8', '.'],
|
||||||
[".",".",".","4","1","9",".",".","5"],
|
['.', '.', '.', '4', '1', '9', '.', '.', '5'],
|
||||||
[".",".",".",".","8",".",".","7","9"]]
|
['.', '.', '.', '.', '8', '.', '.', '7', '9']]
|
||||||
print(is_valid_sudoku(board))
|
print(is_valid_sudoku(board))
|
||||||
# => false
|
# => false
|
||||||
# explanation: duplicated value in column
|
# explanation: duplicated value in column
|
||||||
|
|
||||||
board = [["8","3",".",".","7",".","3",".","."],
|
board = [['8', '3', '.', '.', '7', '.', '3', '.', '.'],
|
||||||
["6",".",".","1","9","5",".",".","."],
|
['6', '.', '.', '1', '9', '5', '.', '.', '.'],
|
||||||
[".","9","8",".",".",".",".","6","."],
|
['.', '9', '8', '.', '.', '.', '.', '6', '.'],
|
||||||
["8",".",".",".","6",".",".",".","3"],
|
['8', '.', '.', '.', '6', '.', '.', '.', '3'],
|
||||||
["4",".",".","8",".","3",".",".","1"],
|
['4', '.', '.', '8', '.', '3', '.', '.', '1'],
|
||||||
["7",".",".",".","2",".",".",".","6"],
|
['7', '.', '.', '.', '2', '.', '.', '.', '6'],
|
||||||
[".","6",".",".",".",".","2","8","."],
|
['.', '6', '.', '.', '.', '.', '2', '8', '.'],
|
||||||
[".",".",".","4","1","9",".",".","5"],
|
['.', '.', '.', '4', '1', '9', '.', '.', '5'],
|
||||||
[".",".",".",".","8",".",".","7","9"]]
|
['.', '.', '.', '.', '8', '.', '.', '7', '9']]
|
||||||
print(is_valid_sudoku(board))
|
print(is_valid_sudoku(board))
|
||||||
# => false
|
# => false
|
||||||
# explanation: duplicated value in row
|
# explanation: duplicated value in row
|
||||||
|
|
||||||
board = [["8","3",".",".","7",".",".",".","."],
|
board = [['8', '3', '.', '.', '7', '.', '.', '.', '.'],
|
||||||
["6",".",".","1","9","5",".",".","."],
|
['6', '.', '.', '1', '9', '5', '.', '.', '.'],
|
||||||
[".","9","8",".",".",".",".","6","."],
|
['.', '9', '8', '.', '.', '.', '.', '6', '.'],
|
||||||
[".",".",".",".","6",".",".",".","3"],
|
['.', '.', '.', '.', '6', '.', '.', '.', '3'],
|
||||||
["4",".",".","8",".","3",".",".","1"],
|
['4', '.', '.', '8', '.', '3', '.', '.', '1'],
|
||||||
["7",".",".",".","2",".",".",".","6"],
|
['7', '.', '.', '.', '2', '.', '.', '.', '6'],
|
||||||
[".","6",".",".",".",".","2","8","."],
|
['.', '6', '.', '.', '.', '.', '2', '8', '.'],
|
||||||
[".",".",".","4","1","9",".",".","5"],
|
['.', '.', '.', '4', '1', '9', '.', '.', '5'],
|
||||||
[".",".",".",".","8",".",".","7","9"]]
|
['.', '.', '.', '.', '8', '.', '.', '7', '9']]
|
||||||
print(is_valid_sudoku(board))
|
print(is_valid_sudoku(board))
|
||||||
# => false
|
# => false
|
||||||
# explanation: duplicated value in 3x3 grid
|
# explanation: duplicated value in 3x3 grid
|
||||||
|
@ -181,6 +186,7 @@ require 'set'
|
||||||
def is_valid_sudoku(board)
|
def is_valid_sudoku(board)
|
||||||
return false unless check_rows(board)
|
return false unless check_rows(board)
|
||||||
return false unless check_cols(board)
|
return false unless check_cols(board)
|
||||||
|
|
||||||
row = -3
|
row = -3
|
||||||
while (row += 3) < 9
|
while (row += 3) < 9
|
||||||
col = - 3
|
col = - 3
|
||||||
|
@ -198,8 +204,9 @@ def check_grid(board, start_point)
|
||||||
ss = Set.new
|
ss = Set.new
|
||||||
(row..(row + 2)).each do |cur_row|
|
(row..(row + 2)).each do |cur_row|
|
||||||
(col..(col + 2)).each do |cur_col|
|
(col..(col + 2)).each do |cur_col|
|
||||||
next if board[cur_row][cur_col] == "."
|
next if board[cur_row][cur_col] == '.'
|
||||||
return false if ss.member?(board[cur_row][cur_col])
|
return false if ss.member?(board[cur_row][cur_col])
|
||||||
|
|
||||||
ss.add board[cur_row][cur_col]
|
ss.add board[cur_row][cur_col]
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
@ -209,8 +216,9 @@ end
|
||||||
def check_col(board, col)
|
def check_col(board, col)
|
||||||
ss = Set.new
|
ss = Set.new
|
||||||
(0..8).each do |row|
|
(0..8).each do |row|
|
||||||
next if board[row][col] == "."
|
next if board[row][col] == '.'
|
||||||
return false if ss.member?(board[row][col])
|
return false if ss.member?(board[row][col])
|
||||||
|
|
||||||
ss.add board[row][col]
|
ss.add board[row][col]
|
||||||
end
|
end
|
||||||
true
|
true
|
||||||
|
@ -219,8 +227,9 @@ end
|
||||||
def check_row(board, row)
|
def check_row(board, row)
|
||||||
ss = Set.new
|
ss = Set.new
|
||||||
(0..8).each do |col|
|
(0..8).each do |col|
|
||||||
next if board[row][col] == "."
|
next if board[row][col] == '.'
|
||||||
return false if ss.member?(board[row][col])
|
return false if ss.member?(board[row][col])
|
||||||
|
|
||||||
ss.add board[row][col]
|
ss.add board[row][col]
|
||||||
end
|
end
|
||||||
true
|
true
|
||||||
|
@ -240,53 +249,53 @@ def check_cols(board)
|
||||||
true
|
true
|
||||||
end
|
end
|
||||||
|
|
||||||
board = [["5","3",".",".","7",".",".",".","."],
|
board = [['5', '3', '.', '.', '7', '.', '.', '.', '.'],
|
||||||
["6",".",".","1","9","5",".",".","."],
|
['6', '.', '.', '1', '9', '5', '.', '.', '.'],
|
||||||
[".","9","8",".",".",".",".","6","."],
|
['.', '9', '8', '.', '.', '.', '.', '6', '.'],
|
||||||
["8",".",".",".","6",".",".",".","3"],
|
['8', '.', '.', '.', '6', '.', '.', '.', '3'],
|
||||||
["4",".",".","8",".","3",".",".","1"],
|
['4', '.', '.', '8', '.', '3', '.', '.', '1'],
|
||||||
["7",".",".",".","2",".",".",".","6"],
|
['7', '.', '.', '.', '2', '.', '.', '.', '6'],
|
||||||
[".","6",".",".",".",".","2","8","."],
|
['.', '6', '.', '.', '.', '.', '2', '8', '.'],
|
||||||
[".",".",".","4","1","9",".",".","5"],
|
['.', '.', '.', '4', '1', '9', '.', '.', '5'],
|
||||||
[".",".",".",".","8",".",".","7","9"]]
|
['.', '.', '.', '.', '8', '.', '.', '7', '9']]
|
||||||
print(is_valid_sudoku(board))
|
print(is_valid_sudoku(board))
|
||||||
# => true
|
# => true
|
||||||
|
|
||||||
board = [["8","3",".",".","7",".",".",".","."],
|
board = [['8', '3', '.', '.', '7', '.', '.', '.', '.'],
|
||||||
["6",".",".","1","9","5",".",".","."],
|
['6', '.', '.', '1', '9', '5', '.', '.', '.'],
|
||||||
[".","9","8",".",".",".",".","6","."],
|
['.', '9', '8', '.', '.', '.', '.', '6', '.'],
|
||||||
["8",".",".",".","6",".",".",".","3"],
|
['8', '.', '.', '.', '6', '.', '.', '.', '3'],
|
||||||
["4",".",".","8",".","3",".",".","1"],
|
['4', '.', '.', '8', '.', '3', '.', '.', '1'],
|
||||||
["7",".",".",".","2",".",".",".","6"],
|
['7', '.', '.', '.', '2', '.', '.', '.', '6'],
|
||||||
[".","6",".",".",".",".","2","8","."],
|
['.', '6', '.', '.', '.', '.', '2', '8', '.'],
|
||||||
[".",".",".","4","1","9",".",".","5"],
|
['.', '.', '.', '4', '1', '9', '.', '.', '5'],
|
||||||
[".",".",".",".","8",".",".","7","9"]]
|
['.', '.', '.', '.', '8', '.', '.', '7', '9']]
|
||||||
print(is_valid_sudoku(board))
|
print(is_valid_sudoku(board))
|
||||||
# => false
|
# => false
|
||||||
# explanation: duplicated value in column
|
# explanation: duplicated value in column
|
||||||
|
|
||||||
board = [["8","3",".",".","7",".","3",".","."],
|
board = [['8', '3', '.', '.', '7', '.', '3', '.', '.'],
|
||||||
["6",".",".","1","9","5",".",".","."],
|
['6', '.', '.', '1', '9', '5', '.', '.', '.'],
|
||||||
[".","9","8",".",".",".",".","6","."],
|
['.', '9', '8', '.', '.', '.', '.', '6', '.'],
|
||||||
["8",".",".",".","6",".",".",".","3"],
|
['8', '.', '.', '.', '6', '.', '.', '.', '3'],
|
||||||
["4",".",".","8",".","3",".",".","1"],
|
['4', '.', '.', '8', '.', '3', '.', '.', '1'],
|
||||||
["7",".",".",".","2",".",".",".","6"],
|
['7', '.', '.', '.', '2', '.', '.', '.', '6'],
|
||||||
[".","6",".",".",".",".","2","8","."],
|
['.', '6', '.', '.', '.', '.', '2', '8', '.'],
|
||||||
[".",".",".","4","1","9",".",".","5"],
|
['.', '.', '.', '4', '1', '9', '.', '.', '5'],
|
||||||
[".",".",".",".","8",".",".","7","9"]]
|
['.', '.', '.', '.', '8', '.', '.', '7', '9']]
|
||||||
print(is_valid_sudoku(board))
|
print(is_valid_sudoku(board))
|
||||||
# => false
|
# => false
|
||||||
# explanation: duplicated value in row
|
# explanation: duplicated value in row
|
||||||
|
|
||||||
board = [["8","3",".",".","7",".",".",".","."],
|
board = [['8', '3', '.', '.', '7', '.', '.', '.', '.'],
|
||||||
["6",".",".","1","9","5",".",".","."],
|
['6', '.', '.', '1', '9', '5', '.', '.', '.'],
|
||||||
[".","9","8",".",".",".",".","6","."],
|
['.', '9', '8', '.', '.', '.', '.', '6', '.'],
|
||||||
[".",".",".",".","6",".",".",".","3"],
|
['.', '.', '.', '.', '6', '.', '.', '.', '3'],
|
||||||
["4",".",".","8",".","3",".",".","1"],
|
['4', '.', '.', '8', '.', '3', '.', '.', '1'],
|
||||||
["7",".",".",".","2",".",".",".","6"],
|
['7', '.', '.', '.', '2', '.', '.', '.', '6'],
|
||||||
[".","6",".",".",".",".","2","8","."],
|
['.', '6', '.', '.', '.', '.', '2', '8', '.'],
|
||||||
[".",".",".","4","1","9",".",".","5"],
|
['.', '.', '.', '4', '1', '9', '.', '.', '5'],
|
||||||
[".",".",".",".","8",".",".","7","9"]]
|
['.', '.', '.', '.', '8', '.', '.', '7', '9']]
|
||||||
print(is_valid_sudoku(board))
|
print(is_valid_sudoku(board))
|
||||||
# => false
|
# => false
|
||||||
# explanation: duplicated value in 3x3 grid
|
# explanation: duplicated value in 3x3 grid
|
||||||
|
|
|
@ -71,9 +71,7 @@ def two_sum(nums, target)
|
||||||
target_difference = target - num
|
target_difference = target - num
|
||||||
|
|
||||||
nums.each_with_index do |num, j|
|
nums.each_with_index do |num, j|
|
||||||
if i != j && num == target_difference
|
return [i, j] if i != j && num == target_difference
|
||||||
return [i, j]
|
|
||||||
end
|
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
|
@ -38,7 +38,7 @@ def is_anagram(s, t)
|
||||||
counter[t[i]] -= 1
|
counter[t[i]] -= 1
|
||||||
end
|
end
|
||||||
|
|
||||||
counter.each do |k, v|
|
counter.each do |_k, v|
|
||||||
return false unless v == 0
|
return false unless v == 0
|
||||||
end
|
end
|
||||||
|
|
||||||
|
|
|
@ -32,7 +32,7 @@ def arrays_intersection(arr1, arr2, arr3)
|
||||||
add_to_hash(arr2, hash)
|
add_to_hash(arr2, hash)
|
||||||
add_to_hash(arr3, hash)
|
add_to_hash(arr3, hash)
|
||||||
|
|
||||||
hash.select { |key, value| value == 3 }.keys
|
hash.select { |_key, value| value == 3 }.keys
|
||||||
end
|
end
|
||||||
|
|
||||||
def add_to_hash(arr, hash)
|
def add_to_hash(arr, hash)
|
||||||
|
|
|
@ -44,8 +44,8 @@ def common_characters(arr)
|
||||||
result
|
result
|
||||||
end
|
end
|
||||||
|
|
||||||
puts common_characters(["bella","label","roller"])
|
puts common_characters(%w[bella label roller])
|
||||||
# => ["e","l","l"]
|
# => ["e","l","l"]
|
||||||
|
|
||||||
puts common_characters(["cool","lock","cook"])
|
puts common_characters(%w[cool lock cook])
|
||||||
# => ["c","o"]
|
# => ["c","o"]
|
||||||
|
|
|
@ -40,4 +40,4 @@ puts(num_identical_pairs(nums))
|
||||||
|
|
||||||
nums = [1, 2, 3]
|
nums = [1, 2, 3]
|
||||||
puts(num_identical_pairs(nums))
|
puts(num_identical_pairs(nums))
|
||||||
# Output: 0
|
# Output: 0
|
||||||
|
|
|
@ -2,7 +2,7 @@
|
||||||
#
|
#
|
||||||
# Given two strings s and t, determine if they are isomorphic.
|
# Given two strings s and t, determine if they are isomorphic.
|
||||||
# Two strings s and t are isomorphic if the characters in s can be replaced to get t.
|
# Two strings s and t are isomorphic if the characters in s can be replaced to get t.
|
||||||
# All occurrences of a character must be replaced with another character while preserving the order of characters.
|
# All occurrences of a character must be replaced with another character while preserving the order of characters.
|
||||||
# No two characters may map to the same character, but a character may map to itself.
|
# No two characters may map to the same character, but a character may map to itself.
|
||||||
#
|
#
|
||||||
# Example 1:
|
# Example 1:
|
||||||
|
@ -38,27 +38,27 @@ def isomorphic_strings_check(s, t)
|
||||||
char2 = t[i]
|
char2 = t[i]
|
||||||
|
|
||||||
# if char1 is mapped
|
# if char1 is mapped
|
||||||
if map[char1]
|
if map[char1]
|
||||||
# return false if char1 is mapped to a different character than already present
|
# return false if char1 is mapped to a different character than already present
|
||||||
return false if map[char1] != char2
|
return false if map[char1] != char2
|
||||||
# if char1 is not mapped
|
# if char1 is not mapped
|
||||||
else
|
else
|
||||||
# return false if char2 is already mapped to a different character
|
# return false if char2 is already mapped to a different character
|
||||||
return false if set.include?(char2)
|
return false if set.include?(char2)
|
||||||
|
|
||||||
# checks passed: add new character map and track that char2 has been mapped
|
# checks passed: add new character map and track that char2 has been mapped
|
||||||
map[char1] = char2
|
map[char1] = char2
|
||||||
set << char2
|
set << char2
|
||||||
end
|
end
|
||||||
|
|
||||||
end
|
end
|
||||||
return true
|
true
|
||||||
end
|
end
|
||||||
|
|
||||||
puts isomorphic_strings_check("egg", "add")
|
puts isomorphic_strings_check('egg', 'add')
|
||||||
# => true
|
# => true
|
||||||
|
|
||||||
puts isomorphic_strings_check("foo", "bar")
|
puts isomorphic_strings_check('foo', 'bar')
|
||||||
# => false
|
# => false
|
||||||
|
|
||||||
puts isomorphic_strings_check("paper", "title")
|
puts isomorphic_strings_check('paper', 'title')
|
||||||
# => true
|
# => true
|
||||||
|
|
|
@ -42,18 +42,16 @@ def find_richest_customer_wealth(accounts)
|
||||||
end
|
end
|
||||||
|
|
||||||
highest_value = 0
|
highest_value = 0
|
||||||
result_hash.each do |k, v|
|
result_hash.each do |_k, v|
|
||||||
if v > highest_value
|
highest_value = v if v > highest_value
|
||||||
highest_value = v
|
|
||||||
end
|
|
||||||
end
|
end
|
||||||
|
|
||||||
highest_value
|
highest_value
|
||||||
end
|
end
|
||||||
|
|
||||||
puts find_richest_customer_wealth([[1,2,3],[3,2,1]])
|
puts find_richest_customer_wealth([[1, 2, 3], [3, 2, 1]])
|
||||||
# => 6
|
# => 6
|
||||||
puts find_richest_customer_wealth([[1,5],[7,3],[3,5]])
|
puts find_richest_customer_wealth([[1, 5], [7, 3], [3, 5]])
|
||||||
# => 10
|
# => 10
|
||||||
puts find_richest_customer_wealth([[2,8,7],[7,1,3],[1,9,5]])
|
puts find_richest_customer_wealth([[2, 8, 7], [7, 1, 3], [1, 9, 5]])
|
||||||
# => 17
|
# => 17
|
||||||
|
|
|
@ -48,9 +48,7 @@ def two_sum(nums, target)
|
||||||
nums.each_with_index do |num, i|
|
nums.each_with_index do |num, i|
|
||||||
difference_target = target - num
|
difference_target = target - num
|
||||||
|
|
||||||
if hash[difference_target] && hash[difference_target] != i
|
return [i, hash[difference_target]] if hash[difference_target] && hash[difference_target] != i
|
||||||
return [i, hash[difference_target]]
|
|
||||||
end
|
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
|
|
|
@ -24,7 +24,7 @@
|
||||||
# Time Complexitiy: O(n)
|
# Time Complexitiy: O(n)
|
||||||
|
|
||||||
def find_uncommon_words(strA, strB)
|
def find_uncommon_words(strA, strB)
|
||||||
array = strA.concat(" ", strB).split(" ")
|
array = strA.concat(' ', strB).split(' ')
|
||||||
hash = Hash.new(0)
|
hash = Hash.new(0)
|
||||||
result = []
|
result = []
|
||||||
|
|
||||||
|
@ -33,16 +33,14 @@ def find_uncommon_words(strA, strB)
|
||||||
end
|
end
|
||||||
|
|
||||||
hash.each do |k, v|
|
hash.each do |k, v|
|
||||||
if v < 2
|
result.push(k) if v < 2
|
||||||
result.push(k)
|
|
||||||
end
|
|
||||||
end
|
end
|
||||||
|
|
||||||
result
|
result
|
||||||
end
|
end
|
||||||
|
|
||||||
puts find_uncommon_words("this apple is sweet", "this apple is sour")
|
puts find_uncommon_words('this apple is sweet', 'this apple is sour')
|
||||||
# => ["sweet", "sour"]
|
# => ["sweet", "sour"]
|
||||||
|
|
||||||
puts find_uncommon_words("apple apple", "banana")
|
puts find_uncommon_words('apple apple', 'banana')
|
||||||
# => ["banana"]
|
# => ["banana"]
|
||||||
|
|
|
@ -12,7 +12,7 @@
|
||||||
# All of the methods in our circular data structure are of constant time complexity.
|
# All of the methods in our circular data structure are of constant time complexity.
|
||||||
#
|
#
|
||||||
# Space Complexity: O(N).
|
# Space Complexity: O(N).
|
||||||
# The overall space complexity of the data structure is linear, where N is the pre-assigned capacity of the queue.
|
# The overall space complexity of the data structure is linear, where N is the pre-assigned capacity of the queue.
|
||||||
# However, it is worth mentioning that the memory consumption of the data structure remains as its pre-assigned capacity during its entire life cycle.
|
# However, it is worth mentioning that the memory consumption of the data structure remains as its pre-assigned capacity during its entire life cycle.
|
||||||
|
|
||||||
class CircularQueue
|
class CircularQueue
|
||||||
|
@ -38,8 +38,7 @@ class CircularQueue
|
||||||
end
|
end
|
||||||
|
|
||||||
def add(x)
|
def add(x)
|
||||||
raise "Queue is at max capacity" if size == max_size
|
raise 'Queue is at max capacity' if size == max_size
|
||||||
|
|
||||||
|
|
||||||
queue[back] = x
|
queue[back] = x
|
||||||
@back = (back + 1) % max_size
|
@back = (back + 1) % max_size
|
||||||
|
@ -47,7 +46,7 @@ class CircularQueue
|
||||||
end
|
end
|
||||||
|
|
||||||
def pop
|
def pop
|
||||||
raise "Queue is empty" if size == 0
|
raise 'Queue is empty' if size == 0
|
||||||
|
|
||||||
temp = queue[front]
|
temp = queue[front]
|
||||||
queue[front] = nil
|
queue[front] = nil
|
||||||
|
@ -62,7 +61,7 @@ queue = CircularQueue.new(3)
|
||||||
|
|
||||||
begin
|
begin
|
||||||
queue.pop
|
queue.pop
|
||||||
rescue => e
|
rescue StandardError => e
|
||||||
puts e.message
|
puts e.message
|
||||||
end
|
end
|
||||||
|
|
||||||
|
@ -72,7 +71,7 @@ queue.add(3)
|
||||||
|
|
||||||
begin
|
begin
|
||||||
queue.add(4)
|
queue.add(4)
|
||||||
rescue => e
|
rescue StandardError => e
|
||||||
puts e.message
|
puts e.message
|
||||||
end
|
end
|
||||||
|
|
||||||
|
|
|
@ -1,62 +1,56 @@
|
||||||
#You are climbing a staircase. It takes n steps to reach the top.
|
# You are climbing a staircase. It takes n steps to reach the top.
|
||||||
#Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?
|
# Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?
|
||||||
|
|
||||||
#Example 1:
|
# Example 1:
|
||||||
#Input: n = 2
|
# Input: n = 2
|
||||||
#Output: 2
|
# Output: 2
|
||||||
#Explanation: There are two ways to climb to the top.
|
# Explanation: There are two ways to climb to the top.
|
||||||
#1. 1 step + 1 step
|
# 1. 1 step + 1 step
|
||||||
#2. 2 steps
|
# 2. 2 steps
|
||||||
|
|
||||||
#Example 2:
|
# Example 2:
|
||||||
#Input: n = 3
|
# Input: n = 3
|
||||||
#Output: 3
|
# Output: 3
|
||||||
#Explanation: There are three ways to climb to the top.
|
# Explanation: There are three ways to climb to the top.
|
||||||
#1. 1 step + 1 step + 1 step
|
# 1. 1 step + 1 step + 1 step
|
||||||
#2. 1 step + 2 steps
|
# 2. 1 step + 2 steps
|
||||||
#3. 2 steps + 1 step
|
# 3. 2 steps + 1 step
|
||||||
|
|
||||||
#Constraints:
|
# Constraints:
|
||||||
#1 <= n <= 45
|
# 1 <= n <= 45
|
||||||
|
|
||||||
|
# Dynamic Programming, Recursive Bottom Up Approach - O(n) Time / O(n) Space
|
||||||
|
# Init memoization hash (only 1 parameter)
|
||||||
|
# Set base cases which are memo[0] = 1 and memo[1] = 1, since there are only 1 way to get to each stair
|
||||||
|
# Iterate from 2..n and call recurse(n, memo) for each value n.
|
||||||
|
# Return memo[n].
|
||||||
|
|
||||||
|
# recurse(n, memo) - Recurrence Relation is n = (n - 1) + (n - 2)
|
||||||
|
# return memo[n] if memo[n] exists.
|
||||||
#Dynamic Programming, Recursive Bottom Up Approach - O(n) Time / O(n) Space
|
# otherwise, memo[n] = recurse(n - 1, memo) + recurse(n - 2, memo)
|
||||||
#Init memoization hash (only 1 parameter)
|
|
||||||
#Set base cases which are memo[0] = 1 and memo[1] = 1, since there are only 1 way to get to each stair
|
|
||||||
#Iterate from 2..n and call recurse(n, memo) for each value n.
|
|
||||||
#Return memo[n].
|
|
||||||
|
|
||||||
#recurse(n, memo) - Recurrence Relation is n = (n - 1) + (n - 2)
|
|
||||||
#return memo[n] if memo[n] exists.
|
|
||||||
#otherwise, memo[n] = recurse(n - 1, memo) + recurse(n - 2, memo)
|
|
||||||
|
|
||||||
|
|
||||||
# @param {Integer} n
|
# @param {Integer} n
|
||||||
# @return {Integer}
|
# @return {Integer}
|
||||||
def climb_stairs(n)
|
def climb_stairs(n)
|
||||||
memo = Hash.new
|
memo = {}
|
||||||
|
|
||||||
memo[0] = 1
|
|
||||||
memo[1] = 1
|
|
||||||
|
|
||||||
return memo[n] if n == 0 || n == 1
|
|
||||||
|
|
||||||
(2..n).each do |n|
|
|
||||||
recurse(n, memo)
|
|
||||||
end
|
|
||||||
|
|
||||||
memo[n]
|
|
||||||
end
|
|
||||||
|
|
||||||
|
memo[0] = 1
|
||||||
|
memo[1] = 1
|
||||||
|
|
||||||
|
return memo[n] if [0, 1].include?(n)
|
||||||
|
|
||||||
|
(2..n).each do |n|
|
||||||
|
recurse(n, memo)
|
||||||
|
end
|
||||||
|
|
||||||
|
memo[n]
|
||||||
|
end
|
||||||
|
|
||||||
def recurse(n, memo)
|
def recurse(n, memo)
|
||||||
return memo[n] if memo[n]
|
return memo[n] if memo[n]
|
||||||
|
|
||||||
memo[n] = recurse(n - 1, memo) + recurse(n - 2, memo)
|
|
||||||
end
|
|
||||||
|
|
||||||
|
memo[n] = recurse(n - 1, memo) + recurse(n - 2, memo)
|
||||||
|
end
|
||||||
|
|
||||||
puts climb_stairs(2)
|
puts climb_stairs(2)
|
||||||
# => 2
|
# => 2
|
||||||
|
|
|
@ -30,16 +30,16 @@
|
||||||
# Approach: Using Recursion + Memoization, Top Down Dynamic Programming
|
# Approach: Using Recursion + Memoization, Top Down Dynamic Programming
|
||||||
#
|
#
|
||||||
|
|
||||||
#
|
#
|
||||||
# Algorithm: Dynamic Programming state transition.
|
# Algorithm: Dynamic Programming state transition.
|
||||||
#
|
#
|
||||||
# F(0) = 1
|
# F(0) = 1
|
||||||
# F(n)a = F(n-1)a + F(n-1)e + F(n-1)i + F(n-1)o +F(n-1)u
|
# F(n)a = F(n-1)a + F(n-1)e + F(n-1)i + F(n-1)o +F(n-1)u
|
||||||
# F(n)e = F(n-1)e + F(n-1)i + F(n-1)o + F(n-1)u
|
# F(n)e = F(n-1)e + F(n-1)i + F(n-1)o + F(n-1)u
|
||||||
# F(n)i = F(n-1)i + F(n-1)o +F(n-1)u
|
# F(n)i = F(n-1)i + F(n-1)o +F(n-1)u
|
||||||
# F(n)o = F(n-1)o + F(n-1)u
|
# F(n)o = F(n-1)o + F(n-1)u
|
||||||
# F(n)u = F(n-1)u
|
# F(n)u = F(n-1)u
|
||||||
#
|
#
|
||||||
|
|
||||||
# @param {Integer} n
|
# @param {Integer} n
|
||||||
# @return {Integer}
|
# @return {Integer}
|
||||||
|
|
|
@ -69,6 +69,7 @@ end
|
||||||
|
|
||||||
def generate(num_rows)
|
def generate(num_rows)
|
||||||
return [[1]] if num_rows < 1
|
return [[1]] if num_rows < 1
|
||||||
|
|
||||||
result = [[1], [1, 1]]
|
result = [[1], [1, 1]]
|
||||||
|
|
||||||
(2...num_rows + 1).each do |row|
|
(2...num_rows + 1).each do |row|
|
||||||
|
|
|
@ -3,10 +3,10 @@
|
||||||
|
|
||||||
def abs_max(x, y)
|
def abs_max(x, y)
|
||||||
num = x - y
|
num = x - y
|
||||||
max_value = ((x + y + num.abs()) / 2)
|
max_value = ((x + y + num.abs) / 2)
|
||||||
"The Abs Max of #{x} and #{y} is #{max_value}."
|
"The Abs Max of #{x} and #{y} is #{max_value}."
|
||||||
rescue
|
rescue StandardError
|
||||||
"Error: Provide number only!"
|
'Error: Provide number only!'
|
||||||
end
|
end
|
||||||
|
|
||||||
# Valid inputs
|
# Valid inputs
|
||||||
|
@ -20,11 +20,11 @@ puts abs_max(9, -121)
|
||||||
# The Abs Max of 9 and -121 is 9.
|
# The Abs Max of 9 and -121 is 9.
|
||||||
|
|
||||||
# Invalid inputs
|
# Invalid inputs
|
||||||
puts abs_max(2, "-1")
|
puts abs_max(2, '-1')
|
||||||
# Error: Provide number only!
|
# Error: Provide number only!
|
||||||
|
|
||||||
puts abs_max("3", "5")
|
puts abs_max('3', '5')
|
||||||
# Error: Provide number only!
|
# Error: Provide number only!
|
||||||
|
|
||||||
puts abs_max("a", "5")
|
puts abs_max('a', '5')
|
||||||
# Error: Provide number only!
|
# Error: Provide number only!
|
||||||
|
|
|
@ -3,10 +3,10 @@
|
||||||
|
|
||||||
def abs_min(x, y)
|
def abs_min(x, y)
|
||||||
num = x - y
|
num = x - y
|
||||||
min_value = ((x + y - num.abs()) / 2)
|
min_value = ((x + y - num.abs) / 2)
|
||||||
"The Abs Min of #{x} and #{y} is #{min_value}."
|
"The Abs Min of #{x} and #{y} is #{min_value}."
|
||||||
rescue
|
rescue StandardError
|
||||||
"Error: Provide number only!"
|
'Error: Provide number only!'
|
||||||
end
|
end
|
||||||
|
|
||||||
#
|
#
|
||||||
|
@ -24,11 +24,11 @@ puts abs_min(9, -121)
|
||||||
#
|
#
|
||||||
# Invalid inputs
|
# Invalid inputs
|
||||||
#
|
#
|
||||||
puts abs_min(2, "-1")
|
puts abs_min(2, '-1')
|
||||||
# Error: Provide number only!
|
# Error: Provide number only!
|
||||||
|
|
||||||
puts abs_min("3", "5")
|
puts abs_min('3', '5')
|
||||||
# Error: Provide number only!
|
# Error: Provide number only!
|
||||||
|
|
||||||
puts abs_min("a", "5")
|
puts abs_min('a', '5')
|
||||||
# Error: Provide number only!
|
# Error: Provide number only!
|
||||||
|
|
18
maths/add.rb
18
maths/add.rb
|
@ -4,15 +4,15 @@
|
||||||
|
|
||||||
def add(*array)
|
def add(*array)
|
||||||
sum = 0
|
sum = 0
|
||||||
array.each { |a| sum+=a }
|
array.each { |a| sum += a }
|
||||||
puts "The sum of following elements #{array} is #{sum}"
|
puts "The sum of following elements #{array} is #{sum}"
|
||||||
rescue
|
rescue StandardError
|
||||||
puts "Error: Please provide number only!"
|
puts 'Error: Please provide number only!'
|
||||||
end
|
end
|
||||||
|
|
||||||
#
|
#
|
||||||
# Valid inputs
|
# Valid inputs
|
||||||
#
|
#
|
||||||
|
|
||||||
puts add(1)
|
puts add(1)
|
||||||
# The sum of following elements [1] is 1
|
# The sum of following elements [1] is 1
|
||||||
|
@ -23,12 +23,12 @@ puts add(2, 5, -4)
|
||||||
puts add(25, 45)
|
puts add(25, 45)
|
||||||
# The sum of following elements [25, 45] is 70
|
# The sum of following elements [25, 45] is 70
|
||||||
|
|
||||||
#
|
#
|
||||||
# Invalid inputs
|
# Invalid inputs
|
||||||
#
|
#
|
||||||
|
|
||||||
puts add("1", 2, 3)
|
puts add('1', 2, 3)
|
||||||
# Error: Please provide number only!
|
# Error: Please provide number only!
|
||||||
|
|
||||||
puts add("a", 1)
|
puts add('a', 1)
|
||||||
# Error: Please provide number only!
|
# Error: Please provide number only!
|
||||||
|
|
|
@ -11,9 +11,9 @@ def armstrong_number(number)
|
||||||
num = number
|
num = number
|
||||||
sum = 0
|
sum = 0
|
||||||
len = number.digits.count
|
len = number.digits.count
|
||||||
while(number != 0)
|
while number != 0
|
||||||
remainder = number % 10
|
remainder = number % 10
|
||||||
sum += remainder ** len
|
sum += remainder**len
|
||||||
number /= 10
|
number /= 10
|
||||||
end
|
end
|
||||||
|
|
||||||
|
@ -22,8 +22,8 @@ def armstrong_number(number)
|
||||||
else
|
else
|
||||||
"The number #{num} is not an Armstrong number."
|
"The number #{num} is not an Armstrong number."
|
||||||
end
|
end
|
||||||
rescue
|
rescue StandardError
|
||||||
"Error: Please provide number only!"
|
'Error: Please provide number only!'
|
||||||
end
|
end
|
||||||
|
|
||||||
#
|
#
|
||||||
|
@ -50,8 +50,8 @@ puts armstrong_number(123)
|
||||||
#
|
#
|
||||||
# Invalid inputs
|
# Invalid inputs
|
||||||
#
|
#
|
||||||
puts armstrong_number("153")
|
puts armstrong_number('153')
|
||||||
# Error: Please provide number only!
|
# Error: Please provide number only!
|
||||||
|
|
||||||
puts armstrong_number("a")
|
puts armstrong_number('a')
|
||||||
# Error: Please provide number only!
|
# Error: Please provide number only!
|
||||||
|
|
|
@ -5,15 +5,15 @@ module AverageMean
|
||||||
def self.average_mean(n, *array)
|
def self.average_mean(n, *array)
|
||||||
if n.instance_of? Integer
|
if n.instance_of? Integer
|
||||||
if n == array.size
|
if n == array.size
|
||||||
puts "The average mean of the following elements #{array} is #{array.sum/array.size}."
|
puts "The average mean of the following elements #{array} is #{array.sum / array.size}."
|
||||||
else
|
else
|
||||||
puts "Provide the required #{n} elements properly!"
|
puts "Provide the required #{n} elements properly!"
|
||||||
end
|
end
|
||||||
else
|
else
|
||||||
raise
|
raise
|
||||||
end
|
end
|
||||||
rescue
|
rescue StandardError
|
||||||
puts "Error: Please provide number only!"
|
puts 'Error: Please provide number only!'
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
|
@ -24,5 +24,5 @@ AverageMean.average_mean(3, 2, 2, 2)
|
||||||
|
|
||||||
# Invalid inputs
|
# Invalid inputs
|
||||||
AverageMean.average_mean(2, 3, 1, 5)
|
AverageMean.average_mean(2, 3, 1, 5)
|
||||||
AverageMean.average_mean(2, 3, "a")
|
AverageMean.average_mean(2, 3, 'a')
|
||||||
AverageMean.average_mean("a", 1, 2)
|
AverageMean.average_mean('a', 1, 2)
|
||||||
|
|
|
@ -6,8 +6,8 @@ module AverageMedian
|
||||||
if n.instance_of? Integer
|
if n.instance_of? Integer
|
||||||
if n == array.size
|
if n == array.size
|
||||||
array.sort
|
array.sort
|
||||||
if array.size % 2 == 0
|
if array.size.even?
|
||||||
mid_element_1 = array.size/2
|
mid_element_1 = array.size / 2
|
||||||
mid_element_2 = mid_element_1 + 1
|
mid_element_2 = mid_element_1 + 1
|
||||||
puts "The average median of the following elements #{array} is #{(array[mid_element_1 - 1] + array[mid_element_2 - 1]) / 2}."
|
puts "The average median of the following elements #{array} is #{(array[mid_element_1 - 1] + array[mid_element_2 - 1]) / 2}."
|
||||||
else
|
else
|
||||||
|
@ -20,14 +20,14 @@ module AverageMedian
|
||||||
else
|
else
|
||||||
raise
|
raise
|
||||||
end
|
end
|
||||||
rescue
|
rescue StandardError
|
||||||
puts "Error: Please provide number only!"
|
puts 'Error: Please provide number only!'
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
#
|
#
|
||||||
# Valid inputs
|
# Valid inputs
|
||||||
#
|
#
|
||||||
|
|
||||||
puts AverageMedian.average_median(2, 3, 1)
|
puts AverageMedian.average_median(2, 3, 1)
|
||||||
# The average median of the following elements [3, 1] is 2.
|
# The average median of the following elements [3, 1] is 2.
|
||||||
|
@ -41,14 +41,14 @@ puts AverageMedian.average_median(3, 2, 2, 2)
|
||||||
puts AverageMedian.average_median(1, 5)
|
puts AverageMedian.average_median(1, 5)
|
||||||
# The average median of the following elements [5] is 5.
|
# The average median of the following elements [5] is 5.
|
||||||
|
|
||||||
#
|
#
|
||||||
# Invalid inputs
|
# Invalid inputs
|
||||||
#
|
#
|
||||||
|
|
||||||
puts AverageMedian.average_median(2, 3, 1, 5)
|
puts AverageMedian.average_median(2, 3, 1, 5)
|
||||||
# Provide the required 2 elements properly!
|
# Provide the required 2 elements properly!
|
||||||
|
|
||||||
puts AverageMedian.average_median(2, 3, "a")
|
puts AverageMedian.average_median(2, 3, 'a')
|
||||||
# Traceback (most recent call last):
|
# Traceback (most recent call last):
|
||||||
# 4: from /Users/voliveira/.rvm/rubies/ruby-2.7.0/bin/irb:23:in `<main>'
|
# 4: from /Users/voliveira/.rvm/rubies/ruby-2.7.0/bin/irb:23:in `<main>'
|
||||||
# 3: from /Users/voliveira/.rvm/rubies/ruby-2.7.0/bin/irb:23:in `load'
|
# 3: from /Users/voliveira/.rvm/rubies/ruby-2.7.0/bin/irb:23:in `load'
|
||||||
|
@ -56,5 +56,5 @@ puts AverageMedian.average_median(2, 3, "a")
|
||||||
# 1: from (irb):30
|
# 1: from (irb):30
|
||||||
# NameError (undefined local variable or method `verageMedian' for main:Object)
|
# NameError (undefined local variable or method `verageMedian' for main:Object)
|
||||||
|
|
||||||
puts AverageMedian.average_median("a", 1, 2)
|
puts AverageMedian.average_median('a', 1, 2)
|
||||||
# Error: Please provide number only!
|
# Error: Please provide number only!
|
||||||
|
|
|
@ -26,7 +26,6 @@
|
||||||
# Input: n = 33
|
# Input: n = 33
|
||||||
# Output: 66045
|
# Output: 66045
|
||||||
|
|
||||||
|
|
||||||
#
|
#
|
||||||
# Approach: Math
|
# Approach: Math
|
||||||
#
|
#
|
||||||
|
|
|
@ -1,8 +1,6 @@
|
||||||
=begin
|
# A ruby program calculate factorial of a given number.
|
||||||
A ruby program calculate factorial of a given number.
|
# Mathematical Explanation: The factorial of a number is the product of all the integers from 1 to that number.
|
||||||
Mathematical Explanation: The factorial of a number is the product of all the integers from 1 to that number.
|
# i.e: n! = n*(n-1)*(n-2)......*2*1
|
||||||
i.e: n! = n*(n-1)*(n-2)......*2*1
|
|
||||||
=end
|
|
||||||
|
|
||||||
#
|
#
|
||||||
# Approach: Interative
|
# Approach: Interative
|
||||||
|
@ -10,14 +8,14 @@ i.e: n! = n*(n-1)*(n-2)......*2*1
|
||||||
|
|
||||||
def factorial(n)
|
def factorial(n)
|
||||||
return nil if n < 0
|
return nil if n < 0
|
||||||
|
|
||||||
fac = 1
|
fac = 1
|
||||||
|
|
||||||
while n > 0
|
while n > 0
|
||||||
fac *= n
|
fac *= n
|
||||||
n -= 1
|
n -= 1
|
||||||
end
|
end
|
||||||
|
|
||||||
fac
|
fac
|
||||||
end
|
end
|
||||||
|
|
||||||
|
|
|
@ -8,15 +8,15 @@
|
||||||
|
|
||||||
def factorial(number)
|
def factorial(number)
|
||||||
if number < 0
|
if number < 0
|
||||||
"Please check your input number! The given number is a negative number."
|
'Please check your input number! The given number is a negative number.'
|
||||||
elsif number == 0
|
elsif number == 0
|
||||||
"The factorial of #{number} is 1."
|
"The factorial of #{number} is 1."
|
||||||
else
|
else
|
||||||
result = (1..number).inject(:*)
|
result = (1..number).inject(:*)
|
||||||
"The factorial of #{number} is #{result}."
|
"The factorial of #{number} is #{result}."
|
||||||
end
|
end
|
||||||
rescue
|
rescue StandardError
|
||||||
"Error: Please provide integer only!"
|
'Error: Please provide integer only!'
|
||||||
end
|
end
|
||||||
|
|
||||||
# Valid inputs
|
# Valid inputs
|
||||||
|
@ -36,8 +36,8 @@ puts factorial(-5)
|
||||||
# Please check your input number! The given number is a negative number.
|
# Please check your input number! The given number is a negative number.
|
||||||
|
|
||||||
# Invalid inputs
|
# Invalid inputs
|
||||||
puts factorial("a")
|
puts factorial('a')
|
||||||
# Error: Please provide integer only!
|
# Error: Please provide integer only!
|
||||||
|
|
||||||
puts factorial("2")
|
puts factorial('2')
|
||||||
# Error: Please provide integer only!
|
# Error: Please provide integer only!
|
||||||
|
|
|
@ -4,27 +4,25 @@
|
||||||
def find_max(*array)
|
def find_max(*array)
|
||||||
max = array[0]
|
max = array[0]
|
||||||
array.each do |a|
|
array.each do |a|
|
||||||
if a >= max
|
max = a if a >= max
|
||||||
max = a
|
|
||||||
end
|
|
||||||
end
|
end
|
||||||
"The Max of the following elements #{array} is #{max}."
|
"The Max of the following elements #{array} is #{max}."
|
||||||
rescue
|
rescue StandardError
|
||||||
"Error: Please provide number only!"
|
'Error: Please provide number only!'
|
||||||
end
|
end
|
||||||
|
|
||||||
# Max method will return the maximum element from the set of input elements provided
|
# Max method will return the maximum element from the set of input elements provided
|
||||||
def predefined_max(*array)
|
def predefined_max(*array)
|
||||||
"The Max of the following elements #{array} is #{array.max}."
|
"The Max of the following elements #{array} is #{array.max}."
|
||||||
rescue
|
rescue StandardError
|
||||||
"Error: Please provide number only!"
|
'Error: Please provide number only!'
|
||||||
end
|
end
|
||||||
|
|
||||||
# Sort method will sort the elements in ascending order. Last method will return the end element out of the array
|
# Sort method will sort the elements in ascending order. Last method will return the end element out of the array
|
||||||
def predefined_sort_last_max(*array)
|
def predefined_sort_last_max(*array)
|
||||||
"The Max of the following elements #{array} is #{array.sort.last}."
|
"The Max of the following elements #{array} is #{array.max}."
|
||||||
rescue
|
rescue StandardError
|
||||||
"Error: Please provide number only!"
|
'Error: Please provide number only!'
|
||||||
end
|
end
|
||||||
|
|
||||||
# Using find_max
|
# Using find_max
|
||||||
|
@ -36,7 +34,7 @@ puts find_max(-221, -852, -1100, -10)
|
||||||
# The Max of the following elements [-221, -852, -1100, -10] is -10.
|
# The Max of the following elements [-221, -852, -1100, -10] is -10.
|
||||||
|
|
||||||
# Invalid inputs
|
# Invalid inputs
|
||||||
puts find_max(5, "95", 2)
|
puts find_max(5, '95', 2)
|
||||||
# Error: Please provide number only!
|
# Error: Please provide number only!
|
||||||
|
|
||||||
# Using predefined_max
|
# Using predefined_max
|
||||||
|
@ -48,7 +46,7 @@ puts predefined_max(-11, -51, -10, -10)
|
||||||
# The Max of the following elements [-11, -51, -10, -10] is -10.
|
# The Max of the following elements [-11, -51, -10, -10] is -10.
|
||||||
|
|
||||||
# Invalid inputs
|
# Invalid inputs
|
||||||
puts predefined_max("x", 5, 95, 2)
|
puts predefined_max('x', 5, 95, 2)
|
||||||
# Error: Please provide number only!
|
# Error: Please provide number only!
|
||||||
|
|
||||||
# Using predefined_sort_last_max
|
# Using predefined_sort_last_max
|
||||||
|
@ -60,5 +58,5 @@ puts predefined_sort_last_max(-21, -52, -100, -1)
|
||||||
# The Max of the following elements [-21, -52, -100, -1] is -1.
|
# The Max of the following elements [-21, -52, -100, -1] is -1.
|
||||||
|
|
||||||
# Invalid inputs
|
# Invalid inputs
|
||||||
puts predefined_sort_last_max(5, 95, 2, "a")
|
puts predefined_sort_last_max(5, 95, 2, 'a')
|
||||||
# Error: Please provide number only!
|
# Error: Please provide number only!
|
||||||
|
|
|
@ -4,27 +4,25 @@
|
||||||
def find_min(*array)
|
def find_min(*array)
|
||||||
min = array[0]
|
min = array[0]
|
||||||
array.each do |a|
|
array.each do |a|
|
||||||
if a <= min
|
min = a if a <= min
|
||||||
min = a
|
|
||||||
end
|
|
||||||
end
|
end
|
||||||
"The Min of the following elements #{array} is #{min}."
|
"The Min of the following elements #{array} is #{min}."
|
||||||
rescue
|
rescue StandardError
|
||||||
"Error: Please provide number only!"
|
'Error: Please provide number only!'
|
||||||
end
|
end
|
||||||
|
|
||||||
# Min method will return the minimum element from the set of input elements provided
|
# Min method will return the minimum element from the set of input elements provided
|
||||||
def predefined_min(*array)
|
def predefined_min(*array)
|
||||||
"The Min of the following elements #{array} is #{array.min}."
|
"The Min of the following elements #{array} is #{array.min}."
|
||||||
rescue
|
rescue StandardError
|
||||||
"Error: Please provide number only!"
|
'Error: Please provide number only!'
|
||||||
end
|
end
|
||||||
|
|
||||||
# Sort method will sort the elements in ascending order. First method will return the beginning element out of the array
|
# Sort method will sort the elements in ascending order. First method will return the beginning element out of the array
|
||||||
def predefined_sort_first_min(*array)
|
def predefined_sort_first_min(*array)
|
||||||
"The Min of the following elements #{array} is #{array.sort.first}."
|
"The Min of the following elements #{array} is #{array.min}."
|
||||||
rescue
|
rescue StandardError
|
||||||
"Error: Please provide number only!"
|
'Error: Please provide number only!'
|
||||||
end
|
end
|
||||||
|
|
||||||
# Using find_min
|
# Using find_min
|
||||||
|
@ -36,7 +34,7 @@ puts find_min(-221, -852, -1100, -10)
|
||||||
# The Min of the following elements [-221, -852, -1100, -10] is -10.
|
# The Min of the following elements [-221, -852, -1100, -10] is -10.
|
||||||
|
|
||||||
# Invalid inputs
|
# Invalid inputs
|
||||||
puts find_min(5, "95", 2)
|
puts find_min(5, '95', 2)
|
||||||
# Error: Please provide number only!
|
# Error: Please provide number only!
|
||||||
|
|
||||||
# Using predefined_min
|
# Using predefined_min
|
||||||
|
@ -48,7 +46,7 @@ puts predefined_min(-11, -51, -10, -10)
|
||||||
# The Min of the following elements [-11, -51, -10, -10] is -10.
|
# The Min of the following elements [-11, -51, -10, -10] is -10.
|
||||||
|
|
||||||
# Invalid inputs
|
# Invalid inputs
|
||||||
puts predefined_min("x", 5, 95, 2)
|
puts predefined_min('x', 5, 95, 2)
|
||||||
# Error: Please provide number only!
|
# Error: Please provide number only!
|
||||||
|
|
||||||
# Using predefined_sort_first_min
|
# Using predefined_sort_first_min
|
||||||
|
@ -60,5 +58,5 @@ puts predefined_sort_first_min(-21, -52, -100, -1)
|
||||||
# The Min of the following elements [-21, -52, -100, -1] is -1.
|
# The Min of the following elements [-21, -52, -100, -1] is -1.
|
||||||
|
|
||||||
# Invalid inputs
|
# Invalid inputs
|
||||||
puts predefined_sort_first_min(5, 95, 2, "a")
|
puts predefined_sort_first_min(5, 95, 2, 'a')
|
||||||
# Error: Please provide number only!
|
# Error: Please provide number only!
|
||||||
|
|
|
@ -13,9 +13,9 @@
|
||||||
|
|
||||||
def lucas(number)
|
def lucas(number)
|
||||||
golden_ratio = (1 + 5**0.5) / 2
|
golden_ratio = (1 + 5**0.5) / 2
|
||||||
((golden_ratio**number).round()).to_i
|
(golden_ratio**number).round.to_i
|
||||||
rescue
|
rescue StandardError
|
||||||
"Error: Provide number only!"
|
'Error: Provide number only!'
|
||||||
end
|
end
|
||||||
|
|
||||||
puts lucas(4)
|
puts lucas(4)
|
||||||
|
@ -24,7 +24,7 @@ puts lucas(4)
|
||||||
puts lucas(3)
|
puts lucas(3)
|
||||||
# 4
|
# 4
|
||||||
|
|
||||||
puts lucas("3")
|
puts lucas('3')
|
||||||
# Error: Provide number only!
|
# Error: Provide number only!
|
||||||
|
|
||||||
puts lucas(2)
|
puts lucas(2)
|
||||||
|
|
|
@ -1,4 +1,4 @@
|
||||||
# Given an integer row_index, return the rowIndexth (0-indexed) row of the Pascal's triangle.
|
# Given an integer row_index, return the rowIndexth (0-indexed) row of the Pascal's triangle.
|
||||||
|
|
||||||
# Example 1:
|
# Example 1:
|
||||||
#
|
#
|
||||||
|
@ -16,12 +16,12 @@
|
||||||
# Output: [1,1]
|
# Output: [1,1]
|
||||||
|
|
||||||
# Complexity Analysis
|
# Complexity Analysis
|
||||||
#
|
#
|
||||||
# Time complexity: O(k).
|
# Time complexity: O(k).
|
||||||
# Space complexity: O(k).
|
# Space complexity: O(k).
|
||||||
|
|
||||||
def get_row(row_index)
|
def get_row(row_index)
|
||||||
(0..row_index).map {|num| combination(row_index, num) }
|
(0..row_index).map { |num| combination(row_index, num) }
|
||||||
end
|
end
|
||||||
|
|
||||||
def combination(num1, num2)
|
def combination(num1, num2)
|
||||||
|
|
|
@ -38,7 +38,7 @@
|
||||||
def is_power_of_two(n)
|
def is_power_of_two(n)
|
||||||
if n == 1
|
if n == 1
|
||||||
true
|
true
|
||||||
elsif n % 2 == 0
|
elsif n.even?
|
||||||
is_power_of_two(n / 2)
|
is_power_of_two(n / 2)
|
||||||
else
|
else
|
||||||
false
|
false
|
||||||
|
@ -67,9 +67,7 @@ puts is_power_of_two(n)
|
||||||
# Time Complexity: O(n)
|
# Time Complexity: O(n)
|
||||||
#
|
#
|
||||||
def is_power_of_two(n)
|
def is_power_of_two(n)
|
||||||
while n % 2 == 0 && n != 0
|
n /= 2 while n.even? && n != 0
|
||||||
n /= 2
|
|
||||||
end
|
|
||||||
n == 1
|
n == 1
|
||||||
end
|
end
|
||||||
|
|
||||||
|
|
|
@ -3,15 +3,15 @@
|
||||||
|
|
||||||
# Prime number check function
|
# Prime number check function
|
||||||
def prime_number(number)
|
def prime_number(number)
|
||||||
if number <= 1
|
non_prime_flag = if number <= 1
|
||||||
non_prime_flag = true
|
true
|
||||||
elsif number == 2
|
elsif number == 2
|
||||||
non_prime_flag = false
|
false
|
||||||
elsif number % 2 == 0
|
elsif number.even?
|
||||||
non_prime_flag = true
|
true
|
||||||
else
|
else
|
||||||
non_prime_flag = (2..Math.sqrt(number)).any? { |i| number % i == 0 }
|
(2..Math.sqrt(number)).any? { |i| number % i == 0 }
|
||||||
end
|
end
|
||||||
|
|
||||||
if !non_prime_flag
|
if !non_prime_flag
|
||||||
puts "The given number #{number} is a Prime."
|
puts "The given number #{number} is a Prime."
|
||||||
|
|
|
@ -10,7 +10,7 @@
|
||||||
# C 100
|
# C 100
|
||||||
# D 500
|
# D 500
|
||||||
# M 1000
|
# M 1000
|
||||||
#
|
#
|
||||||
# For example, 2 is written as II in Roman numeral, just two one's added together. 12 is written as XII, which is simply X + II. The number 27 is written as XXVII, which is XX + V + II.
|
# For example, 2 is written as II in Roman numeral, just two one's added together. 12 is written as XII, which is simply X + II. The number 27 is written as XXVII, which is XX + V + II.
|
||||||
#
|
#
|
||||||
# Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used:
|
# Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used:
|
||||||
|
@ -36,13 +36,13 @@
|
||||||
# Because only a constant number of single-value variables are used, the space complexity is O(1).
|
# Because only a constant number of single-value variables are used, the space complexity is O(1).
|
||||||
|
|
||||||
ROM_NUMS = {
|
ROM_NUMS = {
|
||||||
"I" => 1,
|
'I' => 1,
|
||||||
"V" => 5,
|
'V' => 5,
|
||||||
"X" => 10,
|
'X' => 10,
|
||||||
"L" => 50,
|
'L' => 50,
|
||||||
"C" => 100,
|
'C' => 100,
|
||||||
"D" => 500,
|
'D' => 500,
|
||||||
"M" => 1000
|
'M' => 1000
|
||||||
}
|
}
|
||||||
|
|
||||||
# Now, recall that each symbol adds its own value, except for when a smaller
|
# Now, recall that each symbol adds its own value, except for when a smaller
|
||||||
|
@ -61,7 +61,7 @@ def roman_to_int(s)
|
||||||
|
|
||||||
s.chars.each_with_index do |el, i|
|
s.chars.each_with_index do |el, i|
|
||||||
# subtractive case: if at least 2 symbols remaining AND value of s[i] < value of s[i + 1]
|
# subtractive case: if at least 2 symbols remaining AND value of s[i] < value of s[i + 1]
|
||||||
if ROM_NUMS[s[i + 1]] && ROM_NUMS[el] < ROM_NUMS[s[i+1]]
|
if ROM_NUMS[s[i + 1]] && ROM_NUMS[el] < ROM_NUMS[s[i + 1]]
|
||||||
temp = ROM_NUMS[el]
|
temp = ROM_NUMS[el]
|
||||||
else
|
else
|
||||||
# Else this is NOT the subtractive case.
|
# Else this is NOT the subtractive case.
|
||||||
|
@ -73,24 +73,24 @@ def roman_to_int(s)
|
||||||
res
|
res
|
||||||
end
|
end
|
||||||
|
|
||||||
s = "III"
|
s = 'III'
|
||||||
puts roman_to_int(s)
|
puts roman_to_int(s)
|
||||||
# Output: 3
|
# Output: 3
|
||||||
|
|
||||||
s = "IV"
|
s = 'IV'
|
||||||
puts roman_to_int(s)
|
puts roman_to_int(s)
|
||||||
# Output: 4
|
# Output: 4
|
||||||
|
|
||||||
s = "IX"
|
s = 'IX'
|
||||||
puts roman_to_int(s)
|
puts roman_to_int(s)
|
||||||
# Output: 9
|
# Output: 9
|
||||||
|
|
||||||
s = "LVIII"
|
s = 'LVIII'
|
||||||
puts roman_to_int(s)
|
puts roman_to_int(s)
|
||||||
# Output: 58
|
# Output: 58
|
||||||
# Explanation: L = 50, V= 5, III = 3.
|
# Explanation: L = 50, V= 5, III = 3.
|
||||||
|
|
||||||
s = "MCMXCIV"
|
s = 'MCMXCIV'
|
||||||
puts roman_to_int(s)
|
puts roman_to_int(s)
|
||||||
# Output: 1994
|
# Output: 1994
|
||||||
# Explanation: M = 1000, CM = 900, XC = 90 and IV = 4.
|
# Explanation: M = 1000, CM = 900, XC = 90 and IV = 4.
|
||||||
|
|
|
@ -2,7 +2,7 @@
|
||||||
#
|
#
|
||||||
# Write a program to count the number of days between two dates.
|
# Write a program to count the number of days between two dates.
|
||||||
#
|
#
|
||||||
# The two dates are given as strings, their format is YYYY-MM-DD as shown in the examples.
|
# The two dates are given as strings, their format is YYYY-MM-DD as shown in the examples.
|
||||||
# Example 1:
|
# Example 1:
|
||||||
# Input: date1 = "2019-06-29", date2 = "2019-06-30"
|
# Input: date1 = "2019-06-29", date2 = "2019-06-30"
|
||||||
# Output: 1
|
# Output: 1
|
||||||
|
@ -13,7 +13,6 @@
|
||||||
#
|
#
|
||||||
# Constraints: The given dates are valid dates between the years 1971 and 2100.
|
# Constraints: The given dates are valid dates between the years 1971 and 2100.
|
||||||
|
|
||||||
|
|
||||||
#
|
#
|
||||||
# Approach 1: Using Ruby built-in feature Date.parse
|
# Approach 1: Using Ruby built-in feature Date.parse
|
||||||
# Time complexity: O(1)
|
# Time complexity: O(1)
|
||||||
|
@ -28,8 +27,8 @@ def number_of_days(date1, date2)
|
||||||
(end_date - beginning_date).to_i.abs
|
(end_date - beginning_date).to_i.abs
|
||||||
end
|
end
|
||||||
|
|
||||||
puts number_of_days("2019-06-29", "2019-06-30")
|
puts number_of_days('2019-06-29', '2019-06-30')
|
||||||
# => 1
|
# => 1
|
||||||
|
|
||||||
puts number_of_days("2020-01-15", "2019-12-31")
|
puts number_of_days('2020-01-15', '2019-12-31')
|
||||||
# => 15
|
# => 15
|
||||||
|
|
|
@ -1,79 +1,76 @@
|
||||||
#Given an m x n 2D binary grid grid which represents a map of '1's (land) and '0's (water), return the number of islands.
|
# Given an m x n 2D binary grid grid which represents a map of '1's (land) and '0's (water), return the number of islands.
|
||||||
#An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.
|
# An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.
|
||||||
|
|
||||||
#Example 1:
|
# Example 1:
|
||||||
#Input: grid = [
|
# Input: grid = [
|
||||||
# ["1","1","1","1","0"],
|
# ["1","1","1","1","0"],
|
||||||
# ["1","1","0","1","0"],
|
# ["1","1","0","1","0"],
|
||||||
# ["1","1","0","0","0"],
|
# ["1","1","0","0","0"],
|
||||||
# ["0","0","0","0","0"]
|
# ["0","0","0","0","0"]
|
||||||
#]
|
# ]
|
||||||
#Output: 1
|
# Output: 1
|
||||||
|
|
||||||
#Example 2:
|
# Example 2:
|
||||||
#Input: grid = [
|
# Input: grid = [
|
||||||
# ["1","1","0","0","0"],
|
# ["1","1","0","0","0"],
|
||||||
# ["1","1","0","0","0"],
|
# ["1","1","0","0","0"],
|
||||||
# ["0","0","1","0","0"],
|
# ["0","0","1","0","0"],
|
||||||
# ["0","0","0","1","1"]
|
# ["0","0","0","1","1"]
|
||||||
#]
|
# ]
|
||||||
#Output: 3
|
# Output: 3
|
||||||
|
|
||||||
#Constraints:
|
# Constraints:
|
||||||
#m == grid.length
|
# m == grid.length
|
||||||
#n == grid[i].length
|
# n == grid[i].length
|
||||||
#1 <= m, n <= 300
|
# 1 <= m, n <= 300
|
||||||
#grid[i][j] is '0' or '1'.
|
# grid[i][j] is '0' or '1'.
|
||||||
|
|
||||||
|
# DFS, Recursive Bottom Up Approach - O(n*m) Time / O(1) Space
|
||||||
|
# Init num_of_islands = 0, return if the grid is empty
|
||||||
|
# Start a double loop with index to iterate through each plot (each value is a plot of either water or land in this case)
|
||||||
|
# if the plot is land, dfs(grid, x, y)
|
||||||
|
# num_of_islands += 1
|
||||||
|
# Return num_of_islands
|
||||||
|
|
||||||
|
# dfs(grid, x, y)
|
||||||
|
# Return if x or y are out of bounds, or if the plot is water
|
||||||
#DFS, Recursive Bottom Up Approach - O(n*m) Time / O(1) Space
|
# Make the current plot water
|
||||||
#Init num_of_islands = 0, return if the grid is empty
|
# Call dfs again for up, down, left, and right
|
||||||
#Start a double loop with index to iterate through each plot (each value is a plot of either water or land in this case)
|
|
||||||
#if the plot is land, dfs(grid, x, y)
|
|
||||||
#num_of_islands += 1
|
|
||||||
#Return num_of_islands
|
|
||||||
|
|
||||||
#dfs(grid, x, y)
|
|
||||||
#Return if x or y are out of bounds, or if the plot is water
|
|
||||||
#Make the current plot water
|
|
||||||
#Call dfs again for up, down, left, and right
|
|
||||||
|
|
||||||
# @param {Character[][]} grid
|
# @param {Character[][]} grid
|
||||||
# @return {Integer}
|
# @return {Integer}
|
||||||
def num_islands(grid)
|
def num_islands(grid)
|
||||||
return 0 if grid.empty?
|
return 0 if grid.empty?
|
||||||
|
|
||||||
#init num of islands
|
# init num of islands
|
||||||
islands = 0
|
islands = 0
|
||||||
|
|
||||||
#loop through each element (plot) in the 2d array
|
# loop through each element (plot) in the 2d array
|
||||||
grid.each_with_index do |row, x|
|
grid.each_with_index do |row, x|
|
||||||
row.each_with_index do |plot, y|
|
row.each_with_index do |plot, y|
|
||||||
#if the plot is water, start a dfs
|
# if the plot is water, start a dfs
|
||||||
if plot == "1"
|
next unless plot == '1'
|
||||||
dfs(grid, x, y)
|
|
||||||
#add 1 to islands once all connected land plots are searched
|
dfs(grid, x, y)
|
||||||
islands += 1
|
# add 1 to islands once all connected land plots are searched
|
||||||
end
|
islands += 1
|
||||||
end
|
|
||||||
end
|
end
|
||||||
|
end
|
||||||
#return ans
|
|
||||||
islands
|
# return ans
|
||||||
|
islands
|
||||||
end
|
end
|
||||||
|
|
||||||
def dfs(grid, x, y)
|
def dfs(grid, x, y)
|
||||||
#don't search if out of bounds, or if it's already water
|
# don't search if out of bounds, or if it's already water
|
||||||
return if x < 0 || x >= grid.length || y < 0 || y >= grid[0].length || grid[x][y] == "0"
|
return if x < 0 || x >= grid.length || y < 0 || y >= grid[0].length || grid[x][y] == '0'
|
||||||
|
|
||||||
#set the plot to water
|
# set the plot to water
|
||||||
grid[x][y] = "0"
|
grid[x][y] = '0'
|
||||||
|
|
||||||
#search each adjacent plot
|
# search each adjacent plot
|
||||||
dfs(grid, x - 1, y) #up
|
dfs(grid, x - 1, y) # up
|
||||||
dfs(grid, x + 1, y) #down
|
dfs(grid, x + 1, y) # down
|
||||||
dfs(grid, x, y - 1) #left
|
dfs(grid, x, y - 1) # left
|
||||||
dfs(grid, x, y + 1) #right
|
dfs(grid, x, y + 1) # right
|
||||||
end
|
end
|
||||||
|
|
|
@ -11,7 +11,10 @@ def cocktail_sort(array)
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
break unless swapped
|
break unless swapped
|
||||||
start, finish, way = swapped, start, -way
|
|
||||||
|
finish = start
|
||||||
|
start = swapped
|
||||||
|
way = -way
|
||||||
end
|
end
|
||||||
array
|
array
|
||||||
end
|
end
|
||||||
|
|
|
@ -9,4 +9,3 @@ class TestInsertionSort < Minitest::Test
|
||||||
cocktail_sort(input)
|
cocktail_sort(input)
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
|
|
|
@ -1,7 +1,7 @@
|
||||||
def comb_sort(array)
|
def comb_sort(array)
|
||||||
gap = array.length
|
gap = array.length
|
||||||
swaps = true
|
swaps = true
|
||||||
while gap > 1 or swaps
|
while (gap > 1) || swaps
|
||||||
gap = [1, (gap / 1.25).to_i].max
|
gap = [1, (gap / 1.25).to_i].max
|
||||||
swaps = false
|
swaps = false
|
||||||
0.upto(array.length - gap - 1) do |i|
|
0.upto(array.length - gap - 1) do |i|
|
||||||
|
|
|
@ -1,5 +1,6 @@
|
||||||
def pancake_sort(array)
|
def pancake_sort(array)
|
||||||
return array if array.length <= 1
|
return array if array.length <= 1
|
||||||
|
|
||||||
(array.length - 1).downto(1) do |index|
|
(array.length - 1).downto(1) do |index|
|
||||||
max_index = array[0..index].index(array[0..index].max)
|
max_index = array[0..index].index(array[0..index].max)
|
||||||
next if max_index == index
|
next if max_index == index
|
||||||
|
|
Loading…
Reference in a new issue