Advertisement
Guest User

Untitled

a guest
Oct 9th, 2015
115
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.73 KB | None | 0 0
  1. class Triplet
  2.  
  3. def initialize(*input)
  4. @numbers = *input
  5. end
  6.  
  7. def sum
  8. @numbers.reduce(:+)
  9. end
  10.  
  11. def product
  12. @numbers.reduce(:*)
  13. end
  14.  
  15. def pythagorean?
  16. squares=@numbers.map {|m| square(m)}.sort
  17. squares[2]==squares[0]+squares[1]
  18. end
  19.  
  20. def self.where(conditions)
  21. max = conditions[:max_factor]
  22. min = conditions[:min_factor] || 1
  23. sum = conditions[:sum]
  24.  
  25. available_integers = Array(min..max)
  26.  
  27. triplet_min_to_max = available_integers.combination(3).to_a.map{|m| Triplet.new(m[0],m[1],m[2])}
  28.  
  29. pythagorean_triplets = triplet_min_to_max.select {|s| s.pythagorean?}
  30.  
  31. sum ? pythagorean_triplets.select! {|s| s.sum==sum} : pythagorean_triplets
  32. end
  33.  
  34. private
  35. def square(x)
  36. x**2
  37. end
  38. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement