Skip to content

Instantly share code, notes, and snippets.

@nerboda
Last active September 26, 2016 02:53
Show Gist options
  • Save nerboda/f95420a155e12cdbabbd425b1becbed5 to your computer and use it in GitHub Desktop.
Save nerboda/f95420a155e12cdbabbd425b1becbed5 to your computer and use it in GitHub Desktop.
Weekly Challenge - Pythagorean Triplet
# A class for auto-generating pythagorean triplets according to
# certain criteria, as well as testing whether a set of 3 numbers
# is a valid pythagorean triplet.
class Triplet
def initialize(*nums)
@nums = nums
end
def sum
@nums.reduce(:+)
end
def product
@nums.reduce(:*)
end
def pythagorean?
@nums[0]**2 + @nums[1]**2 == @nums[2]**2
end
class << self
def where(options)
min = options[:min_factor] || 1
max = options[:max_factor]
sum = options[:sum]
factors = (min..max).to_a
factors.combination(3).map do |a, b, c|
triplet = Triplet.new(a, b, c)
triplet if valid?(triplet, sum)
end.compact
end
private
def valid?(triplet, expected_sum)
if expected_sum
triplet.pythagorean? && triplet.sum == expected_sum
else
triplet.pythagorean?
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment