Skip to content

Instantly share code, notes, and snippets.

@raven29
Created June 25, 2012 06:59
Show Gist options
  • Save raven29/2987086 to your computer and use it in GitHub Desktop.
Save raven29/2987086 to your computer and use it in GitHub Desktop.
SumCheckerHash
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
@raven29
Copy link
Author

raven29 commented Jun 25, 2012

Call with a number parameter runs corresponding sum checking.
Call without parameters runs tests (verification and productivity).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment