Logo

Programming-Idioms

History of Idiom 27 > diff from v20 to v21

Edit summary for version 21 by :
Restored version 19

Version 20

2016-02-18, 16:57:58

Version 21

2016-02-18, 17:21:43

Idiom #27 Create a 3-dimensional array

Declare and initialize a 3D array x, having dimensions boundaries m, n, p, and containing real numbers.

Idiom #27 Create a 3-dimensional array

Declare and initialize a 3D array x, having dimensions boundaries m, n, p, and containing real numbers.

Code
X : array (1 .. M, 1 .. N, 1 .. P) of Float := (others => (others => (others => 1.0)));
Code
func make3D(m, n, p int) [][][]float64 {
	buf := make([]float64, m*n*p)

	x := make([][][]float64, m)
	for i := range x {
		x[i] = make([][]float64, n)
		for j := range x[i] {
			x[i][j] = buf[:p:p]
			buf = buf[p:]
		}
	}
	return x
}
Code
func make3D(m, n, p int) [][][]float64 {
	buf := make([]float64, m*n*p)

	x := make([][][]float64, m)
	for i := range x {
		x[i] = make([][]float64, n)
		for j := range x[i] {
			x[i][j] = buf[:p:p]
			buf = buf[p:]
		}
	}
	return x
}
Comments bubble
This works even when m, n, p are not compile-time constants.
This code allocates one big slice for the numbers, then a few slices for intermediate dimensions.
To same function would be rewritten, for types other than float64.
Comments bubble
This works even when m, n, p are not compile-time constants.
This code allocates one big slice for the numbers, then a few slices for intermediate dimensions.
To same function would be rewritten, for types other than float64.
Origin
https://golang.org/doc/effective_go.html#two_dimensional_slices
Origin
https://golang.org/doc/effective_go.html#two_dimensional_slices
Demo URL
http://play.golang.org/p/AL5GBCgYTM
Demo URL
http://play.golang.org/p/AL5GBCgYTM
Code
const m, n, p = 2, 2, 3
var x [m][n][p]float64
Code
const m, n, p = 2, 2, 3
var x [m][n][p]float64
Comments bubble
m, n, p must be constant for this syntax to be valid.
Here x is of type [2][2][3]float64, it is not a slice.
Comments bubble
m, n, p must be constant for this syntax to be valid.
Here x is of type [2][2][3]float64, it is not a slice.
Demo URL
http://play.golang.org/p/BMuuwLrp0q
Demo URL
http://play.golang.org/p/BMuuwLrp0q