如何使用块/lambda 表达式从 Ruby 数组中删除 n 个相同值的元素?

发布于 2024-10-26 17:56:15 字数 513 浏览 1 评论 0原文

我正在学习 Ruby,并且尝试以 Ruby 的方式思考。但是,尽我所能,我无法解决这个问题:

例如,我有以下源数组:

a = [1, 3, 5, 4, 5, 5, 7, 5]

# param 1 = number matching, param 2 times matching
b = a.remove_repeated(5, 3)

那么 b 的值将是:

b = [1, 3, 4, 7, 5]

在我试图匹配的只有两个值的情况下,我也希望将它们全部删除。如:

a = [1, 4, 8, 4, 9, 2]
b = a.remove_repeated(4, 3)

那么 b 的值将是:

a = [1, 8, 9, 2]

我知道如何以迭代和递归的方式执行此操作。相反,我正在寻找一种 Rubyesque 的方式来做到这一点。

I'm in the process of learning Ruby and I'm trying to think in a Ruby way. However, try as I might, I can't wrap my mind around this problem:

For example, I have the following source array:

a = [1, 3, 5, 4, 5, 5, 7, 5]

# param 1 = number matching, param 2 times matching
b = a.remove_repeated(5, 3)

Then b's value would be:

b = [1, 3, 4, 7, 5]

In the case that there were only two value values that I was trying to match, I would want them all removed as well. Such as:

a = [1, 4, 8, 4, 9, 2]
b = a.remove_repeated(4, 3)

Then b's value would be:

a = [1, 8, 9, 2]

I know how to do this a in both a iterative and a recursive way. Rather, I'm looking for a Rubyesque way of doing it.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

活泼老夫 2024-11-02 17:56:15
class Array
  def remove_repeated(obj, limit)
    reject{|e| e == obj && (limit-=1) >= 0}
  end
end

Array.reject 一次复制数组一个元素,但块为 true 的元素除外。

class Array
  def remove_repeated(obj, limit)
    reject{|e| e == obj && (limit-=1) >= 0}
  end
end

Array.reject copies the array one element at a time, except for the elements for which the block is true.

花辞树 2024-11-02 17:56:15

您正在寻找类似此代码的内容吗?

class Array
  def remove_repeated(item, count)
    inject([]) do |filtered, current|
      filtered << current unless item==current && (count-=1) >= 0
      filtered
    end
  end
end

a = [1, 3, 5, 4, 5, 5, 7, 5]
p a.remove_repeated(5, 3) # => [1, 3, 4, 7, 5]

a = [1, 4, 8, 4, 9, 2]
p a.remove_repeated(4, 3) # => [1, 8, 9, 2]

Is something like this code what you're looking for?

class Array
  def remove_repeated(item, count)
    inject([]) do |filtered, current|
      filtered << current unless item==current && (count-=1) >= 0
      filtered
    end
  end
end

a = [1, 3, 5, 4, 5, 5, 7, 5]
p a.remove_repeated(5, 3) # => [1, 3, 4, 7, 5]

a = [1, 4, 8, 4, 9, 2]
p a.remove_repeated(4, 3) # => [1, 8, 9, 2]
哀由 2024-11-02 17:56:15

我不知道为什么你想部分删除重复项,但如果你想在一个步骤中删除所有重复项:

a = [1, 3, 5, 4, 5, 5, 7, 5]

b = a.uniq
# => a = [1, 3, 5, 4, 5, 5, 7, 5], b = [1, 3, 5, 4, 7]

a.uniq!
# => a = [1, 3, 5, 4, 7]

I don't know why you want to partially remove the duplicates, but if you want to remove all duplicates in a single step:

a = [1, 3, 5, 4, 5, 5, 7, 5]

b = a.uniq
# => a = [1, 3, 5, 4, 5, 5, 7, 5], b = [1, 3, 5, 4, 7]

or

a.uniq!
# => a = [1, 3, 5, 4, 7]
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文