-2

Write a function isIncreasing that takes a list of Ints and returns true if numbers are in increasing (equals OK) order. An empty list should result in true.

func isIncreasing(_ l: [Int]) -> Bool {
    
    var flagreturn=true
    if l.count == 0 {
        flagreturn=true
        
        
    } else {
        for i: Int in l {
            if l[i] < l[i + 1] {
              flagreturn=true
                
            }
            else{
                flagreturn=false
                
            }
           
        
            
        }
    }
    return flagreturn

}

Not sure if I implemented the true and false correctly in the code.

tyoung1385
  • 15
  • 3
  • You're setting your `flagreturn` on every step of the loop, so whatever you set on the last iteration will over-write anything that came from previous iteration. – Edward Peters Nov 25 '22 at 22:54
  • Once you detect a non-incremental result, you should break the loop - but as stated, start with assumption it is (incrementing) and when you find a condition where it’s not, set the flag to false and break out of the loop – MadProgrammer Nov 25 '22 at 23:08

1 Answers1

1

You can zip the sequence with itself dropping the first element and check if it all satisfy a condition like $0 <= $1:

func isIncreasing(_ l: [Int]) -> Bool {
    zip(l, l.dropFirst()).allSatisfy { $0 <= $1 }
}

isIncreasing([1,2])        // true
isIncreasing([0,1,1,2])    // true
isIncreasing([0,1,1,2,1])  // false

Expanding on that you can extend sequence constraining its elements to Comparable an d create a generic property like areInIncreasingOrder:

extension Sequence where Element: Comparable {
    var areInIncreasingOrder: Bool {
        zip(self, dropFirst()).allSatisfy { $0 <= $1 }
    }
}

Usage:

[1,2].areInIncreasingOrder               // true
[1,2].dropFirst(2).areInIncreasingOrder  // true
[0,1,1,2].areInIncreasingOrder           // true
[0,1,1,2,1].areInIncreasingOrder         // false
Leo Dabus
  • 229,809
  • 59
  • 489
  • 571