Avatar of clechasseur

clechasseur's solution

to Rail Fence Cipher in the Java Track

Published at Jul 15 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"));
    }
}
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

class RailFenceCipher {
    private final int numRails;

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

    String getEncryptedData(String input) {
        List<StringBuilder> rails = new ArrayList<>();
        for (int i = 0; i < numRails; ++i) {
            rails.add(new StringBuilder());
        }
        List<Integer> railNums = getRailNums(input.length()).collect(Collectors.toList());
        for (int i = 0; i < input.length(); ++i) {
            rails.get(railNums.get(i)).append(input.charAt(i));
        }
        return rails.stream().map(StringBuilder::toString).collect(Collectors.joining());
    }

    String getDecryptedData(String input) {
        List<StringBuilder> rails = new ArrayList<>();
        for (int i = 0; i < numRails; ++i) {
            rails.add(new StringBuilder());
        }
        List<Integer> sortedRailNums = getRailNums(input.length()).sorted().collect(Collectors.toList());
        for (int i = 0; i < input.length(); ++i) {
            rails.get(sortedRailNums.get(i)).append(input.charAt(i));
        }
        return getRailNums(input.length()).map(railNum -> {
            StringBuilder sb = rails.get(railNum);
            String s = sb.substring(0, 1);
            sb.deleteCharAt(0);
            return s;
        }).collect(Collectors.joining());
    }

    private Stream<Integer> getRailNums(int inputSize) {
        return Stream.iterate(new OscillatorData(), data -> {
            OscillatorData newData = new OscillatorData(data.number + (data.up ? 1 : -1), data.up);
            if (newData.number >= numRails) {
                newData = new OscillatorData(data.number - 1, false);
            } else if (newData.number < 0) {
                newData = new OscillatorData(1, true);
            }
            return newData;
        }).limit(inputSize).map(data -> data.number);
    }

    private static final class OscillatorData {
        final int number;
        final boolean up;

        OscillatorData() {
            this.number = 0;
            this.up = true;
        }

        OscillatorData(int number, boolean up) {
            this.number = number;
            this.up = up;
        }
    }
}

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?