1
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?

More than 3 years have passed since last update.

【Ruby】2つの配列で、和集合・積集合・差集合を取得したい。

Posted at

概要

Rubyの操作の学習として、「和集合・積集合・差集合」の取得方法をまとめました。

和集合(A∪B)

和集合.png

2つの配列の和集合をとるにはAeeay#|メソッドを使用します。

# 和集合(A∪B)
array1 = [1,2,3]
array2 = [4,5,6]
array3 = [2,3,4]
array4 = ["A","B","C"]
array5 = ["B","B","C","D"]

array_result1 = array1 | array2 #=> [1, 2, 3, 4, 5, 6]
array_result2 = array1 | array3 #=> [1, 2, 3, 4]
array_result3 = array4 | array5 #=> ["A", "B", "C", "D"]

p array_result1
p array_result2
p array_result3

積集合(A∩B)

積集合.png

2つの配列の積集合をとるにはAeeay#&メソッドを使用します。

# 積集合(A∩B)
array1 = [1,2,3]
array2 = [4,5,6]
array3 = [2,3,4]
array4 = ["A","B","C"]
array5 = ["B","B","C","D"]

array_result1 = array1 & array2 #=> []
array_result2 = array1 & array3 #=> [2, 3]
array_result3 = array4 & array5 #=> ["B", "C"]

p array_result1
p array_result2
p array_result3

差集合(A\B)

差集合.png

2つの配列の差集合をとるにはAeeay#-メソッドを使用します。

# 差集合(A\B)
array1 = [1,2,3]
array2 = [4,5,6]
array3 = [2,3,4]
array4 = ["A","B","C"]
array5 = ["B","B","C","D"]

array_result1 = array1 - array2 #=> [1, 2, 3]
array_result2 = array1 - array3 #=> [1]
array_result3 = array4 - array5 #=> ["A"]

p array_result1
p array_result2
p array_result3

参考

◇Ruby 3.0.0 リファレンスマニュアル Arrayクラス
https://docs.ruby-lang.org/ja/latest/class/Array.html

◇和集合
https://ja.wikipedia.org/wiki/%E5%92%8C%E9%9B%86%E5%90%88

◇差集合
https://ja.wikipedia.org/wiki/%E5%B7%AE%E9%9B%86%E5%90%88

◇共通部分(積集合)
https://ja.wikipedia.org/wiki/%E5%85%B1%E9%80%9A%E9%83%A8%E5%88%86_(%E6%95%B0%E5%AD%A6)

1
0
0

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
1
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?