java代写 | 算法代写 | 数据结构代写 – Project 1: The Enigma

java代写 | 算法代写 | 数据结构代写 – 这是一个利用java进行的典型的数据结构的题目,该题目需要背景知识深厚,难度系数很高

Project 1: The Enigma

Introduction

This programming assignment is intended to exercise a few useful datastructures and an object-based view of a programming problem. There is somebackground reading, but the necessary program is not (or rather need not be)terribly big. The video walkthrough is located here.

We will be grading largely on whether you manage to get yourprogram to work (according to our tests). In addition, we willbe looking at your own tests (which you should be sure to turn in as well).While we have supplied a few unit tests and some simple integration tests andtesting utilities, the tests in skeleton are entirely inadequate for testingyour program. There is also a stylistic component: the submission andgrading machinery require that your program pass a mechanized stylecheck (style61b), which mainly checks for formatting and thepresence of comments in the proper places. See the course websitefor a brief description of the style rules. You may change any of the code we’veprovided, as long as theresulting program works according to the specifications here.

To obtain the skeleton files (and set up an initial entry for yourproject in the repository), you can use the command sequence

git fetch sharedgit merge shared/proj1 -m "Get proj1 skeleton"

from your Git working directory. Should we update the skeleton, you can useexactly the same sequence to update your project with the same changes.

Background

You may have heard of the Enigma machines that Germany used duringWorld War II to encrypt its military communications.If you have not, I recommend you read thewikipedia page on them, or similar resource,especially the part about design and operation.This projectinvolves building a simulator for a generalized version of thismachine (which itself had several different versions.)Your program will take descriptions of possibleinitial configurations of the machine and messages to encode or decode(the Enigma algorithms were reciprocal, meaning thatencryption is its own inverse operation.)

The Enigmas effect a substitution cipher on the letters of amessage. That is, at any given time, the machine performs apermutation—a one-to-one mapping—of the alphabet onto itself.The alphabet consists solely of the 26 letters in one case(there were various conventions for spaces and punctuation).

Plain substitution ciphers are easy to break (you’ve probably seenpuzzles in newspapers that consist of breaking such ciphers). TheEnigma, however, implements a progressive substitution, differentfor each subsequent letter of the message. This made decryptionconsiderably more difficult.

The device consists of a simple mechanicalsystem of (partially) interchangeable rotors (Walzen) thatsit side-by-side on ashaft and make electrical contact with each other.Most of these rotors have26 contacts on both sides, which are wired together internally so asto effect a permutationof signals coming in from one side onto thecontacts on the other (and the inverse permutation when going in thereverse direction). To the left of the rotors, one could selectone of a set of reflectors (Umkehrwalzen), with contacts on theirright sides only, and wired to connecthalf of those contacts to the other half.A signal starting fromthe rightmost rotor enters through one of the 26 possible contacts, flows through wiresin therotors, “bounces” off the reflector, and then comes back through thesame rotors (in reverse) by a different route, always ending up being permuted to aletter position different from where it started. (This was a significantcryptographic weakness, as it turned out. It doesn’t really do awould-be code-breaker any good to know that some letters in anencrypted message might be the same as the those in the plaintext if hedoesn’t know which ones. But it does a great deal of good to be ableto eliminate possible decryptions because some of their lettersare the same as in the plaintext.)

Each rotor and each reflectorimplements a different permutation, and the overall effectdepends on their configuration: which rotors and reflector are used,what order they areplaced in the machine, and which rotational position they areinitially set to.This configuration is the first part of the secret key used toencrypt or decrypt a message.In what follows, we’ll refer to the selected rotors in a machine’sconfiguration as 1 through N, with 1 being the reflector, and Nthe rightmost rotor. In our simulator, N will be a configuration parameter.In actual Enigma machines, it was fixed for any given model (the Navy usedfour and the Wehrmacht used three.)

The overall permutation changes with each successive letter because someof the rotors rotate after encrypting a letter.Each rotor has a circular ratchet on its right side andan “alphabet ring” (Ringstellung) on its left side that fits over theratchet of the rotor to its left.Before a letter of a message is translated, a spring-loadedpawl (lever)—one to the rightof each rotating rotor—triesto engage the ratchet on the right side of itsrotor and thus rotate its rotor by one position,changing the permutation performed by the rotor.Thus, pawls always try to engage with the ratchet of their own rotor.The lever on therightmost rotor (N) always succeeds, so that rotor N (the “fast” rotor)rotates one position before each character. The pawls pushingthe other rotors, however, are normally blocked fromengaging their rotors by the alphabet ring on the left side of the rotor totheir right.

This ring usually holds the pawl away from its own ratchet,preventing the rotor wheel to its left from moving.However, the rings have notches in them (either one or two in theoriginal Enigma machines), and when the pawl ispositioned over a notch in the ring for the rotor to its right,it slips through to its own rotor and pushes it forward.A “feature” of the design called “double stepping” (corrected in otherversions of the Enigma, since it reduced the period of the cipher)is that when a pawl is in a notch, it also moves the notch itself and therotor the notch is connected to. Since the notch for rotor i

i

is connected to rotor i

i

,when the pawl of rotor i1

i1

slips through into the notch for rotor i

i

, rotorson both sides of the pawl move (so rotor i1

i1

and rotor i

i

move).

Let’s illustrate with a much simplified version. Suppose our alphabet hasonly the letters A-C and we have four rotors (numbered 1-4) each of which hasone notch on its ring at the C position. Suppose also that there are 3pawls, one for each of rotors 2-4. We will still refer to these as pawls 2-4,to maintain that pawl i

i

belongs to rotor i

i

. There is no pawl forrotor 1, which will therefore not rotate.We’ll start with the rotors set atAAAA. The next 19 positions are as follows:

AAAB  AAAC  AABA  AABB  AABC  AACA  ABAB  ABACABBA  ABBB  ABBC  ABCA  ACAB  ACAC  ACBA  ACBBACBC  ACCA  AAAB

As you can see,

  • Rotor 4, the fast rotor, advances each time, pushed by pawl 4. Rotor 4 has no rotor to its right, so there isn’t a ring blocking it from engaging with its ratchet.
  • Rotor 3 advances whenever Rotor 4 is at C. Rotor 4 has a notch at C, so pawl 3 can engage with the corresponding ratchet (the ratchet belonging to Rotor 3) and advance Rotor 3 by pushing on its ratchet. This would also rotate Rotor 4, since pawl 3 contacts its ratchet through the notch of Rotor 4, and therefore pushes the side of the notch when it moves. However, since Rotor 4 always rotates anyway (because pawl 4 is always unblocked), this doesn’t really change anything.
  • Rotor 2 advances whenever Rotor 3 is at C, pushed by pawl 2. Rotor 3 has a notch at C, so pawl 2 slips into the notch and engages with its ratchet (the ratchet belonging to Rotor 2). Rotor 3 also advances when it is at C, because when pawl 2 is engaged through Rotor 3’s notch it will push against that notch when it moves, moving Rotor 3, as well as moving Rotor 2 by pushing on Rotor 2’s ratchet.
  • There is no pawl 1, so Rotor 2 (unlike Rotor 3) does not advance just because it is at C.
  • Rotor 1 never changes, since there is no pawl on either side of it.

Each rotor can only advance at most one position per keypress.

So the advancement of the rotors, while similar to that of the wheels of anodometer, is not quite the same. If it were, then the next position afterAACA would be AACB, rather than ABAB.

The effect of advancing a wheel is to change where on the wheelany given signal enters or leaves. When a wheel is in its ‘A’ settingin the machine, then a signal that arrives from the right at, say,the ‘C’ position,goes into the ‘C’ contact on the wheel. Likewise, a signal that leavesthe wheel from its left ‘C’ contact exits at the ‘C’ position. When thewheel is rotated by one to its ‘B’ setting, a signal that arrives atthe ‘C’ position goes instead into the ‘D’ contact on the wheel, and asignal that leaves through the ‘D’ contact does so at the ‘C’position. It’s easier to calculate if we use numbers 0–25 rather thanletters (‘A’ is 0, ‘B’ is 1, etc.). Then, when the wheel is in itsk

k

setting, a signal entering at the p

p

position enters the p+kmod26

p+kmod26

contact on the wheel, and a signal exiting through the c

c

contact does so at the ckmod26

ckmod26

position.For example,Figure 1 shows one of the rotors from the real Enigma machines (calledrotor “I”) and the effect of moving from its ‘A’ to its ‘B’ setting.

Figure 1. Permutations performed by a rotor in its ‘A’ and ‘B’settings. The italicized alphabets at the top and bottom indicate the letterscorresponding to the positions around the rotor. The inner alphabetsindicate the positions along the rotor itself. The rotor depicted wasdesignated ‘I’ in the original Enigma machine used by the German military.

Thecontacts on the rightmost rotor’s right side connect with stationaryinput and output contacts, which run to keys that, when pressed, directcurrent to the contact from a battery or, when not pressed, directcurrent back from the contact to a light bulb indicating a letter of thealphabet. Since a letter never encrypts or decrypts to itself aftergoing back and forth through the rotors, theto and from directions never conflict.

The German Navy used a machine with 12 rotors and five slots for them:

  • Eight rotors labeled with roman numerals I–VIII, of which three will be used in any given configuration as the rightmost rotors,
  • Two additional non-moving rotors (Zusatzwalzen) labeled “Beta” and “Gamma”, of which one will be used in any configuration, as the fourth-from-right rotor, and
  • Two reflectors (Umkehrwalzen), labeled ‘B’ and ‘C’, of which one will be used in any given configuration as the leftmost rotor.

Given just this equipment, there are 614,175,744 possible configurations (orkeys):

  • Two possible reflectors, times
  • Two possible rotors in the fourth position, times
  • 8!/(83)!=336

    8!/(83)!=336

    choices for the rightmost three rotors and their ordering, times

  • 264

    264

    possible initial rotational settings for the rightmost four rotors (each reflector had only one possible position.).

Especially by today’s standards, this is not a large keysize (less than 30 bits). To make things more difficult for code-breakers,therefore, the Enigma incorporated a plugboard (Steckerbrett) betweenthe keyboard and the rightmost wheel. It acted as a non-moving, configurablerotor. The operator could choose any set of disjoint pairs of letters by meansof cables placed between them on the plugboard. Each selected pair would then beswapped going into the machine from the keyboard and coming out into theindicator lights. Thus, if the operator connected (“steckered”) the lettersA and P, then P would be substituted for each A typed and vice versa. Likewise,if an ingoing letter was encrypted to P by the other rotors, it would displayas A, and letters decrypted as A would display as P.

Describing Permutations

Since the rotors and the plugboard implement permutations, we’ll need astandard way to describe them. We could simply have a table showing eachletter and what it maps to, but we’ll use a more compact notationknown as cycle representation. The idea is that any permutation of a set maybe described as a set of cyclic permutations. For example, the notation

(AELTPHQXRU) (BKNW) (CMOY) (DFG) (IV) (JZ) (S)

describes the permutation in Figure 1. It describes seven cycles:

  • A maps to E, E to L, L to T, …, R to U, and U back to A.
  • B maps to K, K to N, N to W, and W back to B.
  • C maps to M, M to O, O to Y, and Y back to C.
  • D maps to F, F to G, and G back to D.
  • I maps to V and V back to I.
  • J maps to Z and Z back to J.
  • S maps to itself.

The inverse permutation just reverses these cycles:

  • U maps to R, R to X, …, E to A, and A back to U.
  • S maps to itself.

Each letter appears in one and only one cycle, so the mapping is unambiguous.As a shorthand, we’ll say that if a letter is left out of all cycles, it mapsto itself (so that we could have left off “(S)” In the example above.)

Figure 2 shows the permutations corresponding to therotors used in the German Navy’s Enigma machine.

Rotor Permutation (as cycles) Notch
Rotor I (AELTPHQXRU) (BKNW) (CMOY) (DFG) (IV) (JZ) (S) Q
Rotor II (FIXVYOMW) (CDKLHUP) (ESZ) (BJ) (GR) (NT) (A) (Q) E
Rotor III (ABDHPEJT) (CFLVMZOYQIRWUKXSG) (N) V
Rotor IV (AEPLIYWCOXMRFZBSTGJQNH) (DV) (KU) J
Rotor V (AVOLDRWFIUQ)(BZKSMNHYC) (EGTJPX) Z
Rotor VI (AJQDVLEOZWIYTS) (CGMNHFUX) (BPRK) Z and M
Rotor VII (ANOUPFRIMBZTLWKSVEGCJYDHXQ) Z and M
Rotor VIII (AFLSETWUNDHOZVICQ) (BKJ) (GXY) (MPR) Z and M
Rotor Beta (ALBEVFCYODJWUGNMQTZSKPR) (HIX)
Rotor Gamma (AFNIRLBSQWVXGUZDKMTPCOYJHE)
Reflector B (AE) (BN) (CK) (DQ) (FU) (GY) (HW) (IJ) (LO) (MP) (RX) (SZ) (TV)
Reflector C (AR) (BD) (CO) (EJ) (FN) (GT) (HK) (IV) (LM) (PW) (QZ) (SX) (UY)

Figure 2. The rotors used in the Naval Enigma, showing the permutations they> implement and the point(s) at which there are notches that allow theirleft neighbor rotor to advance. Thus, when Rotor I is at ‘Q’ and themachine advances, the rotor to the left of Rotor I will advance. TheBeta and Gamma rotors and the reflectors do not rotate. Thereflectors shown here are the “thin” versions of the reflectors usedin the naval M4 Enigma machine. The B reflector together with theBeta rotor in the ‘A’ position had the same effect as the usual(“thick”) B reflector in the older three-rotor M3 Enigma machine(likewise the C reflector with the Gamma rotor). This allowed the M4to encrypt and decrypt messages to and from M3 Enigmas. Source:Tony Sale’s pages.

Example

As an example of a translation, consider the set of rotors fromFigure 2, and suppose that

  • The rotors in positions 1–5 are, respectively, B, Beta, III, IV, and I.
  • The rotors in positions 2–5 are currently at positions A, X, L, E, respectively.
  • In the plugboard, the letter pair ‘Y’ and ‘F’ and the letter pair ‘Z’ and ‘H’ are both interchanged.

We input the letter ‘Y’, which causes the following steps:

  1. The pawls all move. This causes rotor 5 to advance from E to F. The other two pawls are not over notches, so rotors 3 and 4 do not move.
  2. The letter ‘Y’ enters the plugboard and is converted to ‘F’.
  3. The letter ‘F’ enters the right side of rotor 5 (an I rotor) at position 5, since ‘F’ is the 5th letter of the alphabet numbering from 0. Since the current setting of rotor 5 is ‘F’, the signal enters the rotor at position 5

    5

    , but hits contact 5+5=10

    5+5=10

    , or ‘K’.

  4. According to Figure 2, rotor I converts ‘K’ to ‘N’ (letter number 13). Because the setting of rotor I is ‘F’, however, the signal actually comes out at letter position 135=8

    135=8

    (‘I’).

  5. The ‘I’ signal from rotor 5 now goes into the right side of rotor 4. Since rotor 4 is a IV rotor and is in the ‘L’ (or 11) setting, the ‘I’ enters at contact 8+11=19

    8+11=19

    (‘T’), and is translated to ‘G’ (6), which comes out at position 611=5=21mod26

    611=5=21mod26

    , the fifth letter from the end of the alphabet (‘V’).

  6. The ‘V’ from rotor 4 goes now to the right side of rotor 3, a III rotor in setting ‘X’ (23). The signal enters the rotor at contact 21+23=44=18mod26

    21+23=44=18mod26

    (‘S’), is translated to ‘G’ (6), which exits at position 623=17=9mod26

    623=17=9mod26

    (‘J’).

  7. Rotor 2 (Beta) is in position ‘A’, and thus translates ‘J’ to ‘W’.
  8. Rotor 1 (B) converts the ‘W’ to ‘H’ and bounces it back to the left side of rotor 2.
  9. Rotor 2 (Beta in the ‘A’ position) converts ‘H’ on its left to ‘X’ (23) on its right.
  10. The ‘X’ from rotor 2 now goes into the 23+23=46=20mod26

    23+23=46=20mod26

    (‘U’) contact on the left side of rotor 3 (III in setting’X’), and is converted to ‘W’ (22), which comes out at position 2223=1=25mod26

    2223=1=25mod26

    (‘Z’) on the right side of rotor 3.

  11. ‘Z’ now enters the left side of rotor 4 (IV in setting ‘L’) at 25+11=36=10mod26

    25+11=36=10mod26

    (‘K’), and is translated to ‘U’ (20), which comes out at position 2011=9

    2011=9

    (‘J’) on the right side of rotor 4.

  12. The ‘J’ from rotor 4 enters the left side of rotor 5 (I at setting ‘F’) at contact 9+5=14

    9+5=14

    (‘O’), is translated to ‘M’ (12), and comes out at position 125=7

    125=7

    (‘H’) on the right side of rotor 5.

  13. Finally,the letter ‘H’ is converted to ‘Z’ by the plugboard.

Therefore, ‘Y’ is converted to ‘Z’.

After a total of 12 characters are converted, the rotor settings willhave become ‘AXLQ’. Just before the next character is converted,rotor 5 will advance to ‘R’ and, since its notch is at position ‘Q’,rotor 4 will advance to ‘M’, so that the rotor configuration will be’AXMR’ before the 13th character is converted. After an additional597 characters have been converted, the configuration will be’AXIQ’. The character after that will advance rotor 5 to ‘R’ androtor 4 to ‘J’, giving ‘AXJR’. The next character will advance 5 to’S’,and, since rotor IV’s notch is at ‘J’, rotor 3 will advance to ‘Y’.Also, as rotor 3’s pawl advances rotor 3, it also moves the notch onrotor 4, advancing rotor 4 to ‘K’, so that the configuration goes from’AXJR’ to ‘AYKS’. Rotor 3 in this case has a notch at ‘V’, but sincerotor 2 has no pawl, rotor 3’s notch never has any effect.

Input and Output

To run your program on the command line, first compile all of your files with

    javac -g -Xlint:unchecked enigma/*.java

or, if you have it, just use

    make

After compiling, you can use the command

    java -ea enigma.Main [configuration file] [input file] [output file]

to run your program.The configuration file contains descriptions of the machine and theavailable rotors. The data are in free format. That is, they consist ofstrings of non-whitespace characters separated by arbitrary whitespace (spaces,tabs, and newlines), so that indentation, spacing, and line breaksare irrelevant. Each file has the following contents:

  • A string of the form C1

    C1

    -C2

    C2

    where C1

    C1

    and C2

    C2

    are non-blank characters other than “-“, “(“, and “)“, with C1C2

    C1C2

    . This specifies that the alphabet consists of characters C1

    C1

    and C2

    C2

    , with lower-case letters mapped to upper-case.
    Unless you do the extra credit, C1

    C1

    and C2

    C2

    will always be upper-case letters.

  • Two integer numerals, S>P0

    S>P0

    , where S

    S

    is the number of rotor slots (including the reflector) and P

    P

    is the number of pawls—that is, the number of rotors that move. The moving rotors and their pawls are all to the right of any non-moving ones.

  • Any number of rotor descriptors. Each has the following components (separated by whitespace):

    • A name containing any non-blank characters other than parentheses.
    • One of the characters R, N, or M, indicating that the rotor is a reflector, a non-moving rotor, or a moving rotor, respectively. Non-moving rotors can only be used in positions 2

      2

      through SP

      SP

      and moving rotors in positions SP+1

      SP+1

      through S

      S

      .

    • Immediately after the M for a moving rotor come(s) the letter(s) at which there is a notch on the rotor’s ring (no space between M and these letters).
    • The cycles of the permutation, using the notation discussed above.

For example, the German Naval Enigma machine might be described withthis configuration file (see Figure 2):

          A-Z          5 3          I MQ      (AELTPHQXRU) (BKNW) (CMOY) (DFG) (IV) (JZ) (S)          II ME     (FIXVYOMW) (CDKLHUP) (ESZ) (BJ) (GR) (NT) (A) (Q)          III MV    (ABDHPEJT) (CFLVMZOYQIRWUKXSG) (N)          IV MJ     (AEPLIYWCOXMRFZBSTGJQNH) (DV) (KU)          V MZ      (AVOLDRWFIUQ)(BZKSMNHYC) (EGTJPX)          VI MZM    (AJQDVLEOZWIYTS) (CGMNHFUX) (BPRK)          VII MZM   (ANOUPFRIMBZTLWKSVEGCJYDHXQ)          VIII MZM  (AFLSETWUNDHOZVICQ) (BKJ) (GXY) (MPR)          Beta N    (ALBEVFCYODJWUGNMQTZSKPR) (HIX)          Gamma N   (AFNIRLBSQWVXGUZDKMTPCOYJHE)          B R       (AE) (BN) (CK) (DQ) (FU) (GY) (HW) (IJ) (LO) (MP)                    (RX) (SZ) (TV)          C R       (AR) (BD) (CO) (EJ) (FN) (GT) (HK) (IV) (LM) (PW)                    (QZ) (SX) (UY)

The input file to your program will consist of a sequence of messages todecode, each preceded by a line giving the initial settings.Given the configuration file above, a settings line looks like this:

* B BETA III IV I AXLE (YF) (ZH)

(all upper case.)This particular example means that the rotors used are reflector B,and rotors Beta, III, IV, and I, with rotor I in the rightmost, or fast,slot. The remaining parenthesized items indicate that the letter pairY and F and the pair Z and M are steckered (swapped going in fromthe keyboard and going out to the lights).

In general for this particular configuration,rotor 1 is always the reflector; rotor 2 is Beta orGamma, and each of 3-5is one of rotors I-VIII. A rotor may not be repeated. The four lettersof the following word (AXLE in the example)give the initial positions of rotors 2-5,respectively (i.e., not including the reflector). Any number of steckered pairsmay follow (including none).

After each settings line comes a message on any number of lines.Each line of a messageconsists only of letters, spaces, and tabs (0 or more).The program should ignore the blanks and tabs and convert allletters to upper case. The end of message is indicated either by theend of the input or by a new configuration line (distinguished by itsleading asterisk).The machine is not reset between lines, but continues stepping fromwhere it left off on the previous message line.Because the Enigma is a reciprocal cipher, a given translation mayeither be a decryption or encryption; you don’t have to worry aboutwhich, since the process is the same in any case.

Output the translation for each message linein groups of five upper-case letters, separatedby a space (the last group may have fewer characters, depending on themessage length). Figure 3 contains an examplethat shows an encryption followed by a decryptionof the encrypted message. Since we have yet to cover the details ofFile I/O, you will be provided the File IO machinery for this project.

             Input                              |         Output* B BETA III IV I AXLE (HQ) (EX) (IP) (TR) (BY) | QVPQS OKOIL PUBKJ ZPISF XDWFROM his shoulder Hiawatha                      | BHCNS CXNUO AATZX SRCFY DGUTook the camera of rosewood                     | FLPNX GXIXT YJUJR CAUGE UNCFM KUFMade of sliding folding rosewood                | WJFGK CIIRG XODJG VCGPQ OHNeatly put it all together                      | ALWEB UHTZM OXIIV XUEFP RPRIn its case it lay compactly                    | KCGVP FPYKI KITLB URVGT SFUFolded into nearly nothing                      | SMBNK FRIIM PDOFJ VTTUG RZMBut he opened out the hinges                    | UVCYL FDZPG IBXRE WXUEB ZQJOPushed and pulled the joints                    | YMHIP GRRE   and hinges                                   | GOHET UXDTW LCMMW AVNVJ VHTill it looked all squares                      | OUFAN TQACK   and oblongs                                  | KTOZZ RDABQ NNVPO IEFQA FSLike a complicated figure                       | VVICV UDUER EYNPF FMNBJ VGQin the Second Book of Euclid                    |                                                | FROMH ISSHO ULDER HIAWA THA* B BETA III IV I AXLE (HQ) (EX) (IP) (TR) (BY) | TOOKT HECAM ERAOF ROSEW OODQVPQS OKOIL PUBKJ ZPISF XDW                     | MADEO FSLID INGFO LDING ROSEW OODBHCNS CXNUO AATZX SRCFY DGU                     | NEATL YPUTI TALLT OGETH ERFLPNX GXIXT YJUJR CAUGE UNCFM KUF               | INITS CASEI TLAYC OMPAC TLYWJFGK CIIRG XODJG VCGPQ OH                      | FOLDE DINTO NEARL YNOTH INGALWEB UHTZM OXIIV XUEFP RPR                     | BUTHE OPENE DOUTT HEHIN GESKCGVP FPYKI KITLB URVGT SFU                     | PUSHE DANDP ULLED THEJO INTSSMBNK FRIIM PDOFJ VTTUG RZM                     | ANDHI NGESUVCYL FDZPG IBXRE WXUEB ZQJO                    | TILLI TLOOK EDALL SQUAR ESYMHIP GRRE                                      | ANDOB LONGSGOHET UXDTW LCMMW AVNVJ VH                      | LIKEA COMPL ICATE DFIGU REOUFAN TQACK                                     | INTHE SECON DBOOK OFEUC LIDKTOZZ RDABQ NNVPO IEFQA FS                      |VVICV UDUER EYNPF FMNBJ VGQ                     |

Figure 3. Sample input and output (using the Naval cipher).

Handling Errors

You can see a number of opportunities for input errors:

  • The configuration file may have the wrong format.
  • The input might not start with a setting.
  • The setting line can contain the wrong number of arguments.
  • The rotors might be misnamed.
  • A rotor might be repeated in the setting line.
  • The first rotor might not be a reflector.
  • The initial positions string might be the wrong length or contain characters not in the alphabet.

A significant amount of a program will typically be devoted todetecting such errors, and taking corrective action. In our case, themain program is set up in such a way that theonly corrective action needed is to throw an EnigmaExceptionwith an explanatory message.The existing code in the main program will catch this exception,print its message, and exit with a standard Unix error indication.The skeleton supplies a simple static utility method, error, whichprovides a convenient way to create error exceptions. There are examples of itsuse in the skeleton.

Testing

The directory testing contains the scripts test-correct and test-errorfor testing the execution of enigma.Main.

  • bash test-correct F1.inp F2.inp … will run the program for each of the message files F1.inp, F2.inp …, comparing the results to the corresponding output files F1.out, F2.out, …. The configuration files used are F1.conf, F2.conf, …. However, if any of these is missing, the file default.conf (from the same directory as the input file) is used instead.
  • bash test-error F1.inp F2.inp … will run the program for each of the message files F1.inp, F2.inp …, checking that the program reports at least one error in each case. The configuration files are as for test-correct.

This needs to be run in your proj1 directory, with paths to test-correctand input files. For example:

bash testing/test-correct testing/correct/trivial1.inp

The tests we’ve supplied are nowhere near adequate to test your program, so youwill need to generate your own integration tests as well as unit tests (we will checkto see that you make an effort to test).

Extra Credit

If you feel up to it, consider extending your program to work on more generalalphabets. To specify an arbitrary alphabet, the first stringin the configuration will be allowed to have the form C1C2C3Cn

C1C2C3Cn

,where the Ci

Ci

are non-whitespace characters,not including lower-case letters, orthe special characters “(“, “)“, “-“, or “*“.The standard C1

C1

-C2

C2

notation should continue to work, so that forexample, A-Z is equivalent to ABCDEFGHIJKLMNOPQRSTUVWXYZ.

The effect of the more general specification is to specify the character set andthe ordering of the characters along the rotors. For example, an alphabetspecification of ACEDB means that the only characters in the alphabet areAE, with A at the 0 position on each rotor, C at the 1 position, etc.

Office Hours

For office hours debugging, we will stick to the following norms.

  • Course staff will spend at most ~10 minutes per student.
  • You must provide a useful description of your question, or the staff may choose to help another person on the queue that does have one. Please preface your question with one of the following 4 sections of the project – Permutations, Rotors, Machine, Main.
  • Your code must be well documented, including all methods you write, according to the style guide. This is to minimize time spent verbally explaining what each method does.
  • Your code must be well organized and explainable. It is not a good use of your time or the TAs’ time to try to find bugs in something that is disorganized and brittle. When we do provide debugging help, it may be at a high level, where we suggest ways to reorganize your code in order to make clarity and debugging easier.
  • If your question is for debugging help, you must be prepared to explain the error that is being caused and have a test or input that can easily reproduce the bug for ease of debugging. If you come to us saying something does not work, but have not written any tests or attempted to use the debugger, we will not help you. Saying “I am failing test X” is not an explanation of the error that is being caused. Where is it happening? What is the type of error? What led up to this?
  • We will attempt to group students in office hours to reduce queue time. This means you should talk to your surrounding neighbors and discuss possible approaches to each other’s bugs. You may not get 1-on-1 debugging help at peak office hours times, but a high level plan of attack to identify and narrow down the causes of your bug.

Checkpoint

By Wednesday, October 3, (10/3) you must have completed the following in order to receive 2 points of extra credit.

  1. Completed this conceptual quiz. Note – you do not need to answer all questions correctly to receive full points, but you should understand all of the correct answers by the time you start coding. Feel free to ask any questions you have about the quiz in office hours, but please refrain from revealing answers on Piazza.
  2. Have made some changes to the Permutations and Rotors parts of the project. This involves significant edits being made in the following files: – Permutations.javaRotor.javaMovingRotor.javaReflector.javaFixedRotor.java
  3. All of your code compiles.

What To Turn In

  1. You should commit and push your completed project with the commit you want graded tagged and tags pushed. Your submission should contain no debugging print statements upon submission.
  2. Your program must pass the style checker with 0 errors. This includes adequately commenting all methods.
  3. You should have added adequate unit tests, both for the provided methods and any additional methods you write. We say “adequate” because the amount may change depending on how many additional methods you write or how rigorous each test is. You will know if your test suite is adequate.
  4. You should have added additional integration tests beyond those provided in the skeleton. Again, the exact number is not specified, but we recommend having enough that you feel confident that passing them means your program is correct.

Advice

First, get started immediately, of course. Don’t just jump in andcode, though. Make sure you understand the specifications(which have their subtleties) andplan out how you’re going to meet them. Read the skeleton code and understand the design.Figure out how to break thisproblem down into small pieces, and how to implement and test them onepiece at a time. Know in detail how you’re going to do somethingbefore writing a line of Java code for it. In particular, take sometime to understand how the rotors work, and especially how the rotorposition modifies the permutation.

Don’t allow things to remain mysterious to you, or they’ll surely biteyou at some point. You don’t have to use any of the skeletoncode we’ve provided as long as the command java enigma.Mainworks as specified. However, if you find yourself throwing somethingaway because you don’t understand it, STOP! You’re allowingyourself to be mystified by something that is intended to be simple.

There is a fair amount of string-hacking involved.The Java library can help you. Look at the documentation ofString, HashMap, ArrayList, and Scannerin the on-line Java library documentation.We particularly invite you to consider the constructors and the methods

From String From ArrayList From HashMap From Scanner
charAt add get next
replaceAll get put nextInt
split size hasNext()
startsWith hasNext(…)
substring nextLine
toUpper
trim
indexOf

Be creatively lazy. Feel free to browse the Java library for usefulstuff, even if you haven’t seen it in class.If you find yourself writing:

if (rotor.equals("I") {    if (c == 'A')        e = 'E';    else if (c == 'B')        e = 'K';    ...}

or something equally hideous, STOP! you are doing something wrong!

You can write JUnit tests and integration tests (see the testing directory)before you write aline of code.Be particularly careful to include tests that at one point caused yourprogram to fail (regression tests) so that you can be sure youdon’t backslide when you make further changes. There’s no reason youcan’t have tests that you fail, by the way; they’ll serve to remindyou of things you still need to do.

Use the git repository. Frequently commit your work so that you’ll neverhave to reconstruct too much if your files somehow vanishmysteriously.

Above all, it is always fair to ask for help and advice. We don’tever want to hear about how you’ve been beating your headagainst the wall over some problem for hours. If you can’t makeprogress, don’t waste your time guessing or bleeding: ask. Ifnobody’s available to ask, do something else (or get some sleep).

A Plan of Attack some TAs found useful was

  • Write tests for permutations, then all code for Permutations.
  • Write tests for rotors, then all code for the various Rotor classes, going from least specific to most.
  • Write code for Machine, creating tests as you account for various edge cases or error cases while coding.
  • Finally, finish Main, again adding tests for various edge cases as you go.

Common Bugs

  1. % in Java is remainder, and has different behavior than you might expect with negative numbers. Please see the provided method wrap for modular conversions, or see what the body of wrap does and replicate this if you prefer to use your own methods.
</main>

发表评论

电子邮件地址不会被公开。 必填项已用*标注