Avatar of vadhri

vadhri's solution

to Rail Fence Cipher in the Rust Track

Published at Apr 05 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: u32
}

impl RailFence {
    pub fn generate_zig_zag(n: u32, length: u32) -> Vec<(u32, u32)> {
        let mut col_down = (0..n).collect::<Vec<u32>>();
        let mut col_up = (1..n-1).collect::<Vec<u32>>();
        let mut counter = 0;
        let mut output: Vec<(u32, u32)> = Vec::new();

        col_up.reverse();
        col_down.extend(col_up);

        let mut citer_row = col_down.iter().cycle();

        while counter < length {
            output.push((*citer_row.next().unwrap(), counter));

            counter += 1;
        }

        output
    }

    pub fn new(rails: u32) -> RailFence {
        RailFence {
            rails: rails
        }
    }

    pub fn encode(&self, text: &str) -> String {
        let cipher_chars: Vec<char> = text.chars().collect();
        let height = self.rails;
        let string_length = cipher_chars.len() as usize;

        let matrix = RailFence::generate_zig_zag(height, string_length as u32);
        let mut matrix_sorted = matrix.clone();

        let mut output: Vec<Vec<char>> = Vec::new();
        let mut encoded_string: String = String::new();

        matrix_sorted.sort_by_key(|x| x.0);

        for _x in 0..height {
            output.push(vec!['-'; string_length as usize]);
        }

        for (_index, item) in matrix.iter().enumerate() {
            output[item.0 as usize][item.1 as usize] = cipher_chars[_index];

        }

        for (_index, item) in matrix_sorted.iter().enumerate() {
            encoded_string.push(output[item.0 as usize][item.1 as usize]);
        }

        encoded_string
    }

    pub fn decode(&self, cipher: &str) -> String {
        let cipher_chars: Vec<char> = cipher.chars().collect();
        let height = self.rails;
        let string_length = cipher_chars.len() as usize;

        let matrix = RailFence::generate_zig_zag(height, string_length as u32);
        let mut matrix_sorted = matrix.clone();

        let mut output: Vec<Vec<char>> = Vec::new();
        let mut decoded_string: String = String::new();

        matrix_sorted.sort_by_key(|x| x.0);

        for _x in 0..height { 
            output.push(vec!['-'; string_length as usize]);
        }

        for (index, item) in matrix_sorted.iter().enumerate() {
            output[item.0 as usize][item.1 as usize] = cipher_chars[index];
        }

        for (_index, item) in matrix.iter().enumerate() {
            decoded_string.push(output[item.0 as usize][item.1 as usize]);
        }

        decoded_string
    }
}

Community comments

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

vadhri's Reflection

Compiling rail_fence_cipher v1.1.0 (/Users/venkat/exercism/rust/rail-fence-cipher)
Finished test [unoptimized + debuginfo] target(s) in 1.12s
Running target/debug/deps/rail_fence_cipher-db2ee161877ce969

running 0 tests

test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out

Running target/debug/deps/rail_fence_cipher-dec8efdf6bee7356

running 7 tests
test test_decode_with_five_rails ... ok
test test_decode_with_three_rails ... ok
test test_encode_with_ending_in_the_middle ... ok
test test_encode_with_two_rails ... ok
test test_encode_with_three_rails ... ok
test test_encode_wide_characters ... ok
test test_decode_with_six_rails ... ok

test result: ok. 7 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out

Doc-tests rail_fence_cipher

running 0 tests

test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out