Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions config.json
Original file line number Diff line number Diff line change
Expand Up @@ -1181,6 +1181,19 @@
"transforming"
]
},
{
"slug": "rail-fence-cipher",
"name": "Rail Fence Cipher",
"uuid": "f78800c1-8e89-4aac-83a4-3988e276225f",
"practices": [],
"prerequisites": [],
"difficulty": 5,
"topics": [
"algorithms",
"strings",
"arrays"
]
},
{
"slug": "bowling",
"name": "Bowling",
Expand Down
57 changes: 57 additions & 0 deletions exercises/practice/rail-fence-cipher/.docs/instructions.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
# Instructions

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:

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

```text
WECRLTEERDSOEEFEAOCAIVDEN
```

To decrypt a message you take the zig-zag shape and fill the ciphertext along the rows.

```text
? . . . ? . . . ? . . . ? . . . ? . . . ? . . . ?
. ? . ? . ? . ? . ? . ? . ? . ? . ? . ? . ? . ? .
. . ? . . . ? . . . ? . . . ? . . . ? . . . ? . .
```

The first row has seven spots that can be filled with "WECRLTE".

```text
W . . . E . . . C . . . R . . . L . . . T . . . E
. ? . ? . ? . ? . ? . ? . ? . ? . ? . ? . ? . ? .
. . ? . . . ? . . . ? . . . ? . . . ? . . . ? . .
```

Now the 2nd row takes "ERDSOEEFEAOC".

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

```text
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.
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@

func encode(_ message: String, rails: Int) -> String {
encodeDecode(message, rails: rails, mode: .encode)
}

func decode(_ message: String, rails: Int) -> String {
encodeDecode(message, rails: rails, mode: .decode)
}

fileprivate enum Mode {
case encode
case decode
}

fileprivate func encodeDecode(_ message: String, rails: Int, mode: Mode) -> String {
var output = Array(repeating: Character(" "), count: message.count)
let maxStep = 2 * (rails - 1)
var posCipher = 0
let chars = Array(message)

for rail in 0..<rails {
var step = (rail == 0) ? maxStep : 2 * rail
var posText = rail

while posText < chars.count {
if mode == .encode {
output[posCipher] = chars[posText]
} else {
output[posText] = chars[posCipher]
}

posCipher += 1
step = (step == maxStep) ? maxStep : maxStep - step
posText += step
}
}

return String(output)
}
19 changes: 19 additions & 0 deletions exercises/practice/rail-fence-cipher/.meta/config.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
{
"authors": [
"Sencudra"
],
"files": {
"solution": [
"Sources/RailFenceCipher/RailFenceCipher.swift"
],
"test": [
"Tests/RailFenceCipherTests/RailFenceCipherTests.swift"
],
"example": [
".meta/Sources/RailFenceCipher/RailFenceCipherExample.swift"
]
},
"blurb": "Implement encoding and decoding for the rail fence cipher.",
"source": "Wikipedia",
"source_url": "https://en.wikipedia.org/wiki/Transposition_cipher#Rail_Fence_cipher"
}
20 changes: 20 additions & 0 deletions exercises/practice/rail-fence-cipher/.meta/template.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import Testing
import Foundation
@testable import {{exercise | camelCase}}

let RUNALL = Bool(ProcessInfo.processInfo.environment["RUNALL", default: "false"]) ?? false

@Suite struct {{exercise | camelCase}}Tests {
{% outer: for case in cases %}
{% for subCase in case.cases %}
{% if forloop.outer.first and forloop.first %}
@Test("{{subCase.description}}")
{% else -%}
@Test("{{subCase.description}}", .enabled(if: RUNALL))
{% endif -%}
func test{{subCase.description | camelCase}}() {
#expect({{subCase.property}}("{{subCase.input.msg}}", rails: {{subCase.input.rails}}) == "{{subCase.expected}}")
}
{% endfor %}
{% endfor %}
}
28 changes: 28 additions & 0 deletions exercises/practice/rail-fence-cipher/.meta/tests.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
# This is an auto-generated file.
#
# Regenerating this file via `configlet sync` will:
# - Recreate every `description` key/value pair
# - Recreate every `reimplements` key/value pair, where they exist in problem-specifications
# - Remove any `include = true` key/value pair (an omitted `include` key implies inclusion)
# - Preserve any other key/value pair
#
# As user-added comments (using the # character) will be removed when this file
# is regenerated, comments can be added via a `comment` key.

[46dc5c50-5538-401d-93a5-41102680d068]
description = "encode -> encode with two rails"

[25691697-fbd8-4278-8c38-b84068b7bc29]
description = "encode -> encode with three rails"

[384f0fea-1442-4f1a-a7c4-5cbc2044002c]
description = "encode -> encode with ending in the middle"

[cd525b17-ec34-45ef-8f0e-4f27c24a7127]
description = "decode -> decode with three rails"

[dd7b4a98-1a52-4e5c-9499-cbb117833507]
description = "decode -> decode with five rails"

[93e1ecf4-fac9-45d9-9cd2-591f47d3b8d3]
description = "decode -> decode with six rails"
21 changes: 21 additions & 0 deletions exercises/practice/rail-fence-cipher/Package.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
// swift-tools-version: 6.0

import PackageDescription

let package = Package(
name: "RailFenceCipher",
products: [
.library(
name: "RailFenceCipher",
targets: ["RailFenceCipher"])
],
dependencies: [],
targets: [
.target(
name: "RailFenceCipher",
dependencies: []),
.testTarget(
name: "RailFenceCipherTests",
dependencies: ["RailFenceCipher"]),
]
)
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@

// Write your solution to the 'RailFenceCipher' exercise in this file.
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import Foundation
import Testing

@testable import RailFenceCipher

let RUNALL = Bool(ProcessInfo.processInfo.environment["RUNALL", default: "false"]) ?? false

@Suite struct RailFenceCipherTests {

@Test("encode with two rails")
func testEncodeWithTwoRails() {
#expect(encode("XOXOXOXOXOXOXOXOXO", rails: 2) == "XXXXXXXXXOOOOOOOOO")
}

@Test("encode with three rails", .enabled(if: RUNALL))
func testEncodeWithThreeRails() {
#expect(encode("WEAREDISCOVEREDFLEEATONCE", rails: 3) == "WECRLTEERDSOEEFEAOCAIVDEN")
}

@Test("encode with ending in the middle", .enabled(if: RUNALL))
func testEncodeWithEndingInTheMiddle() {
#expect(encode("EXERCISES", rails: 4) == "ESXIEECSR")
}

@Test("decode with three rails", .enabled(if: RUNALL))
func testDecodeWithThreeRails() {
#expect(decode("TEITELHDVLSNHDTISEIIEA", rails: 3) == "THEDEVILISINTHEDETAILS")
}

@Test("decode with five rails", .enabled(if: RUNALL))
func testDecodeWithFiveRails() {
#expect(decode("EIEXMSMESAORIWSCE", rails: 5) == "EXERCISMISAWESOME")
}

@Test("decode with six rails", .enabled(if: RUNALL))
func testDecodeWithSixRails() {
#expect(
decode("133714114238148966225439541018335470986172518171757571896261", rails: 6)
== "112358132134558914423337761098715972584418167651094617711286")
}

}