如何在Golang中将二维数组打印为网格?

huangapple go评论86阅读模式
英文:

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

问题

我正在尝试打印一个作为棋盘的10x10二维数组。我是一个完全不懂Go语言的新手,这是我的期末项目。

我正在尝试制作贪吃蛇和梯子游戏。我需要将一个10x10的二维数组打印成一个网格,以便看起来更像一个棋盘。

我尝试使用以下代码:

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

但是它失败了。

有没有什么函数或方法可以实现这个功能?

英文:

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 &lt; 10; row ++ 10{
                   } for column := 0; column &lt; 10; column++{
                   fmt.Println()
                   }

But it fails.

Any function or any method to do so?

答案1

得分: 1

你离成功不远了,你应该将要打印的变量传递给fmt.Println。同时要记住,这将始终在输出的末尾添加一个换行符。你可以使用fmt.Print函数只打印变量。

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

额外提示,你可以使用range来循环遍历每个元素,而不是使用硬编码的大小,这适用于任何大小的数组/切片。

英文:

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 &lt; 10; row++ {
    for column := 0; column &lt; 10; column++{
        fmt.Print(board[row][column], &quot; &quot;)
    }
    fmt.Print(&quot;\n&quot;)
} 

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.

答案2

得分: 0

基于范围的解决方案

使用范围可以避免直接传递长度,因此可以使函数适用于不同高度和宽度的二维数组。(Go By Example range页面

通用的二维矩阵迭代器

使用范围循环遍历二维数组中的每个值可能如下所示...

在Go playground中运行此代码

// 例如,某个类型为[][]int的“board”矩阵的代码...
board := [][]int{
	{1, 2, 3},
	{4, 5, 6},
}


// 首先我们迭代“board”,它是一个行的数组:
for r, _ := range board {

    // 然后我们迭代每行的项:
    for c, colValue := range board[r] {

		// 请参阅字符串格式化文档
		// https://gobyexample.com/string-formatting
		fmt.Printf("索引[%d][%d]的值", r, c)
		fmt.Println("是", colValue)
	}
}

下划线的含义

下划线是必要的,用于声明的变量不会被使用,否则(编译器?)会抛出错误并且代码不会运行。

变量rc用于在矩阵中给我们提供持续访问整数索引的能力,从0开始计数。我们必须在r之后传递一个下划线_,因为该位置会给我们访问整个行对象的权限,而我们在代码中后面从未使用过它。(是的,我们可以选择定义range row而不是range board[r],然后我们将使用行对象。)

如果我们在Printf语句中后面没有使用c,我们也必须在c的位置传递_。这是一个更简单的版本(和Go Playground),没有索引访问:

// 只打印所有的值。
for _, row := range board {
    for _, colValue := range row {
		fmt.Println(colValue)
	}
}

为什么是“colValue”而不是“col”?

在这个模式中,使用了一些描述性的名称,如“colValue”,而不是column。这是因为在代码的这个内部点上,我们已经深入到单个元素而不是像通过访问board[r]整行的整个元素集合。

在这里,我们根本不使用索引,所以它们必须写为_

英文:

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 &quot;board&quot; matrix of type [][]int, for example...
board := [][]int{
	{1, 2, 3},
	{4, 5, 6},
}


// First we iterate over &quot;board&quot;, 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(&quot;value at index [%d][%d]&quot;, r, c)
		fmt.Println(&quot; is&quot;, 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 _.

huangapple
  • 本文由 发表于 2022年5月11日 02:33:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/72191437.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定