ruby - 方法不返回 Ruby 中的预期值

标签 ruby algorithm

我试图在 Ruby 中实现 Karatsuba 乘法..

# takes two integer x and y and partition them to x=a+b and y=c+d
# example if x = 1234 a=12 and b=34
# recursively compute a*c,a*d,b*c and b*d
def mult (x,y)
    if len(x) == 1 && len(y) == 1
             return  x*y 
       elsif len(x) > 1 && len(y) > 1
             ab = partition(x)
             cd =  partition(y)
             return ab.product(cd).each{ |num| mult(num[0],num[1]) }
       end
end
#method for partitioning works fine..
def partition(number)
     number.divmod( 10**(len(number)/2) )
end
#method to find size of integer works fine...
def len(value)
    value.to_s.split("").compact.size
end

所以预期返回为

 p mult(12,34) should be 3,4,6,8
 but is [[1, 3], [1, 4], [2, 3], [2, 4]]

代替return x*y,当我在line no:3中使用print "#{x*y}"时,它会打印3、4、6、8。我无法理解为什么 mult 方法为 x*y 返回 nil

最佳答案

问题是错误的迭代器:

#              ⇓⇓⇓⇓    
ab.product(cd).each{ |num| mult(num[0],num[1]) }

你想要的是Enumerable#map相反:

ab.product(cd).map { |num| mult(num[0], num[1]) }

旁注:您也不需要显式调用 return:

def mult (x,y)
  if len(x) == 1 && len(y) == 1
    x*y
  elsif len(x) > 1 && len(y) > 1
    ab = partition(x)
    cd = partition(y)
    ab.product(cd).map { |num| mult(num[0], num[1]) }
  else
    raise "We got a problem"
  end
end
#method for partitioning works fine..
def partition(number)
  number.divmod( 10**(len(number)/2) )
end
#method to find size of integer works fine...
def len(value)
  value.to_s.size
end

p mult 12, 34
#⇒ [3,4,6,8]

关于ruby - 方法不返回 Ruby 中的预期值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44263031/

相关文章:

algorithm - 了解 O(max(m,n)) 的时间复杂度

ruby-on-rails - Rails - 有什么方法可以为模型的 ActiveRecord::Relation 查询设置可重写的 "default"过滤器(即预运行类方法)?

ruby - 正则表达式:如何替换除单词/模式序列之外的所有字符?

algorithm - 进行递归二分查找

python - 遍历包含表单的网站的算法

python - 在随机列表生成中强制执行 "no 2 same contiguous elements"

ruby - Ruby 方法定义中的等号

ruby - 如何使用 ruby​​ 将大文件从客户端传输到服务器?

ruby - 在 Ruby 中解压签名的小端

算法 : random unique string