2017-05-30 2 views
1

私は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 

を期待値を返さないので、代わりにreturn x*y

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

の期待リターン、私はprint "#{x*y}"を使用line no:3それは3,4,6,8を印刷します。 multメソッドがnilの返信理由を理解できません。x*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

を停止したときに、それぞれの値を繰り返し処理し、 'mult(x、y)'メソッドに渡す必要があるときです。 – 0sfh

+0

'each'はiterable自体を返します。' map'は実際にiterableを 'mult'メソッドから返された新しい値に変換します。 – mudasobwa

関連する問題