How to resolve the algorithm Burrows–Wheeler transform step by step in the Swift programming language
Published on 12 May 2024 09:40 PM
How to resolve the algorithm Burrows–Wheeler transform step by step in the Swift programming language
Table of Contents
Problem Statement
The Burrows–Wheeler transform (BWT, also called block-sorting compression) rearranges a character string into runs of similar characters. This is useful for compression, since it tends to be easy to compress a string that has runs of repeated characters by techniques such as move-to-front transform and run-length encoding. More importantly, the transformation is reversible, without needing to store any additional data. The BWT is thus a "free" method of improving the efficiency of text compression algorithms, costing only some extra computation.
Source: Burrows–Wheeler transform
Let's start with the solution:
Step by Step solution about How to resolve the algorithm Burrows–Wheeler transform step by step in the Swift programming language
Source code in the swift programming language
import Foundation
private let stx = "\u{2}"
private let etx = "\u{3}"
func bwt(_ str: String) -> String? {
guard !str.contains(stx), !str.contains(etx) else {
return nil
}
let ss = stx + str + etx
let table = ss.indices.map({i in ss[i...] + ss[ss.startIndex..<i] }).sorted()
return String(table.map({str in str.last!}))
}
func ibwt(_ str: String) -> String? {
let len = str.count
var table = Array(repeating: "", count: len)
for _ in 0..<len {
for i in 0..<len {
table[i] = String(str[str.index(str.startIndex, offsetBy: i)]) + table[i]
}
table.sort()
}
for row in table where row.hasSuffix(etx) {
return String(row.dropFirst().dropLast())
}
return nil
}
func readableBwt(_ str: String) -> String {
return str.replacingOccurrences(of: "\u{2}", with: "^").replacingOccurrences(of: "\u{3}", with: "|")
}
let testCases = [
"banana",
"appellee",
"dogwood",
"TO BE OR NOT TO BE OR WANT TO BE OR NOT?",
"SIX.MIXED.PIXIES.SIFT.SIXTY.PIXIE.DUST.BOXES",
"\u{2}ABC\u{3}"
]
for test in testCases {
let b = bwt(test) ?? "error"
let c = ibwt(b) ?? "error"
print("\(readableBwt(test)) -> \(readableBwt(b)) -> \(readableBwt(c))")
}
You may also check:How to resolve the algorithm Find limit of recursion step by step in the Pascal programming language
You may also check:How to resolve the algorithm Arithmetic numbers step by step in the FutureBasic programming language
You may also check:How to resolve the algorithm Multiple distinct objects step by step in the Icon and Unicon programming language
You may also check:How to resolve the algorithm Elementary cellular automaton step by step in the MiniScript programming language
You may also check:How to resolve the algorithm Loops/For step by step in the Babel programming language