# 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! – Tom Gullen Mar 8 '11 at 16:44
• @Tom, because everyone wanted to prove that your comment about using a 64-bit integer was pointing in the wrong direction :P – Peter Taylor Mar 8 '11 at 18:15
• Title request: Cod Elf, Go! – user54200 Jul 9 '16 at 12:48
• "Falcon Rage, go mad!" – Geobits Oct 6 '16 at 17:25
• My name suggestion: "are they anagrams" → "manage the arrays" – Esolanging Fruit Oct 31 '17 at 4:32

JavaScript (67)

function(a,b){return ""+a.split("").sort()==""+b.split("").sort()}

• Wanted to post the same solution before I even saw yours – dwana Jan 30 '15 at 7:38

VBScript

172 characters

wscript.echo "boat, boat         = " & s("boat, boat")
wscript.echo "toab, boat         = " & s("toab, boat")
wscript.echo "oabt, toab         = " & s("oabt, toab")
wscript.echo "a, aa              = " & s("a, aa")
wscript.echo "zzz, zzzzzzzz      = " & s("zzz, zzzzzzzz")
wscript.echo "zyyyzzzz, yyzzzzzy = " & s("zyyyzzzz, yyzzzzzy")
wscript.echo "sleepy, pyels      = " & s("sleepy, pyels")
wscript.echo "p,p                = " & s("p,p")

function s(a):b=split(replace(a," ",""),","):c=0:for x=1 to len(b(0)):if instr(b(1),mid(b(0),x,1)) then c=c+1
next:if len(b(1))-c=0 then s=true else s=false
end function


I was kinda suprised I could get it under 200.

• 131 characters if I pass the values seperatly. function s(a,b):c=0:for x=1 to len(a):if instr(b,mid(a,x,1)) then c=c+1 next:if len(b)-c=0 then s=true else s=false end function – user775 Mar 9 '11 at 14:40

Ruby (40)

a.unpack('c*').sort==b.unpack('c*').sort

• I've formatted your code for you. The tool bar above the edit box has the most commonly used functions, and the sidebar has a link to more detailed info. – dmckee --- ex-moderator kitten Mar 9 '11 at 6:47

Another Ruby (46)

(a.size==b.size)&&(a<<b.count(a,b)==a<<b.size)


C function (147 chars), using brute-force

int c(char*x,char*y){int i=0,l=0;for(;y[l]&&x[l];l++);if(y[l]||x[l])return 0;
while(*x&&i!=l){for(i=0;i<l&&y[i]!=*x;i++);y[i]=0,x++;}return(i!=l);}


## Ruby (39)

Accepts the input as given in the question. Run with ruby -n.

$cat t.rb$_=~/, /;p $'.chars.sort==$.chars.sort

$echo -n "word, wrdo" | ruby -n t.rb true  # Ruby 1.9 - 32 x=->{gets.chars.sort} p x[]==x[]  • Cool! x=->{gets.sum} passes the test cases but is kind of a cheat. – Jonas Elfström Mar 17 '11 at 16:18 • BTW, why 1.9.1 and not 1.9.2? It works in 1.9.2. – Jonas Elfström Mar 17 '11 at 16:19 • That's just the version of Ruby 1.9 I have. – david4dev Mar 17 '11 at 20:40 ## R, 77 f=function(x,y)identical(sort(strsplit(x,"")[[1]]),sort(strsplit(y,"")[[1]]))  Sample output: f("boat","boat") [1] TRUE f("toab","boat") [1] TRUE f("oabt","toab") [1] TRUE f("a","aa") [1] FALSE f("zzz","zzzzzzzz") [1] FALSE f("zyyyzzzz","yyzzzzzy") [1] TRUE f("sleepy","pyels") [1] FALSE f("p","p") [1] TRUE  • Why not simply f=function(x,y) identical(sort(strsplit(x,"")[[1]]),sort(strsplit(y,"")[[1]]))? – plannapus Oct 19 '13 at 8:28 • You're completely right! Stupid me! I replaced the code with your solution. – Paolo Oct 21 '13 at 9:14 ## Matlab: 10 characters without using sort a*a'==b*b'  ## Julia - 36 f=s->==(map(sort,map(collect,s))...)  Used as f(["foo", "bar"]) Using a list for calling it kind of feels like cheating though. 43 characters f=(a,b)->sort(collect(a))==sort(collect(b))  Used as f("foo", "bar") Both solutions just sort the words and compare the result Woohoo, my first real CodeGolf submission ^_^ Mathcad, 38 chars including non-character keys s(a):sort(str2vec(a)) f(a,b):s(a)©=s(b)  © stands for the Ctrl key. Displayed by Mathcad formatted as: s(a):=sort(str2vec(a)) f(a,b):=s(a)=s(b)  Converts the strings to vectors (one-dimensional arrays) of symbols' ASCII values, sorts them, then compares the vectors. Input is supplied to function f. Returns 1 on success and 0 on failure. Example: f("toab","boat") returns 1 # Pyth 10 7 qFSMczd  Takes input as two space-separated words. Try it here. Essentially, it splits the elements into an array, sorts each element, and checks if the elements are unique. My first attempt at Code Golf. Any advice appreciated :o) Edit: It should be noted that this is not a valid answer to the code-golf question, seeing as the language Pyth was invented after the question was asked. • Welcome to PPCG! You can't know this yet, but it's policy around here that languages invented after a challenge was created are not eligible for winning. You are still welcome to post an answer, but it's usually common to include a short disclaimer (in this case that Pyth was invented after the challenge was posted) so that the OP doesn't accidentally accept the answer. (This isn't even currently the shortest answer, but I tend to include the notice anyway.) Keep golfing! :) – Martin Ender Aug 3 '15 at 20:46 • I got this to 8 bytes: !.{SMczd. If you accept input in the form ['wrod','word'], you can get it to 6 bytes: !.{SMQ. – kirbyfan64sos Aug 3 '15 at 21:15 • Also, you can replace !.{ with qF, giving you 7 bytes with the current input method and 5 with the other one I mentioned. – kirbyfan64sos Aug 3 '15 at 21:17 • Thank you both! I made a note mentioning how the answer is valid for the problem, and changed my code accordingly. – JPeroutek Aug 4 '15 at 14:15 # PHP, 44 Bytes <?=($c=count_chars)($argv[1])==$c($argv[2]);  ## Perl, 41 bytes 40 bytes code + 1 for -p. Since this uses a slightly different trick to the other Perl answers I thought I'd share it. Input is separated by newlines. @{$.}=sort/./g}{$_="@1"eq"@2"?true:false  Uses the magic variable $. which tracks the line number to store the words, as character lists, in @1 and @2 which are then compared.

### Usage

perl -pe '@{$.}=sort/./g}{$_="@1"eq"@2"?true:false' <<< 'wrdo
word'
true

perl -pe '@{$.}=sort/./g}{$_="@1"eq"@2"?true:false' <<< 'word
wwro'
false

perl -pe '@{$.}=sort/./g}{$_="@1"eq"@2"?true:false' <<< 'boat
toba'
true


# Python, 151, 89 bytes

Handles arbitrarily many inputs from stdin. Comma separated, one pair per line.

import sys
f=sorted
for l in sys.stdin:a,b=l.split(',');print f(a.strip())==f(b.strip())

• Mwahaha, first time I see a Python solution longer than C# :) – Timwi Mar 8 '11 at 16:05
• Won't this return True for aab, bba? – gnibbler Mar 8 '11 at 20:28
• @gnibbler; Yes, it will, I wasn't thinking this morning. Fixed – Hoa Long Tam Mar 9 '11 at 1:52

# Brain-Flak, 170 bytes

{({}[(()()()()()){}]<>)<>}<>([]){{}(<>())<>{({}[(((((()()()()()){}){}){})){}])({({})({}[()])()}{}{}())({<({}[()])><>({})<>}{}<><{}>)<>}{}([])}<>({}[{}])((){[()](<{}>)}{})


Try it online!

Takes input on two lines.

This program makes a Gödel encoding of letter frequencies in each string. This means I need to map each letter to a unique prime number. For that, I use the polynomial n^2 + n + 41, which is known to give prime results for 0 <= n <= 40. I subtract 90 from the ascii code for each letter before passing it to the polynomial, to get a number in the proper range. When the primes are multiplied together, the results should be equal only when the strings are permutations of each other.

# Brachylog, 2 bytes

pᵈ


Try it online!

The p predicate is essentially a declaration that the variables on either side of it are permutations of each other. The ᵈ meta-predicate modifies the predicate to which it is attached to interpret the input variable as a list of two items, which are effectively placed on either side of the predicate (with the output variable being unified with the second element of the input). So, given a pair of strings as input, the predicate pᵈ will succeed if they are anagrams, and fail if they are not.

If anyone's suspicious of the header on TIO, it just goes through the list of test cases and prints a list of "true"/"false" values based on whether the predicate succeeded or failed for each case. The predicate can be run as a standalone program that prints "true." if it succeeds for the single test case it is given and "false." if it fails.

• Caveat (?): takes a list of two strings, doesn't do anything to parse a one-string input, some people seem to have been worried about that on their answers but those were also different times so I'm not sure what to think Also, technically, the one-byte p would count, but I'd have a hard time justifying that as an answer (plus it's nice to finally have a good use for the declare metapredicate). – Unrelated String Mar 1 '19 at 3:18

Yet another Python answer :). (43 characters including whitespace)

This also includes reading in input and displaying output.

i,s=raw_input,sorted
print s(i())==s(i())


Matlab (24)

Given two strings a and b.

isequal(sort(a),sort(b))


C++ Counting sort, fixed version

int a(char*x,char*y){int i=0,u[256];while(i<256)u[i++]=0;
while(*x&&*y)u[*x++]++,u[*y++]--;if(*x||*y)return 0;
for(i=255;i&&!u[i--];);return!i;}


Unrolled, so you can see what's going on:

int a(const char *x,const char *y) {
int i=0,u[256];for(;i<256;u[i++]=0);
for(i=0;x[i]&&y[i];i++)u[x[i]]++,u[y[i]]--;
if(x[i]||y[i])return 0;
for(i=0;i<256 && !u[i];i++);
return (i==256);
}


(with due credit to Matthew Read's very elegant counting sort strategy)

Perl - 78 characters[1]

@x=map{join("",sort(split("")))}split(",",<>);print$x[0]eq$x[1]?"true":"false";


[1] Unlike some other Perl code above, this actually reads the input in "foo,bar" format and prints "true" or "false". Could be shorter otherwise.

## Python 3 (64)

This is not a particularly good golf given how short some of the earlier Python solutions that use sorted() are, but here's a version that uses collections.Counter (an unlovable module from a golfing perspective, but with some neat stuff). It reads two lines from input and outputs True or False. Going with Python 3 versus 2.7 saved 4 chars with input() instead of raw_input(), but lost 1 for the parens for print since it is now a function.

from collections import *;c,i=Counter,input;print(c(i())==c(i()))

• Shave one character by changing import * to import*. – Steven Rumbalski Sep 13 '11 at 18:01
• I tried your challenge of not using sorted, but also avoided using collections.Counter. Best I was able to get was 66 character. – Steven Rumbalski Sep 13 '11 at 18:03

### Python 2, without sorting as that starts to get boring - 104 chars

def f(a,b):
a,b=list(a),list(b)
while a:
try:b.remove(a.pop())
except:return
return len(a)==len(b)


## Clojure - 30 chars

Too many people seem to be relying on sorting so I thought of an interesting alternative way to do this via a histogram:

#(apply = (map frequencies %))


Use this as a function, i.e.:

(#(apply = (map frequencies %)) ["boat" "toab"])
=> true


## Python 3 (66)

Like jloy's answer, I eschewed using sorted because so many other answers did so. I also didn't want to rehash his use of collections.Counter so I used str.count instead. With these constraints I got within 3 characters of jloy.

i=input;a=i();b=i();print(all(a.count(s)==b.count(s)for s in a+b))

• good use of semicolons! – Andbdrew Sep 14 '11 at 21:29

k4 - 11 chars

Given strings a and b:

(a@<a)~b@<b

a:"word"
b:"wrdo"
(a@<a)~b@<b
1b


At the cost of 2 chars this can be made into a function:

{(x@<x)~y@<y}["word";"wrdo"]
1b


Implementation is same as the J implementation; sort the vectors then compare equivalence.

~ is match

< is grade up (indices were the vector to be sorted ascending)

@ is index

• If you take input as a list of two strings you can do slightly better: ~/{x@<x}'("baot";"boat") – JohnE Aug 3 '15 at 21:49

# Q, 25

{(~). asc each(,/)each x}


sample output:

q){(~). asc each(,/)each x}("boat";"boat")
1b
q){(~). asc each(,/)each x}("toab";"boat")
1b
q){(~). asc each(,/)each x}("oabt";"toab")
1b
q){(~). asc each(,/)each x}("a";"aa")
0b
q){(~). asc each(,/)each x}("zzz";"zzzzz")
0b
q){(~). asc each(,/)each x}("zyyyzzzzz";"yyzyzzzzz")
1b
q){(~). asc each(,/)each x}("p";"p")
1b


# Python - 137 chars

def h(s):
r={}
for c in s:
try:r[c]+=1
except:r[c]=1
return r
x=raw_input().split(',')
print h(x[0])==h(x[1])


Sample: (I defined a function anagram to do the work of the last 2 lines.)

   anagram('boat','boat')
True
anagram('toab','boat')
True
anagram('oabt','toab')
True
anagram('a','aa')
False
anagram('zzz','zzzzzzzz')
False
anagram('zyyyzzzz','yyzzzzzy')
True
anagram('sleepy','pyels')
False
anagram('p','p')
True


Not counting imports, Haskell can do it in 10 chars:

import Data.List
import Data.Function
on(==)sort


Called like this:

λ> on(==)sort "balaclava" "aabllcav"
False

λ> on(==)sort "balaclava" "aabllcava"
True


# Pyth - 87 6

MqSGSH


Defines function with two args, the two words.

M       define function g with two args, G and H
q       equals
SQ     sorted first arg
SH     sorted last arg


If that cheating golfscript program counts with hardcoded input, we can do that too with : qSS

And for just two more characters you can have it check an infinite number of words:

ql{mSdQ1

q    1       Equals 1
l           Length
{          Set constructor (eliminate all duplicates)
m  Q      Map on evaluated input
Sd       Sort each element

• How would qSS work? I am trying to learn pyth and I am curious. – ericmarkmartin Jan 27 '15 at 20:07
• @ericmark26 its the same as the golfscript and its cheating because it need hardcoding. qss just means equals, sort, sort. You'll have to put the strings after the S`'s – Maltysen Jan 27 '15 at 20:35