Last active
November 26, 2015 17:19
-
-
Save mkweick/3df4ac0f6405a18e2eb6 to your computer and use it in GitHub Desktop.
Pythagorean Triplet
This file contains hidden or 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 Triplet | |
attr_reader :a, :b, :c | |
def initialize(a, b, c) | |
@a = a | |
@b = b | |
@c = c | |
end | |
def sum | |
[a, b, c].inject(:+) | |
end | |
def product | |
[a, b, c].inject(:*) | |
end | |
def pythagorean? | |
[a**2, b**2].inject(:+) == c**2 | |
end | |
def self.where(values) | |
TestTriplets.new(values).get_triplets | |
end | |
end | |
class TestTriplets | |
attr_reader :min_max, :sum | |
def initialize(values) | |
min_factor = values.fetch(:min_factor, 1) | |
max_factor = values.fetch(:max_factor) | |
@min_max = (min_factor..max_factor).to_a | |
@sum = values.fetch(:sum, nil) | |
end | |
def get_triplets | |
triplets = [] | |
min_max.combination(3).each do |a, b, c| | |
triplet_class = Triplet.new(a, b, c) | |
triplets.push(triplet_class) if valid_triplet?(triplet_class) | |
end | |
triplets | |
end | |
def valid_triplet?(triplet_class) | |
if sum.nil? | |
triplet_class.pythagorean? | |
else | |
triplet_class.pythagorean? && triplet_class.sum == sum | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment