🎉 Exercism Research is now launched. Help Exercism, help science and have some fun at research.exercism.io 🎉
Avatar of GHDIShfdiod876dhs

GHDIShfdiod876dhs's solution

to Rail Fence Cipher in the PHP Track

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

  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
    

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.

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()
    {
        $plainText  = "WEAREDISCOVEREDFLEEATONCE";
        $rails = 3;
        $expected = "WECRLTEERDSOEEFEAOCAIVDEN";
        $this->assertEquals(encode($plainText, $rails), $expected);
    }

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

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

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

function encode(string $message, int $rails): string
{
  if ($rails < 1) {
    throw new InvalidArgumentException();
  }

  $message = str_split(sanitize($message));
  $zigzag = zigzag($rails);
  $lines = array_fill(0, $rails, '');

  foreach ($message as $i => $letter) {
    $lines[$zigzag[$i % count($zigzag)]] .= $letter;
  }

  return join($lines);
}


function decode(string $message, int $rails): string
{
  if ($rails < 1) {
    throw new InvalidArgumentException();
  }

  $message = str_split(sanitize($message));
  $message_length = count($message);
  $zigzag = zigzag($rails);

  $spaces = [];
  foreach ($message as $i => $_) {
    $spaces[] = $zigzag[$i % count($zigzag)];
  }
  $rail_lengths = array_count_values($spaces);

  $lines = [];
  for ($i = 0; $i < $rails; $i++) {
    $lines[] = array_splice($message, 0, $rail_lengths[$i]);
  }
  
  $decoded = '';
  for ($i = 0; $i < $message_length; $i++) {
    $decoded .= array_shift($lines[$zigzag[$i % count($zigzag)]]);
  }
  
  return $decoded;
}

function zigzag(int $rails): array
{
  return array_merge(range(0, $rails - 1), range($rails - 2, 1));
}

function sanitize(string $message): string
{
  return preg_replace('/[^A-Z0-9]/', '', strtoupper($message));
}

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?