Created
June 25, 2012 06:59
-
-
Save raven29/2987086 to your computer and use it in GitHub Desktop.
SumCheckerHash
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 SumCheckerHash | |
def initialize(file_name) | |
@hsh = {} | |
File.open(file_name).each{|line| @hsh[line.to_i] = @hsh[line.to_i].nil? ? 1 : (@hsh[line.to_i]+1)} | |
end | |
def check(sum) | |
@hsh.each_key{|i| return true if @hsh.has_key?(sum - i) && ((2*i != sum) || (@hsh[i] > 1))} | |
return false | |
end | |
end | |
require 'test/unit' | |
class SumCheckTest < Test::Unit::TestCase | |
@@test = { | |
231552=>true, | |
234756=>false, | |
596873=>true, | |
648219=>true, | |
726312=>true, | |
981237=>false, | |
988331=>true, | |
1277361=>false, | |
1283379=>false | |
} | |
def test_01_verify | |
sch = SumCheckerHash.new('input.txt') | |
@@test.each do|key, val| | |
assert_equal(val, sch.check(key)) | |
end | |
end | |
def test_02_productivity | |
puts | |
sch = SumCheckerHash.new('input.txt') | |
@@test.each do|key, val| | |
ts1 = Time.now.to_f | |
puts key.to_s + " - " + (sch.check(key) ? "yes" : "no") | |
ts2 = Time.now.to_f | |
puts "elapsed: " + (ts2 - ts1).to_s + " s" | |
end | |
end | |
end | |
if (ARGV[0]) | |
sch = SumCheckerHash.new('input.txt') | |
puts sch.check(ARGV[0].to_i) ? "yes" : "no" | |
exit 0 | |
else | |
puts "Haven't got a valid sum value to check, loading tests..." | |
puts "=" * 45 | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Call with a number parameter runs corresponding sum checking.
Call without parameters runs tests (verification and productivity).