我想知道如何用相应的变化元素映射每个板块元素。
func convert () {
var i,j,k int
k = 1
change := [64]int {}
board := [8][8]string{}
for i = 0; i < 8; i++ {
for j = 0; j < 8; j++ {
board[i][j] = string(i+65) + string(j+49)
fmt.Print(board[i][j] ," ")
}
fmt.Println()
}
fmt.Println()
for i = 0 ; i < 64 ; i++ {
change[i] = k
k++
fmt.Print(change[i] ," ")
}
fmt.Println()
}
}
答案 0 :(得分:2)
像这样的工作示例代码使用int(s[0]-'A')*8 + int(s[1]-'0')
:
package main
import "fmt"
func main() {
fmt.Println(toNumber("A1")) // 1
fmt.Println(toNumber("A2")) // 2
fmt.Println(toNumber("B1")) // 9
fmt.Println(toNumber("H8")) // 64
convert()
}
func toNumber(s string) int {
if len(s) != 2 {
panic("len(string) != 2")
}
return int(s[0]-'A')*8 + int(s[1]-'0')
}
func convert() {
change := [64]int{}
board := [8][8]string{}
k := 0
for i := 0; i < 8; i++ {
for j := 0; j < 8; j++ {
board[i][j] = string(i+65) + string(j+49)
fmt.Print(board[i][j], " ")
change[k] = toNumber(board[i][j])
k++
}
fmt.Println()
}
fmt.Println()
for i := 0; i < 64; i++ {
fmt.Print(change[i], " ")
}
fmt.Println()
}
输出:
1
2
9
64
A1 A2 A3 A4 A5 A6 A7 A8
B1 B2 B3 B4 B5 B6 B7 B8
C1 C2 C3 C4 C5 C6 C7 C8
D1 D2 D3 D4 D5 D6 D7 D8
E1 E2 E3 E4 E5 E6 E7 E8
F1 F2 F3 F4 F5 F6 F7 F8
G1 G2 G3 G4 G5 G6 G7 G8
H1 H2 H3 H4 H5 H6 H7 H8
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
答案 1 :(得分:1)
您可以使用地图而不是change
的切片:
change := make(map[int]string)
for i = 0; i < 8; i++ {
for j = 0; j < 8; j++ {
board[i][j] = string(i+65) + string(j+49)
// map 1->A1, 2->A2...64->H8
change[i*8 + j+1] = board[i][j]
fmt.Print(board[i][j] ," ")
}
}
不应该需要第二个循环。