jobi818
jobi818

Reputation: 21

How do I print a 2-Dimensional array as a grid in Golang?

The 2D Array I am trying to print as a board

Note: I am a complete novice at using Go and need this for a final project.

I am making an attempt to make the game, snake and ladders. I need to print a 10x10 2D array as a grid so it can look more like a board.

I've tried using:

                 for row := 0; row < 10; row ++ 10{
                   } for column := 0; column < 10; column++{
                   fmt.Println()
                   }

But it fails.

Any function or any method to do so?

Upvotes: 2

Views: 3213

Answers (2)

YungLink
YungLink

Reputation: 19

Range-Based Solution

Ranges save us from passing the length directly, and so could make the function re-usable for 2D arrays of differing heights and widths. (Go By Example range page).

A general purpose 2D matrix iterator

Using a range to loop over every value in a 2D array might look like ...

Run this code in Go playground here

// Code for some "board" matrix of type [][]int, for example...
board := [][]int{
    {1, 2, 3},
    {4, 5, 6},
}


// First we iterate over "board", which is an array of rows:
for r, _ := range board {

    // Then we iterate over the items of each row:
    for c, colValue := range board[r] {

        // See string formatting docs at 
        // https://gobyexample.com/string-formatting
        fmt.Printf("value at index [%d][%d]", r, c)
        fmt.Println(" is", colValue)
    }
}

What the underscores mean

Underscores are necessary where declared variables would not be used, or the (compiler?) will throw an error and won't run the code.

The variables r and c are used to give us ongoing access to integer indexes within the matrix, starting at 0 and counting up. We have to pass an underscore _ there after the r because that space would give us access to the whole row object, which we don't ever use later in the code. (Yes, we could alternatively have defined range row instead of range board[r], and then we would be using the row object. )

We also would have had to pass a _ in position of c if we hadn't later used c in the Printf statement. Here is a simpler version (and Go Playground) with no index-access:

// Just prints all the values. 
for _, row := range board {
    for _, colValue := range row {
        fmt.Println(colValue)
    }
}

why is "colValue" and not "col" ?

In this pattern, some telling name like "colValue" is used instead of column. This is because at this inner point in the code, we have drilled down to a single element instead of a whole set of elements like by accessing whole rows with board[r]

Here, we don't use the indices at all, so they have to be written with _.

Upvotes: 0

Dylan Reimerink
Dylan Reimerink

Reputation: 7928

You are almost there, you should pass the variable you want to print to fmt.Println. Also keep in mind that this will always add a newline to the end of the output. You can use the fmt.Print function to just print the variable.

for row := 0; row < 10; row++ {
    for column := 0; column < 10; column++{
        fmt.Print(board[row][column], " ")
    }
    fmt.Print("\n")
} 

Bonus tip, instead of using hardcoded sizes you can also use range to loop over each element which works for arrays/slices of any size.

Upvotes: 2

Related Questions