Software Engineering

Highest Rank Quantity in an Array in Golang

Highest Rank Quantity in an Array in Golang
Written by admin


The problem

Full the strategy which returns the quantity which is most frequent within the given enter array. If there’s a tie for probably the most frequent quantity, return the biggest quantity amongst them.

Notice: no empty arrays can be given.

Examples

[12, 10, 8, 12, 7, 6, 4, 10, 12]              -->  12
[12, 10, 8, 12, 7, 6, 4, 10, 12, 10]          -->  12
[12, 10, 8, 8, 3, 3, 3, 3, 2, 4, 10, 12, 10]  -->   3

The answer in Golang

Choice 1:

bundle resolution
func HighestRank(nums []int) int {
  mii, maxK, maxV := map[int]int{}, 0, 0
  for _, v := vary nums {
    mii[v]++
    if mii[v] > maxV || (mii[v] == maxV && v > maxK) {
      maxK = v
      maxV = mii[v]
    }
  }
  return maxK
}

Choice 2:

bundle resolution
func HighestRank(nums []int) int {
  fs := make(map[int]int)
  for _, n := vary nums {
    fs[n]++
  }
  maxf, maxfn := 0, 0
  for n, f := vary fs {
    if f >= maxf && (f > maxf || n > maxfn) {
      maxf, maxfn = f, n
    }
  }
  return maxfn
}

Choice 3:

bundle resolution
func HighestRank(nums []int) int {
  occurrences := make(map[int]int)
  var max, val int
  for _, worth := vary nums {
    occurrences[value]++
  }
  max, val = occurrences[nums[0]], nums[0]
  for worth, occasions := vary occurrences {
    if occasions > max {
      val = worth
      max = occasions
    } else if occasions == max {
      if worth > val {
        val = worth
      }
    }
  }
  return val
}

Take a look at instances to validate our resolution

bundle solution_test
import (
  . "github.com/onsi/ginkgo"
  . "github.com/onsi/gomega"
)
var _ = Describe("Assessments", func() {
    Describe("Pattern exams", func() {
        It("Pattern check 1: 12, 10, 8, 12, 7, 6, 4, 10, 12", func() {
            Anticipate(HighestRank([]int{12, 10, 8, 12, 7, 6, 4, 10, 12 })).To(Equal(12))
        })
    })
})

About the author

admin

Leave a Comment