Skip to content

Instantly share code, notes, and snippets.

@alexbowe
Created November 23, 2010 11:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alexbowe/711644 to your computer and use it in GitHub Desktop.
Save alexbowe/711644 to your computer and use it in GitHub Desktop.
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