mik
mik

Reputation: 356

Define map with keys with arbitrary dimension

The following code serves to create a counter for each pair of float64.
Because the keys of a map cannot be a slice, I have to use arrays as keys, which forces me to to define a dimension with a constant.

counter := make( map[ [2]float64 ] int )
for _, comb := range combinations{ //combinations is a [n][2]float64
    for _, row := range data{  
        counter[ [...]float64{ row[comb[0]] , row[comb[1]] } ]++
    }
}

Having said that, is there a way to make this map dependent on the length of the keys (dependent on the dimensions of combinations?
I tried using a struct as key, but as far as I remember (I might be wrong), it was a bit slower... For my purposes (to apply this for all combinations ~n!) this is not the ideal solution.

Right now I'm only considering combinations of size 2 and 3, and I had to split this in two separate functions, which makes my code very verbose and harder to maintain. Can you find a way to simplify this, so I can scale it to more dimensions?

Thanks for any input

Upvotes: 1

Views: 103

Answers (1)

Alex Efimov
Alex Efimov

Reputation: 3703

Why not use the pointer to a slice as key?

You could create a slice with make with a big enough capacity, while you do not surpass it's capacity, the pointer will remain the same.

Take a look here https://play.golang.org/p/333tRMpBLv , it exemplifies my suggestion. see that while len < cap the pointer of the slice is not changed, append only creates a new slice when len exceeds cap.

Upvotes: 1

Related Questions