What is a fast way to convert a string of two characters to an array of booleans?

前端 未结 8 1541
我寻月下人不归
我寻月下人不归 2021-02-04 10:24

I have a long string (sometimes over 1000 characters) that I want to convert to an array of boolean values. And it needs to do this many times, very quickly.

let         


        
相关标签:
8条回答
  • 2021-02-04 11:13

    What about a more functional style? It's not fastest (47 ms), today, for sure...

    import Cocoa
    
    let start = clock()
    
    let bools = [Bool](([Character] ("010101011001010101001010101100101010100101010110010101010101011001010101001010101100101010100101010101011001010101001010101100101010100101010".characters)).map({$0 == "1"}))
    
    let msec = (clock() - start) * 1000 / UInt(CLOCKS_PER_SEC);
    print("Time taken \(Double(msec)/1000.0) seconds \(msec%1000) milliseconds");
    
    0 讨论(0)
  • 2021-02-04 11:15

    This should be a little faster than the enumerate() where char == "1" version (0.557s for 500_000 alternating ones and zeros vs. 1.159s algorithm 'A' from diampiax)

    let input = inputStr.utf8
    let n = input.count
    var output = [Bool](count: n, repeatedValue: false)
    let one = UInt8(49) // 1
    for (idx, char) in input.enumerate() {
        if char == one { output[idx] = true }
    }
    

    but it's also a lot less readable ;-p

    edit: both versions are slower than the map variant, maybe you forgot to compile with optimizations?

    0 讨论(0)
提交回复
热议问题