# 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

# Python, 32 bytes

f=lambda a,b,S=sorted:S(a)==S(b)

• @Debanjan, This is just the same as def f(a,b):return sorted(a)==sorted(b) The trade off is that you get to replace def+return with lambda in exchange for not using any statements – gnibbler Mar 8 '11 at 22:23
• @Debanjan, I think it only saves you one character. I have used a variation here, but it works out the same length as yours because I swap a newline for a comma – gnibbler Mar 9 '11 at 0:09
• @Tomas, nonsense. The question doesn't specify complete program, so either a function or a complete program are acceptable. – gnibbler Feb 2 '14 at 23:47
• @Tomas, The majority of answers here fail to pass your criteria. Why not give an upvote to all those that do? – gnibbler Feb 2 '14 at 23:56
• @Tomas, it's not rule abuse. Some questions are deliberately openended like this one appears to be. Compare with a well specified question like this. If you don't like these answers complain to the question asker – gnibbler Feb 3 '14 at 0:41

### Golfscript, 3 chars?

=


usage:

'boat'$'baot'$=
1

'toab'$'boat'$=
1

'oabt'$'toab'$=
1

'a'$'aa'$=
0

'zzz'$'zzzzzzzz'$=
0

'zyyyzzzz'$'yyzzzzzy'$=
1

'sleepy'$'pyels'$=
0

'p'$'p'$=
1

• This is an interesting interpretation of how to supply the input :) – gnibbler Mar 9 '11 at 0:10
• Explanation please :( – st0le Mar 9 '11 at 5:41
• @st0le, seriously? I don't know golfscript, but it's obviously $(sort),$ (sort), = (compare) – Peter Taylor Mar 9 '11 at 8:10
• Isn't this cheating a little? I mean, it isn't variable input. It has to be hard-coded. In any case, I would add 4 to the character count for the quote (') characters. – Thomas Eding Jul 30 '11 at 0:18
• This isn't valid by our current rules. You could, however, change it to @JanDvorak's 4-byte function, which would accept input via a valid input format. – Doorknob May 17 '16 at 19:28

## J, 8

-:&(/:~)


Literaly, match (-:) on (&) sort up (/:~)

Sample use:

   'boat' -:&(/:~) 'boat'
1
'toab' -:&(/:~) 'boat'
1
'oabt' -:&(/:~) 'toab'
1
'a' -:&(/:~) 'aa'
0
'zzz' -:&(/:~) 'zzzzzzzz'
0
'zyyyzzzz' -:&(/:~) 'yyzzzzzy'
1
'sleepy' -:&(/:~) 'pyels'
0
'p' -:&(/:~) 'p'
1


Where do the 64-bit integers come into play?

• Is it not possible to write functions/subroutines in J? – user475 Mar 8 '11 at 15:57
• @Tim Nordenfur: they're called "verbs", and take either one argument on their right as in v arg (monads) or two on both sides as in arg1 v arg2 (dyads). The one I submitted is obviously a dyad. I didn't bother to name it, since it wasn't requested and is shorter this way. Should you really want to give it a name, you'd do that like this: is_anagram_of =: -:&(/:~) and then use as 'a' is_anagram_of 'aa'. – J B Mar 8 '11 at 16:21
• It felt a bit cheap to substitute the arguments into the code, but I see now that it's essentially a dyad. Never mind. – user475 Mar 8 '11 at 16:26
• J always looks like the remains of an emoticon factory explosion. – st0le Mar 9 '11 at 6:58

## Javascript, 192157152147 125 bytes

Ok some of these languages are a lot more flexibile than I thought! Anyway this is the longer way I guess, but a different technique at least.

Compressed

Thanks to Peter and David for squeezing more chars out!

for(a=[j=p=2];j<123;)a[j]?p%a[++j]<1&&p++&&(j=0):(a[j]=p,j=0);function b(c,i){return c[i=i||0]?a[c.charCodeAt(i)]*b(c,++i):1}


Then do:

alert(b("hello")==b("elloh"));


Expanded Code

The compressed has had lots of changes, but this is the basic theory:

// Define dictionary of primes
a = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101];

// Returns the unique ID of the word (order irrelevant)
function b(c) {
r = 1;
for (i = 0; i < c.length; i++)
r *= a[c[i].charCodeAt(0) - 97];
return r
}


• Great idea using primes. – user475 Mar 8 '11 at 16:06
• @Tim thanks! Got it down to 157 now. – Tom Gullen Mar 8 '11 at 16:12
• You can shave a couple of characters off the dictionary initialisation using the sieve. a=[2];for(p=3,j=0;j<26;)if(a[j]){if(p%a[j++]==0){p++;j=0}}else{a[j]=p;j=0} – Peter Taylor Mar 8 '11 at 17:06
• @Tom, depends on how well optimised the sorting routines are, given that you've limited inputs to 8 characters :P – Peter Taylor Mar 9 '11 at 11:13
• 125 characters. Recursion and ternaries FTW: for(a=[j=p=2];j<123;)a[j]?p%a[++j]<1&&p++&&(j=0):(a[j]=p,j=0);function b(c,i){return c[i=i||0]?a[c.charCodeAt(i)]*b(c,++i):1} – David Murdoch Mar 9 '11 at 14:03

# Golfscript, 8 bytes

This defines a function called A

{$\$=}:A


Test cases

;
'boat' 'boat' A
'toab' 'boat' A
'oabt' 'toab' A
'a' 'aa' A
'zzz' 'zzzzzzzz' A
'zyyyzzzz' 'yyzzzzzy' A
'sleepy' 'pyels' A
'p' 'p' A


## function - 31

import List
f=(.sort).(==).sort


## program - 8158 55

import List
g=sortfmapgetLine
main=(fmapg).(==)=<<g


Usage:

$runghc anagram.hs boat boat True$ runghc anagram.hs
toab
boat
True
return array_count_values(str_split($s)); } echo d($argv[1]) == d($argv[2]);  # Javascript A (very) slightly shorter version of @zzzzBov's solution, that uses .join() instead of String boxing: function a(b,c){return b.split('').sort().join()==c.split('').sort().join()} alert(a('abc','bca')); //true  Similarly: function a(b){return b.split('').sort().join()} alert(a('abc')==a('bca')); //true  • this is answer ID 1337. congratz – TheDoctor Oct 30 '15 at 19:50 Clojure REPL 41 chars (= (sort (read-line)) (sort (read-line)))  # Java (everyone's favorite language apparently!) 173 chars: import java.util.*;class g{public static void main(String[]p){String[]a=p[0].split(""),b=p[1].split("");Arrays.sort(a);Arrays.sort(b);System.out.print(Arrays.equals(a,b));}}  (Doesn't print newline char to save 2 chars from println) Compile and run: javac g.java java -cp . g abcdef fedcba true  Love to see a shorter one... # sed, 45 chars It's even possible in my favourite - sed! Just one regular expression to solve the anagram! Just keep removing the corresponding letters: : s/(.)(.*,.*)\1/\2/ t /\w/{i\false d} i\true  (to be invoked with -nE) # Perl, 48 1while s/(.)(.*,.*)\1/\2/;$_=/\w/?"false":"true"


To be invoked with -p.

# Perl function, 39

sub f{$,while s/(.)(.*,.*)\1/\2/;!/\w/}  # APL, 2 chars ≡⍦  This is the Multiset Match function from Nars2000, one of the leading-edge APL implementations. When applied to strings, it computes exactly the function required:  'elvis' ≡⍦ 'lives' 1 'alec guinness' ≡⍦ 'genuine class' 1  • Just curious, how many bytes is this? 4? 6? – Maltysen Jan 30 '15 at 2:04 • It depends on the encoding. 6 bytes in UTF-8, 4 bytes in UCS-2, 2 bytes if any of the legacy single-byte APL charsets have the ⍦ symbol, which I doubt. – Tobia Jan 30 '15 at 10:22 # 05AB1E, 6 4 bytes (non-competing) {I{Q  Try it online! This took a while because of input difficulties. Golfed down due to pop. Explanation: {I{Q Original code { Takes first input e.g. word and sorts -> 'dorw' I Takes second input e.g. 'wrdo' { Sorts second input -> 'dorw' Q Compare if sorted 1 = sorted 2, then print result. 'dorw' = 'dorw', so prints 1.  • Since 05AB1E is newer than this challenge, this answer is non-competing. – Loovjo Oct 6 '16 at 17:56 • Sorry - didn't realise. – Geno Racklin Asher Oct 6 '16 at 18:04 ## Perl, 77 75 chars The I/O of the problem aren't well specified; this reads two lines from stdin and outputs true or false to stdout. sub p{join'',sort split'',$a}$a=<>;$x=p;$a=<>;print$x eq p()?"true":"false"


(Thanks to Tim for 77 -> 75)

• Something is wrong. $a=;? Also, you can skip the parens of sort and the space after print. – user475 Mar 8 '11 at 16:00 • @Tim, the genius who developed this platform for sharing code over the net decided that in code blocks people should have to escape less-than characters. But hey, no big deal: it's not as though anyone uses them in code, right? Keeps catching me out. – Peter Taylor Mar 8 '11 at 16:32 • Ok, I removed the downvote. You might want to use the code formatting in the future, i.e. indent code with four spaces. – user475 Mar 8 '11 at 16:46 • Ok, so there are three ways of formatting code (one inline and two block), and both the block ones are inconvenient in different ways. Sigh. – Peter Taylor Mar 8 '11 at 18:13 # Perl, 62 bytes This function takes the strings as arguments and returns true or false. sub f{my@a;for$.(1,-1){$a[ord]+=$.for split//,pop}!grep{$_}@a}  Stores the ASCII values in an array and checks if it evens out. Increments for the first word and decrements for the second word. ## Python 3, 1079776 64 s=sorted;a,b=input().split(', ') print(str(s(a)==s(b)).lower())  Obviously this can be shortened if we don't take the OP's wording literally and lowercase "true" and "false"... • You can shave off a few characters if you append ;s=sorted to the first line and then replace the two instances of sorted with s in the second line. Should save... 3 characters? – Alex Van Liew Aug 6 '15 at 17:58 • Indeed. Python 3 also saves a bit of space, and is probably reasonable to use now, 5 years after this answer was posted. Also, the .strip() was redundant, given the specified inputs. – Wooble Aug 10 '15 at 12:55 • Yeah, sorry. I didn't notice how old this question was when I commented, only that it was on the frontpage. ^^; – Alex Van Liew Aug 10 '15 at 22:39 # Python, 32 bytes p=sorted f=lambda a,b:p(a)==p(b)  • Does nothing in python. Are you sure it is a complete program that takes the input and produces the output as requested? – Tomas Feb 2 '14 at 23:48 • @Tomas It's a function – TuxCrafting Oct 8 '16 at 19:51 # Bash, 88 characters diff <(grep -o .<<<$1|sort) <(grep -o .<<<\$2|sort)>/dev/null && echo true || echo false


# R, 54 bytes

function(x,y,~=sort,+=utf8ToInt)identical(~+x,~+y)


Try it online!

• I'm highly intrigued by your use of utf8ToInt, not only in this answer, but in many others that I have seen. – Sumner18 Dec 17 '18 at 22:43
• Have you seen tips for golfing in R? utf8ToInt and its reverse tend to make for shorter string-splitting than the conventional functions. – J.Doe Dec 18 '18 at 0:41

## Scala in REPL (32)

readLine.sorted==readLine.sorted


## Scala function (43)

def f(a:String,b:String)=a.sorted==b.sorted


## Scala program (61)

object A extends App{println(args(0).sorted==args(1).sorted)}


These leverage a neat feature of Scala whereby a String can also be treated as a sequence of characters (Seq), with all the operations on Seq being available.

# APL - 13 chars

{(⍺[⍋⍺])≡⍵[⍋⍵]}


Call like this:

      'boat' {(⍺[⍋⍺])≡⍵[⍋⍵]} 'baot'
1
'baot' {(⍺[⍋⍺])≡⍵[⍋⍵]} 'boat'
1
(,'a') {(⍺[⍋⍺])≡⍵[⍋⍵]} 'aa'
0


In the last example, 'a' represents a single character, and the prefix , will convert it into a string.

# Java (134 bytes)

int[][]c=new int[2][26];
for(int i=0;i<2;i++)for(byte a:args[i].getBytes())c[i][a-97]++;
System.out.print(Arrays.equals(c[0],c[1]));


This makes an array to count the number of times each letter appears, and then compares the arrays to check if they are equal.

• Welcome to PPCG! Nice first post! There are 2 spaces you can remove, (c[0], c[1]) and for (int i=0;. – Rɪᴋᴇʀ Oct 6 '16 at 22:23

# JavaScript, 41

Comparison function (41):

a=b=>''+[...b].sort()
b=(c,d)=>a(c)==a(d)

alert(b('abc', 'cba')) // true


Comparator function (21):

a=b=>''+[...b].sort()

alert(a('abc') == a('bca')); //true


Comparator function (48):

function a(b){return String(b.split('').sort())}

alert(a('abc')==a('bca')); //true


Comparison function (78):

function a(b,c){return String(b.split('').sort())==String(c.split('').sort())}

alert(a('abc','bca')); //true


Assumes String has split and Array has sort.

• 38 bytes: c=>d=>(a=b=>''+[...b].sort())(c)==a(d)` – Shieru Asakoto Mar 19 '19 at 6:17