Ethiopian multiplication: Difference between revisions

Content added Content deleted
(→‎{{header|LOLCODE}}: Named functions is from the 1.3 proposal, not 1.2 spec)
Line 3,049: Line 3,049:
Iterative and recursive implementations here.
Iterative and recursive implementations here.
I've chosen to highlight the example 20*5 which I think is more illustrative.
I've chosen to highlight the example 20*5 which I think is more illustrative.
<lang ruby>def even(x); x.even?; end
<lang ruby>def halve(x) x/2 end
def halve(x); x/2; end
def double(x) x*2 end
def double(x); x*2; end


# iterative
# iterative
def ethopian_multiply(a, b)
def ethiopian_multiply(a, b)
product = 0
product = 0
while a >= 1
while a >= 1
p [a, b, even(a) ? "STRIKE" : "KEEP"] if $DEBUG
p [a, b, a.even? ? "STRIKE" : "KEEP"] if $DEBUG
product += b if not even(a)
product += b unless a.even?
a = halve(a)
a = halve(a)
b = double(b)
b = double(b)
Line 3,066: Line 3,065:


# recursive
# recursive
def rec_ethopian_multiply(a, b)
def rec_ethiopian_multiply(a, b)
return 0 if a < 1
return 0 if a < 1
p [a, b, even(a) ? "STRIKE" : "KEEP"] if $DEBUG
p [a, b, a.even? ? "STRIKE" : "KEEP"] if $DEBUG
(even(a) ? 0 : b) + rec_ethopian_multiply(halve(a), double(b))
(a.even? ? 0 : b) + rec_ethiopian_multiply(halve(a), double(b))
end
end


$DEBUG = true # $DEBUG also set to true if "-d" option given
$DEBUG = true # $DEBUG also set to true if "-d" option given
a, b = 20, 5
a, b = 20, 5
puts "#{a} * #{b} = #{ethopian_multiply(a,b)}"; puts</lang>
puts "#{a} * #{b} = #{ethiopian_multiply(a,b)}"; puts</lang>


{{out}}
Output:
<pre>[20, 5, "STRIKE"]
<pre>
[20, 5, "STRIKE"]
[10, 10, "STRIKE"]
[10, 10, "STRIKE"]
[5, 20, "KEEP"]
[5, 20, "KEEP"]
Line 3,100: Line 3,100:
def test_rec6; assert_equal(0, rec_ethopian_multiply(0,5)); end
def test_rec6; assert_equal(0, rec_ethopian_multiply(0,5)); end
end</lang>
end</lang>
<pre>Loaded suite ethopian
<pre>Run options:

Started
# Running tests:

............
............
Finished in 0.001 seconds.
Finished tests in 0.014001s, 857.0816 tests/s, 857.0816 assertions/s.

12 tests, 12 assertions, 0 failures, 0 errors, 0 skips


ruby -v: ruby 2.0.0p247 (2013-06-27) [i386-mingw32]
12 tests, 12 assertions, 0 failures, 0 errors</pre>
</pre>


=={{header|Scala}}==
=={{header|Scala}}==