Swift Bug?

The function below should print 25 pairs of numbers which works fine. Now uncomment the commented line and the combination 2,4 is missing. I am using XCode 11. Tried this on playground as well as in an Xcode project (command line utility)


func solve(arr: [Int]) -> Int {

    for i in arr.indices {
            for j in arr.indices {
                print("i is \(i) j is \(j)")
               
//                guard i < j  else {
//                    continue
//                }
//                let (x,y) = (arr[i] , arr[j])
//                guard (x * y) <= arr[i...j].max()! else{
//                    break
//                }
            }
        }
   
    return 0
}

let a: [Int] = [1, 1, 2, 4, 2]
solve(arr: a)
Answered by DelawareMathGuy in 401620022

hi,


i'm not sure why you think there's a bug here, but i'm not even sure what you're trying to accomplish in this loop. with the lines uncommented, it is doing what it is written to do.


i've added a where qualifier on the inner loop to start simplifying your code, so try this first.


func solve(arr: [Int]) -> Int {

  for i in arr.indices {
    for j in arr.indices where i < j {
      print("i is \(i) j is \(j)")
      // let (x,y) = (arr[i] , arr[j])
      // guard (x * y) <= arr[i...j].max()! else {
      //   print("array arr[i...j] is \(arr[i...j])")
      //   print("breaking")
      //   break
      // }
    }
  }

  return 0
}

let a: [Int] = [1, 1, 2, 4, 2]
let x = solve(arr: a) // x will be zero


if you uncomment the commented lines, there will be a point where you break out of the inner loop, since 2*4 = 8, and this is bigger than the largest element in the array (4). the index combination of 2 and 4 with then be skipped.


hope that helps,

DMG

Accepted Answer

hi,


i'm not sure why you think there's a bug here, but i'm not even sure what you're trying to accomplish in this loop. with the lines uncommented, it is doing what it is written to do.


i've added a where qualifier on the inner loop to start simplifying your code, so try this first.


func solve(arr: [Int]) -> Int {

  for i in arr.indices {
    for j in arr.indices where i < j {
      print("i is \(i) j is \(j)")
      // let (x,y) = (arr[i] , arr[j])
      // guard (x * y) <= arr[i...j].max()! else {
      //   print("array arr[i...j] is \(arr[i...j])")
      //   print("breaking")
      //   break
      // }
    }
  }

  return 0
}

let a: [Int] = [1, 1, 2, 4, 2]
let x = solve(arr: a) // x will be zero


if you uncomment the commented lines, there will be a point where you break out of the inner loop, since 2*4 = 8, and this is bigger than the largest element in the array (4). the index combination of 2 and 4 with then be skipped.


hope that helps,

DMG

Sorry, I just realized I have been very silly indeed. Of course I am breaking out of the inner loop! I have just had a brain freeze! 🙂

Swift Bug?
 
 
Q