ðŸŽ‰ Exercism Research is now launched. Help Exercism, help science and have some fun at research.exercism.io ðŸŽ‰

# bdf74's solution

## to Rail Fence Cipher in the PHP Track

Published at Aug 03 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 . .
``````

``````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

1. Go to the root of your PHP exercise directory, which is `<EXERCISM_WORKSPACE>/php`. To find the Exercism workspace run

`````` % exercism debug | grep Workspace
``````
2. Get PHPUnit if you don't have it already.

`````` % wget --no-check-certificate https://phar.phpunit.de/phpunit.phar
% chmod +x phpunit.phar
``````
3. Execute the tests:

`````` % ./phpunit.phar rail-fence-cipher/rail-fence-cipher_test.php
``````

## Submitting Incomplete Solutions

It's possible to submit an incomplete solution so you can see how others have completed the exercise.

### rail-fence-cipher_test.php

``````<?php
require_once "rail-fence-cipher.php";

class RailFenceCipherTest extends PHPUnit\Framework\TestCase
{

/**
* Test encode with two rails.
*/
public function testEncodeWithTwoRails()
{

\$plainText  = "XOXOXOXOXOXOXOXOXO";
\$rails = 2;
\$expected = "XXXXXXXXXOOOOOOOOO";
\$this->assertEquals(encode(\$plainText, \$rails), \$expected);
}
/**
* Test encode with three rails.
*/
public function testEncodeWithThreeRails()
{
\$this->markTestSkipped();
\$plainText  = "WEAREDISCOVEREDFLEEATONCE";
\$rails = 3;
\$expected = "WECRLTEERDSOEEFEAOCAIVDEN";
\$this->assertEquals(encode(\$plainText, \$rails), \$expected);
}

/**
* Test encode with ending in the middle.
*/
public function testEncodeWithEndingInTheMiddle()
{
\$this->markTestSkipped();
\$plainText  = "EXERCISES";
\$rails = 4;
\$expected = "ESXIEECSR";
\$this->assertEquals(encode(\$plainText, \$rails), \$expected);
}

/**
* Test decode with three rails.
*/
public function testDecodeWithThreeRails()
{
\$this->markTestSkipped();
\$encryptedText  = "TEITELHDVLSNHDTISEIIEA";
\$rails = 3;
\$expected = "THEDEVILISINTHEDETAILS";
\$this->assertEquals(decode(\$encryptedText, \$rails), \$expected);
}
/**
* Test decode with five rails.
*/
public function testDecodeWithFiveRails()
{
\$this->markTestSkipped();
\$encryptedText  = "EIEXMSMESAORIWSCE";
\$rails = 5;
\$expected = "EXERCISMISAWESOME";
\$this->assertEquals(decode(\$encryptedText, \$rails), \$expected);
}

/**
* Test decode with six rails.
*/
public function testDecodeWithSixRails()
{
\$this->markTestSkipped();
\$encryptedText  = "133714114238148966225439541018335470986172518171757571896261";
\$rails = 6;
\$expected = "112358132134558914423337761098715972584418167651094617711286";
\$this->assertEquals(decode(\$encryptedText, \$rails), \$expected);
}
}``````
``````<?php
const FORWARD = 1;
const BACK = 2;

function encode(\$plainText, \$rails) {

// This puts my text on the rails, in a zigzag path.
\$arr = prepareRails(\$plainText, \$rails);

// Let's collect my characters sequentially, rail by rail.
\$output = "";
for (\$i = 0; \$i < count(\$arr); \$i++) {
\$output .= implode("",\$arr[\$i]);
};
return str_replace(".","",\$output);
};

function decode(\$plainText, \$rails) {
// Let's prepare my rails with the question marks (see README.md)
\$arr = prepareRails(str_repeat("?",strlen(\$plainText)), \$rails);

// This writes text sequentially, rail by rail, replacing the question marks.
\$textIndex = 0;
for (\$rowIndex = 0; \$rowIndex < count(\$arr); \$rowIndex++) {
for (\$colIndex = 0; \$colIndex < count(\$arr[\$rowIndex]); \$colIndex++) {
if (\$arr[\$rowIndex][\$colIndex] === "?") {
\$arr[\$rowIndex][\$colIndex] = \$plainText[\$textIndex];
\$textIndex++;
};
}
};

// Let's decode the text, following a zigzag path through my rails.
\$currentRail = 0;
\$index = 0;
\$direction = FORWARD;
\$output = "";

while (\$index < count(\$arr[0])) {
\$output .= \$arr[\$currentRail][\$index];
\$index++;
// Which rail should we select next?
list (\$currentRail, \$direction) = nextRail(\$currentRail, \$direction, \$arr);
};
return \$output;
};

function prepareRails(\$plainText, \$rails) {

// This puts a text on the rails, in a zigzag path.

\$arr = [];  // Initialization...
for (\$i = 0; \$i < \$rails; \$i++) {
array_push(\$arr, []);
};

\$currentRail = 0;
\$index = 0;
\$direction = FORWARD;
foreach (str_split(\$plainText) as \$ch) {
for (\$row = 0; \$row < count(\$arr); \$row++) {
if (\$row === \$currentRail) {
\$arr[\$row][\$index] = \$ch;
} else {
\$arr[\$row][\$index] = ".";
}
};
\$index++;
// Which rail should we select next?
list (\$currentRail, \$direction) = nextRail(\$currentRail, \$direction, \$arr);
};
return \$arr;
};

function nextRail (\$currentRail, \$direction, \$arr) {
// Input: the current rail and the direction.
// Output: the new rail (in a zigzag movement) and the direction.

if (\$direction === FORWARD) {
if (\$currentRail === (count(\$arr) -1)  )  {
\$currentRail--;
\$direction = BACK;
} else {
\$currentRail++;
}
} else {
if (\$currentRail === 0  )  {
\$currentRail++;
\$direction = FORWARD;
} else {
\$currentRail--;
};
};
\$output = [\$currentRail, \$direction];
return \$output;
};``````

### 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?