Avatar of mbraak

mbraak's solution

to Run Length Encoding in the Swift Track

Published at Aug 02 2019 · 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),
        ]
    }
}
import Foundation

class RunLengthEncoding {
  static func encode(_ input: String) -> String {
    let regex = try! NSRegularExpression(pattern: #"(.)\1+|(.)"#, options: [])
    let range = NSRange(input.startIndex..<input.endIndex, in: input)

    let r = regex.matches(in: input, options: [], range: range).map {
      let i = String.Index(utf16Offset: $0.range.location, in: input)

      if $0.range.length == 1 {
        return String(input[i])
      } else {
        return "\($0.range.length)\(String(input[i]))"
      }
    }.joined(separator: "")

    return r
  }

  static func decode(_ input: String) -> String {
    let regex = try! NSRegularExpression(pattern: #"\d+.|."#, options: [])
    let range = NSRange(input.startIndex..<input.endIndex, in: input)

    return regex.matches(in: input, options: [], range: range).map {
      let r = $0.range
      let start = input.index(input.startIndex, offsetBy: r.location)
      let end = input.index(input.startIndex, offsetBy: r.location + r.length)
      var match = String(input[start..<end])

      let c = match.removeLast()
      let n = Int(match) ?? 1
      return String(repeating: c, count: n)
    }.joined(separator: "")
  }
}

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?