3 kyu
Rail Fence Cipher: Encoding and Decoding
2,080 of 9,077darrentburgess
Loading description...
Algorithms
Ciphers
Cryptography
Strings
Security
View
This comment has been reported as {{ abuseKindText }}.
Show
This comment has been hidden. You can view it now .
This comment can not be viewed.
- |
- Reply
- Edit
- View Solution
- Expand 1 Reply Expand {{ comments?.length }} replies
- Collapse
- Spoiler
- Remove
- Remove comment & replies
- Report
{{ fetchSolutionsError }}
-
-
Your rendered github-flavored markdown will appear here.
-
Label this discussion...
-
No Label
Keep the comment unlabeled if none of the below applies.
-
Issue
Use the issue label when reporting problems with the kata.
Be sure to explain the problem clearly and include the steps to reproduce. -
Suggestion
Use the suggestion label if you have feedback on how this kata can be improved.
-
Question
Use the question label if you have questions and/or need help solving the kata.
Don't forget to mention the language you're using, and mark as having spoiler if you include your solution.
-
No Label
- Cancel
Commenting is not allowed on this discussion
You cannot view this solution
There is no solution to show
Please sign in or sign up to leave a comment.
good math, ty
Excellent kata! I really enjoyed it! I would suggest adding more basic test cases.
Great challenge. It took me some time to get the mathematics for the decoder.
This comment has been hidden.
Not a kata suggestion. See https://docs.codewars.com/training/troubleshooting#post-discourse.
in JS: expected 'WEIEWEIEWEIEWEIEWEIEWEIEW' to equal 'WEAREDISCOVEREDFLEEATONCE' How should a final result be obtained from such a set of characters???
Well, you're given the number of rails which should help you decode the input string back into normal again.
"ABCDEF" decoded to "GHJKLM" seriously?
You sure that's the input and not your result? You can print the string and the rail number at the start of the function, y'know.
Not an issue, a question. But you can keep discussing your current problem.
Very tricky kata, keep it up, many congratulations.
This comment has been hidden.
my encode and decode should work correctly but there is a test cases which got a spaces and i handled them but still there is an errors, you might need to look at it
The tests are fine, your code fails some tests like the ones with an empty string:
Check your code, not a kata issue.
Very good Kata! Thanks to author!
Make encoding: 15min. Make decoding: 2h.
Am I missing something with the JavaScript encode? It looks like there's a test for
encodeRailFenceCipher('',3)
that is expecting an empty string, but if I return an empty string, I getexpected undefined to equal ''
. Is something in the test case coercing the empty string into undefined?No, but you might want to check
decodeRailFenceCipher("", 3)
as well.decoding so hard (
finally i could )..my first! 3 kyu kata!
Very well designed kata, doesn't need one specific solution and still manages to be pretty difficult. Took me 2 hours personally. Well done!
It took me 2 days to do this kata haha, I should be in shame that I am 3kyu :(
(A really nice kata btw)
This comment has been hidden.
like 6 or 7
This was a really interesting kata. Could have been solved a lot of different ways too. Nice one!
Scala translation
Really nice kata... once you get de encode working, the decode part is really easy
Encode is the easy part, decoding is harder
I'm getting this error wether I'm using Python 3.8 or 3.10: ImportError: cannot import name 'decode_rail_fence_cipher' from 'solution' (/workspace/default/solution.py)
Make sure you didn't rename the functions:
i bleed for this
Swift translation
Do not really understand what decode function should do. I thought that logic is almost the same as in encode function but it is not and I am stuck. Can someone help me?
It's hard to help in general without solving (part of) the problem for you. You'd better ask more concrete questions. I think it's clear enough from the description: if you see how
encode
works, then you understand whatdecode
should do: just reverse the encoding process. Clear doesn't mean easy, but this is a 3kyu for a reason, meaning it is supposed to be part of the relatively hard katas.Thank you for trying to help me. I will give you an example for better understanding me. For input "H !e,Wdloollr", 4 the output is "Hello, World!". But my answer is Hdr Wll!,oleo.
D translation
This comment has been hidden.
Did the same, I was so happy when I thought of that as well!
It looks easy when you are encoding. But decoding is much more difficult. Nice Kata.
This comment has been hidden.
Please use a spoiler flag when you post code somewhere (I put the flag on for you). Raw code is not displayed properly in markdown, so please use markdown tags as explained there to format your code for it to be usable, as explained there: https://docs.codewars.com/training/troubleshooting/#post-discourse
Thanks for this kata, a realy beautifull one.
COBOL translation (author inactive).
approved
https://www.codewars.com/kumite/61e083bde8c73e00579ca983 I hope this would prevent random tests with n = 1 from appearing (for Python 3.8), which the Kata description seems to suggest shouldn't occur.
thx
This comment has been hidden.
do anyone know max n in encode and decode?
I assume Python? Max
n
is 10 in Python.50 for Java's random tests
No module called codewars_test
Change Python version to 3.8
This comment has been hidden.
Kata description says that there are always at least 2 rails, but there is a test case with 1 rail only...
What language? From what I can see (for instance) Java always has >= 2.
No answer, user gone.
In java when i use String.charAt(0) function it says this:String index out of range:0. i have solved the encode correctly but cannot run it because of this issue.
If your solution doesn't work for empty strings, that's your problem. Not an issue.
Very enjoyable kata, thanks
A hint: you don't really have to draw a fence, you can solve it with a trick ;)
Really cool kata! 👍
For those stuck, do not forget to draw the rails out. Example's string at rails 8+ may be tricky to decode, depending on the algo. Once passed unit tests, I found the edge cases' decoding strings confusing to read, so i generated my own (google rail fence cipher crypto corner).
for decoding, break it down. and reverse engineer. start with the rails (arrays) needed. then lengths of each rail. for my process, lots of shifting and pushing.
I wrote the rails out using 4 rails, gives you all the insights. For decoding I used the same strategy, but i was able to use patterns from the encoding code.
Seeing as many others have passed this I think the fault is mine but I can't figure out what I'm doing wrong here. With the parameters
WEAREDISCOVEREDFLEEATONCE, 8
I'm gettingWDEEFARLREEEVEEDOACICTNSO
which looks like this:But it says the answer is
WADCEFACTLROIREESVEEOENED
. It seems I'm doing what the task is asking, where am I going wrong?This comment has been hidden.
I don't have the bandwidth to make this change.
small hint? please.
Well, it's really an easy kata for a 3kyu, the description is very clear, think and try out :)
Try drawing the
WEAREDISCOVEREDFLEEATONCE
with 4 rails and start working out some index magic ^^Very cool kata! After finishing the Encode method in like half an hour I thought it was rated too easy but Decode is definitely way harder.
This comment has been hidden.
VB Translation ready for review.
Approved
After doing the encode part easily I thought the decode part would follow. Big mistake. Sunday afternoon gone. I give up for now!
This comment has been hidden.
Hi,
I have added a TypeScript translation.
Will anyone please review it, thanks!
pen and paper help a lot while trying to decipher It does not feel like a 3kyu though Some 5kyu cipher katas that I have solved are more difficult than this Still a nice kata though:)
really enjoyed this, even though it took me days to solve....something great (And useful) to wrap your head around.
Looking at some of the other solutions tho....
I think I'm missing something with this test: Test.assert_equals(encode_rail_fence_cipher( ;
I'm a bit confused on what the intent is here. Any hints?
Not sure why but my solution failed the sample tests(see above) but passed the full test suite.
Does anyone know what the maximum number of rails will be?
no limit
Railfence has a limit by defniniton of how many letters there are, but the way you design your solution should not matter...
Great kata, thanks a lot!
Fun Kata, took a couple of hours to complete. Encoding was pretty straight forward, but came up with a hacky solution for decoding, but eventually passed all tests.
Thank you for a great kata @darrentburgess.
I've eventually coped with it. (Not sure if it's a decent solution, but it works :))
And I would like to notice that in rust basic tests there's two tiny syntax errors
cannot find function `encodeRailFenceCipher` in this scope
. The fix is to rename the function.using language c++
Expected: equal to #C4RBGf[VdqjG)KpIC8d/*_@& Actual: #C4RBGf[VdqjG)KpIC8d/_@&
anyone know how to fix this issue, im not sure if there are extra white spaces in my actual test or the kata test tried .erase(result.find_last_not_of(" \t\n\r\f\v") + 1); to remove white spaces at end but still didnt work, thats tuff!
Not an issue. Print the result before returning it (e.g.
std::cout << "~~~" << result << "~~~" << std::endl
- the input string never includes tildes), and you'll most likely see trailing whitespaces. Otherwise, your algorithm is wrong.Just became the 5th person to solve via PHP. Took me the better part of a week. Encoding was easy, but decoding, whoof.
darrentburgess -- that was BRUTAL -- but thank you for such an incredible challenge.
aidvu -- thanks for the PHP translation!
Bwahahahahahah! I am delighted to have contributed to your suffering grasshopper. ;-)
I passed sample tests. For random it says I passed 1 and failed 0. The left window is outluned in red and the arrow in front of random tests is red. What is the problem? Is it not optimal enough? Did I fail randoms but it just doesnt show? Works with every case I test myself. Using C++
The test cases in the rust version use the wrong function names (camel case instead of underscore).
Yes, the last two. They are still not corrected.
Fixed
Random tests in PHP can be easily cheated.
As I said in your review, the tests are the same as the original ones. An example or explanation would be useful.
Updated the translations (need approval), and added one for 7.0. Should be what you're asking for.
Fixed.
PHP Translation awaiting approval.
Really good kata.
Rust translation awaiting approval.
approved
Language: C++
Something seems wrong with the tests!!
I had the same issue and it was because my index had exceeded the bounds of the string str, so blank characters were being added to my result. Maybe have another look at your loop conditions? Try printing the string one char at a time to see where the blanks are being added
Can someone explain how this output is the correct answer:
Input: WEAREDISCOVEREDFLEEATONCE
with n=2
the expected output is WADCEFACTLROIREESVEEOENED
but even working it out manually I find the answer to be WAEICVRDLETNEERDSOEEFEAOC (as take every other letter and put on one other rail)? eg
Hi, there is a small error in the rail that you wrote above. If you look closely, there is an extra "E" in your "DISCOVEREED". I hope this helps and happy coding (sorry, I see that this question is from a month ago, but I just completed the exercise).
Extra E aside does anyone know why the expected result is different?
Input WEAREDISCOVEREDFLEEATONCE rails = 2.
Expected was WADCEFACTLROIREESVEEOENED but my result was WAEICRLTEEOSDREEICVDEOAFE
Manually working this out also gave me
This comment has been hidden.
Maybe I've missed something, but how can the expected result for the decoder function be a longer string than the input one? Using JavaScript
Here's the log I get when I print the string input and the string lenght.
Log Encode
anoA aiu upm irm imrnn t axidsrrtueaisaa traau au foesueii.ui sfq to m sem edun tPtsinstc mstrD,itoa s!erecvtpeetdicoicv ee tuurep gsn tt s!juevinotpriaiseaixdlarnsdp ioismee etoe r aml flV ienear iek!u ,ti aqeocbrfi u iieiimon iipreeo ee
string length : 244
Decode
asintiooPniAts tpancdiu sudmn esru tapmrlmeDd s,x iiimtar oemoas t i saiq!imferrsrpn etnico uvnt.ti ipvaieexeeuiutjdsd!seisroc rfott ituuc eavna si egsue aa paate rurtu
string length : 173 Expected: 'anoA aiu upm irm imrnn t axidsrrtueaisaa traau au foesueii.ui sfq to m sem edun tPtsinstc mstrD,itoa s!erecvtpeetdicoicv ee tuurep gsn tt s!juevinotpriaiseaixdlarnsdp ioismee etoe r aml flV ienear iek!u ,ti aqeocbrfi u iieiimon iipreeo ee', instead got: 'anoA aiu upm irm imrnn t axidsrrtueaisaa traau au foesueii.ui sfq to m sem edun tPtsinstc mstrD,itoa s!erecvtpeetdicoicv ee tuurep gsn tt s!juevinotpriaiseaixdlarnsdp ioi'
I can pass all 10 basic tests, but none of the random, if anyone can help
To me it seems like the random tests are reversed. When I look at my output and what the output should be, the wrong function is called. Using Python 3.6.
Python works fine for me.
that's because both functions (encode+decode) are called in the random tests => if one of them is wrong, you'll fail the test even if your other function is correct.
"You can optionally include or dis-include punctuation." "Don't filter out the punctuation as they are a part of the string."
So, which is it?
I removed the first statement as I see it could be confusing.
Thank you.
Go translation awaiting approval.
🖖
C# Translation added.Please review and approve,cheer~
really good one,the beauty comes with different solutions.Cheers !
Beautiful kata, many different ways to go about this one. The math involved in the cipher was easy to grasp once I drew out diagrams of several different examples.
This comment has been hidden.
I'm having trouble with the random tests. Everything I test myself works fine, but the randoms fail about half the time.
I'm trying to figure out if it's the Encode or Decode function messing up, but it looks like they're both being run on all the randoms. Any tips for how to test this?
Print a message which would specify what function is being run.
I did a console.log in each function, and they both show up on every test.
I think it is too easy for a 3kyu kata interesting kata tho, maby making one that requires some higher level ofoptimization would be interesting
They did not magically come up with a number, difficulty is average of assessed ranking from the people who completed it in beta stage, plus this kata can be solved with a variety of approaches.
ranks can't be changed
Please check the random tests for Python.(Decoding function) The tests return results that have longer length than the original string. Should'nt both strings be the same length? Thanks
I love creative katas like this one!
This comment has been hidden.
Man, I expected to see a lot of golfy solutions compared to mine, but holy shit. Ruby has way too many handy array functions for its own good. I guess I get nerd points for being the only one (I think) who did it with trig...
Lovely kata, forgot to eat dinner because I couldn't pry myself away.
C++ translation. Please, review and approve.
.
Haha, was thinking to create a Haskell translation. This great kata suddenly gets a lot of attention, and it deserves it. Imho it is a little bit overrated, I would rank it 4 or 5. Nonetheless very original kata. If you ar into encryption consider solving this one.
This comment has been hidden.
I wouldn't call your solution a
7 kyu
, the code itself looks like yellow-level stuff...This comment has been hidden.
Assessing rank by solution's logic instead of algorithm difficulty and implementation difficulty :+1:
Now do a
O(n)
solution, this one is terribly slow :PI've seen your C+-translation. It should be tried for high crimes against readability. :P
I think my
O(m×n)
solution is on the right side of the balance between performance and elegance. ^^I've seen your C+-translation. It should be tried for high crimes against readability. :P
I think my
O(m×n)
solution is on the right side of the balance between performance and elegance. ^^My
O(n)
code passes 10^4 random tests in 0.8 sec, yourO(m*n)
in 9 sec - not very good. And idk what you mean by elegant, it's just as (not) readable as mine one...Except there aren't 1e4 random tests - there are 20.
If performance is important to you, get a bigger computer.
We clearly have different values.
makes a bad register joke, re: different values
Also, yeah I always liked this kata... that's why I finally got around to making a translation to get it more attention :)
Haskell translation
.
Java translation, please review and accept.
cheers
done
thx :)
Thanks for the kata and the translation. Has been much fun! :D
well, this is a nice 6 kyu! Thx for the points!!
I'm really surprised nobody thought about the right approach before... :o
Yes, the right approach... ;-)
I have seen 7 kyu katas which were more work to solve.
Python translation submitted, please take a look
Hey, encountered a bit of trouble in the "Should encode/decode w/arbitrary rail sizes and original message" section of the tests. Boiled down to missing definitions for 'get_rails' and 'get_indices' which I think I managed to reverse engineer but there still seems to be some reference data missing when running the tests, leading to list index out of range. Care to take a look? :)
Let me know if you need more detailed output or if I can otherwise be of assistance!
refresh the page, it has been corrected (I mean, I could complete the kata, on my side)
Been fixed, but thanks for offering to help! You're right by the way.. that was the issue :)
Cheers!
fun kata! the decoding part took me long enough, I had almost given up.
This comment has been hidden.
I did notice this when implementing the encoder, but I didn't use it :)
The Instructions section mentions "omitting punctuation and spaces". To make the instructions less misleading, it'd be better to mention that punctuation is actually used in the tests.
Thanks for the feedback! I updated the instructions to make it clearer that punctuation is included in the test strings.
My god, this Kata was fun. Encoding was easy. Decoding I was ripping my hair out.
This comment has been hidden.
Great first kata! Could you add some random tests before approval? :)
Yep. Seeing the other solutions, it definitely needs some random test cases.
so would some of the solutions not pass if there were random test cases?
There is one half-random test case ( the number of rails is randomized, but not the string)
I added random test cases for both ruby and javascript. Thanks for the feedback!
This comment has been hidden.
yes, if the number of rails is randomized the result is different. Now, the number of rails is random and the long lorem string is shuffled for 20 random tests. Hopefully impossible to hack!
Nice kata! Thanks.
In the example tests there is two times "encode". The second method-call should be decode.
Good catch, this is fixed, thanks!