HomeSoftware EngineeringThe best way to carry out Array Ingredient Parity in Golang

# The best way to carry out Array Ingredient Parity in Golang

## The problem#

You can be given an array of integers whose components have each a destructive and a constructive worth, apart from one integer that’s both solely destructive or solely constructive. Your activity shall be to search out that integer.

Examples:

`[1, -1, 2, -2, 3] => 3`

`3` has no matching destructive look

`[-3, 1, 2, 3, -1, -4, -2] => -4`

`-4` has no matching constructive look

`[1, -1, 2, -2, 3, 3] => 3`

(the only-positive or only-negative integer could seem greater than as soon as)

Possibility 1:

``````package deal answer

func Remedy(arr []int) int {
hash := make(map[int]bool)
ans := 0
for _, entry := vary arr {
if _, worth := hash[entry]; !worth {
hash[entry] = true
ans += entry
}
}
return ans
}
``````

Possibility 2:

``````package deal answer

func Remedy(a []int) int {
s, n := 0, 0
for _, v := vary a {
s += v
if v < 0 { n-- } else { n++ }
}
if n < 0 { n = -n }
return s/n
}
``````

Possibility 3:

``````package deal answer

func Discover(arr []int, elem int) bool {
for _, x := vary arr {
if elem == x {
return true
}
}
return false
}

func Remedy(arr []int) int {
for _, x := vary arr {
if !Discover(arr, -x) {
return x
}
}
return 0
}
``````

## Take a look at circumstances to validate our answer#

``````package deal solution_test
import (
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
)

func dotest(arr []int, exp int) {
var ans = Remedy(arr)
Anticipate(ans).To(Equal(exp))
}

var _ = Describe("Instance assessments", func() {
It("It ought to work for primary assessments", func() {
dotest([] int{1,-1,2,-2,3}, 3)
dotest([] int{-3,1,2,3,-1,-4,-2}, -4)
dotest([] int{1,-1,2,-2,3,3}, 3)
dotest([] int{-110,110,-38,-38,-62,62,-38,-38,-38}, -38)
dotest([] int{-9,-105,-9,-9,-9,-9,105}, -9)
})
})
``````
RELATED ARTICLES