Skip to content

Instantly share code, notes, and snippets.

@dkarbayev
Created December 30, 2018 19:36
Show Gist options
  • Save dkarbayev/cc3baef5af585a1cf80430763db61166 to your computer and use it in GitHub Desktop.
Save dkarbayev/cc3baef5af585a1cf80430763db61166 to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
)
// tl = top left
// tr = top right
// bl = bottom left
// br = bottom right
func rotateCW(m [][]byte) {
l := len(m)
for j := 0; j < l / 2; j++ {
p := l - j - 1
for i := j; i < l - j - 1; i++ {
q := l - i - 1
t := m[i][p]
// tl -> tr
m[i][p] = m[j][i]
// bl -> tl
m[j][i] = m[q][j]
// br -> bl
m[q][j] = m[p][q]
// tr -> br
m[p][q] = t
}
}
}
func rotateCCW(m [][]byte) {
l := len(m)
for j := 0; j < l / 2; j++ {
p := l - j - 1
for i := j; i < p; i++ {
q := l - i - 1
t := m[i][p]
// br -> tr
m[i][p] = m[p][q]
// bl -> br
m[p][q] = m[q][j]
// tl -> tr
m[q][j] = m[j][i]
// tr -> tl
m[j][i] = t
}
}
}
func compare(m1 [][]byte, m2 [][]byte) bool {
if len(m1) != len(m2) {
return false
}
for i := 0; i < len(m1); i++ {
if len(m1[i]) != len(m2[i]) {
return false
}
for j := 0; j < len(m1[i]); j++ {
if m1[i][j] != m2[i][j] {
return false
}
}
}
return true
}
func main() {
m := [][]byte {
{ 1, 2, 3, 4, 5 },
{ 4, 5, 6, 7, 8 },
{ 7, 8, 9, 0, 1 },
{ 0, 1, 2, 3, 4 },
{ 3, 4, 5, 6, 7 },
}
// duplicate the matrix as a reference
q := make([][]byte, len(m))
for i := 0; i < len(m); i++ {
q[i] = make([]byte, len(m))
copy(q[i], m[i])
}
// rotate the matrix clockwise and counter-clockwise
rotateCW(m)
rotateCCW(m)
// compare matrices
eq := "are"
if !compare(m, q) {
eq += " not"
}
fmt.Println("The matrices", eq, "equal")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment