Arrays of Int arrays. Storing duplicates in order only

后端 未结 6 1431
灰色年华
灰色年华 2021-01-11 18:37

I need to store an array of Int array for ordered duplicates (which are in a Array).

Example:

  • Given array:
    mainArray = [7, 7, 3, 2, 2, 2, 1,
6条回答
  •  鱼传尺愫
    2021-01-11 18:54

    Another approach extending collections where elements are equatable

    extension Collection where Element: Equatable {
        var grouped: [[Element]] {
            var result: [[Element]] = []
            for element in self {
                if element == result.last?.last {
                    result[result.index(before: result.endIndex)].append(element)
                } else {
                    result.append([element])
                }
            }
            return result
        }
    }
    

    let array = [7, 7, 3, 2, 2, 2, 1, 7, 5, 5]
    
    array.grouped  // [[7, 7], [3], [2, 2, 2], [1], [7], [5, 5]]
    

提交回复
热议问题