设置2D数组的值从末尾开始。

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

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&lt;m; i++{
    var arr = make([]int, n)
    for j:=0;j&lt;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 &lt; 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 &gt; 0; i-- {
	var arr = make([]int, n)
	for j := n; j &gt; 0; j-- {
		arr[j-1] = j
	}
	dp[i-1] = arr
}
fmt.Println(dp)

huangapple
  • 本文由 发表于 2022年8月14日 21:52:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/73352203.html
匿名

发表评论

匿名网友

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

确定