-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathplugboard.cpp
More file actions
70 lines (56 loc) · 1.85 KB
/
Copy pathplugboard.cpp
File metadata and controls
70 lines (56 loc) · 1.85 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
#include "plugboard.hpp"
#include <stdexcept>
Plugboard::Plugboard() {
reset();
}
Plugboard::Plugboard(string pairs) : Plugboard() {
transform(pairs.begin(), pairs.end(), pairs.begin(), ::tolower);
stringstream ss(pairs);
string currentPair;
while(ss >> currentPair) {
if(currentPair.length() != 2) {throw invalid_argument("Invalid plugboard configuration: '" + currentPair + "' is not a valid pair.");}
char c1 = currentPair[0], c2 = currentPair[1];
connect(c1, c2);
}
}
void Plugboard::connect(char x, char y) {
x = tolower(x);
y = tolower(y);
validateConnection(x, y);
letters[x - 'a'] = y;
letters[y - 'a'] = x;
lastConnections.push({x, y});
connections++;
}
void Plugboard::reset() {
for(char i='a'; i<='z'; i++) {
letters[i - 'a'] = i;
}
connections = 0;
while(!lastConnections.empty()) lastConnections.pop();
}
void Plugboard::undoConnection() {
if(lastConnections.empty()) return;
pair<char,char> p = lastConnections.top();
letters[p.first - 'a'] = p.first;
letters[p.second - 'a'] = p.second;
lastConnections.pop();
connections--;
}
void Plugboard::swap(char &x) const {
if(isalpha(x)) {
x = letters[tolower(x) - 'a'];
}
}
void Plugboard::validateConnection(char x, char y) const {
string currentPair = string(1, x) + string(1, y);
if(!isalpha(x) || !isalpha(y)) {
throw invalid_argument("Invalid plugboard configuration: '" + currentPair + "' has non-alphabetic characters.");
}
if(x == y) {
throw invalid_argument("Invalid plugboard configuration: '" + currentPair + "' can not connect the same letter.");
}
if(letters[x-'a'] != x || letters[y-'a'] != y) {
throw invalid_argument("Invalid plugboard configuration: '" + currentPair + "' already have connected letters.");
}
}