Find Difference between values of Key in Map

Hi Team,
I have created sample code below
https://play.golang.org/p/ln2lhcDQC243
Example
map: map[8191:0]
map: map[8191:1]
map: map[8191:2]
map: map[8191:2]

map: map[17:1]
map: map[17:2]
map: map[17:7]

I need to find difference of Key Values For value 0 and 1(Result 1) of 8191and 2 and 2 difference (Result-0) and same I have to do for 17 also.

Is there any way achieve this?

Thanks,
Raja

@Raja_Pandian your snippet link is 404ing for me. Might be good to reshare the link.

Yes.Please find below link
https://play.golang.org/p/ln2lhcDQC24

Thanks,
Rajapandian.B

I’m not sure what you’re trying to do here, but remember that maps must have unique keys, so your m[pid] = cc inside the loop is just updating the value for the key pid in the map, not adding a new entry to the map.

1 Like

Ok Thanks.Is there any way to find this value belongs to particular key?
For Example
[8191:5]
[17:8]

I need to find 5 value belongs to key 8191 and 8 value is belongs to key 17.

Thanks,
Rajapandian

What if there are two keys with identical values? Which one do you want to get then?

But in general something like this would work, if you do not care which key you get in that case:

func keyOfValue(m map[int]int, needle) (int, bool) {
  for k, v := range m {
    if v == needle {
      return k, true
    }
  }
  return 0, false
}

But why do you want to do that? depending on how many KV pairs there are in the map, it can be a costly operation, as it will scan the complete map if there is no value equal to the needle.

Perhaps its better to build a map which mirrors the first? But that can add a lot of bookkeeping and also there are again some edge cases you need to consider when implementing it.

2 equal values can bring you a lot of trouble when doing the reverse map.

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.