Skip to content

fix: RailFenceCipher silently drops newline characters - #7572

Merged
DenizAltunkapan merged 1 commit into
TheAlgorithms:masterfrom
SEPURI-SAI-KRISHNA:fix/rail-fence-cipher-character-loss
Aug 15, 2026
Merged

fix: RailFenceCipher silently drops newline characters#7572
DenizAltunkapan merged 1 commit into
TheAlgorithms:masterfrom
SEPURI-SAI-KRISHNA:fix/rail-fence-cipher-character-loss

Conversation

@SEPURI-SAI-KRISHNA

Copy link
Copy Markdown
Contributor

Problem

RailFenceCipher.encrypt builds a rails x length matrix and fills every cell with '\n' to mark it as unused. When reading the matrix back it skips every cell that still holds '\n':

Arrays.fill(strRail[i], '\n');
...
if (ch != '\n') {
    encryptedString.append(ch);
}

The placeholder is indistinguishable from a real newline in the plaintext, so any '\n' in the input is silently discarded. The ciphertext comes out shorter than the plaintext and the round trip is corrupted:

RailFenceCipher cipher = new RailFenceCipher();
String message = "ab\ncdef";              // 7 characters

cipher.encrypt(message, 3);               // "adbcef"  -> 6 characters, the newline is gone
cipher.decrypt(cipher.encrypt(message, 3), 3);  // "abfcde" -> not the original message

A transposition cipher must be a permutation of its input, so dropping characters is a correctness bug rather than a formatting quirk.

Fix

encrypt now collects each rail into its own StringBuilder instead of writing into a matrix that needs a sentinel value. Every character of the input is appended exactly once and read back in rail order, so no character can be mistaken for a blank cell. This also drops the memory use from O(rails * length) to O(length).

Additionally, encrypt and decrypt now reject null input and non-positive rail counts with IllegalArgumentException. Previously encrypt("abc", 0) threw ArrayIndexOutOfBoundsException and encrypt("abc", -1) threw NegativeArraySizeException, both leaking internal implementation details.

decrypt is unchanged: its '*' marker is written and consumed positionally, so a '*' in the ciphertext was never at risk.

Tests

The class had no test class at all. RailFenceCipherTest is added, covering:

  • the classic WEAREDISCOVEREDFLEEATONCE / 3 rails vector, in both directions

  • round trips over several messages and rail counts

  • control characters (\n, \r, \t) surviving encryption for 2..5 rails — this fails on the old code

  • degenerate rail counts (rails == 1, rails >= length, empty input)

  • the new validation for non-positive rail counts and null input

  • I have read CONTRIBUTING.md.

  • This pull request is all my own work -- I have not plagiarized it.

  • All filenames are in PascalCase.

  • All functions and variable names follow Java naming conventions.

  • All new algorithms have a URL in their comments that points to Wikipedia or other similar explanations.

  • All new algorithms include a corresponding test class that validates their functionality.

  • All new code is formatted with clang-format -i --style=file path/to/your/file.java

@codecov-commenter

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 80.43%. Comparing base (346f591) to head (75728a4).

Additional details and impacted files
@@            Coverage Diff            @@
##             master    #7572   +/-   ##
=========================================
  Coverage     80.42%   80.43%           
- Complexity     7460     7461    +1     
=========================================
  Files           815      815           
  Lines         24056    24057    +1     
  Branches       4733     4734    +1     
=========================================
+ Hits          19348    19351    +3     
+ Misses         3945     3944    -1     
+ Partials        763      762    -1     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@DenizAltunkapan DenizAltunkapan left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@DenizAltunkapan
DenizAltunkapan merged commit a0f6b0d into TheAlgorithms:master Aug 15, 2026
7 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants