Skip to content

Instantly share code, notes, and snippets.

@holdenhinkle
Last active March 12, 2016 16:25
Show Gist options
  • Save holdenhinkle/5ac1688dd5b423068f35 to your computer and use it in GitHub Desktop.
Save holdenhinkle/5ac1688dd5b423068f35 to your computer and use it in GitHub Desktop.
pythagorean_triplet
require 'pry'
class Triplet
attr_reader :a, :b, :c
def initialize(a, b, c)
@a = a
@b = b
@c = c
end
def self.where(args)
max_factor_given(args)
end
def sum
a + b + c
end
def product
a * b * c
end
def pythagorean?
a**2 + b**2 == c**2
end
private
def self.max_factor_given(args)
triplets = []
args[:min_factor] ? min_c = args[:min_factor] + 2 : min_c = 3
args[:max_factor].downto(min_c) do |c|
b = c - 1
while b**2 > c**2 / 2 do
a = Math.sqrt(c**2 - b**2).to_i
if min_factor_given?(args)
triplets << Triplet.new(a, b, c) if Triplet.new(a, b, c).pythagorean? && a >= args[:min_factor]
elsif sum_given?(args)
triplets << Triplet.new(a, b, c) if Triplet.new(a, b, c).pythagorean? && Triplet.new(a, b, c).sum == args[:sum]
else
triplets << Triplet.new(a, b, c) if Triplet.new(a, b, c).pythagorean?
end
b -= 1
end
b = c - 1
end
triplets
end
def self.min_factor_given?(args)
args.has_key?(:min_factor)
end
def self.sum_given?(args)
args.has_key?(:sum)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment