Re: Any way to make this code more compact, and/or be able to change at runtime?
"Protoman" <Protoman2050@gmail.com> wrote in message
news:1183431632.634841.99550@e9g2000prf.googlegroups.com...
I've written this program that simulates a 36 character, 10 rotor
reciprocal rotor cipher, w/ a plugboard. Any way I can make the
plugboard function more compact and/or be able to change the mapping
at runtime?
char Enigma::plugboard(char Char)
{
if(Char=='A')
return '0';
else if(Char=='B')
return 'Q';
else if(Char=='C')
return 'W';
else if(Char=='D')
return 'E';
else if(Char=='E')
return 'D';
else if(Char=='F')
return 'T';
else if(Char=='G')
return 'Y';
else if(Char=='H')
return 'U';
else if(Char=='I')
return 'I';
else if(Char=='J')
return 'O';
else if(Char=='K')
return 'P';
else if(Char=='L')
return 'S';
else if(Char=='M')
return 'N';
else if(Char=='N')
return 'M';
else if(Char=='O')
return 'J';
else if(Char=='P')
return 'K';
else if(Char=='Q')
return 'B';
else if(Char=='R')
return 'Z';
else if(Char=='S')
return 'L';
else if(Char=='T')
return 'F';
else if(Char=='U')
return 'H';
else if(Char=='V')
return 'X';
else if(Char=='W')
return 'C';
else if(Char=='X')
return 'V';
else if(Char=='Y')
return 'G';
else if(Char=='Z')
return 'R';
else if(Char=='0')
return 'A';
else if(Char=='1')
return '9';
else if(Char=='2')
return '8';
else if(Char=='3')
return '7';
else if(Char=='4')
return '6';
else if(Char=='5')
return '5';
else if(Char=='6')
return '4';
else if(Char=='7')
return '3';
else if(Char=='8')
return '2';
else if(Char=='9')
return '1';
}
If you need any more info, just ask and I'll produce it. Thanks!!!!
I can think of a few ways to do it more compact. a std::map would be one
way, although you'd still have to add the members to the map. I think it
depends on what is your primary concern, speed of execution or
maintanability. One simple thing, however, is that you only have the
letters 'A' through 'Z' and the digits '0' through '9'.
Consider something like the following (untested bug ridden) code:
char Enigma::plugboard(char Char)
{
char Vallues* = "0QWEDTYU'I'OPSNMJKBZLFHXCVGRA987654321"
if ( Char >= 'A' && Char <= 'Z' )
return Values[Char - 'A'];
else if ( Char >= '0' && Char <= '0' )
return Values[ 26 + Char - '0' ];
else
return 0;
)
However, this will only work on platforms where 'A' through 'Z' and '0'
through '9' are contiguous (ASCII, wouldn't work in EBSIDIC (sp?) ).
You can also create an array to find the postion:
char Characters* = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
so find the Char in Characters, get it's postion, return Values[Position];
Now, this is more compact, and you can change what Values points at (make it
array, pass in a pointer, whatever).