Objective: I have been solving question 6 from the book 'Cracking the Coding interview' by using Go.
NOTE I DO NOT WAN'T HELP OR SOLUTIONS TO THIS QUESTION
Given an image represented by an NxN matrix, where each pixel in the image is 4 bytes, write a method to rotate the image by 90 degrees. Can you do this in place?
Problem: I made an array of arrays to represent the matrix and I created a swap function to swap the elements clockwise in the matrix. For some reason I get this really weird error when trying to compile:
./Q6.go:29: invalid operation: b[N - col - 1] (index of type *int)
./Q6.go:30: invalid operation: b[N - row - 1] (index of type *int)
Where am I getting type *int as an index? In the Go documenation, len(v) returns type int and everything else is in the value of 'N - col - 1' is type int so how am I getting type *int index?
Code:
package main
import "fmt"
func main() {
b := [][]int{{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16}} // 4 by 4 array going from 1 to 16
N := len(b)
for row := 0; row < N / 2; row++ {
for col := row; col < N - row - 1; col++ {
a := &b[row][col]
b := &b[col][N - row - 1]
c := &b[N - col - 1][col] // <-- Error here
d := &b[N - row - 1][N - col - 1] // <-- Error here
fourSwap(a, b, c, d)
}
}
for r := range b {
for c:= range b[0] {
fmt.Print(b[r][c])
}
fmt.Print("
")
}
}
// [a][-][-][b] [c][-][-][a]
// [-][-][-][-] --> [-][-][-][-]
// [-][-][-][-] --> [-][-][-][-]
// [c][-][-][d] [d][-][-][b]
func fourSwap(a, b, c, d *int) {
temp := *b
*b = *a
*a = *c
*c = *d
*d = temp
}