Created
April 25, 2014 13:56
-
-
Save crcatala/11290422 to your computer and use it in GitHub Desktop.
Pythagorean Triplets by Christian -- MKS Week 1
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'benchmark' | |
def triplet(perimeter) | |
# Algorithm | |
# Creates array of side pair [a,b] combinations | |
# stores in array side_values | |
# The largest side value tested is (perimeter/2) | |
# since no triangle can be formed with anything | |
# higher with fulfilling our conditions. | |
# The smallest value tested is (perimeter/4) | |
# (this was an approximation, from stats | |
#gathered from testing up to perimeter = 10000) | |
# iterates through the side_values | |
# and checks for fulfilled conditions for | |
# pythagorean triplet | |
return false if perimeter <12 | |
triplets = [] | |
start_num = perimeter/4 | |
end_num = perimeter/2 | |
side_values = (start_num..end_num).to_a.combination(2).to_a | |
# - [[1,2],[1,3],[1,4]...] | |
side_values.each do |a,b| | |
c = Math.sqrt(a**2 + b**2) | |
if is_integer(c) && a+b+c < perimeter | |
triplets << [a,b,c.to_i] | |
end | |
end | |
triplets_perimeter = triplets.map { |x| x.inject(&:+)} | |
max_index = triplets_perimeter.each_with_index.max[1] | |
max_triplet = triplets[max_index] | |
return max_triplet | |
end | |
def is_integer(float_num) | |
float_num.to_i == float_num | |
end | |
# puts triplet(10000).inspect | |
# puts Benchmark.measure {triplet(10000) } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Try this with the number 30. It should return 5, 12, 13