mirror of
https://github.com/cubixle/codekata-golang.git
synced 2026-04-24 21:24:46 +01:00
28: number spiral diagonals
This commit is contained in:
32
28_number_spiral_diagonals/main.go
Normal file
32
28_number_spiral_diagonals/main.go
Normal file
@@ -0,0 +1,32 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
)
|
||||
|
||||
func main() {
|
||||
nums, _ := findSprialDiagonals(1001)
|
||||
sum := 0
|
||||
for _, n := range nums {
|
||||
sum += n
|
||||
}
|
||||
fmt.Printf("nums=%v\nsum=%d\n", nums, sum)
|
||||
}
|
||||
|
||||
func findSprialDiagonals(width int) ([]int, error) {
|
||||
if width%2 == 0 {
|
||||
return nil, errors.New("invalid width")
|
||||
}
|
||||
x := 3
|
||||
ret := []int{1}
|
||||
cw := 3
|
||||
d := 2
|
||||
for width/cw > 0 {
|
||||
ret = append(ret, []int{x, x + d, x + 2*d, x + 3*d}...)
|
||||
x = x + 3*d + cw + 1
|
||||
cw += 2
|
||||
d = cw - 1
|
||||
}
|
||||
return ret, nil
|
||||
}
|
||||
61
28_number_spiral_diagonals/main_test.go
Normal file
61
28_number_spiral_diagonals/main_test.go
Normal file
@@ -0,0 +1,61 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"reflect"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func Test_findSprialDiagonals(t *testing.T) {
|
||||
type args struct {
|
||||
width int
|
||||
}
|
||||
tests := []struct {
|
||||
name string
|
||||
args args
|
||||
want []int
|
||||
wantErr bool
|
||||
}{
|
||||
{
|
||||
"1",
|
||||
args{1},
|
||||
[]int{1},
|
||||
false,
|
||||
},
|
||||
{
|
||||
"2",
|
||||
args{2},
|
||||
nil,
|
||||
true,
|
||||
},
|
||||
{
|
||||
"3",
|
||||
args{3},
|
||||
[]int{1, 3, 5, 7, 9},
|
||||
false,
|
||||
},
|
||||
{
|
||||
"5",
|
||||
args{5},
|
||||
[]int{1, 3, 5, 7, 9, 13, 17, 21, 25},
|
||||
false,
|
||||
},
|
||||
{
|
||||
"7",
|
||||
args{7},
|
||||
[]int{1, 3, 5, 7, 9, 13, 17, 21, 25, 31, 37, 43, 49},
|
||||
false,
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
got, err := findSprialDiagonals(tt.args.width)
|
||||
if (err != nil) != tt.wantErr {
|
||||
t.Errorf("findSprialDiagonals() error = %v, wantErr %v", err, tt.wantErr)
|
||||
return
|
||||
}
|
||||
if !reflect.DeepEqual(got, tt.want) {
|
||||
t.Errorf("findSprialDiagonals() = %v, want %v", got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user