Skip to content

Instantly share code, notes, and snippets.

@britg
Created October 8, 2015 19:22
Show Gist options
  • Save britg/4ff58bd32c5c5660427c to your computer and use it in GitHub Desktop.
Save britg/4ff58bd32c5c5660427c to your computer and use it in GitHub Desktop.
class Triplet
# Class methods
# these generate Triplet _instances_
def self.up_to max
valid = []
(1..max).each do |x|
y = x+1
z = y+1
while z <= max do
z += 1 while z**2 < x**2 + y**2
test = Triplet.new(x, y, z)
valid << test if test.pythagorean?
y += 1
end
end
valid
end
def self.where opts = {}
matches = []
if opts[:max_factor].present?
matches = self.up_to(opts[:max_factor])
end
if opts[:min_factor].present?
matches.reject!{ |m| m.min_factor < opts[:min_factor] }
end
if opts[:sum].present?
matches.select!{ |m| m.sum == opts[:sum] }
end
matches
end
# Instance methods
# these provide functionality to triplet _instances_
def initialize a, b, c
@a, @b, @c = a, b, c
@items = [@a, @b, @c]
end
def min_factor
@a
end
def max_factor
@z
end
def sum
@items.inject(:+)
end
def product
@items.inject(:*)
end
def pythagorean?
@a**2 + @b**2 == @c**2
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment