【发布时间】:2015-05-01 13:00:18
【问题描述】:
目标:我一直在使用 Go 解决“Cracking the Coding interview”一书中的问题 6。
请注意,我不想为这个问题提供帮助或解决方案
给定一个由 NxN 矩阵表示的图像,其中图像中的每个像素为 4 字节,编写一个将图像旋转 90 度的方法。你能做到这一点吗?
问题:我创建了一个数组数组来表示矩阵,并创建了一个交换函数来顺时针交换矩阵中的元素。出于某种原因,我在尝试编译时遇到了这个非常奇怪的错误:
./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)
我在哪里获得类型 *int 作为索引?在 Go 文档中,len(v) 返回 int 类型,其他所有内容都在 'N - col - 1' 的值中是 int 类型,那么我如何获得 type *int 索引?
代码:
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("\n")
}
}
// [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
}
【问题讨论】:
-
代码在循环内部声明了一个新变量
b,它会遮蔽外部b。我不确定你是否想要。我不明白您要对图像做什么。 -
顺便说一句,您的
fourSwap可以通过 Go 的多重赋值来简化。*a, *b, *c, *d = *c, *a, *d, *b. -
正如@tvblah 所说,这是由于阴影
b。最简单的解决方法是将切片从b := [][]int{更改为其他名称。否则,在b := &b[x][y]之后,你有一个新的b类型为int并且不能再索引它。 -
另外请注意您使用的是slices, not arrays。如果您真的想要使用数组,只需将您的定义更改为
notb := [...][...]int{/*values as before*/}。 “...”让编译器计算出大小。
标签: arrays pointers indexing go