# 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
• @Tom, because everyone wanted to prove that your comment about using a 64-bit integer was pointing in the wrong direction :P Mar 8, 2011 at 18:15
• 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

# 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 Mar 8, 2011 at 22:23
• @Tomas, nonsense. The question doesn't specify complete program, so either a function or a complete program are acceptable. Feb 2, 2014 at 23:47
• @Tomas, The majority of answers here fail to pass your criteria. Why not give an upvote to all those that do? Feb 2, 2014 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 Feb 3, 2014 at 0:41
• You don't need to include the f=. Oct 8, 2016 at 5:02

### 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 :) Mar 9, 2011 at 0:10
• Explanation please :( Mar 9, 2011 at 5:41
• @st0le, seriously? I don't know golfscript, but it's obviously $(sort),$ (sort), = (compare) Mar 9, 2011 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. Jul 30, 2011 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. May 17, 2016 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, 2011 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, 2011 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, 2011 at 16:26
• J always looks like the remains of an emoticon factory explosion. Mar 9, 2011 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
}

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

• Great idea using primes.
– user475
Mar 8, 2011 at 16:06
• @Tim thanks! Got it down to 157 now. Mar 8, 2011 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} Mar 8, 2011 at 17:06
• @Tom, depends on how well optimised the sorting routines are, given that you've limited inputs to 8 characters :P Mar 9, 2011 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} Mar 9, 2011 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


# Haskell, 31 bytes

## 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 Oct 30, 2015 at 19:50 Clojure REPL 41 chars (= (sort (read-line)) (sort (read-line)))  • Welcome to the Stack Exchange network. Formatting help here. Mar 10, 2011 at 4:17 # 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/}  • One less: sub f{1while s/(.)(.*,.*)\1/\2/;!/\w/} Apr 13 at 16:12 # 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? Aug 6, 2015 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. Aug 10, 2015 at 12:55 • Yeah, sorry. I didn't notice how old this question was when I commented, only that it was on the frontpage. ^^; Aug 10, 2015 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? Feb 2, 2014 at 23:48 • @Tomas It's a function Oct 8, 2016 at 19:51 # Bash, 88 characters diff <(grep -o .<<<$1|sort) <(grep -o .<<<$2|sort)>/dev/null && echo true || echo false  ## 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;. Oct 6, 2016 at 22:23 ## 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, 2011 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. Mar 8, 2011 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, 2011 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. Mar 8, 2011 at 18:13

# 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)` Mar 19, 2019 at 6:17