Software Engineering

Tips on how to carry out Array Factor Parity in Golang

Tips on how to carry out Array Factor Parity in Golang
Written by admin


The problem

You’ll be given an array of integers whose parts have each a unfavorable and a constructive worth, aside from one integer that’s both solely unfavorable or solely constructive. Your process can be to seek 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 could seem greater than as soon as)

The answer in Golang

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

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

Possibility 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 primary 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)       
  })
})

About the author

admin

Leave a Comment