当数组中的相同数字超过 3 个时,如何仅删除 3 个相同数字的实例?
假设我有一个数组,其中包含给定数字的重复次数超过 3 次。 我只想删除其中的三个重复项,并将数字的任何剩余实例保留在结果数组中。
例如:
a = [2, 2, 2, 1, 6]
b = a.map{|i|
num = a.select{|v| v == i}.size
num == 3 ? "" : i
}.reject{|v|
v == ""
}
给出了我想要的结果:
b == [1, 6]
但是,在下面的示例中,我希望最后一个“2”保留在数组中。
# I want to reject ONLY triplets.
# In the below example, the last "2" should remain
a = [2, 2, 2, 1, 2]
b = a.map{|i|
num = a.select{|v| v == i}.size
num == 3 ? "" : i
}.reject{|v|
v == ""
}
这里的结果是:
b == [2, 2, 2, 1, 2]
我希望结果是:
b == [1, 2]
我还有另一个代码块,与上面的代码块类似,使用了一点不同的逻辑,但最终得到了相同的结果:
a = [2, 2, 2, 1, 2]
newdice = a.reject { |v|
if a.count(v) == 3
x = v
end
v == x
}
我不知所措,除了一些令人讨厌的技巧,涉及找到 3x 重复数字的第一个实例的索引,并从中切出 [index, 2]。必须有一种更像“红宝石”的方式。
谢谢!
Let's say I have an Array that contains more than three repetitions of a given digit.
I want to remove only three of those repetitions, and leave any remaining instances of the digit in the resulting array.
For example:
a = [2, 2, 2, 1, 6]
b = a.map{|i|
num = a.select{|v| v == i}.size
num == 3 ? "" : i
}.reject{|v|
v == ""
}
gives me my desired result:
b == [1, 6]
However, in the below example, I want the last "2" to remain in the array.
# I want to reject ONLY triplets.
# In the below example, the last "2" should remain
a = [2, 2, 2, 1, 2]
b = a.map{|i|
num = a.select{|v| v == i}.size
num == 3 ? "" : i
}.reject{|v|
v == ""
}
The result here is:
b == [2, 2, 2, 1, 2]
I'd like the result to be:
b == [1, 2]
I also have another code block, similar to the one above, using a bit different logic, but ends up with the same result:
a = [2, 2, 2, 1, 2]
newdice = a.reject { |v|
if a.count(v) == 3
x = v
end
v == x
}
I'm at a loss, other than some nasty trickery that involves finding the index of the first instance of the 3x repeated digit, and slicing out [index, 2] from it. There's got to be a more "ruby-like" way.
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您想删除数组中任何数字的前 3个,这将删除 = 2 的前 3 个元素
,然后类似于:
使用
if
修饰符进一步修改 Matt 的版本:This would remove the first 3 elements that are = 2
if you want to remove the first 3 of any digits in the array then something like:
Matt's version further modified using the
if
-modifier:不确定您希望如何显示项目,但如果您想使用,以下是简单的选项
Not sure how you want item to be displayed but below are the easy options if you want use