Skip to content

Commit

Permalink
day 282: add n^2 solution using n space.
Browse files Browse the repository at this point in the history
  • Loading branch information
vaskoz committed Jun 1, 2019
1 parent 7858bf9 commit 1ec8ca1
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 2 deletions.
30 changes: 28 additions & 2 deletions day282/problem.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
package day282

import "errors"
import (
"errors"
"math"
)

var errNoAnswer = errors.New("no pythagorean triplet exists")

Expand All @@ -9,7 +12,7 @@ func ErrNoAnswer() error {
return errNoAnswer
}

// PythagoreanTriplet returns the triplets that fulfill
// PythagoreanTripletBrute returns the triplets that fulfill
// a^2+b^2=c^2.
// Runs in O(N^3) time and O(1) space.
func PythagoreanTripletBrute(nums []int) (a, b, c int, err error) {
Expand All @@ -30,3 +33,26 @@ func PythagoreanTripletBrute(nums []int) (a, b, c int, err error) {
}
return 0, 0, 0, errNoAnswer
}

// PythagoreanTripletBrute returns the triplets that fulfill
// a^2+b^2=c^2.
// Runs in O(N^2) time and O(N) space.
func PythagoreanTriplet(nums []int) (a, b, c int, err error) {
squared := make(map[int]struct{}, len(nums))
for _, num := range nums {
squared[num*num] = struct{}{}
}
for i := range nums {
for j := range nums {
total := nums[i]*nums[i] + nums[j]*nums[j]
c := int(math.Sqrt(float64(total)))
if _, found := squared[total]; found {
if nums[i] < nums[j] {
return nums[i], nums[j], c, nil
}
return nums[j], nums[i], c, nil
}
}
}
return 0, 0, 0, errNoAnswer
}
17 changes: 17 additions & 0 deletions day282/problem_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,23 @@ var testcases = []struct {
},
}

func TestPythagoreanTriplet(t *testing.T) {
t.Parallel()
for _, tc := range testcases {
if a, b, c, err := PythagoreanTriplet(tc.nums); a != tc.a || b != tc.b || c != tc.c || err != tc.err {
t.Errorf("Expected (%v,%v,%v,%v), got (%v,%v,%v,%v)", tc.a, tc.b, tc.c, tc.err, a, b, c, err)
}
}
}

func BenchmarkPythagoreanTriplet(b *testing.B) {
for i := 0; i < b.N; i++ {
for _, tc := range testcases {
PythagoreanTriplet(tc.nums) // nolint
}
}
}

func TestPythagoreanTripletBrute(t *testing.T) {
t.Parallel()
for _, tc := range testcases {
Expand Down

0 comments on commit 1ec8ca1

Please sign in to comment.