Thursday, September 21, 2023
HomeSoftware EngineeringTips on how to carry out Array Ingredient Parity in Golang

# Tips on how to carry out Array Ingredient Parity in Golang

## The problem#

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

Examples:

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

`3` has no matching unfavorable 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 might seem greater than as soon as)

Choice 1:

``````bundle resolution

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
}
``````

Choice 2:

``````bundle resolution

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
}
``````

Choice 3:

``````bundle resolution

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
}
``````

## Check circumstances to validate our resolution#

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

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

var _ = Describe("Instance exams", func() {
It("It ought to work for fundamental exams", 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