0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

paizaラーニング解答: ハッシュメニュー[Ruby]

Last updated at Posted at 2024-01-12

ハッシュメニュー

STEP: 1 ハッシュ関数とは

n, mod = gets.split.map(&:to_i)
x = n.times.map { gets.to_i }
hash = x.to_h { |i| [i, i % mod] }
puts hash.values

xの要素に対して順番に% modするだけでも解答できますが、それをハッシュテーブルに保存してみました。

STEP: 2 やや複雑なハッシュ

n, a, b, mod = gets.split.map(&:to_i)
x = n.times.map { gets.to_i }
hash = x.to_h { |i| [i, (a * i + b) % mod] }
puts hash.values

STEP: 3 文字列のハッシュ

n = gets.to_i
x = n.times.map { gets.chomp }
hash = x.to_h { |i| [i, i.count('paiz')] }
puts hash.values

FINAL問題 ハッシュ関数を作ってみよう

n = gets.to_i
x = n.times.map { gets.chomp }
x.each do |s|
    hash = 0
    s.each_char.with_index do |char, i|
        hash += (i + 1) * (char.ord - 'a'.ord + 1)
    end
    puts hash % 100
end

STEP: 1 ハッシュテーブル(オープンアドレス法)

n = gets.to_i
x_array = n.times.map { gets.to_i }
table = [-1] * 10
x_array.each do |x|
    hash = x % 10
    if table[hash] == -1
        table[hash] = x
    else
        while table[hash] != -1
            hash = (hash + 1) % 10 
        end
        table[hash] = x
    end
end
puts table

STEP: 2 ハッシュテーブル(チェイン法)

n = gets.to_i
x_array = n.times.map { gets.to_i }
table = Array.new(10) { [] }
x_array.each do |x|
    hash = x % 10
    table[hash] << x
end
table.each do |row|
    puts row.join(' ')
end

FINAL問題 ハッシュテーブルを使おう

a, b = gets.split.map(&:to_i)
q = gets.to_i
table = Array.new(100) { [] }
q.times do
    k, x = gets.split.map(&:to_i)
    hash = (a * x + b) % 100

    if k == 1
        table[hash] << x
    elsif k == 2
        puts table[hash].include?(x) ? "Yes" : "No"
    end
end

table.each do |row|
    puts row.join(' ')
end

追記
@scivola 様よりコードの改善点をご教示いただき、コードの一部を編集いたしました。
この度はご指摘いただきありがとうございました!

0
0
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?