To check if two arrays have the same elements regardless of order in Go, you can sort both arrays and then compare them element by element.
In this example,
arr1
and arr2
with the same elements but in different order.sort.Ints()
function from the sort
package.arraysEqual
that checks if the sorted arrays are equal.arraysEqual
to compare the arrays and print the result to the console.package main
import (
"fmt"
"sort"
)
func main() {
arr1 := []int{1, 2, 3}
arr2 := []int{3, 1, 2}
sort.Ints(arr1)
sort.Ints(arr2)
isEqual := arraysEqual(arr1, arr2)
fmt.Println(isEqual)
}
func arraysEqual(arr1, arr2 []int) bool {
if len(arr1) != len(arr2) {
return false
}
for i := range arr1 {
if arr1[i] != arr2[i] {
return false
}
}
return true
}
true
In this example,
arr3
and arr4
with different elements.sort.Ints()
function from the sort
package.arraysEqual
that checks if the sorted arrays are equal.arraysEqual
to compare the arrays and print the result to the console.package main
import (
"fmt"
"sort"
)
func main() {
arr3 := []int{1, 2, 3}
arr4 := []int{4, 5, 6}
sort.Ints(arr3)
sort.Ints(arr4)
isEqual := arraysEqual(arr3, arr4)
fmt.Println(isEqual)
}
func arraysEqual(arr1, arr2 []int) bool {
if len(arr1) != len(arr2) {
return false
}
for i := range arr1 {
if arr1[i] != arr2[i] {
return false
}
}
return true
}
false
In this tutorial, we learned How to check if Two Arrays have Same Elements (Regardless of Order) in Go language with well detailed examples.