Avatar of AdrJan

AdrJan's solution

to Rail Fence Cipher in the Java Track

Published at Jul 23 2019 · 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 . .

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.

Setup

Go through the setup instructions for Java to install the necessary dependencies:

https://exercism.io/tracks/java/installation

Running the tests

You can run all the tests for an exercise by entering the following in your terminal:

$ gradle test

Use gradlew.bat if you're on Windows

In the test suites all tests but the first have been skipped.

Once you get a test passing, you can enable the next one by removing the @Ignore("Remove to run test") annotation.

Source

Wikipedia https://en.wikipedia.org/wiki/Transposition_cipher#Rail_Fence_cipher

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"));
    }
}
class RailFenceCipher {

    private final int howManyRows;

    RailFenceCipher(int howManyRows) {
        this.howManyRows = howManyRows;
    }

    String getEncryptedData(String data) {
        char [][] dataArray = new char[howManyRows][data.length()];

        fillArrayWithData(data, dataArray);

        return getEncryptedDataFromArray(dataArray);
    }

    String getDecryptedData(String data) {
        char [][] dataArray = new char[howManyRows][data.length()];
        String emptyData = data.replaceAll(".", "*");

        fillArrayWithData(emptyData, dataArray);
        fillArrayWithDataToDecrypt(dataArray, data);

        return getDecryptedDataFromArray(dataArray);
    }

    private void fillArrayWithData(String data, char[][] dataArray) {
        int j = 0;
        boolean dirDown = true;

        for(int i = 0; i < data.length(); i++) {
            dataArray[j][i] = data.charAt(i);

            if(dirDown) {
                j++;
            } else {
                j--;
            }

            if(j >= howManyRows - 1 || j <= 0) {
                dirDown = !dirDown;
            }
        }
    }

    private String getEncryptedDataFromArray(char[][] dataArray) {
        StringBuilder sb = new StringBuilder();

        for(int i = 0; i < howManyRows; i++) {
            for(int k = 0; k < dataArray[0].length; k++) {
                if(dataArray[i][k] != '\u0000') {
                    sb.append(dataArray[i][k]);
                }
            }
        }

        return sb.toString();
    }

    private void fillArrayWithDataToDecrypt(char[][] dataArray, String data) {
        int dataCharIndex = 0;

        for(int i = 0; i < howManyRows; i++) {
            for(int k = 0; k < dataArray[0].length; k++) {
                if(dataArray[i][k] == '*') {
                    dataArray[i][k] = data.charAt(dataCharIndex++);
                }
            }
        }
    }

    private String getDecryptedDataFromArray(char[][] dataArray) {
        int j = 0;
        boolean dirDown = true;
        StringBuilder sb = new StringBuilder();

        for(int i = 0; i < dataArray[0].length; i++) {
            sb.append(dataArray[j][i]);

            if(dirDown) {
                j++;
            } else {
                j--;
            }

            if(j >= howManyRows - 1 || j <= 0) {
                dirDown = !dirDown;
            }
        }

        return sb.toString();
    }
}

Community comments

Find this solution interesting? Ask the author a question to learn more.

What can you learn from this solution?

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.

  • What compromises have been made?
  • Are there new concepts here that you could read more about to improve your understanding?