| Bytes | Lang | Time | Link |
|---|---|---|---|
| 007 | Jelly | 171016T191640Z | caird co |
| 006 | Vyxal 3 | 250818T221534Z | pacman25 |
| 026 | Janet | 250818T182409Z | Adam |
| 009 | Pip r | 200907T040322Z | DLosc |
| 043 | Zsh eo extendedglob | 210311T170113Z | pxeger |
| 066 | PowerShell Core | 200904T052346Z | Julian |
| 048 | R | 200907T132509Z | Dominic |
| 018 | Pip | 200904T044502Z | Razetime |
| 014 | APL Dyalog Unicode | 200904T055949Z | Razetime |
| 087 | Javascript ES7 Draft | 150521T044433Z | nderscor |
| 092 | C99 | 150522T073924Z | rr- |
| 281 | Java | 150525T002142Z | Jack Amm |
| 050 | ><> Fish | 150524T183602Z | randomra |
| 097 | C | 150524T025100Z | Reto Kor |
| 048 | bash | 150521T133856Z | xebtl |
| 056 | Prolog | 150523T050343Z | Persitz |
| 052 | Matlab/Octave | 150521T230259Z | FryAmThe |
| 048 | Matlab | 150522T115338Z | Oebele |
| 035 | KDBQ | 150522T103737Z | WooiKent |
| 080 | Perl | 150521T125336Z | xebtl |
| 083 | Julia | 150521T023913Z | Alex A. |
| 083 | R | 150521T040218Z | MickyT |
| 009 | Pyth | 150521T185227Z | izzyg |
| 011 | CJam | 150521T013641Z | Martin E |
| 2147 | Python 2 147 Bytes | 150521T133906Z | Kade |
| 080 | Python 2 | 150521T144025Z | SylvainD |
| 015 | APL | 150521T110009Z | marinus |
| 057 | Scala | 150521T041506Z | Others |
| 019 | J | 150521T033400Z | randomra |
| 013 | CJam | 150521T021805Z | jimmy230 |
Jelly, 7 bytes
O_/ịØAE
+2 bytes correcting a bug
How it works
O_/ịØAE - Main link. Takes two strings as a list [A, B]
O - Convert to ordinals
_/ - Columnwise subtract
ịØA - Modularly index into the alphabet
E - Are all equal?
Vyxal 3, 6 bytes
⎂O-øA≈
takes input in lowercase, gets the difference between each ordinal and get that letter of the alphabet (øA saves a byte over 26%) then check if every item is the same
Janet, 26 bytes
I had to add this answer to make the number of answers equal to the number of votes again.
Janet is really good at this particular task :D The low byte count compared to other general-purpose scripting languages is due to treating strings as an array of bytes and having a short built-in variadic equality function.
Takes a list of two strings, which must be in a consistent case.
|(=;(map|(mod(-;$&)26);$))
Pip -r, 12 9 bytes
$Qz@$-A^g
Explanation
With the -r flag, g is a list of lines from stdin rather than the usual list of command-line arguments.
$Qz@$-A^g
^g Split each line into a list of characters (vectorizes on lists)
A Convert each character to its ASCII code (vectorizes on lists)
We now have a list of two lists of numbers
$- Fold on subtraction; since - also vectorizes on lists, this does
pairwise subtraction of the character codes, returning a list
of differences
z@ Use each difference as a modular index into z, the lowercase alphabet
$Q Fold that list of characters on string-equals: 1 if all items
are equal, 0 otherwise
Zsh -eo extendedglob, 43 bytes
>$2
repeat 25 {1=`tr a-z b-za<<<$1`;ls ^$1}
Input from command-line arguments and output via exit code. I'm not doing stdin/stdout, that's idiotic.
PowerShell Core, 68 66 bytes
$a,$b=$args;(1..$a.Length|%{($a[--$_]-$b[$_]+26)%26}|gu).count-eq1
(1..$a.Length # Builds an array of the size of one of the input
|%{($a[--$_]-$b[$_]+26)%26} # For each of the characters, gets their distance making sure we stay between 0 and 25
|gu # Remove duplicates
).count-eq1 # Returns True if we have a single record
R, 48 bytes
a=scan(,'');`+`=utf8ToInt;!sd((+a[1]-+a[2])%%26)
Standard deviation (sd) of the differences between the character codes (mod 26) is zero only if they are all the same. Requires all-same-case input.
Pip, 33 18 bytes
$=({Aa-Ab}%26MZqq)
-15 bytes from Dlosc.
Explanation
$=({AB((Ab<Aa?-26 0)+Aa-Ab)}MZab) ; a,b → command line args
MZab ; Map items of a and b to function, pass as (a,b)
{ Aa-Ab } ; Subtract codepoints of a and b
(Ab<Aa?-26 0)+ ; Add -26 if b > a
AB( ) ; Take the absolute value of the whole thing
$= ; Check if all items of the mapped list are equal
APL (Dyalog Unicode), 14 bytes(SBCS)
1=≢∪26|-⌿⎕UCS⎕
Takes input as a two row matrix and returns truthy or falsey value
Explanation
1=≢∪26|-⌿⎕UCS⎕
⎕UCS⎕ ⍝ Convert all characters to Unicode codepoints
-⌿ ⍝ Subtract pairs of matrix along leading axis(x)
26| ⍝ Get residue(modulus) of 26 with each difference(works with negatives)
1=≢∪ ⍝ Check if number of unique remainders is equal to 1.
Javascript (ES7 Draft), 87 bytes
Requires inputs to be the same case.
(p=prompt)(-b[c](i)+26)%26 for(i in b=p(a=p()))].some(x=>x^z))
C99, 92 bytes with bug 101 92 bytes
r,i;main(z,a)char**a;{for(;z=a[2][++i];)r|=(a[1][i]-z+*a[2]-*a[1]+52)%26;putchar(49-!!r);}
Pretty straightforward; assumes words come as first and second arguments, respectively. Compiled with -std=c99.
Java 281
import java.util.*;enum C{E;Scanner s=new Scanner(System.in);public static void main(String[]z){char[]u=E.n(),v=E.n();int i=0,d=(u[0]-v[0]+26)%26;boolean e=true;for(;++i<u.length;)e&=d==(u[i]-v[i]+26)%26;System.out.print(e);}char[]n(){return s.next().toUpperCase().toCharArray();}}
expanded:
import java.util.*;
enum Caesar{
Equivalence;
Scanner input=new Scanner(System.in);
public static void main(String[]z){
char[]firstString=Equivalence.nextInput(),secondString=Equivalence.nextInput();
int index=0,difference=(firstString[0]-secondString[0]+26)%26;
boolean isEqual=true;
for(;++index<firstString.length;)
isEqual&=difference==(firstString[index]-secondString[index]+26)%26;
System.out.print(isEqual);
}
char[]nextInput(){
return input.next().toUpperCase().toCharArray();
}
}
I could save 14 bytes if I got rid of converting everything to uppercase, but I feel like it's more complete to leave it in.
><> (Fish), 50 bytes
i:3b*(?v88+0.;n1<
0)?vc1.>~ri-&l?!^i-&:&-2d*%
;n0<
Expects letters at the same position to have the same case.
Explanation
i:3b*(?vreads the first word into the stack with88+0.providing the looping jump~ri-&removes~the separating space from the stack, reverses the stackr(first letter will be on top), reads in the first letter of the second wordi, calculates the offset from the first word's first letter-and stores it in the register&.l?!^i-&:&-2d*%0)?vreads every next letter of the second word substracting it from the first word's corresponding letter which is at the top of the stack substracts the offset&:&-stored in the register and checks if the result is 0 mod 262d*%. If not prints 0 and terminates0n;.c1.provides the looping jump.- If reached the end of the second word the program prints 1 and terminates
1n;.
C, 97 bytes
#define D (*a[2]++-*a[1]+++26)%26
d,r;main(int c,char**a){for(d=D;*a[1];r|=d-D);puts(r?"N":"Y");}
bash, 71 48
Using the “standard” Unix program caesar(6).
New version (with lots of help from @DigitalTrauma):
read a b;seq -f"caesar %g <<<$a" 26|bash|grep $b
- Inputs have to be on the same line, separated by spaces
- Character case must match between inputs.
- Prints
1for true or nothing for false.
If input via command line arguments is allowed, it can be shortened to 39 bytes:
seq -f"caesar %g <<<$1" 26|bash|grep $2
Old version for the record:
read a b;for i in `seq 26`;do [ `echo $a|caesar $i` = $b ]&&echo 1;done
Prolog, 56 bytes
b([],[],_).
b([A|C],[B|D],N):-N is mod(A-B,26),b(C,D,N).
Not all combinations of cases are supported.
usage
b(`abcd`,`yzab`,_).
Matlab/Octave, 53 52
x=@()input('','s');isscalar(unique(mod(x()-x(),26)))
Input should all be of the same case.
Sadly, Matlab is not very good with user input. As an anonymous handle, this could be only 35 bytes:
@(a,b)isscalar(unique(mod(a-b,26)))
Matlab treats the characters of a string as a vector of numbers. Doing subtraction gets us their difference, and unique converts that vector into a vector containing only unique values. If there is only one number, the words are caeser equivalent and isscalar returns 1, otherwise it will return 0.
Matlab, 49 48 bytes
This was a really quick one. Sadly getting a string from stdin is quite expensive.
x=@()input('','s');sum(diff(mod(x()-x(),26)))==0
Note that it is, like most if not all answers, case sensitive.
EDIT: shaved off one byte by defining an anonymous function!
KDB(Q), 35 bytes
{0=sum(1_-':)mod[;26](-)."i"$(x;y)}
Explanation
"i"$(x;y) / convert to ascii decimal
(-). / get differences
mod[;26] / mod 26
(1_-':) / difference between the differences
0=sum / sum should be 0 if equivalent
{ } / lambda
Test
q){0=sum(1_-':)mod[;26](-)."i"$(x;y)}["abcd";"yzab"]
1b
Perl, 80
Edit: A failed optimization had slipped into the golfed code. Now it matches the ungolfed version. (The byte count was correct, though.)
@a=unpack"W*",<>;for(<>=~/./g){$n=ord()-shift@a;$p=!$c++||$p&&$n==$o;$o=$n}say$p
Run with Perl version 5.10 (perl -M5.10.0 or perl -E …) for say(). Slightly expanded version:
@a=unpack"W*",<>; # read first string, split and convert to numbers
for(<>=~/./g){ # reads the second string and splits it
$n=ord()-shift@a; # convert next character of second string and compare
$p= !$c++ || $p && $n==$o; # compare differences (special case for first char)
$o=$n
}
say $p
The code outputs 1 (truthy in Perl) if the strings are Caesar equivalent, and the empty string (falsy in Perl) if they are not. If this is too loose an interpretation, I need to add 2 bytes for say$p+0, which prints 1 or 0.
Character case must match between inputs.
Julia, 91 87 83 bytes
a=readline()
b=readline()
show(length(Set([mod(a[i]-b[i],26)for i=1:length(a)]))<2)
Ungolfed + explanation:
# Read two strings from STDIN
a = readline()
b = readline()
# Get the absolute difference mod 26 of the character values in the strings
x = [mod(a[i] - b[i], 26) for i = 1:length(a)]
# Construct a set consisting of the elements of x. If the set has only a
# single element, the strings are Caesar equivalent. This will print a
# boolean value to STDOUT.
show(length(Set(x)) < 2)
This takes advantage of the fact that strings in Julia can be treated as character arrays and that arithmetic operations can be performed on character values. The input strings can have any mix of capitalization you want, so long as the capitalization at each position matches between the strings.
R, 83 84
Fairly much the same as the other solutions. Convert the strings into a vector of integers. Mod the difference of the vectors by 26. Do a unique over the list as check the length is 1. It expects the case to be the same in corresponding characters in each string.
length(unique(((S=strtoi)((R=charToRaw)((I=readline)()),16L)-S(R(I()),16L))%%26))<2
It waits for the two strings to be entered
> length(unique(((S=strtoi)((R=charToRaw)((I=readline)()),16L)-S(R(I()),16L))%%26))<2
abcdefghijklmnopqrstuvwxyz
opqrstuvwxyzabcdefghijklmn
[1] TRUE
> length(unique(((S=strtoi)((R=charToRaw)((I=readline)()),16L)-S(R(I()),16L))%%26))<2
Hello
World
[1] FALSE
> length(unique(((S=strtoi)((R=charToRaw)((I=readline)()),16L)-S(R(I()),16L))%%26))<2
Bob
Nan
[1] TRUE
>
Pyth, 9 bytes
}wm=.rzGG
The two strings are expected in lowercase, newline separated.
How it works:
.r is Pyth's rotary translation function. It maps each element in the first argument from its first occurance in the second argument to the next entry in the second argument. In this, case, the second argument is G, the lowercase alphabet, so this is equivalent to a Caesar shift of 1.
Putting an = in front of the function makes it in-place. Thus, =.rzG assigns the Caesar shift of z by one to z. Note that z is initialized to the first line of input in Pyth.
This expression is used inside a map. m=.rzGG applies this transformation to z 26 times, once for each element of G, and saves the results in a list. This gives the list of all possible Caesar shifts of z.
Finally, }w checks whether the next line of input is in that list.
CJam, 17 12 11 bytes
1 byte saved by Dennis.
ll.m26f%)-!
Expects the first string to be lower case and the second to be upper case. Prints 1 for Caesar-equivalent strings and 0 otherwise.
Explanation
ll e# Read two lines of input.
.m e# Take the differences of corresponding characters.
26f% e# Take the differences modulo 26.
)- e# Remove all copies of the last difference from the array. This will
e# yield an empty array if and only if all differences are the same.
! e# Logical NOT, which yields 1 for an empty array and 0 otherwise.
The reason we require the first string in lower case and the second in upper case is to ensure that the difference is always positive. Otherwise taking the modulo might return something negative and would not necessarily be unique, even for Caesar-equivalent strings.
Python 2 - 241 237 188 147 Bytes
Takes input as lowercase string enclosed in quotes, space separated. There has to be a better way..
s=[[ord(x)for x in y]for y in input().split()];v=[];v=[v+[(s[1][i]-s[0][i])%26]for i in xrange(0,len(s[0]))];v=sum(v,[]);print sum(v)//v[0]==len(v)
Ungolfed (260-odd bytes)
strs = [[ord(x) for x in y] for y in raw_input().split()]
vals = []
for i in xrange(0, len(strs[0])):
if strs[0][i]<strs[1][i]:
vals += [strs[1][i]-strs[0][i]]
else:
vals += [26-(strs[0][i]-strs[1][i])]
return sum(vals)//vals[0] == len(vals)
Python 2, 80 bytes
Takes 2 similarly-cased strings from stdin separated by a space :
s,t=raw_input().split();print len(set((ord(c)-ord(d))%26 for c,d in zip(s,t)))<2
Tested on following test cases :
tests = [
("abc", "abc", True),
("abcd", "abc", False),
("abc", "cde", True),
("Abc", "Cde", True),
("abc", "deg", False),
("Hello", "World", False),
("Abcd", "Yzab", True),
("", "", True)
]
for s, t, v in tests:
if len(s) == len(t): # I didn't read that at first
assert v == (len(set((ord(c) - ord(d)) % 26 for c, d in zip(s, t))) < 2)
APL (15)
1=≢∪26|-⌿⎕A⍳↑⍞⍞
It needs the letters to be uppercase, and prints either 1 or 0, like so:
1=≢∪26|-⌿⎕A⍳↑⍞⍞
ABCD
YZAB
1
1=≢∪26|-⌿⎕A⍳↑⍞⍞
HELLO
WORLD
0
Explanation:
↑⍞⍞: read two lines from the keyboard, and arrange the characters in an N×2 matrix.⎕A⍳: for each character, find at which position it occurs in⎕A(the uppercase alphabet).-⌿: for each column, subtract the second value from the first value26|: take the mod-26 of each of those numbers.- If the strings are Caesar-equivalent, all numbers in this list are now equal, so:
≢∪: find the number of unique values in the list1=: compare that to1.
Scala, 57 bytes
(readLine zip readLine map(x=>x._1-x._2%26)toSet).size==1
Little longer than the others, and essentially equivalent, but it is in a vary different style of language!
I also have this version(56 bytes):
(readLine zip readLine map(_._1-x$1._2%26)toSet).size==1
But I don't know if the x$1 working is coincidence or by design...
J, 19 bytes
1=[:#@~.26|-&(3&u:)
Letters at the same position should have the same case.
After converting both input strings to their codepoint representation with &(3&u:) we compare 1 to the length # of the nub ~. of the modulo 26 26| of the difference - of the two arrays. The nub will be 1 if all Caesar-distances are the same.
Usage:
'abcd' (1=[:#@~.26|-&(3&u:)) 'yzab'
1
CJam, 13 bytes
{r(fm26f%}2*=
It requires the first character in each word to be in upper case, others in lower case.
Too bad the APL variants doesn't support character arithmetics...
Explanation
{
r e# Read a word.
(f- e# Return each character value minus the first character.
26f% e# Mod 26.
}2* e# Repeat 2 times.
= e# Check if they are equal.