maybe it's not just a Go-Problem but i have this problem:
I want to multiply two (or more) arrays, so for example:
a := [3]int{2, 3, 5}
b := [2]bool{true, false}
// desired output of "c" =>
// [[2 true] [2 false] [3 true] [3 false] [5 true] [5 false]]
I already found this library here: https://godoc.org/github.com/gonum/matrix/mat64 but i'm not seeing how to use something else than float64
The fallback-solution would be to use multiple for-range-loops but it'd be amazing if there is a "smoother" way to do this
Short answer: go is not intended for this kind of problem. What you want is an equivalent of the zip
function, which is present natively in some languages (e.g. Haskell, Python, ...)
However, in Golang you'll have one big problem: you can't have dynamic types. That is: an array can contain only one type (int OR bool), not several. The workaround is to make an array of interface, but that means you'd have to make ugly type assertions to get the proper type back.
Also, you do have a general way to do that, but the type you'll get at the end will be [][]interface{}
and no way of knowing what's inside.
For your example: here is the simplest way to do what you want (not general):
func main() {
a := [3]int{2, 3, 5}
b := [2]bool{true, false}
var c [6][2]interface{}
i := 0
for _, val1 := range a {
for _, val2 := range b {
c[i] = [2]interface{}{val1, val2}
i += 1
}
}
var a1 int = c[0][0].(int)
var b1 bool = c[0][1].(bool)
fmt.Printf("c[0] is %v, a1 is %d and b1 is %v
", c[0], a1, b1)
fmt.Println(c)
}
As you can see, that's ugly and useless in practice (and very error-prone)
So, if you want to make this kind of transformations, you should use another language, Go was not (and won't) designed for this type of purposes.
This isn't a matrix multiplication, as pointed out above. The two for loops work if there are only two things, but if there are multiple ones it can clearly get tedious.
The way I would do it is to think of a multidimensional array. The total "number" of elements is the product of the sizes, and then use a function like SubFor https://godoc.org/github.com/btracey/meshgrid#SubFor
dims := []int{3,2}
sz := 1
for _,v := range dims {
sz *= v
}
sub := make([]int, len(dims))
for i := 0: i < sz; i++{
meshgrid.SubFor(sub, i, dims)
fmt.Println(a[sub[0]], b[sub[1]])
}
There are some things with types to figure out (appending to a slice, etc.), but that should give you the general gist.