The problem
You can be given an array of integers whose parts have each a damaging and a constructive worth, apart from one integer that’s both solely damaging or solely constructive. Your process can be to seek out that integer.
Examples:
[1, -1, 2, -2, 3] => 3
3
has no matching damaging 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)
The answer in Golang
Possibility 1:
package deal resolution
func Resolve(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 resolution
func Resolve(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 resolution
func Discover(arr []int, elem int) bool {
for _, x := vary arr {
if elem == x {
return true
}
}
return false
}
func Resolve(arr []int) int {
for _, x := vary arr {
if !Discover(arr, -x) {
return x
}
}
return 0
}
Check instances to validate our resolution
package deal solution_test
import (
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
)
func dotest(arr []int, exp int) {
var ans = Resolve(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)
})
})