Skip to content

Commit 0ad247d

Browse files
authored
Add rail-fence-cipher exercise (#665)
* Add rail-fence-cipher exercise We already have a fair number of ciphering exercises, but a few more never hurt. In particular, this one is interesting because it's all about text permutation, and it's not a block cipher: you can't generate any subset of the message without processing the entire thing at once. This means that it's unsuitable for standard text stream traits such as io::Read and io::Write, but by the same token, it means we can design a very simple API for the student to implement. This PR includes one test not present in the canonical data. The intent of this test is to ensure that students are handling individual characters, not just bytes. While the general policy for exercism is to avoid unicode unless it adds something to the exercise, I believe that in this case it adds something to the exercise: as a text permutation exercise, it makes sense to ensure that wide characters are handled properly. One potential extension not included in this exercise would be to add a case oriented around grapheme clusters. As grapheme clustering is fairly complicated and best accomplished through the use of external crates, such a thing would best be hidden behind a feature gate. * implement suggested changes
1 parent 1f3b1dd commit 0ad247d

File tree

7 files changed

+341
-0
lines changed

7 files changed

+341
-0
lines changed

config.json

+12
Original file line numberDiff line numberDiff line change
@@ -464,6 +464,18 @@
464464
"str_vs_string"
465465
]
466466
},
467+
{
468+
"slug": "rail-fence-cipher",
469+
"uuid": "9a8bae4f-2c0b-4e9e-aab2-b92f82dd3b87",
470+
"core": false,
471+
"unlocked_by": "atbash-cipher",
472+
"difficulty": 4,
473+
"topics": [
474+
"chars",
475+
"cipher",
476+
"string_permutation"
477+
]
478+
},
467479
{
468480
"slug": "etl",
469481
"uuid": "0c8eeef7-4bab-4cf9-9047-c208b5618312",
+8
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
# Generated by Cargo
2+
# will have compiled files and executables
3+
/target/
4+
**/*.rs.bk
5+
6+
# Remove Cargo.lock from gitignore if creating an executable, leave it for libraries
7+
# More information here http://doc.crates.io/guide.html#cargotoml-vs-cargolock
8+
Cargo.lock
+3
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
[package]
2+
name = "rail_fence_cipher"
3+
version = "1.1.0"

exercises/rail-fence-cipher/README.md

+119
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,119 @@
1+
# Rail Fence Cipher
2+
3+
Implement encoding and decoding for the rail fence cipher.
4+
5+
The Rail Fence cipher is a form of transposition cipher that gets its name from
6+
the way in which it's encoded. It was already used by the ancient Greeks.
7+
8+
In the Rail Fence cipher, the message is written downwards on successive "rails"
9+
of an imaginary fence, then moving up when we get to the bottom (like a zig-zag).
10+
Finally the message is then read off in rows.
11+
12+
For example, using three "rails" and the message "WE ARE DISCOVERED FLEE AT ONCE",
13+
the cipherer writes out:
14+
15+
```text
16+
W . . . E . . . C . . . R . . . L . . . T . . . E
17+
. E . R . D . S . O . E . E . F . E . A . O . C .
18+
. . A . . . I . . . V . . . D . . . E . . . N . .
19+
```
20+
21+
Then reads off:
22+
23+
```text
24+
WECRLTEERDSOEEFEAOCAIVDEN
25+
```
26+
27+
To decrypt a message you take the zig-zag shape and fill the ciphertext along the rows.
28+
29+
```text
30+
? . . . ? . . . ? . . . ? . . . ? . . . ? . . . ?
31+
. ? . ? . ? . ? . ? . ? . ? . ? . ? . ? . ? . ? .
32+
. . ? . . . ? . . . ? . . . ? . . . ? . . . ? . .
33+
```
34+
35+
The first row has seven spots that can be filled with "WECRLTE".
36+
37+
```text
38+
W . . . E . . . C . . . R . . . L . . . T . . . E
39+
. ? . ? . ? . ? . ? . ? . ? . ? . ? . ? . ? . ? .
40+
. . ? . . . ? . . . ? . . . ? . . . ? . . . ? . .
41+
```
42+
43+
Now the 2nd row takes "ERDSOEEFEAOC".
44+
45+
```text
46+
W . . . E . . . C . . . R . . . L . . . T . . . E
47+
. E . R . D . S . O . E . E . F . E . A . O . C .
48+
. . ? . . . ? . . . ? . . . ? . . . ? . . . ? . .
49+
```
50+
51+
Leaving "AIVDEN" for the last row.
52+
53+
```text
54+
W . . . E . . . C . . . R . . . L . . . T . . . E
55+
. E . R . D . S . O . E . E . F . E . A . O . C .
56+
. . A . . . I . . . V . . . D . . . E . . . N . .
57+
```
58+
59+
If you now read along the zig-zag shape you can read the original message.
60+
61+
## Rust Installation
62+
63+
Refer to the [exercism help page][help-page] for Rust installation and learning
64+
resources.
65+
66+
## Writing the Code
67+
68+
Execute the tests with:
69+
70+
```bash
71+
$ cargo test
72+
```
73+
74+
All but the first test have been ignored. After you get the first test to
75+
pass, open the tests source file which is located in the `tests` directory
76+
and remove the `#[ignore]` flag from the next test and get the tests to pass
77+
again. Each separate test is a function with `#[test]` flag above it.
78+
Continue, until you pass every test.
79+
80+
If you wish to run all tests without editing the tests source file, use:
81+
82+
```bash
83+
$ cargo test -- --ignored
84+
```
85+
86+
To run a specific test, for example `some_test`, you can use:
87+
88+
```bash
89+
$ cargo test some_test
90+
```
91+
92+
If the specific test is ignored use:
93+
94+
```bash
95+
$ cargo test some_test -- --ignored
96+
```
97+
98+
To learn more about Rust tests refer to the [online test documentation][rust-tests]
99+
100+
Make sure to read the [Modules](https://doc.rust-lang.org/book/2018-edition/ch07-00-modules.html) chapter if you
101+
haven't already, it will help you with organizing your files.
102+
103+
## Feedback, Issues, Pull Requests
104+
105+
The [exercism/rust](https://github.com/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!
106+
107+
If you want to know more about Exercism, take a look at the [contribution guide](https://github.com/exercism/docs/blob/master/contributing-to-language-tracks/README.md).
108+
109+
[help-page]: https://exercism.io/tracks/rust/learning
110+
[modules]: https://doc.rust-lang.org/book/2018-edition/ch07-00-modules.html
111+
[cargo]: https://doc.rust-lang.org/book/2018-edition/ch14-00-more-about-cargo.html
112+
[rust-tests]: https://doc.rust-lang.org/book/2018-edition/ch11-02-running-tests.html
113+
114+
## Source
115+
116+
Wikipedia [https://en.wikipedia.org/wiki/Transposition_cipher#Rail_Fence_cipher](https://en.wikipedia.org/wiki/Transposition_cipher#Rail_Fence_cipher)
117+
118+
## Submitting Incomplete Solutions
119+
It's possible to submit an incomplete solution so you can see how others have completed the exercise.
+87
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,87 @@
1+
pub struct RailFence(u32);
2+
3+
fn uncons(s: &str) -> (&str, &str) {
4+
s.split_at(s.chars().next().map_or(0, |c| c.len_utf8()))
5+
}
6+
7+
impl RailFence {
8+
pub fn new(rails: u32) -> RailFence {
9+
RailFence(rails)
10+
}
11+
12+
fn next(&self, down: &mut bool, rail: &mut usize) {
13+
if *down {
14+
if *rail + 1 < self.0 as usize {
15+
*rail += 1;
16+
} else {
17+
*down = false;
18+
*rail -= 1;
19+
}
20+
} else {
21+
if *rail > 0 {
22+
*rail -= 1;
23+
} else {
24+
*down = true;
25+
*rail += 1;
26+
}
27+
}
28+
}
29+
30+
pub fn encode(&self, text: &str) -> String {
31+
let mut rails =
32+
vec![String::with_capacity(1 + (text.len() / self.0 as usize)); self.0 as usize];
33+
let mut down = true;
34+
let mut rail = 0;
35+
36+
for ch in text.chars() {
37+
rails[rail].push(ch);
38+
self.next(&mut down, &mut rail);
39+
}
40+
41+
rails.join("")
42+
}
43+
44+
pub fn decode(&self, cipher: &str) -> String {
45+
let mut rail_caps = vec![0; self.0 as usize];
46+
let mut down = true;
47+
let mut rail = 0;
48+
49+
for _ in cipher.chars() {
50+
rail_caps[rail] += 1;
51+
self.next(&mut down, &mut rail);
52+
}
53+
54+
// this vector owns the text of each rail
55+
let mut rails_own = Vec::with_capacity(self.0 as usize);
56+
let mut skip = 0;
57+
58+
for &cap in rail_caps.iter() {
59+
rails_own.push(
60+
cipher
61+
.chars()
62+
.skip(skip)
63+
.enumerate()
64+
.take_while(|&(i, _)| i < cap)
65+
.map(|(_, c)| c)
66+
.collect::<String>(),
67+
);
68+
skip += cap;
69+
}
70+
71+
// this vector holds string slices viewing into rails_own
72+
let mut rails: Vec<&str> = rails_own.iter().map(|r| r.as_ref()).collect();
73+
74+
let mut out = String::with_capacity(cipher.len());
75+
down = true;
76+
rail = 0;
77+
78+
while rails.iter().any(|r: &&str| r.len() > 0) {
79+
let (head, t_rail) = uncons(rails[rail]);
80+
rails[rail] = t_rail;
81+
self.next(&mut down, &mut rail);
82+
out.push_str(head);
83+
}
84+
85+
out
86+
}
87+
}
+15
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
pub struct RailFence;
2+
3+
impl RailFence {
4+
pub fn new(rails: u32) -> RailFence {
5+
unimplemented!("Construct a new fence with {} rails", rails)
6+
}
7+
8+
pub fn encode(&self, text: &str) -> String {
9+
unimplemented!("Encode this text: {}", text)
10+
}
11+
12+
pub fn decode(&self, cipher: &str) -> String {
13+
unimplemented!("Decode this ciphertext: {}", cipher)
14+
}
15+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,97 @@
1+
//! Tests for rail-fence-cipher
2+
//!
3+
//! Generated by [script][script] using [canonical data][canonical-data]
4+
//!
5+
//! [script]: https://github.com/exercism/rust/blob/master/bin/init_exercise.py
6+
//! [canonical-data]: https://raw.githubusercontent.com/exercism/problem-specifications/master/exercises/rail-fence-cipher/canonical_data.json
7+
//!
8+
//! The tests do not expect any normalization or cleaning.
9+
//! That trade is tested in enough other exercises.
10+
11+
extern crate rail_fence_cipher;
12+
use rail_fence_cipher::*;
13+
14+
/// Process a single test case for the property `encode`
15+
///
16+
/// All cases for the `encode` property are implemented
17+
/// in terms of this function.
18+
fn process_encode_case(input: &str, rails: u32, expected: &str) {
19+
let rail_fence = RailFence::new(rails);
20+
assert_eq!(rail_fence.encode(input), expected);
21+
}
22+
23+
/// Process a single test case for the property `decode`
24+
///
25+
/// All cases for the `decode` property are implemented
26+
/// in terms of this function.
27+
fn process_decode_case(input: &str, rails: u32, expected: &str) {
28+
let rail_fence = RailFence::new(rails);
29+
assert_eq!(rail_fence.decode(input), expected);
30+
}
31+
32+
// encode
33+
34+
#[test]
35+
/// encode with two rails
36+
fn test_encode_with_two_rails() {
37+
process_encode_case("XOXOXOXOXOXOXOXOXO", 2, "XXXXXXXXXOOOOOOOOO");
38+
}
39+
40+
#[test]
41+
#[ignore]
42+
/// encode with three rails
43+
fn test_encode_with_three_rails() {
44+
process_encode_case("WEAREDISCOVEREDFLEEATONCE", 3, "WECRLTEERDSOEEFEAOCAIVDEN");
45+
}
46+
47+
#[test]
48+
#[ignore]
49+
/// encode with ending in the middle
50+
fn test_encode_with_ending_in_the_middle() {
51+
process_encode_case("EXERCISES", 4, "ESXIEECSR");
52+
}
53+
54+
// decode
55+
56+
#[test]
57+
#[ignore]
58+
/// decode with three rails
59+
fn test_decode_with_three_rails() {
60+
process_decode_case("TEITELHDVLSNHDTISEIIEA", 3, "THEDEVILISINTHEDETAILS");
61+
}
62+
63+
#[test]
64+
#[ignore]
65+
/// decode with five rails
66+
fn test_decode_with_five_rails() {
67+
process_decode_case("EIEXMSMESAORIWSCE", 5, "EXERCISMISAWESOME");
68+
}
69+
70+
#[test]
71+
#[ignore]
72+
/// decode with six rails
73+
fn test_decode_with_six_rails() {
74+
process_decode_case(
75+
"133714114238148966225439541018335470986172518171757571896261",
76+
6,
77+
"112358132134558914423337761098715972584418167651094617711286",
78+
);
79+
}
80+
81+
#[test]
82+
#[ignore]
83+
/// encode wide characters
84+
///
85+
/// normally unicode is not part of exercism exercises, but in an exercise
86+
/// specifically oriented around shuffling characters, it seems worth ensuring
87+
/// that wide characters are handled properly
88+
///
89+
/// this text is possibly one of the most famous haiku of all time, by
90+
/// Matsuo Bashō (松尾芭蕉)
91+
fn test_encode_wide_characters() {
92+
process_encode_case(
93+
"古池 蛙飛び込む 水の音",
94+
3,
95+
"古飛 池蛙びむ水音 込の",
96+
);
97+
}

0 commit comments

Comments
 (0)