Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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)
- if min_and_max_factors_given?(args)
- get_tripets(args[:max_factor], min_factor: args[:min_factor])
- elsif max_factor_and_sum_given?(args)
- get_tripets(args[:max_factor], sum: args[:sum])
- elsif max_factor_given?(args)
- get_tripets(args[:max_factor])
- end
- 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)
- args.has_key?(:max_factor)
- end
- def self.min_and_max_factors_given?(args)
- args.has_key?(:min_factor) && args.has_key?(:max_factor)
- end
- def self.max_factor_and_sum_given?(args)
- args.has_key?(:max_factor) && args.has_key?(:sum)
- end
- def self.get_tripets(c_high, options = {})
- triplets = []
- options[:min_factor] == nil ? c_low = 3 : c_low = options[:min_factor] + 2
- c_high.downto(c_low) do |c|
- b = c - 1
- while b**2 > c**2 / 2 do
- a = Math.sqrt(c**2 - b**2).to_i
- if options[:min_factor] != nil
- if Triplet.new(a, b, c).pythagorean? && a >= options[:min_factor]
- triplets << Triplet.new(a, b, c)
- break
- end
- elsif options[:sum] != nil
- if Triplet.new(a, b, c).pythagorean? && Triplet.new(a, b, c).sum == options[:sum]
- triplets << Triplet.new(a, b, c)
- break
- end
- else
- if Triplet.new(a, b, c).pythagorean?
- triplets << Triplet.new(a, b, c)
- break
- end
- end
- b -= 1
- end
- b = c - 1
- end
- triplets
- end
- end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement