假设我有两个阵列:
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
union = [1,1,2,3] 我想这对于得到如此简单的东西似乎很重要。
答案 0 :(得分:1)
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]
对于更强大的内容,请参阅以下答案:
https://stackoverflow.com/a/3852809/183181
如果订单很重要,请点击这里:
https://stackoverflow.com/a/21737172/183181
答案 1 :(得分:0)
我会这样做:
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]