How to resolve the algorithm Run-length encoding step by step in the Swift programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Run-length encoding step by step in the Swift programming language

Table of Contents

Problem Statement

Given a string containing uppercase characters (A-Z), compress repeated 'runs' of the same character by storing the length of that run, and provide a function to reverse the compression. The output can be anything, as long as you can recreate the input with it.

Note: the encoding step in the above example is the same as a step of the Look-and-say sequence.

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Run-length encoding step by step in the Swift programming language

Source code in the swift programming language

import Foundation

// "WWWBWW" -> [(3, W), (1, B), (2, W)]
func encode(input: String) -> [(Int, Character)] {
    return input.characters.reduce([(Int, Character)]()) {
        if $0.last?.1 == $1 { var r = $0; r[r.count - 1].0++; return r }
        return $0 + [(1, $1)]
    }
}

// [(3, W), (1, B), (2, W)] -> "WWWBWW"
func decode(encoded: [(Int, Character)]) -> String {
    return encoded.reduce("") { $0 + String(count: $1.0, repeatedValue: $1.1) }
}

let input = "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW"
let output = decode(encode(input))
print(output == input)

// "3W1B2W" -> "WWWBWW"
func decode(encoded: String) -> String {
    let scanner = NSScanner(string: encoded)
    var char: NSString? = nil
    var count: Int = 0
    var out = ""

    while scanner.scanInteger(&count) {
        while scanner.scanCharactersFromSet(NSCharacterSet.letterCharacterSet(), intoString: &char) {
            out += String(count: count, repeatedValue: Character(char as! String))
        }
    }

    return out
}

let encodedString = encode(input).reduce("") { $0 + "\($1.0)\($1.1)" }
print(encodedString)
let outputString = decode(encodedString)
print(outputString == input)

  

You may also check:How to resolve the algorithm Caesar cipher step by step in the MATLAB / Octave programming language
You may also check:How to resolve the algorithm Parsing/RPN calculator algorithm step by step in the jq programming language
You may also check:How to resolve the algorithm Web scraping step by step in the AWK programming language
You may also check:How to resolve the algorithm Peaceful chess queen armies step by step in the Fortran programming language
You may also check:How to resolve the algorithm Comments step by step in the ProDOS programming language