繁体   English   中英

Ruby方法返回意外值

[英]Ruby method returns unexpected value

我有一个返回两个3位数字的产品,它是小于制造的最大的回文的方法smaller_than 它应尽可能快地运行。

回文数在两个方向上都相同。 由两个3位数字组成的最小回文数为101101,这是143 * 707的乘积。

这是我的代码:

def palindrome(smaller_than)
  max = 0

  999.downto(143).each do |x|
    999.downto(707).each do |y|
      break if (max > x * y) || (smaller_than < x * y)
      max = x * y if x * y == (x * y).to_s.reverse.to_i
    end
  end

  return max
end

t = Time.now
puts palindrome(800000)
puts "Took #{Time.now-t}"

这给了我723327而不是793397

如果我将代码更改为此:

def palindrome(smaller_than)
  max = 0

  999.downto(143).each do |x|
    999.downto(707).each do |y|
      break if max > x * y
      max = x * y if (x * y == (x * y).to_s.reverse.to_i) && (smaller_than > x * y)
    end
  end

  return max
end

t = Time.now
puts palindrome(800000)
puts "Took #{Time.now-t}"

...它给我正确的值793397

第二种方法有效,但是速度太慢。 为什么更快的第一个方法返回错误的值?

您的第一个版本的问题是它从不应有的内循环中中断。 这是一个工作版本,几乎与不工作版本一样快。

def palindrome2(smaller_than)
  max = 0

  999.downto(143).each do |x|
    999.downto(707).each do |y|
      product = x * y
      break if max > product
      next if smaller_than < product
      max = product if product.to_s == product.to_s.reverse
    end
  end

  return max
end

也,

如果只是重新安排检查条件以启用短路 ,则可以实现相同的加速。

  # max = x * y if (x * y == (x * y).to_s.reverse.to_i) && (smaller_than > x * y)
  max = x * y if (smaller_than > x * y) && (x * y == (x * y).to_s.reverse.to_i)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM