diff --git a/.vscode/launch.json b/.vscode/launch.json new file mode 100644 index 0000000..787b44f --- /dev/null +++ b/.vscode/launch.json @@ -0,0 +1,7 @@ +{ + // Use IntelliSense to learn about possible attributes. + // Hover to view descriptions of existing attributes. + // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 + "version": "0.2.0", + "configurations": [] +} \ No newline at end of file diff --git a/introductory.go b/introductory.go index 4c57c66..0627646 100644 --- a/introductory.go +++ b/introductory.go @@ -104,3 +104,53 @@ func BeautifulPermutations(n int) string { return fmt.Sprint(result) } + +func NumberSpiral(row, col int) int64 { + result := int64(1) + var size int + + if row > col { + size = row + } else { + size = col + } + + for i := 2; i <= size; i++ { + result = result + int64(2*(i-1)) + } + + switch { + case row == col: + return result + case col > row: + if col%2 == 1 { + return result + int64(size-row) + } else { + return result + int64(row-size) + } + case col < row: + if row%2 == 1 { + return result + int64(col-size) + } else { + return result + int64(size-col) + } + } + + return 0 + + /* + maxLoops := size * size + i := int32(1) + j := int32(1) + + for n := int64(1); n <= maxLoops; n++ { + if i == y && j == x { + return n + } + + + } + + return 0 + */ +} diff --git a/introductory_test.go b/introductory_test.go index e88f0d4..ab23fb3 100644 --- a/introductory_test.go +++ b/introductory_test.go @@ -38,3 +38,21 @@ func TestBeautifulPermutations(t *testing.T) { assert.Equal(t, "[9 7 5 3 1 8 6 4 2]", BeautifulPermutations(9)) assert.Equal(t, 48895, len(BeautifulPermutations(10000))) } + +func TestNumberSpiral(t *testing.T) { + assert.Equal(t, int64(8), NumberSpiral(2, 3)) + assert.Equal(t, int64(1), NumberSpiral(1, 1)) + assert.Equal(t, int64(15), NumberSpiral(4, 2)) + assert.Equal(t, int64(11), NumberSpiral(2, 4)) + assert.Equal(t, int64(13), NumberSpiral(4, 4)) + assert.Equal(t, int64(18), NumberSpiral(5, 2)) + assert.Equal(t, int64(24), NumberSpiral(2, 5)) + assert.Equal(t, int64(21), NumberSpiral(5, 5)) + assert.Equal(t, int64(19), NumberSpiral(5, 3)) + assert.Equal(t, int64(23), NumberSpiral(3, 5)) + assert.Equal(t, int64(889344699930098742), NumberSpiral(170550340, 943050741)) + assert.Equal(t, int64(890061110095112626), NumberSpiral(121998376, 943430501)) + assert.Equal(t, int64(593021767041187724), NumberSpiral(689913499, 770079066)) + assert.Equal(t, int64(871712102163621276), NumberSpiral(586095107, 933655238)) + assert.Equal(t, int64(999999997000000003), NumberSpiral(999_999_999, 999_999_999)) +}