Thursday, September 21, 2023
HomeSoftware EngineeringTips on how to Detect if Numbers are in Order in Golang

Tips on how to Detect if Numbers are in Order in Golang


The problem

On this problem, your operate receives an array of integers as enter. Your process is to find out whether or not the numbers are in ascending order. An array is alleged to be in ascending order if there are not any two adjoining integers the place the left integer exceeds the appropriate integer in worth.

For the needs of this problem, you could assume that every one inputs are legitimate, i.e. non-empty arrays containing solely integers.

Examples:

InAscOrder([]int{1, 2, 4, 7, 19}) // returns True
InAscOrder([]int{1, 2, 3, 4, 5}) // returns True
InAscOrder([]int{1, 6, 10, 18, 2, 4, 20}) // returns False
InAscOrder([]int{9, 8, 7, 6, 5, 4, 3, 2, 1}) // returns False as a result of the numbers are in DESCENDING order

The answer in Golang

Possibility 1:

package deal answer

import "kind"

func InAscOrder(numbers []int) bool {
  return kind.IntsAreSorted(numbers)
}

Possibility 2:

package deal answer

func InAscOrder(numbers []int) bool {
  for i:=0; i < len(numbers) - 1; i++ {
    if(numbers[i] > numbers[i+1]) {
      return false
    }
  }
  return true
}

Possibility 3:

package deal answer

func InAscOrder(numbers []int) bool {
  i := 0
  for  ; i < len(numbers)-1 && numbers[i] <= numbers[i+1] ; i++ {}
  return i == len(numbers) - 1
}

Take a look at instances to validate our answer

package deal our_test

import (
  . "github.com/onsi/ginkgo"
  . "github.com/onsi/gomega"
)

var _ = Describe("Take a look at Instance", func() {
  It("ought to take a look at that the answer returns the right worth", func() {
    Count on(InAscOrder([]int{1, 2, 4, 7, 19})).To(Equal(true))
    Count on(InAscOrder([]int{1, 2, 3, 4, 5})).To(Equal(true))
    Count on(InAscOrder([]int{1, 6, 10, 18, 2, 4, 20})).To(Equal(false))
    Count on(InAscOrder([]int{9, 8, 7, 6, 5, 4, 3, 2, 1})).To(Equal(false))
  })
})
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments