mirror of
https://github.com/krahets/hello-algo.git
synced 2026-10-30 04:05:32 +08:00
* Retranslate the complete Japanese online edition from Chinese * Fit Japanese homepage labels and localize heading permalinks * Point Japanese contribution instructions to the Japanese preview * Replace locale conditionals with multilingual UI tables
63 lines
1.1 KiB
Ruby
63 lines
1.1 KiB
Ruby
=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
|
|
|
|
### 排他的論理和ハッシュ ###
|
|
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
|
|
|
|
### 実行用コード ###
|
|
if __FILE__ == $0
|
|
key = "Hello 算法"
|
|
|
|
hash = add_hash(key)
|
|
puts "加算ハッシュの値は #{hash}"
|
|
|
|
hash = mul_hash(key)
|
|
puts "乗算ハッシュの値は #{hash}"
|
|
|
|
hash = xor_hash(key)
|
|
puts "排他的論理和ハッシュの値は #{hash}"
|
|
|
|
hash = rot_hash(key)
|
|
puts "回転ハッシュの値は #{hash}"
|
|
end
|