2017-05-30 32 views
1

我試圖在Ruby中實現Karatsuba乘法沒有返回預期值..方法在Ruby中

# 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,當我使用print "#{x*y}"line no:3它打印3,4,6,8。我無法理解爲什麼mult方法返回nilx*y

+0

'len(x)'?這聽起來像Python – Ursus

+1

@Ursus它聽起來像自我實現的方法,檢查代碼段的最後3行。 – mudasobwa

回答

4

的問題是錯誤的迭代器:

#    ⇓⇓⇓⇓  
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] 
+0

感謝它的工作,我在打印'[[1,3],[1,4],[2,3],[2,4]]'時應該知道並停止了 – 0sfh

+0

但爲什麼不是'each'正常工作當我必須迭代每個值並將其傳遞給'mult(x,y)'方法時。 – 0sfh

+0

因爲'each'本身返回迭代,而'map'實際上將迭代轉換爲從'mult'方法返回的新值。 – mudasobwa