Instantly share code, notes, and snippets.

Embed
What would you like to do?
Tests a regular expression for recognising binary numbers that are divisible by 3.
your_re = // # <= YOUR REGEX GOES BETWEEN THESE SLASHES*************************
#Example: /.*/
# This wraps your regex so the whole binary string has to match it
@re = /^(#{your_re})$/
# Helper code to convert numbers to binary strings
class Fixnum
def to_bin_s
return '0' if self == 0
s = ''
n = self
while n > 0
s = (n % 2).to_s << s
n = n >> 1
end
s
end
end
def test(limit)
incorrect = {:neg => [], :pos => []}
limit.times do |n|
multiple_of_3 = n%3 == 0
incorrect[:pos] << n if @re.match(n.to_bin_s) and !multiple_of_3
incorrect[:neg] << n if !@re.match(n.to_bin_s) and multiple_of_3
end
passed = (incorrect[:pos].empty? and incorrect[:neg].empty?)
passed ? 'Pass =]' : incorrect
end
result = test 50 # <= INCREASE THIS NUMBER TO RUN FOR MORE CASES****************
# Print the results
puts result unless result.class == {}.class
if result.class == {}.class
puts "\nFalse Positives:"
print_bin = lambda {|n| print " #{n.to_bin_s}" }
result[:pos].each &print_bin
puts "\n\nFalse Negatives:"
result[:neg].each &print_bin
puts "\n\nTotal: #{result[:neg].length + result[:pos].length}"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment