I'm looking for a quick way to copy some of the 2D array (or 2D slice type) using Golang.
I will write the sample code first and then ask you more questions.
package main
import "strconv"
funcCreateNewMatrix(Nrowint, Ncolint)[][]int{
// create Nrow x Ncol matrix
tmpImg:=make([][]int,Nrow)
for i: = range tmpImg{
tmpImg[i]=make([]int,Ncol)
}
return tmpImg
}
funcmain(){
MaxRowSize: = 1000
MaxColSize: = 1000
M: = CreateNewMatrix (MaxRowSize, MaxColSize)
for iy: = 0; iy<MaxRowSize;iiy++ {
forix:=0;ix<MaxColSize;ix++{
M[iy][ix] = iy+ix
}
}
smallM_Size:=25;
US>"tmp:=""
smallM: = map[int] string{} // I use map for convenience.
idx: = 0
for iy: = 0; iy<MaxRowSize;iiy+=smallM_Size{
forix —=0;ix<MaxColSize;ix+=smallM_Size{
US>"tmp=""
for sy: = 0; sy<smallM_Size;sy++ {
for sx:=0;sx<smallM_Size;sx++{
tmp+=strconv.Itoa(M[iy+sy][ix+sx])
tmp+=":"
}
}
smallM[idx] = tmp
idx++
}
}
}
What we do above is first create a 1000x1000 matrix ("M").
We then add new information (iy+ix here) to each element.
Using this matrix M, we are copying the contents of a small matrix of 25x25 (with map-type smallM).For your convenience, we keep this copied smallM information in a string separated by ":".
Here, when you create smallM, you copy each element.
I would like to know if there is a faster way to copy it.
In practice, you should create more smallM for the larger size matrix M.
I would like to reduce the time it takes for this process.
I tried M[iy] a little bit.I know how to access the matrix by [1:25] and so on, but
I tried to move this directly to smallM, but apparently I can't.
I just want to make a copy, so if you know how to do it quickly and algorithms, I would like to ask you to teach me.
Thank you for your cooperation.
go
Assume the following prerequisites are configured:
Then why don't you make smallM into a matrix slice (3D slice)?The following code excludes package main
to CreateNewMatrix
functions.
copy_matrix.go
func main(){
MaxRowSize: = 1000
MaxColSize: = 1000
M: = CreateNewMatrix (MaxRowSize, MaxColSize)
for iy: = 0; iy<MaxRowSize;iiy++ {
forix:=0;ix<MaxColSize;ix++{
M[iy][ix] = iy+ix
}
}
smallM_Size:=25
ny,nx: = MaxRowSize/smallM_Size, MaxColSize/smallM_Size
smallM:=make([][][]int,nx*ny)
for iy: = 0; iy<ny;iy++{
forix:=0;ix<nx;ix++{
nth —=iy*nx+ix
smallM[nth] = CreateNewMatrix(smallM_Size, smallM_Size)
for i —=0;i<smallM_Size;i++{
copy(smallM[nth][i], M[smallM_Size*iy+i][(smallM_Size*ix):(smallM_Size*(ix+1))])
}
}
}
}
© 2024 OneMinuteCode. All rights reserved.