LoginSignup
0
0

More than 3 years have passed since last update.

複数の配列を比較し、共通項の数を算出する

Posted at

受け取った6つの数字を親配列に入れ、同様にN回6つの数字を受け取り子配列に入れます。
親配列と子配列を比較し、共通の数字の数を出力します。
※便宜上、基準となる配列を親配列と名付け、比較する配列を子配列と名付けてます。

# 6つの数字を受け取り配列にする
a, b, c, d, e, f = gets.split(' ').map(&:to_i)
# 冗長になるので変数luc_numsに代入
luc_nums = a, b, c, d, e, f

# 試行回数を変数Nに代入する
N = gets.chomp.to_i

# N回下記の処理をする
N.times do |i|
    # 新たに6つの数字を受け取り配列にする
    a_l, b_l, c_l, d_l, e_l, f_l = gets.split(' ').map(&:to_i)
    # 冗長になるので変数lot_numsに代入
    lot_nums = a_l, b_l, c_l, d_l, e_l, f_l
    # luc_numsとlot_numsを比較し、共通項を変数common_numsに代入
    common_nums = luc_nums & lot_nums
    # lengthメソッドでcommon_numsの数を出力
    puts common_nums.length
end

他に簡潔な方法があると思いますが、Rubyの基本のみで解いてます。

最後にコメントアウト無しを載せます。

a, b, c, d, e, f = gets.split(' ').map(&:to_i)
luc_nums = a, b, c, d, e, f

N = gets.chomp.to_i

N.times do |i|
    a_l, b_l, c_l, d_l, e_l, f_l = gets.split(' ').map(&:to_i)
    lot_nums = a_l, b_l, c_l, d_l, e_l, f_l
    common_nums = luc_nums & lot_nums
    puts common_nums.length
end
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