Avatar of oujesky

oujesky's solution

to Rail Fence Cipher in the Java Track

Published at Aug 07 2018 · 0 comments
Instructions
Test suite
Solution

Note:

This exercise has changed since this solution 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 . .

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.

Running the tests

You can run all the tests for an exercise by entering

$ gradle test

in your terminal.

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

public class RailFenceCipher {

    private final int height;

    public RailFenceCipher(int height) {
        this.height = height;
    }

    public String getEncryptedData(String input) {
        List<List<Character>> rows = IntStream.range(0, height)
            .mapToObj(i -> new ArrayList<Character>())
            .collect(Collectors.toList());

        int row = 0;
        int increment = 1;
        for (char character : input.toCharArray()) {
            rows.get(row).add(character);

            if (row + increment < 0 || row + increment >= height) {
                increment = -increment;
            }

            row += increment;
        }

        int[] result = rows.stream()
            .flatMap(Collection::stream)
            .mapToInt(Character::charValue)
            .toArray();

        return new String(result, 0, result.length);
    }

    public String getDecryptedData(String input) {
        int length = input.length();
        int charsPerSegment = getCharsPerSegment();
        int segmentLength = getSegmentLength(length, charsPerSegment);
        char[] result = new char[length];

        int blockOffset = 0;
        for (int row = 0; row < height; row++) {
            int blockLength = getBlockLength(row, length, charsPerSegment, segmentLength);

            for (int blockIndex = 0; blockIndex < blockLength; blockIndex++) {
                int resultIndex = getResultIndex(row, blockIndex, charsPerSegment);
                result[resultIndex] = input.charAt(blockOffset + blockIndex);
            }

            blockOffset += blockLength;
        }

        return new String(result);
    }

    private int getCharsPerSegment() {
        return 2 + 2 * (height - 2);
    }

    private int getSegmentLength(int length, int charsPerSegment) {
        return (int) Math.ceil(length / (double) charsPerSegment);
    }

    private int getBlockLength(int row, int length, int charsPerSegment, int segmentLength) {
        int missing = getMissingLengthInLastSegment(row, length, charsPerSegment, segmentLength);
        return (isFirstOrLastRow(row) ? segmentLength : 2 * segmentLength) - missing;
    }

    private int getMissingLengthInLastSegment(int row, int length, int charsPerSegment, int segmentLength) {
        int maxLength = segmentLength * charsPerSegment;
        int missingChars = maxLength - length;
        int lastIndex = charsPerSegment - missingChars - 1;

        if (isFirstRow(row)) {
            return 0;
        }

        if (isLastRow(row)) {
            return lastIndex >= charsPerSegment / 2 ? 0 : 1;
        }

        if (lastIndex >= charsPerSegment - row) {
            return 0;
        } else if (lastIndex >= row) {
            return 1;
        } else {
            return 2;
        }
    }

    private int getResultIndex(int row, int blockIndex, int charsPerSegment) {
        if (isFirstOrLastRow(row)) {
            return row + blockIndex * charsPerSegment;
        }

        return isBeforeMiddleOfBlock(blockIndex)
            ? row + (blockIndex / 2) * charsPerSegment
            : ((blockIndex / 2) + 1) * charsPerSegment - row;
    }

    private boolean isFirstRow(int row) {
        return row == 0;
    }

    private boolean isLastRow(int row) {
        return row == height - 1;
    }

    private boolean isFirstOrLastRow(int row) {
        return isFirstRow(row) || isLastRow(row);
    }

    private boolean isBeforeMiddleOfBlock(int rowIndex) {
        return rowIndex % 2 == 0;
    }
}

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?