Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a map can match another partially in golang

Tags:

dictionary

go

Suppose, I have two map[string]([]string)

 MAP1 := map[string]([]string) {
    "User" : []string{"11", "33"},
    "Type" : []string{"A"},
    }


MAP2 := map[string]([]string) {
    "User" : []string{"11", "17"},
    "Type" : []string{"B"},
    }

Here, MAP1 matches MAP2 partially.

User = 11 is in both map

How can I check this in a easy way?

like image 342
Shahriar Avatar asked Oct 21 '25 03:10

Shahriar


1 Answers

For example:

package main

import "fmt"

func Max(x, y int) int {
    if x > y {
        return x
    }
    return y
}

func Intersect(as, bs []string) []string {
    i := make([]string, 0, Max(len(as), len(bs)))
    for _, a := range as {
        for _, b := range bs {
            if a == b {
                i = append(i, a)
            }
        }
    }
    return i
}

func main() {

    MAP1 := map[string][]string{
        "User": []string{"11", "33"},
        "Type": []string{"A"},
    }

    MAP2 := map[string][]string{
        "User": []string{"11", "17"},
        "Type": []string{"B"},
    }

    MAP3 := make(map[string][]string)

    for k, _ := range MAP1 {
        MAP3[k] = Intersect(MAP1[k], MAP2[k])
    }

    fmt.Println(MAP3) // MAP3 contains commonalities between MAP1 and MAP2
}

Note that this solution does not exploit any potential performance optimizations (like assuming that the string arrays will be sorted in some way, or else) and hence has a runtime performance of O(m • n2), where:

  • m is the number of keys in the map (assumed to be the same for both maps)
  • n is the number of elements in each string slice (assumed to be the same for both corresponding map entries)

Which is okay but not great.

like image 67
thwd Avatar answered Oct 23 '25 20:10

thwd



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!