# trevans1's solution

## to Rail Fence Cipher in the Java Track

Published at Jul 13 2018 · 0 comments
Instructions
Test suite
Solution

#### Note:

This solution was written on an old version of Exercism. The tests below might not correspond to the solution code, and the exercise may have changed since this code was written.

Implement encoding and decoding for the rail fence cipher.

The Rail Fence cipher is a form of transposition cipher that gets its name from the way in which it's encoded. It was already used by the ancient Greeks.

In the Rail Fence cipher, the message is written downwards on successive "rails" of an imaginary fence, then moving up when we get to the bottom (like a zig-zag). Finally the message is then read off in rows.

For example, using three "rails" and the message "WE ARE DISCOVERED FLEE AT ONCE", the cipherer writes out:

``````W . . . E . . . C . . . R . . . L . . . T . . . E
. E . R . D . S . O . E . E . F . E . A . O . C .
. . A . . . I . . . V . . . D . . . E . . . N . .
``````

``````WECRLTEERDSOEEFEAOCAIVDEN
``````

To decrypt a message you take the zig-zag shape and fill the ciphertext along the rows.

``````? . . . ? . . . ? . . . ? . . . ? . . . ? . . . ?
. ? . ? . ? . ? . ? . ? . ? . ? . ? . ? . ? . ? .
. . ? . . . ? . . . ? . . . ? . . . ? . . . ? . .
``````

The first row has seven spots that can be filled with "WECRLTE".

``````W . . . E . . . C . . . R . . . L . . . T . . . E
. ? . ? . ? . ? . ? . ? . ? . ? . ? . ? . ? . ? .
. . ? . . . ? . . . ? . . . ? . . . ? . . . ? . .
``````

Now the 2nd row takes "ERDSOEEFEAOC".

``````W . . . E . . . C . . . R . . . L . . . T . . . E
. E . R . D . S . O . E . E . F . E . A . O . C .
. . ? . . . ? . . . ? . . . ? . . . ? . . . ? . .
``````

Leaving "AIVDEN" for the last row.

``````W . . . E . . . C . . . R . . . L . . . T . . . E
. E . R . D . S . O . E . E . F . E . A . O . C .
. . A . . . I . . . V . . . D . . . E . . . N . .
``````

If you now read along the zig-zag shape you can read the original message.

# Running the tests

You can run all the tests for an exercise by entering

``````\$ gradle test
``````

## Submitting Incomplete Solutions

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

### RailFenceCipherTest.java

``````import org.junit.Assert;
import org.junit.Ignore;
import org.junit.Test;

public class RailFenceCipherTest {

private RailFenceCipher railFenceCipher;

@Test
public void encodeWithTwoRails() {
railFenceCipher = new RailFenceCipher(2);
Assert.assertEquals("XXXXXXXXXOOOOOOOOO",
railFenceCipher.getEncryptedData("XOXOXOXOXOXOXOXOXO"));
}

@Ignore("Remove to run test")
@Test
public void encodeWithThreeRails() {
railFenceCipher = new RailFenceCipher(3);
Assert.assertEquals("WECRLTEERDSOEEFEAOCAIVDEN",
railFenceCipher.getEncryptedData("WEAREDISCOVEREDFLEEATONCE"));
}

@Ignore("Remove to run test")
@Test
public void encodeWithEndingInTheMiddle() {
railFenceCipher = new RailFenceCipher(4);
Assert.assertEquals("ESXIEECSR",
railFenceCipher.getEncryptedData("EXERCISES"));
}

@Ignore("Remove to run test")
@Test
public void decodeWithThreeRails() {
railFenceCipher = new RailFenceCipher(3);
Assert.assertEquals("THEDEVILISINTHEDETAILS",
railFenceCipher.getDecryptedData("TEITELHDVLSNHDTISEIIEA"));
}

@Ignore("Remove to run test")
@Test
public void decodeWithFiveRails() {
railFenceCipher = new RailFenceCipher(5);
Assert.assertEquals("EXERCISMISAWESOME",
railFenceCipher.getDecryptedData("EIEXMSMESAORIWSCE"));
}

@Ignore("Remove to run test")
@Test
public void decodeWithSixRails() {
railFenceCipher = new RailFenceCipher(6);
Assert.assertEquals("112358132134558914423337761098715972584418167651094617711286",
railFenceCipher.getDecryptedData("133714114238148966225439541018335470986172518171757571896261"));
}
}``````
``````import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

//this was an absolute nightmare.  Can't wait to see all the one-line answers to this...
public class RailFenceCipher {
int numberOfRails;
int sequenceLength; //how many characters before rail is back to 0

public RailFenceCipher(int rails){
numberOfRails = rails;
sequenceLength = 2*rails - 2;
}

//I think I could use a stream for this but this way is easier for me to process mentally
public String getEncryptedData(String input){
StringBuilder[] sba = new StringBuilder[numberOfRails]; //StringBuilder for each rail
for(int i = 0; i < numberOfRails; i++){
sba[i] = new StringBuilder();
}

//Split the string into rails
for(int i = 0; i < input.length(); i++){
if(i%sequenceLength > numberOfRails-1) { //going back up the rails
sba[sequenceLength - (i%sequenceLength)].append(input.charAt(i));
}
else { //going down the rails
sba[i%sequenceLength].append(input.charAt(i));
}
}

//concatenate the rails
for(int i = 1; i < sba.length; i++){
sba[0].append(sba[i]);
}
return sba[0].toString();
}

//processing this mentally was a challenge, period
public String getDecryptedData(String input){
int numSequences = (int)Math.ceil((double)input.length() / sequenceLength);

//char array for each sequence of characters
char[][] sequences = new char[numSequences][sequenceLength];

//split characters into sequences
int currentSequence = 0;
int currentRail = 0;
int remainingSequences = numSequences; //decrement this when the last, partial sequence is filled
boolean firstCharacter = true; //all rails except the top and bottom have 2 characters
int sequenceCounter = 0; //used to find place in sequence string
for(int i = 0; i < input.length(); i++){
//put the character in the array at the right place
if(!firstCharacter){
sequences[currentSequence][sequenceLength - sequenceCounter] = input.charAt(i);
}
else{
sequences[currentSequence][sequenceCounter] = input.charAt(i);
}

//update state
if(!firstCharacter || currentRail == 0 || currentRail == numberOfRails-1){
firstCharacter = true;

//decrement remainingSequences if necessary
if((currentSequence*sequences[0].length) + (sequenceCounter+1) >= input.length()){
remainingSequences = numSequences -1;
}
currentSequence++;
}
else {
//decrement remainingSequences if necessary
if((currentSequence*sequences[0].length) + (sequenceLength-sequenceCounter) >= input.length()){
remainingSequences = numSequences -1;
currentSequence++;
}
else {
firstCharacter = false;
}
}

//hit finished sequence, start next rail
if(currentSequence >= remainingSequences){
currentSequence = 0;
currentRail++;
sequenceCounter++;
}
}

//concatenate the sequences
StringBuilder result = new StringBuilder();
for(char[] sequence : sequences){
result.append(sequence);
}

return result.toString().trim(); //trim off the uninitialized characters
}

}``````