Home > other >  How can i fix the true or false in this code?
How can i fix the true or false in this code?

Time:11-26

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.

CodePudding user response:

func isIncreasing(_ values: [Int]) -> Bool{
    if values.count <= 1 {
        return true
    }
    
    for idx in 1..<values.count {
        if values[idx-1] > values[idx] {
            return false
        }
    }
    
    return true
}

CodePudding user response:

This is way to complicated. And there are multiple serious errors in your code:

e.g:

for i: Int in l {

this will not let you iterate over the index. i will be the value in the array. So this line:

if l[i] < l[i   1] {

will not give you the value you expect.

Also the flagging is unnecassary and implemented wrong. If you detect a not rising value it will be set to false but you don´t stop there. So the next loop could set it to true again.

A more simple solution would be:

func isIncreasing(_ values: [Int]) -> Bool{
    guard values.count > 0 else{
        // if the array is empty
        return true
    }
    
    for (index, _) in values.enumerated(){
        // if this is the last element of the array
        if index == values.count - 1{
            break
        }
        // if any next value is lower or equal than the current the array is not increasing
        // so no need to continue. Return false
        if values[index] >= values[index   1]{
            return false
        }
    }
    // return true if every next value was rising
    return true
}

Edit:

I don´t exactly understand what equals OK means, but if it equal values should be counted as rising this would be the propper algo:

if values[index] > values[index   1]{
    return false
}
  • Related