当它们具有共同的元素时,如何合并没有重复的数组

How can I merge arrays with no duplicates when they have elements in common

Swift - 当数组具有共同的元素时,如何合并不重复的数组? 假设我有一个这样的数组

[[1, 2, 3], [4, 3, 5], [7], [6, 8, 7], [9]]

我想合并所有具有共同元素的数组,不重复。所以输出就像:

[[1, 2, 3, 4, 5], [7, 6, 8], [9]]

前两个数组有3个共同点所以合并,第二个和第三个数组有7个共同点,依此类推

swift有什么方法可以做到这样的方法吗?

让我们试试:

func merge(array: [[Int]]) -> [Set<Int>] {
    
    let setList = array.map({ Set([=10=]) })
    let flags = setList.enumerated().map { (index, set) -> [Bool] in
        return (0..<setList.count).map({ counterIndex in
            return counterIndex != index && !set.intersection(setList[counterIndex]).isEmpty
        })
    }
    
    var processedIndex = Set<Int>()
    
    var result = [Set<Int>]()
    for i in 0..<array.count {
        guard !processedIndex.contains(i) else {
            continue
        }
        result.append(merge(setList: setList, with: flags, currentIndex: i, processedIndex: &processedIndex))
    }
    
    return result
}

func merge(setList: [Set<Int>], with flags: [[Bool]], currentIndex: Int, processedIndex: inout Set<Int>) -> Set<Int> {
    guard !processedIndex.contains(currentIndex) else {
        return []
    }
    
    var rs = setList[currentIndex]
    processedIndex.insert(currentIndex)
    
    for i in currentIndex..<setList.count where !processedIndex.contains(i) && flags[currentIndex][i] {
        rs.formUnion(
            merge(setList: setList, with: flags, currentIndex: i, processedIndex: &processedIndex)
        )
    }
    
    return rs
}

您可以尝试以下方法:

let input = [[1, 2, 3], [4, 3, 5], [7], [6, 8, 7], [9]]
var result = [[Int]]()

input.forEach { item in
    // indicates whether we added an item in this iteration
    var itemAdded = false
    result.forEach { oldItem in
        // check if both items intersect
        if !oldItem.filter(item.contains).isEmpty {
            // create a new item without duplicates
            let newItem: [Int] = Array(Set(oldItem + item))
            // remove the old item in the result...
            result.remove(at: result.firstIndex(of: oldItem)!)
            // ...and replace with a merged one (if wasn't added before)
            if !itemAdded {
                result.append(newItem)
            }
            itemAdded = true
        }
    }
    // if we didn't add any item in this iteration (found no intersections) add the item
    if !itemAdded {
        result.append(item)
    }
}

print(result) // prints [[1, 5, 2, 4, 3], [7, 8, 6], [9]]

如果您希望对结果进行排序,您可以使用 .sorted():

let newItem: [Int] = Array(Set(oldItem + item)).sorted()