# xsolo0's solution

## to Rail Fence Cipher in the Java Track

Published at Dec 12 2018 · 0 comments
Instructions
Test suite
Solution

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.stream.Collectors;
import java.util.stream.IntStream;

public class RailFenceCipher {

private int height;
private int cycle;

public RailFenceCipher(int i) {
height = i;
cycle = 2 * (height - 1);
}

public String getEncryptedData(String text) {
ArrayList<StringBuilder> arrays = new ArrayList<>() {{
IntStream.range(0, height).forEach(n -> add(new StringBuilder()));
}};

int level = 0;
boolean down = true;
for (char c : text.toCharArray()) {
if (down && level == height) {
down = false;
level -= 2;
}

if (!down && level == -1) {
down = true;
level += 2;
}
arrays.get(level).append(c);
if (down) {
level++;
} else {
level--;
}
}
return arrays.stream().map(StringBuilder::toString).collect(Collectors.joining());
}

public String getDecryptedData(String cipher) {
int len = cipher.length();
int nCycles = len / cycle;
int nTop = nCycles + (len % cycle == 0 ? 0 : 1);

char[] result = new char[len];

// the cipher string position tracker
var ref = new Object() {
int index = 0;
};

for (int level = 0; level < height; level++) {
int range = nCycles + ((len % cycle - 1) == level ? 1 : 0);
if (level == 0) {
// TOP LEVEL
IntStream.range(0, nTop).forEach(pos -> result[pos * cycle] = cipher.charAt(ref.index++));
} else if (level == height - 1) {
// BOTTOM
int pos = height - 1;
IntStream.range(0, range).forEach(n -> result[pos + n * cycle] = cipher.charAt(ref.index++));

} else {
// from the middle +/-
int shift = height - 1 - level % cycle;
IntStream.range(0, range).forEach(n -> {
int pos = height - 1 + n * cycle;
result[pos - shift] = cipher.charAt(ref.index++);

if (pos + shift < len) {
result[pos + shift] = cipher.charAt(ref.index++);
}

});
}
}

return new String(result);
}
}``````