数组交并集递归

示例一

module Enumerable
  def comprehend(&block)
    block ? map(&block).compact : self
  end

  def foldr(o, m = nil)
    reverse.inject(m) {|m, i| m ? i.send(o, m) : i}
  end

  def foldl(o, m = nil)
    inject(m) {|m, i| m ? m.send(o, i) : i}
  end
end

 

具体示例:

 

old_data = *(1..5)
new_data = *(3..9)
added = new_data.comprehend { |x| x if not old_data.include?(x) }
removed = old_data.comprehend { |x| x if not new_data.include?(x) }
same = new_data.comprehend { |x| x if old_data.include?(x) }
modified = new_data.comprehend { |x| x**2 if not x % 2 == 0 }
p added                                   # => [6, 7, 8, 9]
p added = new_data - old_data             # => [6, 7, 8, 9]
p removed                                 # => [1, 2]
p removed = old_data - new_data           # => [1, 2]
p same                                    # => [3, 4, 5]
p same = old_data & new_data              # => [3, 4, 5]
p modified                                # => [9, 25, 49, 81]
new_data = [[5, 9], [22, 3], [99, 564]]
bool_vals = new_data.comprehend { |x, y| x <= y }
p bool_vals  # => [true, false, true]
    
p [1, 2, 3, 4, 5].foldl(:+)    # => 15
p [1, 2, 3, 4, 5].foldl(:*)    # => 120
p [1, 2, 3, 4, 5].foldr(:+)    # => 15
p [1, 2, 3, 4, 5].foldr(:*)    # => 120
p [1, 2, 3, 4, 5].foldr(:-, 0) # => 3
p [1, 2, 3, 4, 5].foldl(:-, 0) # => -15

 

示例二

class Array
  def intersection(arr)
    self_sorted = self.sort
    target_sorted = arr.sort
    intersection = []
    jstart = 0
    for i in (0..self_sorted.length - 1)
      for j in (jstart..target_sorted.length - 1)
        if self_sorted[i] == target_sorted[j]
          jstart = j + 1
          intersection[intersection.length] = self_sorted[i]
          break
        end
      end
    end
    return intersection
  end
end

 

具体示例:

 

    p [2, 2, 2, 3, 7, 13, 49] & [2, 2, 2, 5, 11, 107]  # => [2]
    p [2, 2, 2, 3, 7, 13, 49].intersection([2, 2, 2, 5, 11, 107])  # => [2, 2, 2]
    p ['a', 'b', 'a', 'c'] & ['a', 'c', 'a', 'd']  # => ["a", "c"]
    p ['a', 'b', 'a', 'c'].intersection(['a', 'c', 'a', 'd'])  # => ["a", "a", "c"]

 

你可能感兴趣的:(C++,c,C#,J#)