# paulfioravanti's solution

## to Rail Fence Cipher in the Ruby 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 . .
``````

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

## 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``````
``````module RailFenceCipher
RAIL_RANGE = ->(offset, limit) { (offset...(limit - offset)).to_a }
private_constant :RAIL_RANGE
RAILS = ->(n) { Array.new(n) { [] } }
private_constant :RAILS
ZIG_ZAG_PATTERN = lambda { |limit|
(RAIL_RANGE.call(0, limit) + RAIL_RANGE.call(1, limit).reverse).cycle
}
private_constant :ZIG_ZAG_PATTERN

module_function

def encode(message, num_rails)
pattern_iterator = ZIG_ZAG_PATTERN.call(num_rails)
zig_zag_transpose(message, num_rails, pattern_iterator).join
end

def decode(message, num_rails)
pattern = ZIG_ZAG_PATTERN.call(num_rails).first(message.length)
message_on_rails =
zig_zag_transpose(message, num_rails, pattern.sort.each)
pattern.map { |index| message_on_rails[index].shift }.join
end

def zig_zag_transpose(message, num_rails, pattern_iterator)
message.chars.each_with_object(RAILS.call(num_rails)) do |char, rails|
rails[pattern_iterator.next] << char
end
end
private_class_method :zig_zag_transpose
end``````

This is cool!

Much simpler than the one I did...I did something pretty similar on the encode but then decode made me change direction.

Only one quibble: why the constants/lambdas rather than ordinary methods? They are essentially equivalent but the constants are a little further away from idiomatic ruby (for no obvious benefit?).

Solution Author
commented over 1 year ago

@brushbox commented:

This is cool!

Much simpler than the one I did...I did something pretty similar on the encode but then decode made me change direction.

Only one quibble: why the constants/lambdas rather than ordinary methods? They are essentially equivalent but the constants are a little further away from idiomatic ruby (for no obvious benefit?).

Thanks for checking out my solution, @brushbox !

Here's my train of thought regarding the set of lambdas: take the justification as you will, since it's all subjective.

Whenever I see magic numbers (or partly dynamic values that use magic numbers), I want to give them names and put them in CONSTANTS

I consider 0 and 1 used in ZIG_ZAG_PATTERN to be magic numbers, but I couldn't figure out what name to give them, since they don't seem to have any other meaning other than "specific array indexes that needed to be used to build the pattern". So, I decided to give a name to the zig-zag pattern concept instead and put it up in a constant. Since RAIL_RANGE is only used by ZIG_ZAG_PATTERN, even though it consists completely of dynamic information, I put it in a constant as well since I thought it would look a bit strange to have a constant calling a module function.

RAILS is a constant as it's mostly static information, aside from the dynamic n parameter.

So, like I said, subjective personal preferences that help me keep information in order in my head :)

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