How to Detect if Numbers are in Order in Golang

The challenge

In this challenge, your function receives an array of integers as input. Your task is to determine whether the numbers are in ascending order. An array is said to be in ascending order if there are no two adjacent integers where the left integer exceeds the right integer in value.

For the purposes of this challenge, you may assume that all inputs are valid, i.e. non-empty arrays containing only 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 because the numbers are in DESCENDING order
Code language: Go (go)

The solution in Golang

Option 1:

package solution import "sort" func InAscOrder(numbers []int) bool { return sort.IntsAreSorted(numbers) }
Code language: Go (go)

Option 2:

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

Option 3:

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

Test cases to validate our solution

package our_test import ( . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) var _ = Describe("Test Example", func() { It("should test that the solution returns the correct value", func() { Expect(InAscOrder([]int{1, 2, 4, 7, 19})).To(Equal(true)) Expect(InAscOrder([]int{1, 2, 3, 4, 5})).To(Equal(true)) Expect(InAscOrder([]int{1, 6, 10, 18, 2, 4, 20})).To(Equal(false)) Expect(InAscOrder([]int{9, 8, 7, 6, 5, 4, 3, 2, 1})).To(Equal(false)) }) })
Code language: Go (go)

Tags:
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments