Created
July 20, 2021 11:36
-
-
Save subuk/11cb8a57a277742769e4db81eb7f74ac to your computer and use it in GitHub Desktop.
Matrix Spiral
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import "fmt" | |
var Matrix = [][]int{ | |
{63, 22, 17, 39, 36}, | |
{53, 22, 31, 40, 36}, | |
{43, 81, 11, 41, 36}, | |
{13, 22, 87, 42, 38}, | |
{33, 22, 91, 47, 99}, | |
} | |
type Direction int | |
const ( | |
start = Direction(0) | |
left = Direction(1) | |
right = Direction(2) | |
up = Direction(3) | |
down = Direction(4) | |
) | |
func nextDirection(d Direction) Direction { | |
switch d { | |
case start: | |
return down | |
case down: | |
return left | |
case left: | |
return up | |
case up: | |
return right | |
case right: | |
return down | |
} | |
return d | |
} | |
func main() { | |
elCount := 25 | |
posX, posY := 2, 2 | |
stepNum := 0 | |
stepSize := 1 | |
direction := nextDirection(start) | |
dch := 0 | |
fmt.Printf("%d ", Matrix[posY][posX]) | |
for i := 0; i < elCount-1; i++ { | |
switch direction { | |
default: | |
panic("unknown direction") | |
case up: | |
posY -= 1 | |
case down: | |
posY += 1 | |
case left: | |
posX -= 1 | |
case right: | |
posX += 1 | |
} | |
fmt.Printf("%d ", Matrix[posY][posX]) | |
stepNum++ | |
if stepNum == stepSize { | |
stepNum = 0 | |
direction = nextDirection(direction) | |
dch++ | |
if dch == 2 { | |
stepSize++ | |
dch = 0 | |
} | |
} | |
} | |
fmt.Println("") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment