英文:
GO - Set the values of 2D array from end
问题
我是你的中文翻译助手,以下是你要翻译的内容:
我对GO语言还不熟悉。我想要做的是,我有一个二维整数数组,我想要从二维数组的最后一个索引开始设置值,因为我正在解决一个动态规划问题。GO语言不允许在没有初始化的情况下设置任何索引的值。我通过循环遍历二维数组并在下面的代码中显式设置值来解决了这个问题,但我不确定GO语言是否期望这样做,或者我是否可以直接为二维数组的任何索引分配值而不进行初始化。
var dp = [][]int {}
for i := 0; i < m; i++ {
var arr = make([]int, n)
for j := 0; j < n; j++ {
arr = append(arr, 0)
}
dp = append(dp, arr)
}
英文:
I am new to GO lang. what I am trying to do is, I have 2D array of int and I want to set the values from the last index of 2D array since I am solving one dynamic programming question. GO lang is not allowing to set the values to any index if it is not initialised. I solved this by looping through the 2D array and setting values explicitly described in below code, but I am not sure is this the way GO expecting or can I directly assign values to any index of 2D array without initialising it.
var dp = [][]int {}
for i:=0; i<m; i++{
var arr = make([]int, n)
for j:=0;j<n;j++{
arr = append(arr, 0)
}
dp = append(dp, arr)
}
答案1
得分: 2
make
将为元素分配默认值,对于int
类型来说,默认值是零。
将用于为arr元素赋值的append循环可以替换为创建大小为n的int数组。
arr = append(arr, 0)
和dp = append(dp, arr)
将不再需要。
dp := make([][]int, m)
for i := 0; i < len(dp); i++ {
dp[i] = make([]int, n)
}
英文:
make
will assign default values to the elements, zero in case of int
.
append loop for assiging to elements of arr can be replaced with make-ing array of int of size n
arr = append(arr, 0)
and dp = append(dp, arr)
will not be needed
dp := make([][]int, m)
for i := 0; i < len(dp); i++ {
dp[i] = make([]int, n)
}
答案2
得分: 2
你是不是在寻找这样的内容?在Go语言中,我们需要区分切片(slice)和数组(array)。《Go和Golang中的切片》。
你将dp
声明为一个切片,这使得不可能“从后面添加”,因为切片没有固定的大小。所以你需要将dp
声明为一个大小为m x n的数组,并从后面填充。
m := 10
n := 5
dp := make([][]int, m)
for i := m; i > 0; i-- {
var arr = make([]int, n)
for j := n; j > 0; j-- {
arr[j-1] = j
}
dp[i-1] = arr
}
fmt.Println(dp)
英文:
Are you looking for something like this?
In golang, we need to differentiate between a slice and array. Slices in Go and Golang.
You declared ur dp
as a slice, which made it impossible to "append from back" because there's no fix size for a slice. So what you need to do is to declare your dp as an array with size m x n and backfill from the back.
m := 10
n := 5
dp := make([][]int, m)
for i := m; i > 0; i-- {
var arr = make([]int, n)
for j := n; j > 0; j-- {
arr[j-1] = j
}
dp[i-1] = arr
}
fmt.Println(dp)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论