0

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
  • What kind of mapping are you looking for exactly? Do you mean conversion to a single dimensional array? Commented Aug 10, 2016 at 4:26
  • I want to map A1 to 1, A2 to 2,...B1 to 9,.....H8 to 64 @abhink Commented Aug 10, 2016 at 4:33

2 Answers 2

2

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 
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.