🎉 Exercism Research is now launched. Help Exercism, help science and have some fun at research.exercism.io 🎉
Avatar of mbraak

mbraak's solution

to Atbash Cipher in the Swift Track

Published at Jul 29 2019 · 0 comments
Instructions
Test suite
Solution

Create an implementation of the atbash cipher, an ancient encryption system created in the Middle East.

The Atbash cipher is a simple substitution cipher that relies on transposing all the letters in the alphabet such that the resulting alphabet is backwards. The first letter is replaced with the last letter, the second with the second-last, and so on.

An Atbash cipher for the Latin alphabet would be as follows:

Plain:  abcdefghijklmnopqrstuvwxyz
Cipher: zyxwvutsrqponmlkjihgfedcba

It is a very weak cipher because it only has one possible key, and it is a simple monoalphabetic substitution cipher. However, this may not have been an issue in the cipher's time.

Ciphertext is written out in groups of fixed length, the traditional group size being 5 letters, and punctuation is excluded. This is to make it harder to guess things based on word boundaries.

Examples

  • Encoding test gives gvhg
  • Decoding gvhg gives test
  • Decoding gsvjf rxpyi ldmul cqfnk hlevi gsvoz abwlt gives thequickbrownfoxjumpsoverthelazydog

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 http://en.wikipedia.org/wiki/Atbash

Submitting Incomplete Solutions

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

AtbashCipherTests.swift

import XCTest
@testable import AtbashCipher

class AtbashCipherTests: XCTestCase {

    func testEncodeNo() {
        XCTAssertEqual("ml", AtbashCipher.encode("no") )
    }

    func testEncodeYes() {
        XCTAssertEqual("bvh", AtbashCipher.encode("yes") )
    }

    func testEncodeOMG() {
        XCTAssertEqual("lnt", AtbashCipher.encode("OMG") )
    }

    func testEncodeOMGWithSpaces() {
        XCTAssertEqual("lnt", AtbashCipher.encode("O M G") )
    }

    func testEncodeLongWord() {
        XCTAssertEqual("nrmwy oldrm tob", AtbashCipher.encode("mindblowingly") )
    }

    func testEncodeNumbers() {
        XCTAssertEqual("gvhgr mt123 gvhgr mt",
                       AtbashCipher.encode("Testing, 1 2 3, testing.") )
    }

    func testEncodeSentence() {
        XCTAssertEqual("gifgs rhurx grlm", AtbashCipher.encode("Truth is fiction.") )
    }

    func testEncodeAllTheThings() {
        let plaintext = "The quick brown fox jumps over the lazy dog."
        let cipher = "gsvjf rxpyi ldmul cqfnk hlevi gsvoz abwlt"
        XCTAssertEqual(cipher, AtbashCipher.encode(plaintext) )
    }

    static var allTests: [(String, (AtbashCipherTests) -> () throws -> Void)] {
        return [
            ("testEncodeNo", testEncodeNo),
            ("testEncodeYes", testEncodeYes),
            ("testEncodeOMG", testEncodeOMG),
            ("testEncodeOMGWithSpaces", testEncodeOMGWithSpaces),
            ("testEncodeLongWord", testEncodeLongWord),
            ("testEncodeNumbers", testEncodeNumbers),
            ("testEncodeSentence", testEncodeSentence),
            ("testEncodeAllTheThings", testEncodeAllTheThings),
        ]
    }
}

LinuxMain.swift

import XCTest
@testable import AtbashCipherTests

XCTMain([
    testCase(AtbashCipherTests.allTests),
    ])
func asciiCode(_ c: Character) -> Int {
  let s = String(c)
  return Int(s.unicodeScalars[s.startIndex].value)
}

func toChar(_ n: Int) -> Character {
  return Character(UnicodeScalar(n)!)
}

let asciiCodeA = asciiCode("a")
let asciiCodeZ = asciiCode("z")

func encodeChar(_ c: Character) -> Character {
  if c.isNumber {
    return c
  }

  return toChar(
    (asciiCodeZ - asciiCode(c)) + asciiCodeA
  )
}

func addSpaces(_ input: String, _ n: Int) -> String {
  var result = ""

  for (i, c) in input.enumerated() {
    if i != 0 && i % n == 0 {
      result += " "
    }

    result += String(c)
  }

  return result
}

class AtbashCipher {
  static func encode(_ input: String) -> String {
    return addSpaces(
      String(
        input
          .lowercased()
          .filter { $0.isLetter || $0.isNumber }
          .map { encodeChar($0) }
      ),
      5
    )
  }
}

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?