# ライブラリ「TETRAZ.配列操作」 (Since 2005/11/21)
# by Tetra-Z
#
# class Arrayに次の操作を追加します。
#
# self.array_and_repeat(other)
# 集合の積演算。両方に含まれる要素による新しい配列を返します。
# 重複も加味され、両方に存在する分だけ返します。
#
# self.array_minus_repeat(other)
# 集合の差演算。selfからotherの要素を差し引いた新しい配列を返します。
# 重複も加味され、selfに存在する分からotherに存在する分を差し引いた分を返します。
#------------------------------------------------------------------------------
# 例 :
# self = [1, 2, 3, 2, 1, 2] , other = [3, 1, 1, 4, 1, 2] の場合
# self.array_and_repeat(other)   # => [1, 2, 3, 1]
# self.array_minus_repeat(other) # => [2, 2]
#------------------------------------------------------------------------------
# ver.1.00(2005/11/21)
# 公開

#==============================================================================
# Array
#==============================================================================
class Array
  #--------------------------------------------------------------------------
  # ● 重複加味集合積演算
  #     self  : 配列1
  #     other : 配列2
  #--------------------------------------------------------------------------
  def array_and_repeat(other)
    used = []
    result = []
    for i in 0...self.size
      for j in 0...other.size
        next if used.include?(j)
        if self[i] == other[j]
          result.push(other[j])
          used.push(j)
          break
        end
      end
    end
    return result
  end
  #--------------------------------------------------------------------------
  # ● 重複加味集合差演算
  #     self  : 配列1
  #     other : 配列2
  #--------------------------------------------------------------------------
  def array_minus_repeat(other)
    used = []
    result = []
    for i in 0...self.size
      done = false
      for j in 0...other.size
        next if used.include?(j)
        if self[i] == other[j]
          done = true
          used.push(j)
          break
        end
      end
      result.push(self[i]) if !done
    end
    return result
  end
end

[PR]今週のあなたの運勢は?:精霊が無料診断