special pythagorean triplet

This commit is contained in:
VicRen
2020-10-08 22:23:12 +08:00
parent 0aa5e6e567
commit 836f27c40b
2 changed files with 189 additions and 0 deletions

View File

@@ -0,0 +1,66 @@
package main
import (
"fmt"
)
func main() {
got := SplitIntegerIntoThree(1000)
product := 0
for _, v := range got {
if IsPythagoreanTriplet(v) {
fmt.Println("Pythagorean triplet ", v)
product = GetProduct(v)
break
}
}
fmt.Println("product:", product)
}
func SplitIntegerIntoThree(src int) [][]int {
var ret [][]int
x := 1
for {
left1 := src - x
if left1 < x {
break
}
y := x + 1
for {
var r []int
r = append(r, x)
left2 := left1 - y
if left2 < y+1 {
break
}
r = append(r, y)
r = append(r, left2)
ret = append(ret, r)
y++
}
x++
}
return ret
}
func IsPythagoreanTriplet(ns []int) bool {
if len(ns) != 3 {
return false
}
var squares []int
for _, v := range ns {
squares = append(squares, v*v)
}
if squares[0]+squares[1] == squares[2] {
return true
}
return false
}
func GetProduct(ns []int) int {
product := 1
for _, v := range ns {
product = product * v
}
return product
}

View File

@@ -0,0 +1,123 @@
package main
import (
"reflect"
"testing"
)
func TestSplitInteger(t *testing.T) {
tt := []struct {
name string
src int
want [][]int
}{
{
"5-3",
6,
[][]int{
{1, 2, 3},
},
},
{
"10-3",
10,
[][]int{
{1, 2, 7},
{1, 3, 6},
{1, 4, 5},
{2, 3, 5},
},
},
{
"11-3",
11,
[][]int{
{1, 2, 8},
{1, 3, 7},
{1, 4, 6},
{2, 3, 6},
{2, 4, 5},
},
},
}
for _, tc := range tt {
t.Run(tc.name, func(t *testing.T) {
got := SplitIntegerIntoThree(tc.src)
if !reflect.DeepEqual(got, tc.want) {
t.Errorf("SplitInteger(%d)=%v, want %v", tc.src, got, tc.want)
}
})
}
}
func TestIsPythagoreanTriplet(t *testing.T) {
tt := []struct {
name string
input []int
want bool
}{
{
"3,4",
[]int{3, 4},
false,
},
{
"3,4,5,6",
[]int{3, 4, 5, 6},
false,
},
{
"3,4,5",
[]int{3, 4, 5},
true,
},
{
"3,4,6",
[]int{3, 4, 6},
false,
},
}
for _, tc := range tt {
t.Run(tc.name, func(t *testing.T) {
got := IsPythagoreanTriplet(tc.input)
if got != tc.want {
t.Errorf("IsPythagoreanTriplet(%v)=%v, want %v", tc.input, got, tc.want)
}
})
}
}
func TestGetProduct(t *testing.T) {
tt := []struct {
name string
input []int
want int
}{
{
"0",
[]int{0, 1, 1},
0,
},
{
"2",
[]int{2, 1, 1},
2,
},
{
"3",
[]int{2, 3, 4},
24,
},
}
for _, tc := range tt {
t.Run(tc.name, func(t *testing.T) {
got := GetProduct(tc.input)
if got != tc.want {
t.Errorf("GetProduct(%v)=%d, want %d", tc.input, got, tc.want)
}
})
}
}