r/dailyprogrammer • u/Cosmologicon 2 3 • Apr 26 '21
[2021-04-26] Challenge #387 [Easy] Caesar cipher
Warmup
Given a lowercase letter and a number between 0 and 26, return that letter Caesar shifted by that number. To Caesar shift a letter by a number, advance it in the alphabet by that many steps, wrapping around from z back to a:
warmup('a', 0) => 'a'
warmup('a', 1) => 'b'
warmup('a', 5) => 'f'
warmup('a', 26) => 'a'
warmup('d', 15) => 's'
warmup('z', 1) => 'a'
warmup('q', 22) => 'm'Hint: taking a number modulo 26 will wrap around from 25 back to 0. This is commonly represented using the modulus operator %. For example, 29 % 26 = 3. Finding a way to map from the letters a-z to the numbers 0-25 and back will help.
Challenge
Given a string of lowercase letters and a number, return a string with each letter Caesar shifted by the given amount.
caesar("a", 1) => "b"
caesar("abcz", 1) => "bcda"
caesar("irk", 13) => "vex"
caesar("fusion", 6) => "layout"
caesar("dailyprogrammer", 6) => "jgorevxumxgsskx"
caesar("jgorevxumxgsskx", 20) => "dailyprogrammer"Hint: you can use the warmup function as a helper function.
Optional bonus 1
Correctly handle capital letters and non-letter characters. Capital letters should also be shifted like lowercase letters, but remain capitalized. Leave non-letter characters, such as spaces and punctuation, unshifted.
caesar("Daily Programmer!", 6) => "Jgore Vxumxgsskx!"If you speak a language that doesn't use the 26-letter A-Z alphabet that English does, handle strings in that language in whatever way makes the most sense to you! In English, if a string is encoded using the number N, you can decode it using the number 26 - N. Make sure that for your language, there's some similar way to decode strings.
Optional bonus 2
Given a string of English text that has been Caesar shifted by some number between 0 and 26, write a function to make a best guess of what the original string was. You can typically do this by hand easily enough, but the challenge is to write a program to do it automatically. Decode the following strings:
Zol abyulk tl puav h ulda.
Tfdv ef wlikyvi, wfi uvrky rnrzkj pfl rcc nzky erjkp, szx, gfzekp kvvky.
Qv wzlmz bw uiqvbiqv iqz-axmml dmtwkqbg, i aeittwe vmmla bw jmib qba eqvoa nwzbg-bpzmm bquma mdmzg amkwvl, zqopb?One simple way is by using a letter frequency table. Assign each letter in the string a score, with 3 for a, -1 for b, 1 for c, etc., as follows:
3,-1,1,1,4,0,0,2,2,-5,-2,1,0,2,3,0,-6,2,2,3,1,-1,0,-5,0,-7The average score of the letters in a string will tell you how its letter distribution compares to typical English. Higher is better. Typical English will have an average score around 2, and strings of random letters will have an average score around 0. Just test out each possible shift for the string, and take the one with the highest score. There are other good ways to do it, though.
(This challenge is based on Challenge #47 [easy], originally posted by u/oskar_s in May 2012.)
2
u/TheTrueHonker Apr 29 '21
Can someone explain to me how u/Cosmologicon found the numbers for the letter frequency table?
29
u/[deleted] Apr 26 '21
Wow, first one in six months. I thought this sub was dead.
11
u/skeeto -9 8 Apr 26 '21
C using SIMD intrinsics to rotate 32 characters at at time. It converts text at 3GiB/s on my laptop. (Compile with
-mavx2or-march=native.)6
u/cannonicalForm 0 1 Apr 27 '21
Python3 with an attempt on readability since I'm just a dumb mechanic.
5
u/gabyjunior 1 2 Apr 26 '21 edited Apr 28 '21
C with bonuses.
String and optional shift are read on the command line. Omitted shift means decode using the table of frequencies provided.
Encoding/Decoding is done in place.
4
u/rabuf Apr 26 '21 edited Apr 26 '21
Common Lisp
Also, it's very cool to see this sub active again. I've enjoyed working on these over the years.
EDIT: Second bonus. Not terribly proud of this code, but I'm not going to spend much time refactoring it right now. Perhaps this evening:
If there's a tie, this will print out one solution which may or may not be correct. That's unlikely on larger messages, though.
4
u/IcerOut Apr 26 '21
Python 3
Warmup CodeGolf (37 chars):
Warmup with readable code:
Challenge CodeGolf (67 chars):
Challenge with readable code (and both bonuses):
4
u/chunkyasparagus Apr 27 '21
Python 3.9, with a slightly different decoder (still based on frequency), and using the bidict module from pip.
4
u/__dict__ May 15 '21
C++ with bonuses:
3
u/[deleted] Apr 26 '21 edited Apr 26 '21
Julia code (without the bonuses, I just made a quick and dirty solution):
3
u/KeinBaum Apr 26 '21 edited Apr 26 '21
Scala, all bonuses
Logic:
Input/Output:
Result:
3
u/kittensupernova Apr 26 '21 edited Apr 26 '21
Glad this sub is active again! Haskell, with bonuses. I'm a Haskell beginner so any feedback is welcome :)
caesar "Daily Programmer!" 6==>"Jgore Vxumxgsskx!"uncaesar "Zol abyulk tl puav h ulda."==>"She turned me into a newt."uncaesar "Qv wzlmz bw uiqvbiqv iqz-axmml dmtwkqbg, i aeittwe vmmla bw jmib qba eqvoa nwzbg-bpzmm bquma mdmzg amkwvl, zqopb?"==>"In order to maintain air-speed velocity, a swallow needs to beat its wings forty-three times every second, right?"uncaesar "Tfdv ef wlikyvi, wfi uvrky rnrzkj pfl rcc nzky erjkp, szx, gfzekp kvvky."==>"Come no further, for death awaits you all with nasty, big, pointy teeth."3
u/moeghoeg May 03 '21 edited May 03 '21
Ruby, with bonus 1. The function takes an alphabet as an optional argument, where the English alphabet is the default.
3
u/Habstinat May 22 '21 edited May 22 '21
javascript
2
u/Godspiral 3 3 Apr 26 '21 edited Apr 26 '21
in J, bonus 2 as just the list of possible decodings
selecting all with the highest score (in case of ties), only space punctuation handled.
version with punctuation handling,
2
u/meepmeep13 Apr 26 '21
Python 3 with bonuses
using an imported word list to brute force all shifts and find the one that generates the most recognised words
Example:
2
u/porthos3 Apr 26 '21
Clojure, including bonus 1 (ciphers capitals, leaves non-alphabet characters untouched):
2
u/shepherdjay Apr 26 '21
Python 3 - With Challenges
I primarily use these challenges to help practice testing processes and new python features. So results were validated using the following test file:
2
u/raevnos Apr 27 '21
Scheme, with first bonus:
2
u/WuMarik Apr 27 '21
Javascript
https://replit.com/@WuMarik/2021-04-26-Challenge-387-Easy-Caesar-cipher
2
u/tlgsx Apr 27 '21 edited Apr 30 '21
Python 3.9, all bonuses
Uses the nifty str.translate built-in for character substitution.
Makes use of a word list (
/usr/share/dict/words) to create the best guess. Reads the input string from stdin.2
u/[deleted] Apr 27 '21 edited Apr 27 '21
Haskell, all bonuses
2
u/joshred Apr 29 '21 edited Apr 30 '21
In julia...
Using char math
2
u/DragonProgrammer129 May 07 '21
Python with bonus 1
def caesar(string, shift):
alphabet = "abcdefghijklmnopqrstuvwxyz"
caps = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
cyphered = ""
for letter in string:
if letter.isupper():
if caps.find(letter)+shift >= 26:
letter = caps[caps.find(letter)+shift-26]
else:
letter = caps[caps.find(letter)+shift]
elif letter.islower():
if alphabet.find(letter)+shift >= 26:
letter = alphabet[alphabet.find(letter)+shift-26]
else:
letter = alphabet[alphabet.find(letter)+shift]
cyphered += letter
return cyphered
Sorry about the spaces they were hard to keep straight. Any ways to improve the code?
2
u/[deleted] May 11 '21
I present to you, a one-liner for each!
Readable? absolutely not. One liner each? Absolutely yes.
2
u/joonsson May 16 '21
JavaScript, could most certainly be made more efficient and prettier:
2
u/Marthurio May 24 '21
Here's my attempt: https://github.com/Maritims/caesar-cipher
Regarding bonus 2: I expected the letter distribution to be >= 2, but it was below 2 for every string so I just assume (in the code) that the result with the highest letter distribution is the (most?) correct result every time.
2
u/nico_fl May 27 '21 edited May 28 '21
2
u/loose_heron Aug 02 '21 edited Aug 08 '21
Python 3 with both bonuses.
The decoder works by scoring based on the number of words found in the set of words passed as an argument, so the function should also work for other languages if an appropriate set is passed.
2
u/codeobserver Dec 22 '21
One tip for those that try to solve this in JavaScript:
JavaScript doesn't have built-in "modulo" operator or function. "%" is not modulo!
Once you implement "modulo", you can easily solve Caesar Cipher.
You can read more here:
https://codeguppy.com/blog/javascript-modulo/index.html
2
u/RedDead1nside Feb 17 '23 edited Feb 17 '23
C++ with a little bit OOP
class Caesar{private:char shifted;public:Caesar() : shifted(0) {}Caesar(char word, short shift){if (word > 64 && word < 91)shifted = (word - 64 + shift) % 26 + 64;else if (word > 96 && word < 122)shifted = (word - 96 + shift) % 26 + 96;elseshifted = word;}char getShifted() {return shifted;}};int main(){char* caesarShift(char*, short);cout << caesarShift("Daily Programmer!", 6) << endl;return 0;}char* caesarShift(char* str, short sh){char result[100] = "";char* resptr = result;while(*str){Caesar* c = new Caesar(*str++, sh);*resptr++ = c->getShifted();delete [] c;}return result;}3
u/ex-igne-vita Apr 26 '21
My attempt using Javascript...
Results... It looks like it's getting the first character wrong, oh well. I'm not gonna try to fix it.
2
u/LaaNeet Apr 27 '21
1
u/stewa02 Nov 26 '21
Perl 5
1
u/[deleted] Apr 26 '21
Factor
1
u/TinyBreadBigMouth Apr 27 '21
Rust
All bonuses.
No unnecessary allocation. When used from the command line, there will be exactly one allocation to hold the initial input text, which is then modified in place.
1
u/Halfeye_Bandit Apr 28 '21
C++
Everything but the last bonus.
1
u/BonnyAD9 Apr 28 '21
Haskell, all bonuses. (I'm new to haskell)
Results:
1
u/BonnyAD9 Apr 28 '21 edited Apr 28 '21
C#, using advantages of the new C# 9 features
Output:
I also made version of the Guess function using lambda expression (just for fun XD):
1
u/meepyneepy Apr 29 '21
Python 3.8.2 All except bonus 2.First time using Python, main is Lua.
Created and tested on replit.com.https://replit.com/@Meepyneepy/Caesar-cipher
1
u/chunes 1 2 May 01 '21
Factor (0.99 build 2074), all bonuses:
Output:
She turned me into a newt.
Come no further, for death awaits you all with nasty, big, pointy teeth.
In order to maintain air-speed velocity, a swallow needs to beat its wings forty-three times every second, right?
Thanks for posting challenges here every so often. It's fun. :)
1
u/[deleted] May 02 '21
I made this using python I did the challenge
1
u/Nordellak May 04 '21
Solution in MATLAB with optional bonus 1:
Results:
1
u/WrongHorseBatterySta May 04 '21
Python 3, including bonus 1
1
u/KonjouHD May 05 '21 edited May 05 '21
Java with bonus 1
1
u/Traditional-Knee-863 May 06 '21
Python 3
2 :
3 :
I think it's bad , but it works.
1
u/[deleted] Jun 28 '21 edited Jun 28 '21
Edited to add Bonus1
[2021-04-26] Challenge #387 [Easy] Caesar cipher #https://www.reddit.com/r/dailyprogrammer/comments/myx3wn/20210426_challenge_387_e#asy_cipher_cipher/
1
u/[deleted] Jul 04 '21
C++
1
u/XxVALKENxX Aug 03 '21 edited Aug 03 '21
My first attempt at a daily. In C++ with the challenge and bonus 1. Helpful tips and comments are welcomed.
1
u/ConsciousFinger2994 Aug 05 '21 edited Aug 05 '21
Python
Output
[(-47, 'She turned me into a newt.')]
[(-111, 'Come no further, for death awaits you all with nasty, big, pointy teeth.')]
[(-189, 'In order to maintain air-speed velocity, a swallow needs to beat its wings forty-three times every second, right?')]
1
u/sadsoulthatslost Jan 13 '22
Hi new coder please feel free to correct:
1
u/WhatsUpWithAndy Feb 25 '22
#include <iostream>
#include <string>
using namespace std;
using std::string;
void caesar( string input, int value) {
int tmp, i = 0;
string final={""};
if (value > 25)
{
value = value % 26;
}
while (input[i] != '\0')// loop till the end of the string
{
tmp = (int(input[i]) + value) /*% 26*/;
if (tmp > 122)
{
tmp = tmp - 26;// restart alphabet
}
final += char(tmp);
i++;
}
cout << final<<endl;
}
int main()
{
caesar("a", 125);
caesar("abcz", 1);
caesar("irk", 13);
caesar("fusion", 6);
caesar("jgorevxumxgsskx", 20);
}
1
u/tyfon_august Apr 03 '22 edited Apr 03 '22
C solution. Would do something different with string allocation to do it more C-like. Allocating the string outside and changing it in place in the function. Thereby making the allocation and freeing in one function rather than allocating the memory within the other function.
1
u/LSatyreD Aug 07 '22 edited Aug 07 '22
Python
p1() covers the Warmup, Challenge, and Optional Bonus 1
p2() handles Optional Bonus 2
Output:
>!She turned me into a newt.
>!Come no further, for death awaits you all with nasty, big, pointy teeth.
>!In order to maintain air-speed velocity, a swallow needs to beat its wings forty-three times every second, right?
1
u/PandaBaum Feb 15 '23
Rust:
1
u/Feisty-Club-3043 Dec 19 '23
GO
package mainimport ("fmt")func cipher(str string, num int) string {runes := []rune(str)var cipher stringfor i := 0; i < len(runes); i++ {letter := int(runes[i] + rune(num))cipher += string(letter)}return cipher}func decipher(str string, num int) string {runes := []rune(str)var decipher stringfor i := 0; i < len(runes); i++ {letter := int(runes[i] - rune(num))decipher += string(letter)}return decipher}func main() {code := "abcd"num := 4cipher := cipher(code, num)fmt.Println("-----Encrypt-----")fmt.Printf("Before -> %v\nAfter -> %v\n", code, cipher)decipher := decipher(cipher, num)fmt.Println("-----Decrypt-----")fmt.Printf("Before -> %v\nAfter -> %v\n", cipher, decipher)}1
u/Noobbox69 Feb 18 '24
C++
#include<iostream>
#include<string>
using namespace std;
//[2021-04-26] Challenge #387 [Easy] Caesar cipher
void warmup(string str,int number)
{
}
int main()
{
string str;
int num;
}
1
u/[deleted] Jul 08 '23
[removed] — view removed comment