Avatar of CROUZET

CROUZET's solution

to Rail Fence Cipher in the Ruby Track

Published at Sep 13 2019 · 0 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.


For installation and learning resources, refer to the Ruby resources page.

For running the tests provided, you will need the Minitest gem. Open a terminal window and run the following command to install minitest:

gem install minitest

If you would like color output, you can require 'minitest/pride' in the test file, or note the alternative instruction, below, for running the test file.

Run the tests from the exercise directory using the following command:

ruby rail_fence_cipher_test.rb

To include color from the command line:

ruby -r minitest/pride rail_fence_cipher_test.rb

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

require 'minitest/autorun'
require_relative 'rail_fence_cipher'

class RailFenceCipherTest < Minitest::Test
  def test_encode_with_empty_string
    assert_equal '', RailFenceCipher.encode('', 4)
  end

  def test_encode_with_one_rail
    skip
    assert_equal 'One rail, only one rail',
                 RailFenceCipher.encode('One rail, only one rail', 1)
  end

  def test_encode_with_two_rails
    skip
    assert_equal 'XXXXXXXXXOOOOOOOOO',
                 RailFenceCipher.encode('XOXOXOXOXOXOXOXOXO', 2)
  end

  def test_encode_with_three_rails
    skip
    assert_equal 'WECRLTEERDSOEEFEAOCAIVDEN',
                 RailFenceCipher.encode('WEAREDISCOVEREDFLEEATONCE', 3)
  end

  def test_encode_with_ending_in_the_middle
    skip
    assert_equal 'ESXIEECSR', RailFenceCipher.encode('EXERCISES', 4)
  end

  def test_encode_with_less_letters_than_rails
    skip
    assert_equal 'More rails than letters',
                 RailFenceCipher.encode('More rails than letters', 24)
  end

  def test_decode_with_empty_string
    skip
    assert_equal '', RailFenceCipher.decode('', 4)
  end

  def test_decode_with_one_rail
    skip
    assert_equal 'ABCDEFGHIJKLMNOP',
                 RailFenceCipher.decode('ABCDEFGHIJKLMNOP', 1)
  end

  def test_decode_with_two_rails
    skip
    assert_equal 'XOXOXOXOXOXOXOXOXO',
                 RailFenceCipher.decode('XXXXXXXXXOOOOOOOOO', 2)
  end

  def test_decode_with_three_rails
    skip
    assert_equal 'THEDEVILISINTHEDETAILS',
                 RailFenceCipher.decode('TEITELHDVLSNHDTISEIIEA', 3)
  end
end
class RailFenceCipher

  DOWNWARD = 0
  UPWARD = 1

  attr_reader :phrase, :rail_number, :rail_direction, :actual_rail, :original_phrase_length

  def initialize(phrase, rail_number)
    @phrase = phrase
    @original_phrase_length = phrase.length
    @rail_number = rail_number
    @rail_direction = DOWNWARD
    @actual_rail = 1
  end

  def self.encode(phrase, rail_number)
    return '' if phrase.length.zero?
    new(phrase, rail_number).encode
  end

  def self.decode(phrase, rail_number)
    return '' if phrase.length.zero?
    new(phrase, rail_number).decode
  end

  def encode
    grouped = Hash[(1..rail_number).to_a.product([[]])]

    phrase.chars.each do |letter|
      grouped[actual_rail] = grouped[actual_rail].dup << letter

      next if rail_number == 1
      switch_rail
    end

    grouped.values.join
  end

  def decode
    # Split the phrase in rails parts
    splitted_phrase = []
    rail_number.times do |rail_index|
      rail_letter_number = number_of_letters_on_the_rail(rail_index)
      splitted_phrase[rail_index+1] = @phrase.slice!(0..rail_letter_number-1)
    end

    # Recompose the decoded phrase
    decoded_phrase = ""
    original_phrase_length.times do
      decoded_phrase += splitted_phrase[actual_rail].slice!(0)

      next if rail_number == 1
      switch_rail
    end

    decoded_phrase
  end

  def switch_rail
    if rail_direction == DOWNWARD && actual_rail < rail_number
      @actual_rail += 1
    elsif rail_direction == DOWNWARD
      @actual_rail -= 1
      @rail_direction = UPWARD
    elsif rail_direction == UPWARD && actual_rail > 1
      @actual_rail -= 1
    else
      @actual_rail += 1
      @rail_direction = DOWNWARD
    end
  end

  def number_of_letters_on_the_rail(rail_index)
    if rail_number == 1
      original_phrase_length
    elsif rail_number == 2
      original_phrase_length / 2
    else
      rail_letter_number = original_phrase_length / (rail_number+1)
      rail_letter_number *= 2 unless rail_index == 0 || rail_index == rail_number-1 # x1 for the 1st and last rail, x2 for others
      rail_letter_number += 1 if original_phrase_length.modulo(rail_number) >= rail_index # handle the remaining letters
      rail_letter_number
    end
  end
end

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?