Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/algorithm/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby方法返回意外值_Ruby_Algorithm - Fatal编程技术网

Ruby方法返回意外值

Ruby方法返回意外值,ruby,algorithm,Ruby,Algorithm,我有一个方法,返回由两个小于_的3位数字的乘积生成的最大回文。它应该尽可能快地运行 回文数字的两种读取方式相同。由两个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

我有一个方法,返回由两个小于_的3位数字的乘积生成的最大回文。它应该尽可能快地运行

回文数字的两种读取方式相同。由两个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}"
…它给了我正确的值793397


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

您的第一个版本的问题是,它在不应该的地方中断了内部循环。这是一个工作版本,几乎和非工作版本一样快

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

如果不需要正常工作,任何程序都可以非常快地生成:
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)