Avatar of cmgg

cmgg's solution

to Run Length Encoding in the Swift Track

Published at Mar 14 2020 · 0 comments
Instructions
Test suite
Solution

Implement run-length encoding and decoding.

Run-length encoding (RLE) is a simple form of data compression, where runs (consecutive data elements) are replaced by just one data value and count.

For example we can represent the original 53 characters with only 13.

"WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWB"  ->  "12WB12W3B24WB"

RLE allows the original data to be perfectly reconstructed from the compressed data, which makes it a lossless data compression.

"AABCCCDEEEE"  ->  "2AB3CD4E"  ->  "AABCCCDEEEE"

For simplicity, you can assume that the unencoded string will only contain the letters A through Z (either lower or upper case) and whitespace. This way data to be encoded will never contain any numbers and numbers inside data to be decoded always represent the count for the following character.

Setup

Go through the project setup instructions for Xcode using Swift:

http://exercism.io/languages/swift
http://exercism.io/languages/swift/tests

Notably from the source directory:

swift test runs tests
swift package generate-xcodeproj creates an Xcode project

Source

Wikipedia https://en.wikipedia.org/wiki/Run-length_encoding

Submitting Incomplete Solutions

It's possible to submit an incomplete solution so you can see how others have completed the exercise.

LinuxMain.swift

import XCTest
@testable import RunLengthEncodingTests

XCTMain([
    testCase(RunLengthEncodingTests.allTests),
    ])

RunLengthEncodingTests.swift

import XCTest
@testable import RunLengthEncoding

class RunLengthEncodingTests: XCTestCase {
    func testEncodeSimple() {
        XCTAssertEqual(RunLengthEncoding.encode("AABBBCCCC"), "2A3B4C")
    }

    func testDecodeSimple() {
        XCTAssertEqual(RunLengthEncoding.decode("2A3B4C"), "AABBBCCCC")
    }

    func testEncodeWithSingleValues() {
        XCTAssertEqual(RunLengthEncoding.encode("WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWB"), "12WB12W3B24WB")
    }

    func testDecodeWithSingleValues() {
        XCTAssertEqual(RunLengthEncoding.decode("12WB12W3B24WB"), "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWB")
    }

    func testDecodeEncodeCombination() {
        XCTAssertEqual(RunLengthEncoding.decode(RunLengthEncoding.encode("zzz ZZ  zZ")), "zzz ZZ  zZ")
    }

    func testEncodeUnicode() {
        XCTAssertEqual(RunLengthEncoding.encode("⏰⚽⚽⚽⭐⭐⏰"), "⏰3⚽2⭐⏰")
    }

    func testDecodeUnicode() {
        XCTAssertEqual(RunLengthEncoding.decode("⏰3⚽2⭐⏰"), "⏰⚽⚽⚽⭐⭐⏰")
    }

    static var allTests: [(String, (RunLengthEncodingTests) -> () throws -> Void)] {
        return [
            ("testEncodeSimple", testEncodeSimple),
            ("testDecodeSimple", testDecodeSimple),
            ("testEncodeWithSingleValues", testEncodeWithSingleValues),
            ("testDecodeWithSingleValues", testDecodeWithSingleValues),
            ("testDecodeEncodeCombination", testDecodeEncodeCombination),
            ("testEncodeUnicode", testEncodeUnicode),
            ("testDecodeUnicode", testDecodeUnicode),
        ]
    }
}
//Solution goes in Sources
import Foundation

class RunLengthEncoding
{
    //Encode
    static func encode(_ text: String) -> String
    {
        var code = ""
        var count = 0
        let newText = text + "0"
        var last = text.first!
        for ch in newText
        {
            if last == ch
            {
                count += 1
            }
            else
            {
                if count > 1
                {
                    code += String(count)
                }
                code += String(last)
                last = ch
                count = 1
            }
        }
        return code
    }
    //Decode
    static func decode(_ code: String) -> String
    {
        let newCode = code.map{$0.isNumber ? "\($0)" : "\($0)-"}.joined().split(separator: "-")
        return newCode.reduce(into: String()) { result, item in
            var str = String(item)
            result += String(repeating: str.popLast()!, count: Int(str) ?? 1)
        }
    }
}

Community comments

Find this solution interesting? Ask the author a question to learn more.

What can you learn from this solution?

A huge amount can be learned from reading other people’s code. This is why we wanted to give exercism users the option of making their solutions public.

Here are some questions to help you reflect on this solution and learn the most from it.

  • What compromises have been made?
  • Are there new concepts here that you could read more about to improve your understanding?