Last active
May 3, 2016 21:36
-
-
Save ahirschberg/75b33492d0ec43220dbf to your computer and use it in GitHub Desktop.
Peasant multiplication algorithm implemented in ruby. You can check this out in action at http://repl.it/onr
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class PeasantMultiplication | |
## multiply using the Peasant Multiplication Algorithm | |
def self.multiply(number1, number2) | |
# convert number1 to binary and reverse it | |
# so that the most significant bit is last | |
n1_binary_str = number1.to_s(2).reverse | |
binary_array = n1_binary_str.split '' # convert string to array | |
add_amount = number2 | |
# traverses the binary_array and calculates the total | |
return binary_array.reduce(0) do |total, char| | |
# add add_amount to the total if the binary for | |
# number2 has a 1 in given place | |
total += add_amount if char == '1' | |
# double the add_amount each time | |
add_amount = add_amount + add_amount | |
total | |
end | |
end | |
end | |
## This class verifies the correctness of a given multiplication algorithm | |
class CheckCorrectness | |
MultCase = Struct.new(:n1, :n2, :ans) | |
## initialize array of test cases for multiplication with a range of n numbers | |
def initialize(n) | |
@check_algorithm = [] | |
(0..n).each do |n1| | |
(0..n).each do |n2| | |
@check_algorithm << MultCase.new(n1, n2, n1*n2) | |
end | |
end | |
end | |
def check_correctness(multiplier) | |
@check_algorithm.each { |mult| | |
result = multiplier.multiply(mult.n1, mult.n2) | |
if (result != mult.ans) | |
raise "ERROR: #{mult.n1} * #{mult.n2} calculated to be #{result}, expected #{mult.ans}" | |
end | |
} | |
puts "All examples passed!" | |
end | |
end | |
ckc = CheckCorrectness.new 250 # check multiplication with numbers 1 to 100 | |
ckc.check_correctness PeasantMultiplication # this will output "All examples passed!" |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
PeasantMultiplication.multiply 1, 2 | |
#=> 2 | |
PeasantMultiplication.multiply 400, 2 | |
#=> 800 | |
PeasantMultiplication.multiply 400, 20 | |
#=> 8000 | |
PeasantMultiplication.multiply 400, 200 | |
#=> 80000 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment