Advertisement
Guest User

Untitled

a guest
Oct 10th, 2015
106
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.69 KB | None | 0 0
  1. require 'pry'
  2.  
  3. class Triplet
  4. attr_reader :a, :b, :c
  5.  
  6. def initialize(a, b, c)
  7. @a = a
  8. @b = b
  9. @c = c
  10. end
  11.  
  12. def self.where(args)
  13. if min_and_max_factors_given?(args)
  14. get_tripets(args[:max_factor], min_factor: args[:min_factor])
  15. elsif max_factor_and_sum_given?(args)
  16. get_tripets(args[:max_factor], sum: args[:sum])
  17. elsif max_factor_given?(args)
  18. get_tripets(args[:max_factor])
  19. end
  20. end
  21.  
  22. def sum
  23. a + b + c
  24. end
  25.  
  26. def product
  27. a * b * c
  28. end
  29.  
  30. def pythagorean?
  31. a**2 + b**2 == c**2
  32. end
  33.  
  34. private
  35.  
  36. def self.max_factor_given?(args)
  37. args.has_key?(:max_factor)
  38. end
  39.  
  40. def self.min_and_max_factors_given?(args)
  41. args.has_key?(:min_factor) && args.has_key?(:max_factor)
  42. end
  43.  
  44. def self.max_factor_and_sum_given?(args)
  45. args.has_key?(:max_factor) && args.has_key?(:sum)
  46. end
  47.  
  48. def self.get_tripets(c_high, options = {})
  49. triplets = []
  50. options[:min_factor] == nil ? c_low = 3 : c_low = options[:min_factor] + 2
  51. c_high.downto(c_low) do |c|
  52. b = c - 1
  53. while b**2 > c**2 / 2 do
  54. a = Math.sqrt(c**2 - b**2).to_i
  55. if options[:min_factor] != nil
  56. if Triplet.new(a, b, c).pythagorean? && a >= options[:min_factor]
  57. triplets << Triplet.new(a, b, c)
  58. break
  59. end
  60. elsif options[:sum] != nil
  61. if Triplet.new(a, b, c).pythagorean? && Triplet.new(a, b, c).sum == options[:sum]
  62. triplets << Triplet.new(a, b, c)
  63. break
  64. end
  65. else
  66. if Triplet.new(a, b, c).pythagorean?
  67. triplets << Triplet.new(a, b, c)
  68. break
  69. end
  70. end
  71. b -= 1
  72. end
  73. b = c - 1
  74. end
  75. triplets
  76. end
  77. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement