Avatar of viraltaco

viraltaco's solution

to Run Length Encoding in the Swift Track

Published at Nov 10 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),
        ]
    }
}
fileprivate extension String {
  func nextIndex(from: String.Index) -> String.Index {
    return self.index(from, offsetBy: 1, limitedBy: self.endIndex)
        ?? self.endIndex
  }
}

struct RunLengthEncoding {
  static func encode(_ text: String) -> String {
    var last: Character = "\0"
    var count = 0
    var encoded = ""

    var start = text.startIndex
    let end = text.endIndex

    while start < end {
      while text[start] == last && !last.isWhitespace {
        count += 1
        last = text[start]
        start = text.nextIndex(from: start)
        if start == end {
          break
        }
      }

      if count != 0 {
        let encodedLast = encoded.last
        if encodedLast == last {
          _ = encoded.popLast()
        }
        encoded.append("\(count + 1)\(last)")
        count = 0
      }

      if start < end {
        encoded.append(text[start])
        last = text[start]
        start = text.nextIndex(from: start)
      }
    }

    return encoded
  }

  static func decode(_ text: String) -> String {
    var decoded = ""
    var amount = ""

    var start = text.startIndex
    let end = text.endIndex

    while start < end {
      while text[start].isNumber {
        amount.append(text[start])
        start = text.nextIndex(from: start)
        if start == end {
          break
        }
      }

      if !amount.isEmpty {
        repeatElement(text[start], count: Int(amount) ?? 0).forEach {
          decoded.append($0)
        }
        amount = ""
      } else {
        decoded.append(text[start])
      }

      start = text.nextIndex(from: start)
    }

    return decoded
  }
}

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?