Skip to content

Commit 3c34b13

Browse files
committed
Validate Rail Fence cipher rail counts
1 parent abd8055 commit 3c34b13

2 files changed

Lines changed: 26 additions & 0 deletions

File tree

src/main/java/kyu3/RailFenceCipher.java

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ public class RailFenceCipher {
1111
//3 https://www.codewars.com/kata/58c5577d61aefcf3ff000081/train/java
1212

1313
static String encode(String s, int n) {
14+
validateRailCount(n);
1415
// Distributes characters across rails using a periodic index that walks
1516
// up and down between boundary rails, then concatenates each rail content.
1617
Map<Integer, StringBuilder> map = new TreeMap<>();
@@ -37,6 +38,7 @@ static String encode(String s, int n) {
3738
}
3839

3940
static String decode(String s, int n) {
41+
validateRailCount(n);
4042
// First computes the exact size of each rail, splits ciphertext into
4143
// contiguous rail segments, then reconstructs plaintext by replaying the
4244
// same rail traversal cycle.
@@ -80,6 +82,12 @@ static String decode(String s, int n) {
8082
return result.toString();
8183
}
8284

85+
private static void validateRailCount(int railCount) {
86+
if (railCount < 2) {
87+
throw new IllegalArgumentException("Rail count must be at least 2");
88+
}
89+
}
90+
8391
private static int sumArr(int[] arr, int i) {
8492
// Sum widths of all previous rails to determine the start offset
8593
// of the current rail segment.

src/test/java/kyu3/RailFenceCipherTest.java

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package kyu3;
22

33
import static org.junit.jupiter.api.Assertions.assertEquals;
4+
import static org.junit.jupiter.api.Assertions.assertThrows;
45

56
import java.util.stream.Stream;
67
import org.junit.jupiter.api.Tag;
@@ -28,11 +29,28 @@ void shouldRoundTripPlainTextForDifferentRails(String text, int rails) {
2829
assertEquals(text, RailFenceCipher.decode(encoded, rails));
2930
}
3031

32+
@ParameterizedTest
33+
@MethodSource("invalidRailCounts")
34+
void shouldRejectInvalidRailCounts(int rails) {
35+
assertThrows(IllegalArgumentException.class,
36+
() -> RailFenceCipher.encode("ABC", rails));
37+
assertThrows(IllegalArgumentException.class,
38+
() -> RailFenceCipher.decode("ABC", rails));
39+
}
40+
3141
private static Stream<Arguments> roundTripCases() {
3242
return Stream.of(
3343
Arguments.of("", 2),
3444
Arguments.of("Hello, World!", 4),
3545
Arguments.of("Rail fence cipher keeps punctuation.", 5)
3646
);
3747
}
48+
49+
private static Stream<Arguments> invalidRailCounts() {
50+
return Stream.of(
51+
Arguments.of(-1),
52+
Arguments.of(0),
53+
Arguments.of(1)
54+
);
55+
}
3856
}

0 commit comments

Comments
 (0)