Avatar of jhuiet

jhuiet's solution

to Rail Fence Cipher in the Java Track

Published at Jul 13 2018 · 0 comments
Instructions
Test suite
Solution

Note:

This solution was written on an old version of Exercism. The tests below might not correspond to the solution code, and the exercise may have changed since this code 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"));
	}
}
public class RailFenceCipher {

	int rails;
	String[] lines; 
	
	public RailFenceCipher(int i) {
		this.rails = i;
		lines = new String[rails];
	}

	

	public String getDecryptedData(String input) {
		StringBuilder decrypted = new StringBuilder();
		String[] parts = new String[rails];
		int[] partLengths = new int[rails];
		boolean direction = true;
		int x = 0;
		int count = 0;
		int current = 0;
		int index = 0;
		/*
		 *Determine how long each "rail: should be. There is most likely a mathematical way to accomplish this but this works as well. 
		 */
		for(int i = 0; i < input.length(); i++) {
			partLengths[x]++;
			if(x == rails - 1) {
				direction = false;
			}
			if(x == 0) {
				direction = true;
			}
			x = direction ? x + 1: x - 1;
		}
		direction  = true;
		/*
		 * Assign the appropriate sections of the string to the parts[] array. Essentially creating the "rails" arrays as they are seen.
		 */
		parts[0] = input.substring(0,partLengths[0] );
		index = partLengths[0];
		for(int i = 1 ; i < partLengths.length; i++) {
			parts[i] = input.substring(index, index + partLengths[i]); 	//partlength error in logic
			index += partLengths[i];
		}
		/*
		 * Iterate through each of the assigned rails, appending to (String)decrypted to create the decryped message
		 */
		while(count < input.length()) {
			decrypted.append(parts[current].charAt(0));
			parts[current] = parts[current].substring(1);
			if(current == rails - 1) 
				direction = false;
			if(current == 0) 
				direction = true;
			current = direction ? current + 1: current - 1;
			count++;
		}
		
		return decrypted.toString();
	}



	public String getEncryptedData(String input) {
		boolean direction = true;
		StringBuilder encrypted = new StringBuilder();
		int line = 0;
		for(int i = 0; i < input.length(); i++) {
			System.out.println(line);
			lines[line] += input.charAt(i);
			if(line == rails - 1) 
				direction = false;
			if(line == 0) 
				direction = true;
			line = direction ? line + 1: line - 1;
		}
		
		for(String s: lines) {
			encrypted.append(s);
		}
		//not sure why but each array started with null... this is a way to remove it but may cause errors if the word null is used in the phrase
		return encrypted.toString().replaceAll("null", "");
	}
	
}

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?