Avatar of ErikSchierboom

ErikSchierboom's solution

to Rail Fence Cipher in the Scala Track

Published at Jul 13 2018 · 2 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.

The Scala exercises assume an SBT project scheme. The exercise solution source should be placed within the exercise directory/src/main/scala. The exercise unit tests can be found within the exercise directory/src/test/scala.

To run the tests simply run the command sbt test in the exercise directory.

For more detailed info about the Scala track see the help page.

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.scala

import org.scalatest.{Matchers, FunSuite}

/** @version 1.1.0 */
class RailFenceCipherTest extends FunSuite with Matchers {

  test("encode with two rails") {
    RailFenceCipher.encode("XOXOXOXOXOXOXOXOXO", 2) should be(
      "XXXXXXXXXOOOOOOOOO")
  }

  test("encode with three rails") {
    pending
    RailFenceCipher.encode("WEAREDISCOVEREDFLEEATONCE", 3) should be(
      "WECRLTEERDSOEEFEAOCAIVDEN")
  }

  test("encode with ending in the middle") {
    pending
    RailFenceCipher.encode("EXERCISES", 4) should be("ESXIEECSR")
  }

  test("decode with three rails") {
    pending
    RailFenceCipher.decode("TEITELHDVLSNHDTISEIIEA", 3) should be(
      "THEDEVILISINTHEDETAILS")
  }

  test("decode with five rails") {
    pending
    RailFenceCipher.decode("EIEXMSMESAORIWSCE", 5) should be(
      "EXERCISMISAWESOME")
  }

  test("decode with six rails") {
    pending
    RailFenceCipher.decode(
      "133714114238148966225439541018335470986172518171757571896261",
      6) should be(
      "112358132134558914423337761098715972584418167651094617711286")
  }
}
object RailFenceCipher {
  def track(rails: Int, index: Int): Int = {
    val size = rails * 2 - 2
    def correct(i: Int): Boolean = i % size == 0

    if (correct(index)) 0
    else if (correct(index - rails + 1)) rails - 1
    else (1 to rails - 2).find(i => correct(index - i) || correct(index - size + i)).get
  }

  def encode(plainText: String, rails: Int): String = {
    val lettersByRail = (0 until plainText.length)
      .map(i => (track(rails, i), plainText.charAt(i)))
      .groupBy(_._1)

    lettersByRail
      .keys
      .toList
      .sorted
      .map(i => lettersByRail(i).map(a => a._2).mkString)
      .mkString
  }

  def decode(encodedText: String, rails: Int): String = {
    val railIndices = (0 until encodedText.length)
      .groupBy(i => track(rails, i))

    val letterIndices = railIndices
      .keys
      .toList
      .sorted
      .flatMap(railIndices(_))

    encodedText
      .zip(letterIndices)
      .sortBy(_._2)
      .map(_._1)
      .mkString
  }
}

Community comments

Find this solution interesting? Ask the author a question to learn more.
Avatar of abo64

Interesting. :)

encode and decode contain similar code snippets. Maybe some potential for generalization and code sharing?

Avatar of ErikSchierboom

Probably :)

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?