Sobes.tech
Middle

Kas on slaid monotonne? Monotoonne funktsioon on ühe muutuja funktsioon, mis on määratletud reaalarvude osas, ja mis kas kogu aeg (oma määramisalal) ei vähene, või kogu aeg ei suurene. {1,7} - õige {1,1} - õige {3,3,1} - õige {9,5,1} - õige {23,5,23} - vale

sobes.tech AI

Vastus AI-lt

Et määrata, kas nimekiri on monotooniline, tuleb kontrollida, kas see ei ole kasvav (iga järgnev element ei ole väiksem eelnevast) või mitte kahanev (iga järgnev element ei ole suurem eelnevast).

Näide Go keeles funktsioonist, mis kontrollib täisarvude nimekirja monotoonilisust:

func isMonotonic(nums []int) bool {
    if len(nums) <= 1 {
        return true
    }

    increasing := true
    decreasing := true

    for i := 1; i < len(nums); i++ {
        if nums[i] > nums[i-1] {
            decreasing = false
        }
        if nums[i] < nums[i-1] {
            increasing = false
        }
    }

    return increasing || decreasing
}

Kasutamise näide:

fmt.Println(isMonotonic([]int{1,7}))       // true
fmt.Println(isMonotonic([]int{1,1}))       // true
fmt.Println(isMonotonic([]int{3,3,1}))     // true
fmt.Println(isMonotonic([]int{9,5,1}))     // true
fmt.Println(isMonotonic([]int{23,5,23}))   // false