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)
}
CodePudding user response:
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)
}
CodePudding user response:
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)