# 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! Commented Mar 8, 2011 at 16:44
• Title request: Cod Elf, Go!
– user54200
Commented Jul 9, 2016 at 12:48
• "Falcon Rage, go mad!" Commented Oct 6, 2016 at 17:25
• My name suggestion: "are they anagrams" → "manage the arrays" Commented Oct 31, 2017 at 4:32
• Suggested test case: aaab, bbba = false Commented Aug 3, 2022 at 23:56

## 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
Commented 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. Commented 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 Commented Sep 15, 2014 at 22:25
• @Optimizer did you even try running it? Commented Sep 15, 2014 at 22:37
• Ah, I see. In that case, it will be fine. Commented Sep 16, 2014 at 6:43

# Pyth - 19

qS@cz", "0S@cz", "1


Try it here. Note that the two words in the input must be separated by a comma and a space.

Python Mapping and explanation

q                     #      equal(              "Check equality"
S                    #      sorted(             "Sort"
@                   #      list looku          "Extract element from list"
c                  #      chop(               "Separate by delimiter"
z                 #      input(              "Input variable"
", "             #      ", "                "This delimiter"
0            #      0                   "The 0th element"
S@cz", "1   #      ..                  "The same thing with the 1st element


I'm sure someone can come up with a shorter implementation, but I've only been learning Pyth for a few days. It would also be a lot shorter if I didn't stick strictly to the input format given in the question.

For instance:

qS@Q0S@Q1

Which is only 9 bytes, works if the input is formatted like 'parse','spare'. So which one do you count?

Good practice though!

# Ruby, 32

h=->{gets.chars.sort}
p h[]==h[]


# Javascript, 143 119 bytes

a=prompt()[s="split"](" ");a[0]=a[0][s]("");a[1]=a[1][s]("");a[0].sort();a[1].sort();alert(a[0][j="join"]()==a[1][j]())


Takes a single space-seperated pair of strings as input.

# rs, 35 bytes

+(.)(.*) (.*)\1/\2 \3
\s/
.+/0
^$/1  Yay regexes!! BTW, rs was created way after this was posted, so this technically doesn't count. Still cool. Live demo and all test cases. # R, 63 Bytes length(unique(lapply(strsplit(c(s,m),''),sort))[[1]])==nchar(m)  It seens it passes the test cases. (just realized this question is 4 year old, but posting anyway) • Passing the test cases does not necessary make a working function. Your function only works when the number of unique characters in s is equal to the number of characters in m. For instance, s="boatee" and m="toobee" yields TRUE, when it should actually be FALSE. Commented Dec 17, 2018 at 21:31 ## Javascript (ES6) 35 Requires lambdas Just like the other solutions, but with lambda f=x=>x.split.sort() f(a)==f(b)+""  Usage // a, b = input f=x=>x.split.sort() console.log(f(a)==f(b)+"")  thanks @comment • Welcome to PPCG! Since you're using ES6, you could replace split('')... with split... to save two bytes. Commented Oct 5, 2015 at 17:04 • You can also shave off 3 bytes by replacing x.split with [...x] Commented May 17, 2016 at 19:36 # Powershell 48 bytes param([char[]]$a,[char[]]$b)![bool](diff$a $b)  Cast incoming strings as an array of char. Use diff (compare-object) on the two objects and cast as bool. Since a blank result (diff only shows differences not similarities) is False, negating it with ! will result in true for identical strings. Added benefit: it will work on any arbitrary length strings (if equal whitespace). # Jelly, 5 Bytes (Non-competitive) Ṣ⁼⁴Ṣ¤  Special thanks to Leaky Nun for helping me fix a problem. Outputs one if true. Try it Online! ## Python, 20 bytes lose to golfscript again...... :( sorted(x)==sorted(y)  • This will work, but it does not include the parsing of x and y, which can contribute to the length of the answer. Commented Jan 24, 2015 at 7:17 ## Scala - 64 Bytes Could be made shorter (the toList could be changed to toSeq, I believe) ('a'to'z').forall(c=>y.toList.count(_==c)==z.toList.count(_==c)) ## Racket 92 bytes (λ(a b)(define(g s)(sort(map(λ(x)(char->integer x))(string->list s))>))(equal?(g a)(g b)))  Ungolfed: (define f (λ (a b) (define (g s) ; fn to get sorted list of string chars as numbers. (sort (map (λ(x)(char->integer x)) (string->list s)) >)) (equal? (g a) (g b))))  Testing: (f "test" "ttse") (f "boat" "boat") (f "toab" "boat") (f "oabt" "toab") (f "zyyyzzzz" "yyzzzzzy") (f "a" "aa") (f "zzz" "zzzzzzzz") (f "sleepy" "pyels")  Output: #t #t #t #t #t #f #f #f  ## awk, 63 65 bytes It only accepts chars a-z (0141-0172). gsub counts occurrances of each char in alphabet, appends them to a variable (variable looks something like 140213000000000000..., starts with 140 for initialization) and compares frequencies in variables in the end. It returns the value of the comparison on exit: {for(a=i=140;++i<173;)a=a gsub("\\"i,1);if(p>1)exit(p==a);p=a}  Test it: $ cat file
aabccc
abcacc
$awk '{for(a=i=140;++i<173;)a=a gsub("\\"i,"");if(p>1)exit(p==a);p=a}' file$ echo $? # will output 0 or 1 where 1=true and 0=false 1  # APL (Dyalog), 10 bytes ≡/(⊂∘⍋⌷⊢)¨  Try it online! The program takes in two strings in a single array as its right argument. ### Explanation ¨ For each string (⊂∘⍋⌷⊢) Sort it ≡/ And check if both strings are equal  # Excel VBA, 87 Bytes Anonymous VBE immediate window function that takes input from range A1:B1 and outputs whether the two inputs are anagrams of one another to the VBE immediate window. This a destructive process as the value inputted into range B1 is destroyed For i=1To[Len(A1)]:[B1]=Replace([B1],Mid([A1],i,1),"|",,1):Next:?[B1=Rept("|",len(A1))]  # J, 8 bytes -:&(/:~)  Match -: after sorting /:~ both args &. Try it online! # Julia, 41 bytes g(a,b)=sort(collect(a))==sort(collect(b))  # Python, 99 chars f=lambda w,x,y:w==y if x==""else any([f(w+a,x.replace(a,"",1),y)for a in x]) g=lambda x,y:f("",x,y)  Recursively finds all permutations of x and compares them to y. ## Perl, 60 bytes Perl one-liner perl -lanF -e 'push@a,join"",sort@F;END{exit($a[0]ne$a[1])}'  Takes first two lines of STDIN and compares them. Exits 0 if they're anagrams, 1 otherwise. $ echo -e "word\nwrdo" | \
> perl -lanF -e 'push@a,join"",sort@F;END{exit($a[0]ne$a[1])}' && echo anagram
anagram
$echo -e "word\nwrro" | \ > perl -lanF -e 'push@a,join"",sort@F;END{exit($a[0]ne$a[1])}' && echo anagram$


# Perl, 26 bytes

Includes +1 for p (using -F and @F ends up with the same score)

Give the input strings as 2 lines on STDIN.

(echo word; echo wrdo) | perl -pE '$\=${join W,sort/./g}++}{'


This prints 0 if not an anagram or 1 if it is an anagram

(echo word; echo wrdo) | perl -pE '$_=${join W,sort/./g}++'


comes in at 24 bytes and prints 00 if not an anagram and 01 if it is. If these values are numbers they are in fact valid falsy and thruthy in perl, but as strings they are both thruthy. It's probably fairer to consider them as strings so this solution is invalid

So this is the same length (but without warnings) as Xcali's answer (after optimizing):

(echo word; echo wrdo) | perl -F -E '@{$.}=sort@F}{say@1~~@2'  # Tcl, 82 bytes proc A x\ y {expr {[string le$x]==[string le $y]&[lsort -u [split$x $y]]=="{}"}}  Try it online! # Tcl, 83 bytes proc A x\ y {expr {[string le$x]==[string le $y]&&[lsort -u [split$x $y]]=="{}"}}  Try it online! # Tcl, 84 bytes proc S s {lsort [split$s ""]}
proc A x\ y {set x [S $x] set y [S$y]
expr {$x==$y}}


Try it online!

Previous version was failing for comparing 2 to 20, because after the lsort and join the comparison became 2==02, and == was doing a numerical comparison instead of a numerical one!

# Tcl, 94 bytes

proc S s {join [lsort [split $s ""]] ""} proc A x\ y {set x [S$x]
set y [S $y] expr {$x==\$y}}


Try it online!