enigma-machine/Enigma/Machine.swift

64 lines
1.6 KiB
Swift
Raw Normal View History

2015-07-18 23:01:30 -07:00
//
// Machine.swift
// Enigma
//
// Created by Eryn Wells on 7/18/15.
// Copyright © 2015 Eryn Wells. All rights reserved.
//
import Foundation
class Machine {
let rotors: [Rotor]
let reflector: Reflector
let plugboard: Plugboard
2015-07-19 12:41:42 -07:00
var rotorAdvanceEnabled: Bool = true
2015-07-18 23:01:30 -07:00
init(rotors: [Rotor], reflector: Reflector, plugboard: Plugboard) {
self.rotors = rotors
self.reflector = reflector
self.plugboard = plugboard
}
func encode(c: Character) throws -> Character {
2015-07-19 12:41:42 -07:00
if rotorAdvanceEnabled {
advanceRotors()
}
2015-07-18 23:01:30 -07:00
var output = c
output = try plugboard.encode(output)
for rotor in rotors.reverse() {
2015-07-18 23:01:30 -07:00
output = try rotor.encode(output)
}
output = try reflector.encode(output)
for rotor in rotors {
output = try rotor.inverseEncode(output)
2015-07-18 23:01:30 -07:00
}
output = try plugboard.inverseEncode(output)
2015-07-18 23:01:30 -07:00
return output
}
func encode(string: String) throws -> String {
var output = ""
for character in string.characters {
output += String(try encode(character))
}
return output
}
func advanceRotors() {
2015-07-19 08:45:18 -07:00
var shouldAdvance = true // Always advance the first rotor
for rotor in rotors.reverse() {
if shouldAdvance {
rotor.advance()
}
// Advance the next rotor if this rotor is in the notch position.
if let notch = rotor.notch {
shouldAdvance = rotor.position == notch
} else {
shouldAdvance = false
}
}
2015-07-18 23:01:30 -07:00
}
}