Back to home

Setting up the testSpiral Matrix ImplementationRunning Tests
Go Spiral Matrix main image

Go Spiral Matrix

Base spiral matrix implementation.

Setting up the test

Set up spiral_matrix_test.go with the following file to test inserts, retrievals and validations:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 package sm import ( "fmt" "testing" ) func TestMatrix(t *testing.T) { for _, tt := range testCases { res := genSpiralMatrix(tt.input) fmt.Println(res) for i, v := range res { for j := range v { if res[i][j] != tt.expected[i][j] { t.Errorf("FAIL: Expected %+v but got %+v", tt.expected, res) return } } } t.Logf("PASS: Expected %+v and got %+v", tt.expected, res) } }

Spiral Matrix Implementation

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 package caps func genSpiralMatrix(s int) [][]int { m := make([][]int, s) for x := 0; x < s; x++ { m[x] = make([]int, s) for y := 0; y < s; y++ { m[x][y] = 0 } } count := 1 startCol := 0 endCol := s - 1 startRow := 0 endRow := s - 1 for startCol <= endCol && startRow <= endRow { // top row for i := startCol; i <= endCol; i++ { m[startRow][i] = count count++ } startRow++ // row col ttb for i := startRow; i <= endRow; i++ { m[i][endCol] = count count++ } endCol-- // bottom row rtl for i := endCol; i >= startCol; i-- { m[endRow][i] = count count++ } endRow-- // first col bottom-to-top for i := endRow; i >= startRow; i-- { m[i][startCol] = count count++ } startCol++ } return m }

Running Tests

In the directory, run go test.

Dennis O'Keeffe

@dennisokeeffe92
  • Melbourne, Australia

Hi, I am a professional Software Engineer. Formerly of Culture Amp, UsabilityHub, Present Company and NightGuru.
I am currently working on workingoutloud.dev, Den Dribbles and LandPad .

Related articles


1,200+ PEOPLE ALREADY JOINED ❤️️

Get fresh posts + news direct to your inbox.

No spam. We only send you relevant content.