How to XOR two string arrays in Golang?

4.4k views Asked by At

Let's say I have two string array.

A = [ "ab", "cd", "ef", "gh"]
B = [ "ef", "gh"]

I want to do C = A^B

where C = ["ab", "cd"]

I'm aware Golang allows XOR byte-wise, but I haven't seen anything for string arrays in the documentation.

How would I go about doing this? Perhaps there is a utility someone has already made for this?

1

There are 1 answers

0
Omar On

This doesn't seem like something that would go in a standard library in Go, but here's a bit of code that does the trick:

package main

import (
    "fmt"
)

func main() {
    A := []string{"ab", "cd", "ef", "gh"}
    B := []string{"ef", "gh"}
    fmt.Println(xor(A,B))
}

func xor(list1, list2 []string) []string {
    set1 := make(map[string]bool)
    for _, s := range list1 {
        set1[s] = true
    }
    set2 := make(map[string]bool)
    for _, s := range list2 {
        set2[s] = true
    }

    var c []string
    for _, s := range list1 {
        if !set2[s] {
          c = append(c, s)
        }
    }
    for _, s := range list2 {
        if !set1[s] {
          c = append(c, s)
        }
    }
    return c
}

https://play.golang.org/p/SDPhNIQ66E