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 . .
Then reads off:
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.
You can run all the tests for an exercise by entering
$ gradle test
in your terminal.
Wikipedia https://en.wikipedia.org/wiki/Transposition_cipher#Rail_Fence_cipher
It's possible to submit an incomplete solution so you can see how others have completed the exercise.
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;
import java.util.stream.Collectors;
public class RailFenceCipher {
int rails;
RailFenceCipher(int rails) {
this.rails = rails;
}
private List<Integer>[] getFencePattern(int messageSize) {
@SuppressWarnings("unchecked")
List<Integer>[] pattern = new List[rails];
for (int i = 0; i < pattern.length; i++) {
pattern[i] = new ArrayList<Integer>();
}
int row = 0;
int rowOffset = 1;
for (int col = 0; col < messageSize; col++) {
pattern[row].add(col);
row += rowOffset;
if (!(row >= 0 && row < pattern.length)) {
rowOffset *= -1;
row += rowOffset * 2;
}
}
return pattern;
}
String getEncryptedData(String message) {
List<Integer>[] pattern = getFencePattern(message.length());
return String.join("",Arrays.stream(pattern).map(line -> String.join("",
line.stream().map(col -> String.valueOf(message.charAt(col))).collect(Collectors.toList()))).collect(Collectors.toList()));
}
String getDecryptedData(String encodedMessage) {
List<Integer>[] pattern = getFencePattern(encodedMessage.length());
StringBuilder result = new StringBuilder();
result.setLength(encodedMessage.length());
int index = 0;
for (List<Integer> line : pattern) {
for (int col : line) {
result.setCharAt(col, encodedMessage.charAt(index));
index++;
}
}
return result.toString();
}
}
A huge amount can be learned from reading other people’s code. This is why we wanted to give exercism users the option of making their solutions public.
Here are some questions to help you reflect on this solution and learn the most from it.
Level up your programming skills with 3,104 exercises across 52 languages, and insightful discussion with our volunteer team of welcoming mentors. Exercism is 100% free forever.
Sign up Learn More
Community comments