douzha8489
douzha8489
2016-08-10 04:22
浏览 521
已采纳

如何在Golang中将字符串类型数组的值映射为int类型数组?

I want to know how to map each element of board with respective element of change.

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()
      }
    }
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • doucu9677
    doucu9677 2016-08-10 04:56
    已采纳

    Use int(s[0]-'A')*8 + int(s[1]-'0') like this working sample code:

    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()
    }
    

    output:

    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 
    
    点赞 评论
  • doutan6286
    doutan6286 2016-08-10 04:48

    You could use a map instead of a slice for 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] ," ")  
        }    
    }    
    

    There shouldn't be any need for the second loop.

    Example: https://play.golang.org/p/VOGhNpiG3g

    点赞 评论

相关推荐