r/dailyprogrammer • u/Elite6809 1 1 • Jan 07 '15
[2015-01-07] Challenge #196 [Intermediate] Rail Fence Cipher
(Intermediate): Rail Fence Cipher
Before the days of computerised encryption, cryptography was done manually by hand. This means the methods of encryption were usually much simpler as they had to be done reliably by a person, possibly in wartime scenarios.
One such method was the rail-fence cipher. This involved choosing a number (we'll choose 3) and writing our message as a zig-zag with that height (in this case, 3 lines high.) Let's say our message is REDDITCOMRDAILYPROGRAMMER. We would write our message like this:
R I M I R A R
E D T O R A L P O R M E
D C D Y G M
See how it goes up and down? Now, to get the ciphertext, instead of reading with the zigzag, just read along the lines instead. The top line has RIMIRAR, the second line has EDTORALPORME and the last line has DCDYGM. Putting those together gives you RIMIRAREDTORALPORMEDCDYGM, which is the ciphertext.
You can also decrypt (it would be pretty useless if you couldn't!). This involves putting the zig-zag shape in beforehand and filling it in along the lines. So, start with the zig-zag shape:
? ? ? ? ? ? ?
? ? ? ? ? ? ? ? ? ? ? ?
? ? ? ? ? ?
The first line has 7 spaces, so take the first 7 characters (RIMIRAR) and fill them in.
R I M I R A R
? ? ? ? ? ? ? ? ? ? ? ?
? ? ? ? ? ?
The next line has 12 spaces, so take 12 more characters (EDTORALPORME) and fill them in.
R I M I R A R
E D T O R A L P O R M E
? ? ? ? ? ?
Lastly the final line has 6 spaces so take the remaining 6 characters (DCDYGM) and fill them in.
R I M I R A R
E D T O R A L P O R M E
D C D Y G M
Then, read along the fence-line (zig-zag) and you're done!
Input Description
You will accept lines in the format:
enc # PLAINTEXT
or
dec # CIPHERTEXT
where enc # encodes PLAINTEXT with a rail-fence cipher using # lines, and dec # decodes CIPHERTEXT using # lines.
For example:
enc 3 REDDITCOMRDAILYPROGRAMMER
Output Description
Encrypt or decrypt depending on the command given. So the example above gives:
RIMIRAREDTORALPORMEDCDYGM
Sample Inputs and Outputs
enc 2 LOLOLOLOLOLOLOLOLO
Result: LLLLLLLLLOOOOOOOOO
enc 4 THEQUICKBROWNFOXJUMPSOVERTHELAZYDOG
Result: TCNMRZHIKWFUPETAYEUBOOJSVHLDGQRXOEO
dec 4 TCNMRZHIKWFUPETAYEUBOOJSVHLDGQRXOEO
Result: THEQUICKBROWNFOXJUMPSOVERTHELAZYDOG
dec 7 3934546187438171450245968893099481332327954266552620198731963475632908289907
Result: 3141592653589793238462643383279502884197169399375105820974944592307816406286 (pi)
dec 6 AAPLGMESAPAMAITHTATLEAEDLOZBEN
Result: ?
44
u/OllieShadbolt 1 0 Jan 07 '15
BrainFuck
Was hoping to be able to do more than just this. So far, it can only encrypt text, and only allows a cipher using 3 lines. Because of this, the input is only expecting the plaintext itself. Hopefully I'm able to find a way of allowing an inputted cipher size and the ability to decode cipher text.
4
u/Elite6809 1 1 Jan 07 '15
Solution in C#, as always.
4
u/NoobOfProgramming Jan 07 '15
This took me much longer than i feel like it should have taken.
Messy C++ solution. Help/criticism is appreciated.
19
u/13467 1 1 Jan 07 '15
Short and sweet Haskell.
6
u/louiswins Jan 07 '15
C++ solution, with a few (mildly obfuscating) tricks:
6
u/adrian17 1 4 Jan 07 '15 edited Jan 07 '15
Python 3.
Edit: also implemented /u/jetRink's great idea for using the same mapping for encryption and decryption.
5
u/dongas420 Jan 08 '15 edited Jan 08 '15
Perl:
1
u/Chief_Miller Jan 10 '15 edited Jan 10 '15
Python 3 :
First timer here and it only took me an entire afternoon to complete \o/
I had some trouble with 2 dimentional lists so that was fun to sort out. Also my initial solution had problems handling inputs that were not a multiple of the cypher in length. I hope it's not too bad.
Advice and criticism are welcome :D
1
u/webdev2009 Jan 16 '15
Solution using Javascript. 2 functions pretty similar to one another with necessary tweaks.
1
u/pyfis Jan 24 '15
A solution in D. It took me a while to figure out how to build n-dimensional dynamic arrays, but once I did things went pretty smoothly. I'm not yet using any of D's advance features. I tried to reverse engineer /r/leonardo_m 's post but just couldn't do it. I did however look up the iota function and cycle() from the std lib as a result of what he did. So thanks for that.
code:
and the output:
1
u/[deleted] Feb 17 '15
My second challenge. Very new to coding and using C#, feedback welcome. I included my comments (required for class), hopefully they help in understanding my process. If the # of lines (or height) is for instance 4, then my "lineInFocus" variable focuses on all letters in horizontal row 0 first (top-most), i analyze the whole string, then move onto letters that fit in row 1, etc. My variable "currentLine" moves up and down with the zig-zag as I cycle through each letter. When the two match (the currentLine in focus is the same as the row "lineInFocus" i'm analyzing then I process that current letter (encrypt it or decrypt it). Hopefully that kind of makes sense....it would be easier to show visually. Putting it into words for explanation is escaping me.
1
u/-rg14 Feb 22 '15 edited Feb 22 '15
Java:
3
u/Regimardyl Jan 07 '15
Kinda unelegant but working Haskell solution. The basic idea was rather simple, but it turned out that it wasn't possible to use Haskell's
zipWithor a fold with it, so it didn't exactly turn out as I wanted.3
u/spfy Jan 08 '15
This was ultra fun! Here's my Java solution:
At first I was maintaining the separate lines as an ArrayList of ArrayLists. What a nightmare. Thanks to /u/Elite6809's submission I was reminded that I could just append strings :p
2
u/jetRink Jan 07 '15
Clojure. First, creates a mapping from plaintext to ciphertext position for each character. Then, depending on the mode, uses the map or its inverse to rearrange the characters.
2
u/[deleted] Jan 07 '15 edited Jan 08 '15
Python 2.7:
2
u/Godspiral 3 3 Jan 07 '15 edited Jan 08 '15
in J,
enc =: [: ; (</.~ 0 1 2 1 $~ #)
dec enc 'REDDIT.COM R DAILYPROGRAMMER'
REDDIT.COM R DAILYPROGRAMMER
I missed the number of lines to use :(
2
u/beforan Jan 08 '15 edited Jan 30 '15
Back again with more Lua 5.2
Solution
Output:
2
u/NoobOfProgramming Jan 08 '15
If you write the bits in a a zig-zag instead of the letters, so that
THEQUICKBROWNFOXJUMPSOVERTHELAZYDOG with 23 rails becomes
Q3Q0~°D=è╪┴↓ƒs►3" O≈«╔â+♀♣¢Ç¼╩
and a beep, and also re-encrypt the result a few times, could this be a decent cipher?
2
u/jnazario 2 0 Jan 08 '15 edited Jan 08 '15
scala, a language i'm choosing to focus on for 2015.
usage:
2
u/clermbclermb Jan 08 '15
Python 2.7/3 implementation. I didn't try to optimize the cipher implementation; instead just wrote it as I understood the implementation. I wrote it in it's own class for reusability.
** Source **
** Output **
2
u/YYZtoLHR Jan 09 '15
First time posting, love the sub. My JavaScript (with HTML for inputs) solution. Feedback is great.
2
u/Starbeamrainbowlabs Jan 23 '15
My second post here!
This half solution is in Javascript, I got confused with the decrypting algorithm.
Unminified:
Minified version (with uglifyJS):
1
u/sabrepiez Jan 08 '15
C++
High school student here, would love any comments/critiques!
1
u/ichor Jan 07 '15
Python 2.7 - comments/feedback welcome (it's not the prettiest thing but seems to work)
1
u/hutsboR 3 0 Jan 07 '15
Dart: Very ugly solution.
OUTPUT: Don't look if you're still trying to decipher the last sample input!
1
u/Pretentious_Username Jan 07 '15
Python 2.7 Took me a little while to generate the right sequence of elements to access but once I got that down it was simple enough to implement. There's probably a cleaner way to do it though.
1
u/TheEminentdomain Jan 08 '15
Java Not the best implementation, however, i'm hoping to get better with continuous practice. feedback welcome
1
u/Goggalor Jan 08 '15 edited Jan 08 '15
Comments welcome! C# solution using StringBuilder.
1
u/chunes 1 2 Jan 08 '15
Java:
This could probably be refactored somehow but I'm not sure how.
1
u/Yopu Jan 08 '15
Groovy
It turned out more ugly than I would like.
1
u/OutputStream Jan 08 '15 edited Jan 09 '15
Looking for feedback. Python 3:
1
u/[deleted] Jan 08 '15
Didn't quit get how you all got these nice formulas for repositioning the chars. Though without these it gets pretty long. Critique is desired. Solution is in C#
1
u/witchking87 Jan 08 '15
Java :
1
u/ohheydom Jan 08 '15
golang. Still fairly new to the language so I'd love some feedback!
1
u/HeyThereCharlie Jan 09 '15
My big ugly Haskell solution, after many hours of head-scratching. MUCH room for improvement here, I realize.
1
u/trinity37185 Jan 09 '15 edited Jan 09 '15
C++: I encode the string by creating a vector<string> with as many element as there are rails and then iterating over the supplied string and adding the chars to the right rail. To figure out the right rail i went up and down on the vector<string>.
Decoding turned out to be much more complex, i found out the length of each rail by iterating over the supplied string like in encode and incrementing the correct railcounter in a vector<int>. Then i split the supplied string into the rails, stored in a vector<string>, based on these sizes. To finish it off, I iterated over the rails and created the decoded string by adding the correct chars from the rails to it.
https://gist.github.com/trideon3/c5f486ce08c4275bbfc9
1
u/qaatil_shikaari Jan 09 '15
Not very clean way of doing it, but works (for now).
1
u/Quel Jan 10 '15 edited Jan 10 '15
Solution in R. Answers for the example first:
Code. Feel like my code to decode is pretty messy and overly complicated, but it goes.
1
u/Hellux Jan 10 '15
Python 2 solution. This really needed some thinking along with a lot of trial and error but I'm happy with how short it turned out.
Output:
1
u/[deleted] Jan 11 '15
Python3
1
u/verydapeng Jan 12 '15 edited Jan 12 '15
clojure
edit steal the idea from haskell's solution
1
u/malcolmflaxworth Jan 13 '15
NodeJS
I had a lot of fun with this one. Feedback generously accepted.
program.js
railcipher.js
1
u/richardthetan Jan 14 '15
Done in Javascript.
Looks like I may have done it the long way.
function encode(x){ //line 1 = every 4th starting from 0 //line 2 = every 2nd starting from 1 //line 3 = every 4th starting from 2 var line1=[]; var line2=[]; var line3=[];
1
u/_chebastian Jan 14 '15
Im doing afew weird things here, thats because im testing out loading the code from a lib so i can modify the enryption and /later/ decryption whie running the code. But heres my unpolished encryption in C++
1
u/analysisparalysis334 Jan 17 '15
scala: https://gist.github.com/analysisparalysis334/c14a15ae0b10fe64f0aa
1
u/ChiefSnoopy Jan 19 '15
Browsing back and I didn't see a C solution to this one. Here's what I just slopped together, but it works:
1
u/yitz Jan 21 '15
I'm a little late to this party. But I am surprised that no one here pointed out that the rail fence cipher is nothing more than an application of the schwartzian transform. Here is a simple solution in Haskell that makes it explicit:
1
u/pogotc 2 0 Jan 25 '15
Scala
My attempt in scala inspired by the Haskell submission:
Usage:
1
u/efabs Jan 30 '15
Python 2.7 Comments are welcome
0
u/nixrod Jan 14 '15 edited Jan 14 '15
Solution in Java: see also https://github.com/nixrod/DP196RailFenceCipher
0
u/chielklkr Jan 18 '15
My solution in C++. The decrypt part could have done better I think.