Skip to content

Instantly share code, notes, and snippets.

@valeriofarias
Last active January 1, 2016 16:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save valeriofarias/19277f86ee61a350ace3 to your computer and use it in GitHub Desktop.
Save valeriofarias/19277f86ee61a350ace3 to your computer and use it in GitHub Desktop.
Create Spiral with Arrays in Golang

Task taked from codewars.com: Make a spiral using Golang

Our task, is to create a NxN spiral with a given size.

For example, spiral with size 5 should look like this:

00000 ....0 000.0 0...0 00000

and with the size 10:

0000000000 .........0 00000000.0 0......0.0 0.0000.0.0 0.0..0.0.0 0.0....0.0 0.000000.0 0........0 0000000000

Return value should contain array of arrays, of 0 and 1, for example for given size 5 result should be:

[[1,1,1,1,1],[0,0,0,0,1],[1,1,1,0,1],[1,0,0,0,1],[1,1,1,1,1]]

Because of the edge-cases for tiny spirals, the size will be at least 5.

General rule-of-a-thumb is, that the snake made with '1' cannot touch to itself.

package spiral
func Spiralize(n int) [][]int {
return [][]int{{1, 1}, {0, 1}}
}
package spiral
import (
"reflect"
"testing"
)
func TestSpiralize(t *testing.T) {
cases := []struct {
in int
want [][]int
}{
{1, [][]int{{1}}},
{2, [][]int{
{1, 1},
{0, 1}}},
{3, [][]int{
{1, 1, 1},
{0, 0, 1},
{1, 1, 1}}},
{5, [][]int{
{1, 1, 1, 1, 1},
{0, 0, 0, 0, 1},
{1, 1, 1, 0, 1},
{1, 0, 0, 0, 1},
{1, 1, 1, 1, 1}}},
{13, [][]int{
{1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1},
{1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1},
{1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1},
{1, 0, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1},
{1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1},
{1, 0, 1, 0, 1, 1, 1, 0, 1, 0, 1, 0, 1},
{1, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 1},
{1, 0, 1, 0, 1, 1, 1, 1, 1, 0, 1, 0, 1},
{1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1},
{1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1},
{1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1},
{1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}}},
}
for _, tt := range cases {
actual := Spiralize(tt.in)
if !reflect.DeepEqual(actual, tt.want) {
t.Errorf("Spiralize(%d): expected %v, actual %v", tt.in, tt.want, actual)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment