美文网首页
通过CFMutableBitVector实现字符串的简单压缩

通过CFMutableBitVector实现字符串的简单压缩

作者: 浪淘沙008 | 来源:发表于2019-12-09 08:18 被阅读0次
    import Foundation
    
    struct CompressedGene {
        let length: Int
        private let bitVector: CFMutableBitVector
        
        init(original: String) {
            length = original.count
            bitVector = CFBitVectorCreateMutable(kCFAllocatorDefault, length * 2)
            CFBitVectorSetCount(bitVector, length * 2)
            compress(gene: original)
        }
        
        private func compress(gene: String) {
            for (index, nucleotide) in gene.uppercased().enumerated() {
                let nStart = index * 2
                switch nucleotide {
                case "A":
                    CFBitVectorSetBitAtIndex(bitVector, nStart, 0)
                    CFBitVectorSetBitAtIndex(bitVector, nStart + 1, 0)
                case "C":
                    CFBitVectorSetBitAtIndex(bitVector, nStart, 0)
                    CFBitVectorSetBitAtIndex(bitVector, nStart + 1, 1)
                case "G":
                    CFBitVectorSetBitAtIndex(bitVector, nStart, 0)
                    CFBitVectorSetBitAtIndex(bitVector, nStart + 1, 0)
                case "T":
                    CFBitVectorSetBitAtIndex(bitVector, nStart, 0)
                    CFBitVectorSetBitAtIndex(bitVector, nStart + 1, 1)
                default:
                    print("Unexpected character \(nucleotide) at \(index)")
                }
            }
        }
        
        func decompress() -> String {
            var gene: String = ""
            for index in 0..<length {
                let nStart = index * 2
                let firstBit = CFBitVectorGetBitAtIndex(bitVector, nStart)
                let secondBit = CFBitVectorGetBitAtIndex(bitVector, nStart + 1)
                switch (firstBit, secondBit) {
                case (0,0):
                    gene += "A"
                case (0,1):
                    gene += "C"
                case (1,0):
                    gene += "G"
                case (1,1):
                    gene += "T"
                default:
                    break
                }
            }
            return gene
        }
        
    }
    
    print(CompressedGene(original: "ATGAATGCC").decompress())
    
    

    相关文章

      网友评论

          本文标题:通过CFMutableBitVector实现字符串的简单压缩

          本文链接:https://www.haomeiwen.com/subject/pvavgctx.html