diff options
| author | mo khan <mo@mokhan.ca> | 2015-03-06 14:06:32 -0700 |
|---|---|---|
| committer | mo khan <mo@mokhan.ca> | 2015-03-06 14:06:32 -0700 |
| commit | e07328380b0898fe3ab370732cf12de045f03d52 (patch) | |
| tree | 71b4b8db65fb63484754c4c97757c2c1b39b984a | |
| parent | 17b68b98cb321a63dbb62c7293ceae46dcb18113 (diff) | |
attempt to solve pythagorean triplets.
| -rw-r--r-- | spec/euler/problem_nine_spec.rb | 57 |
1 files changed, 57 insertions, 0 deletions
diff --git a/spec/euler/problem_nine_spec.rb b/spec/euler/problem_nine_spec.rb new file mode 100644 index 0000000..3ec4f76 --- /dev/null +++ b/spec/euler/problem_nine_spec.rb @@ -0,0 +1,57 @@ +require "spec_helper" + +describe "problem nine" do + # A Pythagorean triplet is a set of three natural numbers, a < b < c, for which, a^2 + b^2 = c^2 + # For example, 3^2 + 4^2 = 9 + 16 = 25 = 5^2. + + # There exists exactly one Pythagorean triplet for which a + b + c = 1000. + # Find the product abc. + # + class PythagoreanTriplet + include Enumerable + + def initialize(max = 100_000) + @max = max + end + + def each(&block) + triplets.each(&block) + end + + private + + def triplets + Enumerator.new do |yielder| + 0.upto(@max) do |n| + x = n * n + y = (n+1) * (n+1) + z = (n+2) * (n+2) + if x + y == z + puts "#{n}: MATCH" + yielder.yield([n, n+1, n+2]) + else + puts "#{n}: no match" + end + end + end + end + end + + subject { PythagoreanTriplet.new } + + it "returns the triplet for 25" do + expect(subject.first).to eql([3, 4, 5]) + + result = subject.find do |triplet| + (triplet.last * triplet.last) == 25 + end + expect(result).to eql([3, 4, 5]) + end + + it "returns the triplet for 1000" do + result = subject.find do |triplet| + (triplet.last * triplet.last) == 1_000 + end + expect(result).to eql(10) + end +end |
