Friday, December 1, 2023
HomeSoftware EngineeringEasy methods to Circularly Type an Array in Golang

Easy methods to Circularly Type an Array in Golang


The problem

An array is circularly sorted if the weather are sorted in ascending order however displaced, or rotated, by any variety of steps.

Full the perform/methodology that determines if the given array of integers is circularly sorted.

Examples:

These arrays are circularly sorted (true):

[2, 3, 4, 5, 0, 1]       -->  [0, 1] + [2, 3, 4, 5]
[4, 5, 6, 9, 1]          -->  [1] + [4, 5, 6, 9]
[10, 11, 6, 7, 9]        -->  [6, 7, 9] + [10, 11]
[1, 2, 3, 4, 5]          -->  [1, 2, 3, 4, 5]
[5, 7, 43, 987, -9, 0]   -->  [-9, 0] + [5, 7, 43, 987]
[1, 2, 3, 4, 1]          -->  [1] + [1, 2, 3, 4]

Whereas these will not be (false):

[4, 1, 2, 5]
[8, 7, 6, 5, 4, 3]
[6, 7, 4, 8]
[7, 6, 5, 4, 3, 2, 1]

The answer in Golang

Possibility 1:

bundle answer
func IsCircleSorted(r []int) bool {
    downs := 0
    for i:= 0; i<len(r); i ++ {
      if r[i] > r[(i+1)%len(r)] {
      downs += 1}
    }
    return downs <= 1
}

Possibility 2:

bundle answer
import "kind"
func IsCircleSorted(r []int) bool {
  q := make([]int, len(r))
  for i := 0; i < len(r); i++ {
    for j := 0; j < len(r); j++ {
      q[j] = r[(j+i)%len(r)]
    }
    if kind.IntsAreSorted(q) {
      return true
    }
  }
  return len(r) == 0
}

Possibility 3:

bundle answer
func IsCircleSorted(r []int) bool {
  if len(r) == 0 {
    return true
  }
  decreaseCount := 0
  for i := 1; i < len(r); i++ {
    if r[i-1] > r[i] {
      decreaseCount++
    }
  }
  if r[len(r)-1] > r[0] {
    decreaseCount++
  }
  return decreaseCount <= 1
}

Take a look at circumstances to validate our answer

bundle solution_test
import (
    . "github.com/onsi/ginkgo"
    . "github.com/onsi/gomega"
)
var _ = Describe("Instance Assessments",func() {
    It("Take a look at 1",func() {Anticipate(IsCircleSorted([]int{2,3,4,5,6})).To(Equal(true))})
    It("Take a look at 2",func() {Anticipate(IsCircleSorted([]int{6,2,3,4,5})).To(Equal(true))})
    It("Take a look at 3",func() {Anticipate(IsCircleSorted([]int{3,2,4,5,6})).To(Equal(false))})
})
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments