Home > database >  Find contiguous sequence of elements in an array
Find contiguous sequence of elements in an array

Time:05-01

After research I found only the way to get the discontiguous sequence of elements in an array. I wonder is there an efficient way to get all the contiguous sequence of elements in an array using Swift.

Thanks in advanced

Example:
For [1, 2, 3], the answer would be

1
1 2
1 2 3
2
2 3
3

CodePudding user response:

Just use two loops with list slicing to get all contiguous subsequences.

let arr = [1,2,3,4]

var res = [[Int]]()

for i in 0..<arr.count {
    var temp = [Int]()
    for j in i..<arr.count {
        res.append(Array(arr[i...j]))
    }
}

print(res)
// [[1], [1, 2], [1, 2, 3], [1, 2, 3, 4], [2], [2, 3], [2, 3, 4], [3], [3, 4], [4]]
  • Related