mirror of
https://github.com/krahets/hello-algo.git
synced 2026-09-01 04:47:12 +00:00
Add ru version (#1865)
* Add Russian docs site baseline * Add Russian localized codebase * Polish Russian code wording * Update ru code translation. * Update code translation and chapter covers. * Fix pythontutor extraction. * Add README and landing page. * placeholder of profiles * Use figures of English version * Remove chapter paperbook
This commit is contained in:
@@ -0,0 +1,121 @@
|
||||
=begin
|
||||
File: array_hash_map.rb
|
||||
Created Time: 2024-04-13
|
||||
Author: Xuan Khoa Tu Nguyen (ngxktuzkai2000@gmail.com)
|
||||
=end
|
||||
|
||||
# ## Пара ключ-значение ###
|
||||
class Pair
|
||||
attr_accessor :key, :val
|
||||
|
||||
def initialize(key, val)
|
||||
@key = key
|
||||
@val = val
|
||||
end
|
||||
end
|
||||
|
||||
# ## Хеш-таблица на основе массива ###
|
||||
class ArrayHashMap
|
||||
# ## Конструктор ###
|
||||
def initialize
|
||||
# Инициализировать массив, содержащий 100 корзин
|
||||
@buckets = Array.new(100)
|
||||
end
|
||||
|
||||
# ## Хеш-функция ###
|
||||
def hash_func(key)
|
||||
index = key % 100
|
||||
end
|
||||
|
||||
# ## Операция поиска ###
|
||||
def get(key)
|
||||
index = hash_func(key)
|
||||
pair = @buckets[index]
|
||||
|
||||
return if pair.nil?
|
||||
pair.val
|
||||
end
|
||||
|
||||
# ## Операция добавления ###
|
||||
def put(key, val)
|
||||
pair = Pair.new(key, val)
|
||||
index = hash_func(key)
|
||||
@buckets[index] = pair
|
||||
end
|
||||
|
||||
# ## Операция удаления ###
|
||||
def remove(key)
|
||||
index = hash_func(key)
|
||||
# Присвоить nil, что означает удаление
|
||||
@buckets[index] = nil
|
||||
end
|
||||
|
||||
# ## Получить все пары ключ-значение ###
|
||||
def entry_set
|
||||
result = []
|
||||
@buckets.each { |pair| result << pair unless pair.nil? }
|
||||
result
|
||||
end
|
||||
|
||||
# ## Получить все ключи ###
|
||||
def key_set
|
||||
result = []
|
||||
@buckets.each { |pair| result << pair.key unless pair.nil? }
|
||||
result
|
||||
end
|
||||
|
||||
# ## Получить все значения ###
|
||||
def value_set
|
||||
result = []
|
||||
@buckets.each { |pair| result << pair.val unless pair.nil? }
|
||||
result
|
||||
end
|
||||
|
||||
# ## Вывести хеш-таблицу ###
|
||||
def print
|
||||
@buckets.each { |pair| puts "#{pair.key} -> #{pair.val}" unless pair.nil? }
|
||||
end
|
||||
end
|
||||
|
||||
### Driver Code ###
|
||||
if __FILE__ == $0
|
||||
# Инициализация хеш-таблицы
|
||||
hmap = ArrayHashMap.new
|
||||
|
||||
# Операция добавления
|
||||
# Добавить пару (key, value) в хеш-таблицу
|
||||
hmap.put(12836, "Сяо Ха")
|
||||
hmap.put(15937, "Сяо Ло")
|
||||
hmap.put(16750, "Сяо Суань")
|
||||
hmap.put(13276, "Сяо Фа")
|
||||
hmap.put(10583, "Сяо Я")
|
||||
puts "\nПосле добавления хеш-таблица имеет вид\nКлюч -> Значение"
|
||||
hmap.print
|
||||
|
||||
# Операция поиска
|
||||
# По ключу key получить из хеш-таблицы значение value
|
||||
name = hmap.get(15937)
|
||||
puts "\nДля номера 15937 найдено имя #{name}"
|
||||
|
||||
# Операция удаления
|
||||
# Удалить пару значений (key, value) из хеш-таблицы
|
||||
hmap.remove(10583)
|
||||
puts "\nПосле удаления 10583 хеш-таблица имеет вид\nКлюч -> Значение"
|
||||
hmap.print
|
||||
|
||||
# Обход хеш-таблицы
|
||||
puts "\nОтдельный обход пар ключ-значение"
|
||||
for pair in hmap.entry_set
|
||||
puts "#{pair.key} -> #{pair.val}"
|
||||
end
|
||||
|
||||
puts "\nОтдельный обход ключей"
|
||||
for key in hmap.key_set
|
||||
puts key
|
||||
end
|
||||
|
||||
puts "\nОтдельный обход значений"
|
||||
for val in hmap.value_set
|
||||
puts val
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,34 @@
|
||||
=begin
|
||||
File: built_in_hash.rb
|
||||
Created Time: 2024-04-13
|
||||
Author: Xuan Khoa Tu Nguyen (ngxktuzkai2000@gmail.com)
|
||||
=end
|
||||
|
||||
require_relative '../utils/list_node'
|
||||
|
||||
### Driver Code ###
|
||||
if __FILE__ == $0
|
||||
num = 3
|
||||
hash_num = num.hash
|
||||
puts "Хеш-значение целого числа #{num}: #{hash_num}"
|
||||
|
||||
bol = true
|
||||
hash_bol = bol.hash
|
||||
puts "Хеш-значение булева значения #{bol}: #{hash_bol}"
|
||||
|
||||
dec = 3.14159
|
||||
hash_dec = dec.hash
|
||||
puts "Хеш-значение десятичного числа #{dec}: #{hash_dec}"
|
||||
|
||||
str = "Hello Algo"
|
||||
hash_str = str.hash
|
||||
puts "Хеш-значение строки #{str}: #{hash_str}"
|
||||
|
||||
tup = [12836, 'Сяо Ха']
|
||||
hash_tup = tup.hash
|
||||
puts "Хеш-значение кортежа #{tup}: #{hash_tup}"
|
||||
|
||||
obj = ListNode.new(0)
|
||||
hash_obj = obj.hash
|
||||
puts "Хеш-значение объекта узла #{obj}: #{hash_obj}"
|
||||
end
|
||||
@@ -0,0 +1,44 @@
|
||||
=begin
|
||||
File: hash_map.rb
|
||||
Created Time: 2024-04-14
|
||||
Author: Xuan Khoa Tu Nguyen (ngxktuzkai2000@gmail.com)
|
||||
=end
|
||||
|
||||
require_relative '../utils/print_util'
|
||||
|
||||
### Driver Code ###
|
||||
if __FILE__ == $0
|
||||
# Инициализация хеш-таблицы
|
||||
hmap = {}
|
||||
|
||||
# Операция добавления
|
||||
# Добавить пару (key, value) в хеш-таблицу
|
||||
hmap[12836] = "Сяо Ха"
|
||||
hmap[15937] = "Сяо Ло"
|
||||
hmap[16750] = "Сяо Суань"
|
||||
hmap[13276] = "Сяо Фа"
|
||||
hmap[10583] = "Сяо Я"
|
||||
puts "\nПосле добавления хеш-таблица имеет вид\nКлюч -> Значение"
|
||||
print_hash_map(hmap)
|
||||
|
||||
# Операция поиска
|
||||
# Передать ключ key в хеш-таблицу и получить значение value
|
||||
name = hmap[15937]
|
||||
puts "\nДля номера 15937 найдено имя #{name}"
|
||||
|
||||
# Операция удаления
|
||||
# Удалить пару (key, value) из хеш-таблицы
|
||||
hmap.delete(10583)
|
||||
puts "\nПосле удаления 10583 хеш-таблица имеет вид\nКлюч -> Значение"
|
||||
print_hash_map(hmap)
|
||||
|
||||
# Обход хеш-таблицы
|
||||
puts "\nОтдельный обход пар ключ-значение"
|
||||
hmap.entries.each { |key, value| puts "#{key} -> #{value}" }
|
||||
|
||||
puts "\nОтдельный обход ключей"
|
||||
hmap.keys.each { |key| puts key }
|
||||
|
||||
puts "\nОтдельный обход значений"
|
||||
hmap.values.each { |val| puts val }
|
||||
end
|
||||
@@ -0,0 +1,128 @@
|
||||
=begin
|
||||
File: hash_map_chaining.rb
|
||||
Created Time: 2024-04-13
|
||||
Author: Xuan Khoa Tu Nguyen (ngxktuzkai2000@gmail.com)
|
||||
=end
|
||||
|
||||
require_relative './array_hash_map'
|
||||
|
||||
# ## Хеш-таблица с цепочками ###
|
||||
class HashMapChaining
|
||||
# ## Конструктор ###
|
||||
def initialize
|
||||
@size = 0 # Число пар ключ-значение
|
||||
@capacity = 4 # Вместимость хеш-таблицы
|
||||
@load_thres = 2.0 / 3.0 # Порог коэффициента загрузки для запуска расширения
|
||||
@extend_ratio = 2 # Коэффициент расширения
|
||||
@buckets = Array.new(@capacity) { [] } # Массив корзин
|
||||
end
|
||||
|
||||
# ## Хеш-функция ###
|
||||
def hash_func(key)
|
||||
key % @capacity
|
||||
end
|
||||
|
||||
# ## Коэффициент загрузки ###
|
||||
def load_factor
|
||||
@size / @capacity
|
||||
end
|
||||
|
||||
# ## Операция поиска ###
|
||||
def get(key)
|
||||
index = hash_func(key)
|
||||
bucket = @buckets[index]
|
||||
# Обойти корзину; если найден key, вернуть соответствующее val
|
||||
for pair in bucket
|
||||
return pair.val if pair.key == key
|
||||
end
|
||||
# Если key не найден, вернуть nil
|
||||
nil
|
||||
end
|
||||
|
||||
# ## Операция добавления ###
|
||||
def put(key, val)
|
||||
# Когда коэффициент загрузки превышает порог, выполнить расширение
|
||||
extend if load_factor > @load_thres
|
||||
index = hash_func(key)
|
||||
bucket = @buckets[index]
|
||||
# Обойти корзину; если встретился указанный key, обновить соответствующее val и вернуть
|
||||
for pair in bucket
|
||||
if pair.key == key
|
||||
pair.val = val
|
||||
return
|
||||
end
|
||||
end
|
||||
# Если такого key нет, добавить пару ключ-значение в конец
|
||||
pair = Pair.new(key, val)
|
||||
bucket << pair
|
||||
@size += 1
|
||||
end
|
||||
|
||||
# ## Операция удаления ###
|
||||
def remove(key)
|
||||
index = hash_func(key)
|
||||
bucket = @buckets[index]
|
||||
# Обойти корзину и удалить из нее пару ключ-значение
|
||||
for pair in bucket
|
||||
if pair.key == key
|
||||
bucket.delete(pair)
|
||||
@size -= 1
|
||||
break
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
# ## Расширение хеш-таблицы ###
|
||||
def extend
|
||||
# Временно сохранить исходную хеш-таблицу
|
||||
buckets = @buckets
|
||||
# Инициализация новой хеш-таблицы после расширения
|
||||
@capacity *= @extend_ratio
|
||||
@buckets = Array.new(@capacity) { [] }
|
||||
@size = 0
|
||||
# Перенести пары ключ-значение из исходной хеш-таблицы в новую
|
||||
for bucket in buckets
|
||||
for pair in bucket
|
||||
put(pair.key, pair.val)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
# ## Вывести хеш-таблицу ###
|
||||
def print
|
||||
for bucket in @buckets
|
||||
res = []
|
||||
for pair in bucket
|
||||
res << "#{pair.key} -> #{pair.val}"
|
||||
end
|
||||
pp res
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
### Driver Code ###
|
||||
if __FILE__ == $0
|
||||
# ## Инициализация хеш-таблицы
|
||||
hashmap = HashMapChaining.new
|
||||
|
||||
# Операция добавления
|
||||
# Добавить пару (key, value) в хеш-таблицу
|
||||
hashmap.put(12836, "Сяо Ха")
|
||||
hashmap.put(15937, "Сяо Ло")
|
||||
hashmap.put(16750, "Сяо Суань")
|
||||
hashmap.put(13276, "Сяо Фа")
|
||||
hashmap.put(10583, "Сяо Я")
|
||||
puts "\nПосле завершения добавления хеш-таблица имеет вид\n[Key1 -> Value1, Key2 -> Value2, ...]"
|
||||
hashmap.print
|
||||
|
||||
# Операция поиска
|
||||
# Передать ключ key в хеш-таблицу и получить значение value
|
||||
name = hashmap.get(13276)
|
||||
puts "\nДля номера 13276 найдено имя #{name}"
|
||||
|
||||
# Операция удаления
|
||||
# Удалить пару (key, value) из хеш-таблицы
|
||||
hashmap.remove(12836)
|
||||
puts "\nПосле удаления 12836 хеш-таблица имеет вид\n[Key1 -> Value1, Key2 -> Value2, ...]"
|
||||
hashmap.print
|
||||
end
|
||||
@@ -0,0 +1,147 @@
|
||||
=begin
|
||||
File: hash_map_open_addressing.rb
|
||||
Created Time: 2024-04-13
|
||||
Author: Xuan Khoa Tu Nguyen (ngxktuzkai2000@gmail.com)
|
||||
=end
|
||||
|
||||
require_relative './array_hash_map'
|
||||
|
||||
# ## Хеш-таблица с открытой адресацией ###
|
||||
class HashMapOpenAddressing
|
||||
TOMBSTONE = Pair.new(-1, '-1') # Удалить метку
|
||||
|
||||
# ## Конструктор ###
|
||||
def initialize
|
||||
@size = 0 # Число пар ключ-значение
|
||||
@capacity = 4 # Вместимость хеш-таблицы
|
||||
@load_thres = 2.0 / 3.0 # Порог коэффициента загрузки для запуска расширения
|
||||
@extend_ratio = 2 # Коэффициент расширения
|
||||
@buckets = Array.new(@capacity) # Массив корзин
|
||||
end
|
||||
|
||||
# ## Хеш-функция ###
|
||||
def hash_func(key)
|
||||
key % @capacity
|
||||
end
|
||||
|
||||
# ## Коэффициент загрузки ###
|
||||
def load_factor
|
||||
@size / @capacity
|
||||
end
|
||||
|
||||
# ## Найти индекс корзины, соответствующий key ###
|
||||
def find_bucket(key)
|
||||
index = hash_func(key)
|
||||
first_tombstone = -1
|
||||
# Выполнять линейное пробирование и завершить при встрече с пустой корзиной
|
||||
while !@buckets[index].nil?
|
||||
# Если встретился key, вернуть соответствующий индекс корзины
|
||||
if @buckets[index].key == key
|
||||
# Если ранее встретилась метка удаления, переместить пару ключ-значение на этот индекс
|
||||
if first_tombstone != -1
|
||||
@buckets[first_tombstone] = @buckets[index]
|
||||
@buckets[index] = TOMBSTONE
|
||||
return first_tombstone # Вернуть индекс корзины после перемещения
|
||||
end
|
||||
return index # Вернуть индекс корзины
|
||||
end
|
||||
# Записать первую встретившуюся метку удаления
|
||||
first_tombstone = index if first_tombstone == -1 && @buckets[index] == TOMBSTONE
|
||||
# Вычислить индекс корзины; при выходе за конец вернуться к началу
|
||||
index = (index + 1) % @capacity
|
||||
end
|
||||
# Если key не существует, вернуть индекс точки добавления
|
||||
first_tombstone == -1 ? index : first_tombstone
|
||||
end
|
||||
|
||||
# ## Операция поиска ###
|
||||
def get(key)
|
||||
# Найти индекс корзины, соответствующий key
|
||||
index = find_bucket(key)
|
||||
# Если пара ключ-значение найдена, вернуть соответствующее val
|
||||
return @buckets[index].val unless [nil, TOMBSTONE].include?(@buckets[index])
|
||||
# Если пара ключ-значение не существует, вернуть nil
|
||||
nil
|
||||
end
|
||||
|
||||
# ## Операция добавления ###
|
||||
def put(key, val)
|
||||
# Когда коэффициент загрузки превышает порог, выполнить расширение
|
||||
extend if load_factor > @load_thres
|
||||
# Найти индекс корзины, соответствующий key
|
||||
index = find_bucket(key)
|
||||
# Если пара ключ-значение найдена, перезаписать val и вернуть
|
||||
unless [nil, TOMBSTONE].include?(@buckets[index])
|
||||
@buckets[index].val = val
|
||||
return
|
||||
end
|
||||
# Если пары ключ-значение нет, добавить ее
|
||||
@buckets[index] = Pair.new(key, val)
|
||||
@size += 1
|
||||
end
|
||||
|
||||
# ## Операция удаления ###
|
||||
def remove(key)
|
||||
# Найти индекс корзины, соответствующий key
|
||||
index = find_bucket(key)
|
||||
# Если пара ключ-значение найдена, заменить ее меткой удаления
|
||||
unless [nil, TOMBSTONE].include?(@buckets[index])
|
||||
@buckets[index] = TOMBSTONE
|
||||
@size -= 1
|
||||
end
|
||||
end
|
||||
|
||||
# ## Расширение хеш-таблицы ###
|
||||
def extend
|
||||
# Временно сохранить исходную хеш-таблицу
|
||||
buckets_tmp = @buckets
|
||||
# Инициализация новой хеш-таблицы после расширения
|
||||
@capacity *= @extend_ratio
|
||||
@buckets = Array.new(@capacity)
|
||||
@size = 0
|
||||
# Перенести пары ключ-значение из исходной хеш-таблицы в новую
|
||||
for pair in buckets_tmp
|
||||
put(pair.key, pair.val) unless [nil, TOMBSTONE].include?(pair)
|
||||
end
|
||||
end
|
||||
|
||||
# ## Вывести хеш-таблицу ###
|
||||
def print
|
||||
for pair in @buckets
|
||||
if pair.nil?
|
||||
puts "Nil"
|
||||
elsif pair == TOMBSTONE
|
||||
puts "TOMBSTONE"
|
||||
else
|
||||
puts "#{pair.key} -> #{pair.val}"
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
### Driver Code ###
|
||||
if __FILE__ == $0
|
||||
# Инициализация хеш-таблицы
|
||||
hashmap = HashMapOpenAddressing.new
|
||||
|
||||
# Операция добавления
|
||||
# Добавить пару (key, val) в хеш-таблицу
|
||||
hashmap.put(12836, "Сяо Ха")
|
||||
hashmap.put(15937, "Сяо Ло")
|
||||
hashmap.put(16750, "Сяо Суань")
|
||||
hashmap.put(13276, "Сяо Фа")
|
||||
hashmap.put(10583, "Сяо Я")
|
||||
puts "\nПосле добавления хеш-таблица имеет вид\nКлюч -> Значение"
|
||||
hashmap.print
|
||||
|
||||
# Операция поиска
|
||||
# Передать ключ key в хеш-таблицу и получить значение val
|
||||
name = hashmap.get(13276)
|
||||
puts "\nДля номера 13276 найдено имя #{name}"
|
||||
|
||||
# Операция удаления
|
||||
# Удалить пару (key, val) из хеш-таблицы
|
||||
hashmap.remove(16750)
|
||||
puts "\nПосле удаления 16750 хеш-таблица имеет вид\nКлюч -> Значение"
|
||||
hashmap.print
|
||||
end
|
||||
@@ -0,0 +1,62 @@
|
||||
=begin
|
||||
File: simple_hash.rb
|
||||
Created Time: 2024-04-14
|
||||
Author: Xuan Khoa Tu Nguyen (ngxktuzkai2000@gmail.com)
|
||||
=end
|
||||
|
||||
# ## Аддитивное хеширование ###
|
||||
def add_hash(key)
|
||||
hash = 0
|
||||
modulus = 1_000_000_007
|
||||
|
||||
key.each_char { |c| hash += c.ord }
|
||||
|
||||
hash % modulus
|
||||
end
|
||||
|
||||
# ## Мультипликативное хеширование ###
|
||||
def mul_hash(key)
|
||||
hash = 0
|
||||
modulus = 1_000_000_007
|
||||
|
||||
key.each_char { |c| hash = 31 * hash + c.ord }
|
||||
|
||||
hash % modulus
|
||||
end
|
||||
|
||||
# ## XOR-хеширование ###
|
||||
def xor_hash(key)
|
||||
hash = 0
|
||||
modulus = 1_000_000_007
|
||||
|
||||
key.each_char { |c| hash ^= c.ord }
|
||||
|
||||
hash % modulus
|
||||
end
|
||||
|
||||
# ## Хеширование с циклическим сдвигом ###
|
||||
def rot_hash(key)
|
||||
hash = 0
|
||||
modulus = 1_000_000_007
|
||||
|
||||
key.each_char { |c| hash = (hash << 4) ^ (hash >> 28) ^ c.ord }
|
||||
|
||||
hash % modulus
|
||||
end
|
||||
|
||||
### Driver Code ###
|
||||
if __FILE__ == $0
|
||||
key = "Hello Algo"
|
||||
|
||||
hash = add_hash(key)
|
||||
puts "Хеш-сумма сложением = #{hash}"
|
||||
|
||||
hash = mul_hash(key)
|
||||
puts "Хеш-сумма умножением = #{hash}"
|
||||
|
||||
hash = xor_hash(key)
|
||||
puts "Хеш-сумма XOR = #{hash}"
|
||||
|
||||
hash = rot_hash(key)
|
||||
puts "Хеш-сумма с циклическим сдвигом = #{hash}"
|
||||
end
|
||||
Reference in New Issue
Block a user