0sfh
0sfh

Reputation: 13

Method not returning the expected value in Ruby

I was trying to implement Karatsuba multiplication in 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

So the expected return for

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

instead of return x*y, when i use print "#{x*y}" in line no:3 it prints 3,4,6,8. I am unable to understand why mult method is returning nil for x*y.

Upvotes: 1

Views: 70

Answers (1)

Aleksei Matiushkin
Aleksei Matiushkin

Reputation: 121010

The problem is wrong iterator:

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

What you want is to Enumerable#map instead:

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

Sidenote: you also don’t need to explicitly call 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]

Upvotes: 4

Related Questions