Avatar of coman92

coman92's solution

to Rail Fence Cipher in the Rust Track

Published at May 12 2020 · 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.

Rust Installation

Refer to the exercism help page for Rust installation and learning resources.

Writing the Code

Execute the tests with:

$ cargo test

All but the first test have been ignored. After you get the first test to pass, open the tests source file which is located in the tests directory and remove the #[ignore] flag from the next test and get the tests to pass again. Each separate test is a function with #[test] flag above it. Continue, until you pass every test.

If you wish to run all ignored tests without editing the tests source file, use:

$ cargo test -- --ignored

To run a specific test, for example some_test, you can use:

$ cargo test some_test

If the specific test is ignored use:

$ cargo test some_test -- --ignored

To learn more about Rust tests refer to the online test documentation

Make sure to read the Modules chapter if you haven't already, it will help you with organizing your files.

Further improvements

After you have solved the exercise, please consider using the additional utilities, described in the installation guide, to further refine your final solution.

To format your solution, inside the solution directory use

cargo fmt

To see, if your solution contains some common ineffective use cases, inside the solution directory use

cargo clippy --all-targets

Submitting the solution

Generally you should submit all files in which you implemented your solution (src/lib.rs in most cases). If you are using any external crates, please consider submitting the Cargo.toml file. This will make the review process faster and clearer.

Feedback, Issues, Pull Requests

The exercism/rust repository on GitHub is the home for all of the Rust exercises. If you have feedback about an exercise, or want to help implement new exercises, head over there and create an issue. Members of the rust track team are happy to help!

If you want to know more about Exercism, take a look at the contribution guide.

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

//! Tests for rail-fence-cipher
//!
//! Generated by [script][script] using [canonical data][canonical-data]
//!
//! [script]: https://github.com/exercism/rust/blob/master/bin/init_exercise.py
//! [canonical-data]: https://raw.githubusercontent.com/exercism/problem-specifications/master/exercises/rail-fence-cipher/canonical_data.json
//!
//! The tests do not expect any normalization or cleaning.
//! That trade is tested in enough other exercises.

use rail_fence_cipher::*;

/// Process a single test case for the property `encode`
///
/// All cases for the `encode` property are implemented
/// in terms of this function.
fn process_encode_case(input: &str, rails: u32, expected: &str) {
    let rail_fence = RailFence::new(rails);
    assert_eq!(rail_fence.encode(input), expected);
}

/// Process a single test case for the property `decode`
///
/// All cases for the `decode` property are implemented
/// in terms of this function.
fn process_decode_case(input: &str, rails: u32, expected: &str) {
    let rail_fence = RailFence::new(rails);
    assert_eq!(rail_fence.decode(input), expected);
}

// encode

#[test]
/// encode with two rails
fn test_encode_with_two_rails() {
    process_encode_case("XOXOXOXOXOXOXOXOXO", 2, "XXXXXXXXXOOOOOOOOO");
}

#[test]
#[ignore]
/// encode with three rails
fn test_encode_with_three_rails() {
    process_encode_case("WEAREDISCOVEREDFLEEATONCE", 3, "WECRLTEERDSOEEFEAOCAIVDEN");
}

#[test]
#[ignore]
/// encode with ending in the middle
fn test_encode_with_ending_in_the_middle() {
    process_encode_case("EXERCISES", 4, "ESXIEECSR");
}

// decode

#[test]
#[ignore]
/// decode with three rails
fn test_decode_with_three_rails() {
    process_decode_case("TEITELHDVLSNHDTISEIIEA", 3, "THEDEVILISINTHEDETAILS");
}

#[test]
#[ignore]
/// decode with five rails
fn test_decode_with_five_rails() {
    process_decode_case("EIEXMSMESAORIWSCE", 5, "EXERCISMISAWESOME");
}

#[test]
#[ignore]
/// decode with six rails
fn test_decode_with_six_rails() {
    process_decode_case(
        "133714114238148966225439541018335470986172518171757571896261",
        6,
        "112358132134558914423337761098715972584418167651094617711286",
    );
}

#[test]
#[ignore]
/// encode wide characters
///
/// normally unicode is not part of exercism exercises, but in an exercise
/// specifically oriented around shuffling characters, it seems worth ensuring
/// that wide characters are handled properly
///
/// this text is possibly one of the most famous haiku of all time, by
/// Matsuo Bashō (松尾芭蕉)
fn test_encode_wide_characters() {
    process_encode_case(
        "古池蛙飛び込む水の音",
        3,
        "古びの池飛込水音蛙む",
    );
}
pub struct RailFence {
    rails: usize,
}

#[derive(Debug)]
pub enum Direction {
    Downside,
    Upside,
}

impl Direction {
    fn swap(self) -> Direction {
        match self {
            Direction::Upside => Direction::Downside,
            Direction::Downside => Direction::Upside,
        }
    }
}

impl RailFence {
    pub fn new(rails: u32) -> RailFence {
        RailFence {
            rails: rails as usize,
        }
    }

    pub fn encode(&self, text: &str) -> String {
        let mut cypher: Vec<Vec<char>> = vec![];
        for _ in 0..self.rails {
            cypher.push(vec![])
        }

        let mut current_rail_index: usize = 0;
        let mut direction: Direction = Direction::Downside;
        for c in text.chars() {
            cypher.get_mut(current_rail_index).unwrap().push(c);

            match direction {
                Direction::Downside => current_rail_index += 1,
                Direction::Upside => current_rail_index -= 1,
            }

            if self.should_change_direction(current_rail_index) {
                direction = direction.swap();
            }
        }

        cypher
            .iter()
            .map(|v| v.iter().collect::<String>())
            .collect::<String>()
    }

    fn should_change_direction(&self, current_rail_index: usize) -> bool {
        current_rail_index == 0 || current_rail_index == self.rails - 1
    }

    pub fn decode(&self, cipher: &str) -> String {
        let mut text: Vec<char> = vec![' '; cipher.len()];
        let mut current_rail_index = 0;
        let mut index_to_insert_char = current_rail_index;
        let mut skip_points: usize = self.skip_points_downside(current_rail_index + 1);

        let mut direction: Direction = Direction::Downside;

        for c in cipher.chars() {
            text[index_to_insert_char] = c;
            index_to_insert_char += skip_points;

            if self.should_recalculate_skip_points(current_rail_index) {
                match direction {
                    Direction::Downside => {
                        skip_points = self.skip_points_upside(current_rail_index + 1)
                    }
                    Direction::Upside => {
                        skip_points = self.skip_points_downside(current_rail_index + 1)
                    }
                }
                direction = direction.swap();
            }

            if index_to_insert_char >= cipher.len() {
                current_rail_index += 1;
                index_to_insert_char = current_rail_index;
                skip_points = self.skip_points_downside(current_rail_index + 1);
            }
        }

        text.iter().collect::<String>()
    }

    fn should_recalculate_skip_points(&self, current_rail_index: usize) -> bool {
        current_rail_index != 0 || current_rail_index == self.rails + 1
    }

    fn skip_points_downside(&self, current_rail: usize) -> usize {
        let adjusted_current_rail = if (current_rail) >= self.rails {
            // when current_rail is the last one, skip_points will be the same as for the first rail
            1
        } else {
            current_rail
        };
        let loop_iteration = 1;
        let bottom_rail = 1;
        let middle_rails_below = self.rails - adjusted_current_rail - bottom_rail;

        1 + middle_rails_below * 2 + loop_iteration
    }

    fn skip_points_upside(&self, current_rail: usize) -> usize {
        let loop_iteration = 1;
        let top_rail = 1;
        let rails_above = current_rail - 1;
        let middle_rails_above = rails_above - top_rail;

        1 + middle_rails_above * 2 + loop_iteration
    }
}

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?