Determine whether strings are anagrams

Challenge

Given two strings, work out if they both have exactly the same characters in them.

Example

Input

word, wrdo

This returns true because they are the same but just scrambled.

Input

word, wwro

This returns false.

Input

boat, toba

This returns true

Rules

Here are the rules!

• Assume input will be at least 1 char long, and no longer than 8 chars.
• No special characters, only az
• All inputs can be assumed to be lowercase

Test Cases

boat, boat = true
toab, boat = true
oabt, toab = true
a, aa = false
zzz, zzzzzzzz = false
zyyyzzzz, yyzzzzzy = true
sleepy, pyels = false
p,p = true

• 9 answers in 13 views... wow! Mar 8, 2011 at 16:44
• Title request: Cod Elf, Go!
– user54200
Jul 9, 2016 at 12:48
• "Falcon Rage, go mad!" Oct 6, 2016 at 17:25
• My name suggestion: "are they anagrams" → "manage the arrays" Oct 31, 2017 at 4:32
• Suggested test case: aaab, bbba = false Aug 3, 2022 at 23:56

05AB1E, 3 bytes

Aargh! I can't beat GolfScript!

œså


Try it online!

Explanation

œ   All permutations of the first input
så Do the permutations contain the second input?


œQà

œ   All permutations
Q  Equality with input
à Maximum


€{Ë

€{  Map sort over the input list
Ë Are all items equal?


Julia, 26 bytes

!a=sort([a...])
a\b=!a==!b


Try it online!

TI-Basic, 83 bytes

Prompt Str1,Str2
"seq(inString(Str1+Str2,sub(Ans,I,1)),I,1,length(Ans→u
Str1
u→A
SortA(ʟA
Str2
u→B
SortA(ʟB
0
If dim(ʟA)=dim(ʟB
min(ʟA=ʟB
Ans


Output is stored in Ans and displayed. Outputs 1 if the inputs are anagrams, otherwise 0.

Alice, 11 bytes

/@Mn/
\MOX\


Try it online!

Prints Jabberwocky if the two words are anagrams

Flattened

MM       Reads the two arguments
X      Compute their symmetric difference
n     Empty string becomes Jabberwocky, anything else becomes empty string
O    Print it out
@   Bye


R, 47 bytes

\(x,y)all(table(strsplit(paste0(x,y),""))%%2==0)

• Fails for aab + bcc: try it. Nov 18, 2022 at 23:20

BQN, 3 bytes

≡○∧


Anonymous tacit function that takes two strings; returns 1 if they are anagrams, 0 otherwise. Try it at BQN online!

Explanation

≡    Are the strings identical
○   when both of them
∧  are sorted?


J-uby, 17 bytes

:*&(A|:sort)|+:==


Attempt This Online!

Explanation

:* & (A | :sort) | +:==

:* & (         )         # Map with...
A | :sort          #   convert to character array, then sort
| +:==  # then compare


Nekomata + -e, 2 bytes

↕=


Attempt This Online!

↕       Check if any permutation of the first string
=      is equal to the second string


PHP (51 chars, compressed)

C# 118 chars

using System.Linq;namespace A{class P{static void Main(string[] a){System.Console.Write(!a[0].Except(a[1]).Any());}}}


using System.Linq;

namespace A
{
class P
{
static void Main(string[] a)
{
System.Console.Write(!a[0].Except(a[1]).Any());
}
}
}

• You can remove an extra character: string[]a You also don't need a namespace.
– ICR
Dec 7, 2011 at 13:54

C#

bool IsJumbledPair(string a, string b) {
if(a.Length!=b.Length) return false;
foreach(char c in a.ToCharArray()) {
int i = b.IndexOf(c);
if(i<0) return false;
b = b.Remove(i,1)
}
return (b.Length==0);
}


Readable, and does not require sorting.

Another method:

bool IsJumbledPair(string a, string b) {
string c;
while {
if(a.Length!=b.Length) return false;
if(a.Length==0) return true;
c = a.Chars(0).ToString();
b = b.Replace(c, "");
a = a.Replace(c, "");
}
}


The above version works better when the strings contain a number of duplicated characters, as each distinct character is only compared once using the relatively fast Replace() method.

VB.NET

Same as the first C# example, slightly simpler using Replace() method, but doesn't short-cut like the C# version:

Function IsJumbledPair(a As String, b As String) As Boolean
If a.Length <> b.Length Then Return false
For Each(c As Char In a.ToCharArray())
b = Replace(b, c.ToString(), "", 1, 1)
Next
Return (b.Length=0)
}

• It is likely that the downvotes are because you have made no effort to golf (see the tag?) your solutions, or because you have mixed several distinct solutions in one answer. Mar 9, 2011 at 22:50
• Meh. If I play real golf, it's for socializing or beer, not score-keeping. Guess I should have actually been playing to win... :) Mar 11, 2011 at 6:17
• People generally respond well to solutions in wordy languages (I play in Fortran 77 from time to time), as long as you make an effort to write aggressively compacted <wordy language>, and especially if your languages supports a interesting trick (i.e. fortran has computed branches). Mar 11, 2011 at 16:10

F# (59 chars)

let f a b=(Seq.sort>>Seq.toArray)a=(Seq.sort>>Seq.toArray)b


Very annyoying that sequences can' be directly compared.

type V is array(Character)of Natural;function A(L,R:String)return Boolean is
C,D:V:=(others=>0);begin
for I in L'Range loop
C(L(I)):=C(L(I))+1;end loop;for I in R'Range loop
D(R(I)):=D(R(I))+1;end loop;return C=D;end;


C - 79 90 chars (using strchr & strlen)

r(char*s,char*t){int i=0;for(;*s&&strchr(t,*s++);i++);return i==strlen(t)?1:0;}


Ungolfed...

r( char *s, char *t )
{
int i=0;
for (; *s && strchr(t, *s++); i++)
;
return i == strlen(t) ? 1 : 0;
}


C - 115 110 chars (brute with histogram)

int k,u[256];ρ(char*s,char*t){char*v=s;for(;*s;)u[*s++]++;for(;*t;)u[*t++]--;while(*v&&!(k=u[*v++]));return k?0:1;}


Ungolfed...

int k, u[256];
r(char *s, char*t)
{
char *v = s;

for (;*s;)
u[*s++]++;
for (;*t;)
u[*t++]--;

while(*v && !(k=u[*v++]) )
;
return k ? 0 : 1;
}


EDIT: fixed bug in brute version.

EDIT: added brute version (no library functions).

• You use the table 256 char; if you call that function more that one time it is necessary make that 256 table 0.
– user58988
Oct 7, 2016 at 10:48

Coffee Script (52)

a=(b,c)->b.split('').sort()==c.split('').sort()+''


usage

console.log a 'god', 'dog'


Python 121 Characters

It's not a winner wrt length, but I didn't use sorted!

from sys import argv as s
for i in s[1]+s[2]:
if not s[1].count(i)==s[2].count(i):
print 'False'
break
else:
print 'True'

• You can save 2 characters by changing the import to from sys import* (newline) s=argv. Sep 13, 2011 at 14:45
• Algorithm fails with s[1]='the',s[2]='them'. Sep 13, 2011 at 14:54
• You could avoid the need to dereference s by from sys import* (newline) _,a,b=argv. Sep 13, 2011 at 17:19

Groovy, 46

b={args[it].toList().sort()}
print b(0)==b(1)


Groovy, 54

print args[0].toList().sort()==args[1].toList().sort()

• I've fixed up the formatting for you. Stack Exchange site use MarkDown (though they do accept a subset of html). THe sidebar on the edit page has some hints, the edit toolbar has common operations, and there is a detailed help page. Mar 9, 2011 at 22:46

Java, 173 chars

import java.util.*;class C{public static void main(String[]a){byte[]d,f;Arrays.sort(d=a[0].getBytes());Arrays.sort(f=a[1].getBytes());System.out.print(Arrays.equals(f,d));}}


It's the same that Guus one but changing a couple of methods.

• So it's no shorter but it is buggier? Dec 7, 2011 at 14:04
• Hmmm... Why buggier? Dec 7, 2011 at 14:34
• Maybe this? "The behavior of this method when this string cannot be encoded in the default charset is unspecified." :P Dec 7, 2011 at 14:36
• My bad, forgot to check the spec. I was thinking about characters in the range \u0080 to the end of the BMP, which become more than one byte, and which would allow collisions. Dec 7, 2011 at 15:08

CoffeeScript 129

Longer than the other CoffeeScript entry, but this one uses recursive string comparison, rather than just comparing sorted strings:

z=(x,y)->d=y.length;e=x.length;return 1if(!d&&!e);b=y.indexOf x[0];return 0if b<0;f=x[1..e];g=y[b+1..d];g=y[0..b-1]+g if b;z(f,g)


Outputs 1 or 0 indicating whether the strings are anagrams or not.

Javascript 70 (with primitive GUI)

Here's a Javascript entry that also includes a primitive GUI via two prompts and an alert.

function a(){return prompt('').split('').sort().join()}alert(a()==a())


Have a play – http://jsfiddle.net/liamnewmarch/jGues/

JavaScript 87

alert((a=prompt().split(","))[0].split("").sort().join()==a[1].split("").sort().join())

Prompt requires comma separated list of two "words"

[Prompt]

btoa,boat

Output: true

import java.util.Scanner;
public class Match
{
public static void main(String[] args)
{
Scanner s=new Scanner(System.in);
String s1=s.nextLine();
String s2=s1.toLowerCase();
char []a=s2.toCharArray();
String s3=s.nextLine();
String s4=s3.toLowerCase();
char []e=s4.toCharArray();
int h,g = 0,l=0,r=0,h1=0,m=0;
int b=(int)a[0];
int f=(int)e[0];
//System.out.println();
for(int k=0;k<a.length;k++)
{
for(h=1+k;h<a.length;h++)
{
if(b>(int)a[h])
{
b=a[h];
char temp=a[h];
a[h]=a[k];
a[k]=temp;
}

}
if(l<a.length-1)
{
b=a[++l];
}
}
for(int k1=0;k1<e.length;k1++)
{
for(h1=1+k1;h1<e.length;h1++)
{
if(f>(int)e[h1])
{
f=e[h1];
char temp=e[h1];
e[h1]=e[k1];
e[k1]=temp;
}

}
if(m<e.length-1)
{
f=e[++m];
}
}
if(a.length==e.length)
{
int flag=0;
for(int j=0;j<a.length;j++)
{
if(a[j]==e[j])
{
flag++;
}
}
if(flag==e.length)
{
System.out.println("True");
}
else
{
System.out.println("false");
}
}
else
{
System.out.println("False");
}
}
}


C#, 144 chars

namespace System.Linq{class m{static void Main(string[]a){Console.Write(a[0].Select(t=>a[1].Select(y=>t!=y)).Count()*2==(a[0]+a[1]).Length);}}}


Function: 90 chars

bool i(string a,string b){return a.Select(t=>b.Select(y=>t!=y)).Count()*2==(a+b).Length;}


VB.net

Module Q
Sub Main(a As String())
Console.WriteLine(a(0).Count=-a(0).Sum(Function(c)a(1).Sum(function(x)x=c)))
End Sub
End Module


C 138

Code finds the sum of the differences of the characters then checks if they are same length and sum == 0.

int s,t,i,j;
void f(char*a,char*b)
{
while (*a&&*b){
s+=*a-*b;
a++;b++;
i++;j++;
}
if (i==j&&s==0)t=1;
puts(t?"true":"false");
}

• This can not be ok every input... What about string has the same value example "caa" and "bba" ?
– user58988
Dec 20, 2018 at 15:04

Groovy 44

def f(a,b){print !(a-b)&&a.size()==b.size()}


pure bash 136

There is a method without sorting step!

anagramCmp() {
x=0 y=0
for((i=0;i<${#1};i++));do ((x+=7**(36#${1:i:1}-10)))
((y+=7**(36#${2:i:1}-10)))2>/dev/null done return$((${#1}$x==${#2}$y?0:1))
}


Then now:

if anagramCmp Blah Halb ; then echo Yo; else echo Uh; fi
Yo

if anagramCmp Blahblah Hhaallab ; then echo Yo; else echo Uh; fi
Uh


Javascript - 57 chars

function o(a,b){return b?o(a)==o(b):1+a.split("").sort()}

• Your function will fail if in the first try, b was empty. Sep 14, 2014 at 22:04
• All inputs will be at least 1 char long, you give the function the 2 strings you want to compare so that won't happen Sep 15, 2014 at 22:25
• @Optimizer did you even try running it? Sep 15, 2014 at 22:37
• Ah, I see. In that case, it will be fine. Sep 16, 2014 at 6:43