Comparing arrays in Go language-ThrowExceptions

Exception or error:

How can I correctly compare two arrays in Go?

For instance, how can I compare two dimensional arrays with int entries, or any other types?

How deep is that comparison?

How to solve:

To compare two arrays use the comparison operators == or !=. Quoting from the link:

Array values are comparable if values of the array element type are comparable. Two array values are equal if their corresponding elements are equal.

As a 2D (or ND) array fits the above requirement, you can compare it in the same way.

The question “How deep is that comparison?” doesn’t make sense for arrays.

Answer:

For “Deep” comparison, you can use reflect.DeepEqual.

DeepEqual tests for deep equality. It uses normal == equality where possible but will scan elements of arrays, slices, maps, and fields of structs. In maps, keys are compared with == but elements use deep equality. DeepEqual correctly handles recursive types. Functions are equal only if they are both nil. An empty slice is not equal to a nil slice.

Example:

package main

import (
    "bytes"
    "fmt"
    "reflect"
)

func main() {
    a := []byte{}    // empty slice
    b := []byte(nil) // nil slice
    fmt.Printf("%t\n%t", bytes.Equal(a, b), reflect.DeepEqual(a, b))
}

Returns:

true
false

The caveat is that it’s slow.

Playground

Answer:

If you have 2 int slices/arrays try this:

func IntArrayEquals(a []int, b []int) bool {
    if len(a) != len(b) {
        return false
    }
    for i, v := range a {
        if v != b[i] {
            return false
        }
    }
    return true
}

NOTE: this is for 1D arrays, but you can rewrite it for 2D.

Answer:

if you need to compare 2 string arrays
try this:

package main

import (
    "fmt"
)

func arrayDiffString(a, b []string) (diff []string) {
    isFound := false
    twoB := b

    for _, itemA := range a {
        isFound = false
        for iB, itemB := range b {
            if len(itemA) != len(itemB) {
                continue
            }

            if itemA == itemB {
                twoB = deleteByIndexStrArr(twoB, iB)
                isFound = true
                break
            }
        }

        b = twoB
        if !isFound {
            diff = append(diff, itemA)
        }
    }

    diff = append(diff, twoB...)

    return diff
}

func deleteByIndexStrArr(slice []string, i int) []string {
    copy(slice[i:], slice[i+1:])
    return slice[:len(slice)-1]
}

func main() {
    var a = []string{"one", "two"}
    var b = []string{"one", "two", "one", "one", "three", "four"}
    fmt.Println(arrayDiffString(a, b))

}

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

maybe its a little slow, but it work)

Leave a Reply

Your email address will not be published. Required fields are marked *