【问题标题】:Finding the smallest negative number and the smallest positive number in an array of transactions using .each使用 .each 在事务数组中查找最小的负数和最小的正数
【发布时间】:2019-12-14 12:03:51
【问题描述】:

我有一个交易数据数组:

transactions = [50_000, -2_000, -25_000, 4_000, -12_000, 5_000, -800, -900, 43_000, -30_000, 15_000, 62_000, -50_000, 42_000]

我想从该列表中检索最大的负数(最小的提款)和最小的正数(最小的存款)。取款用负数表示。存款都是正数。

我无法理解获得所需结果所需的逻辑(最小提款和最小存款)

下面,我目前从数组中获得最大的取款和最大的存款:

smallest_withdrawal = 0
transactions.each do |transaction|
  if transaction < smallest_withdrawal
    smallest_withdrawal = transaction
  end
end
puts smallest_withdrawal

smallest_deposit = 0
transactions.each do |transaction|
  if transaction > smallest_deposit
    smallest_deposit = transaction
  end
end
puts smallest_deposit

我没有收到错误消息,但我没有得到我想要的结果,而是得到了相反的结果。我需要逻辑运算符方面的帮助。

【问题讨论】:

  • 是否保证至少有一次存款和一次取款?如果不是,如果没有这两种类型,返回什么?

标签: arrays ruby


【解决方案1】:

如何利用 Ruby 的内置操作为取款和存款定义合适的子集?

smallest_withdrawal = transactions.select { |x| x < 0 }.max
smallest_deposit = transactions.select { |x| x > 0 }.min

这也可以写成:

smallest_withdrawal = transactions.select(&:negative?).max
smallest_deposit = transactions.select(&:positive?).min

另一个变体是:

negatives, positives = transactions.partition(&:negative?)
smallest_withdrawal = negatives.max
smallest_deposit = positives.min

最后,如果你愿意为了得到一个单线而变得神秘:

smallest_withdrawal, smallest_deposit = transactions.partition(&:negative?).map(&:minmax).flatten[1..2]

不过,出于可读性原因,我不建议这样做。

【讨论】:

    【解决方案2】:

    可以单次通过数组。如果保证至少有一笔存款和一笔取款,可以写:

    def closest_to_zero(transactions)
      transactions.minmax_by { |t| 1.0/t }
    end
    

    closest_to_zero(transactions)
      #=> [-800, 4000]
    

    Enumerable#minmax_by。如果没有存款或取款(但至少有两次交易),我们将不得不丑化代码:

    def closest_to_zero(transactions) 
      transactions.minmax_by { |t| 1.0/t }.then do |mn,mx|
        [mn > 0 ? nil : mn, mx < 0 ? nil : mx]
      end
    end
    
    closest_to_zero [ 1,  2,  3]
      #=> [nil, 1] 
    closest_to_zero [-1, -2, -3]
      #=> [-1, nil] 
    

    Object#then(又名yield_self)。 yield_self 是 Ruby v2.5 中的新功能,then 是 v2.6 中的新功能。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-09-10
      • 2013-04-24
      • 2021-11-29
      • 2018-10-17
      • 1970-01-01
      • 1970-01-01
      • 2020-07-12
      • 1970-01-01
      相关资源
      最近更新 更多