从两个数组中删除公共元素,同时在 Ruby 中保留重复元素

Remove common elements from two arrays while keeping duplicates in Ruby

假设我有两个数组:

a = [1,1,2,3,3,3,3] 
b = [1,2]

如果我想从 a 中删除 b,我想要以下结果:

c = [1,3,3,3,3]

如果我不知道 a 和 b 包含什么,我该怎么做才能使以下计算结果都为 c:

a-b = |c| just as b-a=|c|

ruby 中的所有逻辑操作似乎都删除了数组中的重复值。

这看起来很复杂

def try()
  a = [1,1,2,3,3,3,3]
  b = [1,1,2,3,5]
  min = a.length < b.length ? a : b
  c = a & b
  x = []
  for i in 0..c.length-1
    x[i] = min.count(c[i])
  end 
  union=[]
  k = 0;
  for i in 0..c.length-1
    for j in 0..x[i]-1
      union[k]=c[i]
      k +=1
    end
  end
  return union
end

联合 = [1,1,2,3] 我想这似乎很容易得到如此简单的东西。

a = [1,1,2,3,3,3,3]
b = [1,2]

a.each_with_index {|av,ai|
  b.each_with_index {|bv,bi|
    if (av == bv)
      a[ai] = nil
      b.delete_at(bi)
      break
    end
  }
}

# a.compact!: [1,3,3,3,3]

对于更强大的内容,请参阅此答案:

如果顺序很重要,请在此处:

我会这样做:

a = [1,1,2,3,3,3,3]
b = [1,2]

b.each do |value_in_b|
  a.delete_at a.find_index(value_in_b)
end

p a #=> [1, 3, 3, 3, 3]