Swift: How can I remove duplicates from an array of doubles?

前端 未结 3 1050
栀梦
栀梦 2021-01-17 07:09

I have an array of values like [0.75, 0.0050000000000000001, 0.0050000000000000001, 0.0050000000000000001, 0.0050000000000000001, 0.0050000000000000001, 0.004000000000

3条回答
  •  谎友^
    谎友^ (楼主)
    2021-01-17 07:39

    Your problem is a little bit complicated as your equality for Doubles is based on the first 3 digits after the decimal point. Many threads describe about removing duplicates where simple equality applies, but I cannot find one including Doubles with comparison in your question.

    You usually use Set to eliminate duplicates, but Set uses strict equality which does not fulfill your requirement.

    Normalizing the value may work in your case:

    extension Double {
        var my_normalized: Double {
            return (self * 1000).rounded() / 1000
        }
    }
    
    print(0.0050000000000000001.my_normalized == 0.0051.my_normalized) //->true
    

    Using this, you can write something like this:

    let arr = [0.75, 0.0050000000000000001, 0.0050000000000000001, 0.0050000000000000001, 0.0050000000000000001, 0.0050000000000000001, 0.0040000000000000001 /*,...*/]
    
    var valueSet: Set = []
    var result: [Double] = []
    arr.forEach {value in
        let normalizedValue = value.my_normalized
        if !valueSet.contains(normalizedValue) {
            valueSet.update(with: normalizedValue)
            result.append(value)
        }
    }
    print(result) //->[0.75, 0.0050000000000000001, 0.0040000000000000001]
    

    If you do not mind the order of the result and it can contain normalized value, the code can be simpler:

    let simpleResult = Array(Set(arr.map {$0.my_normalized}))
    print(simpleResult) //->[0.75, 0.0050000000000000001, 0.0040000000000000001]
    

提交回复
热议问题