Skip to content

Instantly share code, notes, and snippets.

@masassiez
Created January 27, 2012 13:56
Show Gist options
  • Save masassiez/1688907 to your computer and use it in GitHub Desktop.
Save masassiez/1688907 to your computer and use it in GitHub Desktop.
n本の様々な長さの棒の中から3本使って、できるだけ周長の長い三角形を作る | ruby pythagorean.rb n(省略時:15)
class Pythagorean
def initialize(n)
@sticks = [ *1 .. ( { 0 => 15 }[n] || n ) ]
@triples = @sticks.map(&:to_f).combination(3)
end
def triples
@triples.select( &theorem ).map { |e| e.map(&:to_i) }
end
def theorem
lambda { |args| Math.hypot(*args[0..1]) == args[2] }
end
def triples_groupby_length
triples.group_by { |e| e.inject(:+) }
end
def triples_of_maxlength(&block)
result = triples_groupby_length.max
block_given? ? yield(result) : result
end
def triples_groupby_gcd
triples.group_by { |a, b, c| gcd = a.gcd(b).gcd(c) ; [a, b, c].map { |e| e / gcd } }
end
end
if __FILE__ == $0
n = ARGV[0].to_i
pythagorean = Pythagorean.new(n)
# p pythagorean.triples_groupby_gcd.keys
pythagorean.triples_of_maxlength do |length, triples|
len = length || "N/A"
list = triples ? triples.map(&:inspect) * "," : "N/A"
puts <<-OUTPUT
MaxLength: #{ len }
Triples: #{ list }
OUTPUT
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment