Skip to content

Instantly share code, notes, and snippets.

@yan-aint-nickname
Last active October 23, 2023 16:42
Show Gist options
  • Save yan-aint-nickname/e0f856022d1f09193e126d1777a24796 to your computer and use it in GitHub Desktop.
Save yan-aint-nickname/e0f856022d1f09193e126d1777a24796 to your computer and use it in GitHub Desktop.
SpiralCounter
package main
import "fmt"
func main() {
var rows, columns int
fmt.Scan(&rows, &columns)
matrix := make([][]int, rows)
for c := 0; c < rows; c++ {
matrix[c] = make([]int, columns)
}
var x_min, x_max, x_vector, y_vector, x, y int
var y_min, y_max int
x_min, x_max = 0, rows
y_min, y_max = 0, columns
x_vector, y_vector = 0, 1
x, y = 0, 0
for i := 0; i < rows*columns; i++ {
matrix[x][y] = i
x += x_vector
y += y_vector
if y == y_max-1 && y_vector == 1 {
y_vector = 0
x_vector = 1
x_min += 1
}
if x == x_max-1 && x_vector == 1 {
x_vector = 0
y_vector = -1
y_max -= 1
}
if y == y_min && y_vector == -1 {
y_vector = 0
x_vector = -1
x_max -= 1
}
if x == x_min && x_vector == -1 {
y_vector = 1
x_vector = 0
y_min -= 1
}
}
PrintMatrix(matrix, rows, columns)
}
func PrintMatrix(matrix [][]int, rows, columns int) {
for i := 0; i < rows; i++ {
for j := 0; j < columns; j++ {
if j == columns-1 {
fmt.Printf("%4d\n", matrix[i][j])
} else {
fmt.Printf("%4d", matrix[i][j])
}
}
}
}
// input 2 3
// prints
// 0 1 2
// 5 4 3
// input 3 3
// prints
// 0 1 2
// 7 8 3
// 6 5 4
// etc.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment