96
\$\begingroup\$

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
\$\endgroup\$
7
  • 11
    \$\begingroup\$ 9 answers in 13 views... wow! \$\endgroup\$
    – Tom Gullen
    Commented Mar 8, 2011 at 16:44
  • 5
    \$\begingroup\$ Title request: Cod Elf, Go! \$\endgroup\$
    – user54200
    Commented Jul 9, 2016 at 12:48
  • 7
    \$\begingroup\$ "Falcon Rage, go mad!" \$\endgroup\$
    – Geobits
    Commented Oct 6, 2016 at 17:25
  • 15
    \$\begingroup\$ My name suggestion: "are they anagrams" → "manage the arrays" \$\endgroup\$ Commented Oct 31, 2017 at 4:32
  • 2
    \$\begingroup\$ Suggested test case: aaab, bbba = false \$\endgroup\$
    – Deadcode
    Commented Aug 3, 2022 at 23:56

170 Answers 170

2
\$\begingroup\$

Raku, 22 bytes

{[~~] @_».comb».Bag}

Try it online!

  • .comb converts each input string to a list of its characters.
  • .Bag converts each list of characters into a Bag object (a set with multiplicity).
  • [~~] inserts the ~~ smartmatch operator between the two Bags, which returns true if and only if they have the same contents.
\$\endgroup\$
2
\$\begingroup\$

Thunno 2, 3 bytes

€Ṡạ

Attempt This Online!

Explanation

€Ṡạ  # Implicit input
€    # Apply to both strings:
 Ṡ   #  Sort the string
  ạ  # Are they both equal?
     # Implicit output
\$\endgroup\$
2
\$\begingroup\$

R, 45 39 36 bytes

Edit: -9 bytes thanks to @Dominic van Essen.

\(x,y)identical(table(x),table(x=y))

Attempt This Online!

Takes input as two character vectors.

\$\endgroup\$
3
  • \$\begingroup\$ Why do you need the dnn=0 argument? \$\endgroup\$ Commented Jul 22 at 8:42
  • \$\begingroup\$ Actually, I don't anymore! It was necessary when I tested it with identical(table(x),table(y)) \$\endgroup\$
    – pajonk
    Commented Jul 22 at 8:44
  • 1
    \$\begingroup\$ 36 bytes \$\endgroup\$ Commented Jul 22 at 8:53
1
\$\begingroup\$

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())
\$\endgroup\$
1
\$\begingroup\$

PHP (51 chars, compressed)

function d($s){$s=str_split($s);sort($s);return$s;}

(Split string into an array, sort the array and return)

Example:

var_dump(d("word")===d("drow"));
\$\endgroup\$
1
\$\begingroup\$

Ruby (35)

a,b=ARGV;a.chars.sort==b.chars.sort
\$\endgroup\$
1
  • 1
    \$\begingroup\$ (Five years later...) $* is a handy alias for ARGV for 2 bytes. \$\endgroup\$
    – Jordan
    Commented Aug 18, 2016 at 5:32
1
\$\begingroup\$

Matlab (24)

Given two strings a and b.

isequal(sort(a),sort(b))
\$\endgroup\$
1
\$\begingroup\$

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)

\$\endgroup\$
2
1
\$\begingroup\$

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)
\$\endgroup\$
1
\$\begingroup\$

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
\$\endgroup\$
1
\$\begingroup\$

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))
\$\endgroup\$
1
  • \$\begingroup\$ good use of semicolons! \$\endgroup\$
    – Andbdrew
    Commented Sep 14, 2011 at 21:29
1
\$\begingroup\$

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

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

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
\$\endgroup\$
1
\$\begingroup\$

Bash (66 58)

f(){ fold -w1<<<$1|sort;}
g(){ [ "$(f $1)" == "$(f $2)" ];}

Call it with g <word1> <word2>.

Edit: Stupid me, I do not need to unic -c after I sort

\$\endgroup\$
1
  • \$\begingroup\$ FYI: TIO link with working code. $? emits 0 if the inputs are anagrams (truthy), 1 if not. \$\endgroup\$
    – roblogic
    Commented Nov 22, 2022 at 4:53
1
\$\begingroup\$

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
\$\endgroup\$
1
\$\begingroup\$

Groovy 42

def f(a,b){print ((b as Set)==(a as Set))}
\$\endgroup\$
1
\$\begingroup\$

Pyth - 8 7 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
\$\endgroup\$
2
  • \$\begingroup\$ How would qSS work? I am trying to learn pyth and I am curious. \$\endgroup\$ Commented Jan 27, 2015 at 20:07
  • \$\begingroup\$ @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 \$\endgroup\$
    – Maltysen
    Commented Jan 27, 2015 at 20:35
1
\$\begingroup\$

C - 107 chars

Mark off chars in second string as we go. At the end, if we've passed over the entirety of both strings, then we've got a match.

i;main(p,v)char**v,*p;{for(;*v[1]&(p=strchr(v[2],*v[1]++));)*p=1,i++;puts(*(v[2]+i)|*v[1]?"false":"true");}
\$\endgroup\$
1
\$\begingroup\$

C, (108)

char c[192]={};main(){for(;*a;c[127-*a++]++);for(;*b;c[223-*b++]++);puts(memcmp(c,c+96,95)?"false":"true");}
\$\endgroup\$
1
\$\begingroup\$

PowerShell, 78 51 bytes

param([char[]]$a,[char[]]$b)(diff $a $b).Length-eq0

Takes the two string inputs, and re-casts them as char-arrays. The diff function (an alias for Compare-Object) takes the two arrays and returns items that are different between the two. We leverage that by re-casting the return as an array with (), and then checking its length. If the length is zero, that means that all items of both character arrays are exactly the same (because nothing was returned). PowerShell has an implicit write for evaluated statements like this, so will automatically write out True or False as required.

\$\endgroup\$
1
\$\begingroup\$

Q, 15 Bytes

f:{~/{x@<x}'x}

f is the name of the function

Test

f("boat";"boat")            /1b
f("toab";"boat")            /1b
f("oabt";"toab")            /1b
f(,"a";"aa")                /0b
f("zzz";"zzzzzzzz")         /0b
f("zyyyzzzz";"yyzzzzzy")    /1b
f("sleepy";"pyels")         /0b
f(,"p";,"p")                /1b

Explanation

Argument of the function is a sequence with both words. At each word applies {x@<x}, that sorts x (take from x in ascending index ordering). ~/ reads as "match over", and compares both transformed words

\$\endgroup\$
1
  • \$\begingroup\$ If you're using k rather than Q you can just do ~/x@'<:'x: for 10 bytes. No need to create the outer function f nor the inner function if you set x to be the input. \$\endgroup\$
    – mkst
    Commented Oct 31, 2017 at 9:19
1
\$\begingroup\$

JavaScript, shortest JS answer so far: 57 56 characters, acccepts user input

This prompts the user for a value to compare.

function _(){return prompt().split(0).sort()+''}_()==_()

If no user input is required, this can be trimmed down to 53 52 characters.

Assuming the following variables are set:

var a='test', b='sets';

you can test for it with the following:

function _(a){return a.split(0).sort()+''}_(a)==_(b)

Note: this answer relies on some quirk that allowed using .split(0) instead of .split(""). This behavior no longer exists (at least in Firefox), so to get it running today, you have to replace 0 with "".

\$\endgroup\$
1
\$\begingroup\$

Retina, 10 bytes

This answer is non-competing since Retina is much newer than this challenge. Byte count assumes ISO 8859-1 encoding.

%O`.
D`
¶$

Input is linefeed-separated.

Try it online!

Explanation

%O`.

This sorts (O) the individual characters (.) in each line (%), i.e. it sorts each input string separately.

D`

This deduplicates the input on the (implicit) regex .*, which means it removes the characters from the second line if both strings are equal.

¶$

Finally, this tries to match a linefeed followed by the end of the string. Since the input strings are guaranteed to be non-empty, this can only happen if the second string was removed in the previous stage.

\$\endgroup\$
1
\$\begingroup\$

R, 69 bytes

a=function(b,d)identical(table(strsplit(b,"")),table(strsplit(d,"")))

I think this is the shortest R implementation which deals with a("b","bb") being FALSE.

\$\endgroup\$
1
\$\begingroup\$

C 87 bytes

char*a,*b,*c;d(i,k){return!a[i]||!(c=strchr(b,a[i]))?i==k+1:(*c=1,d(i+1,k<c-b?c-b:k));}

this is one recursive function that has one not common way to have its input and write in one its argument...this use recursion + library function...

/*
char*a,*b,*c;
d(i,k)
{return !a[i]||!(c=strchr(b,a[i]))?i==k+1:(*c=1,d(i+1,k<c-b?c-b:k));}
87 
*/

 main()
{char m1[]="12345", m2[]="54321", m3[]="a", m4[]="e";
 int  r;

 a=m1;b=m2;r=d(0,0);printf("r=%d m1=%s  m2=%s\n", r, m1, m2);
 a=m3;b=m4;r=d(0,0);printf("r=%d m3=%s  m4=%s\n", r, m3, m4);
}
\$\endgroup\$
1
  • \$\begingroup\$ How it is possible 20 min ago I not remember a C solution less than 109 bytes, now I read C solutions less bytes than 80 bytes edited in 2011... \$\endgroup\$
    – user58988
    Commented Oct 7, 2016 at 10:56
1
\$\begingroup\$

C 110 bytes

char*a,*b;l(i,j,k){y:if(!b[j]||!a[i])return i==k+1;if(a[i]==b[j]){b[j]=1;return l(i+1,0,j>k?j:k);}++j;goto y;}

this is one recursive function that has one not common way to have its input and write in one its argument... but not use library functions....

/*
l(i,j,k)
{y: if(!b[j]||!a[i])return i==k+1;
    if(a[i]==b[j]){b[j]=1;return l(i+1,0,j>k?j:k);}
    ++j;goto y;   
}
//110
r=1 m1=12345  m2=?????
r=0 m3=a  m4=e
*/

main()
{char m1[]="12345", m2[]="54321", m3[]="a", m4[]="e";
 int  r;

 a=m1;b=m2;r=l(0,0,0);printf("r=%d m1=%s  m2=%s\n", r, m1, m2);
 a=m3;b=m4;r=l(0,0,0);printf("r=%d m3=%s  m4=%s\n", r, m3, m4);
}
\$\endgroup\$
1
  • 1
    \$\begingroup\$ Please do not vandalize your posts. \$\endgroup\$
    – DJMcMayhem
    Commented Oct 20, 2016 at 17:49
1
\$\begingroup\$

C++14, 104 bytes

As generic function returning via reference parameter. Accepts char[] or std::string or any other container that supports range-based for loop.

Returns 0 for anagram, anything else for non-anagram

#define F(X) for(auto x:X)
void f(auto&A,auto&B,int&r){int C[256]={r=0};F(A)C[x]++;F(B)C[x]--;F(C)r|=x;}

Ungolfed and usage:

#include<iostream>

#define F(X) for(auto x:X)

void f(auto&A,auto&B,int&r){
  int C[256]={r=0}; //declare counting array and set return value to 0
  F(A)C[x]++;       //increase first string chars
  F(B)C[x]--;       //decrease second string chars
  F(C)r|=x;         //if any char is not zero
}

int main(){
  int r;
  #define P(a,b) f(a,b,r); std::cout << a << ", " << b << " -> " << r << "\n"
  P("hello","wrong");
  P("hello","olleh");
  P("zz","zzzzzz");
}
\$\endgroup\$
1
\$\begingroup\$

Mathematica 28 Bytes

Split into list of characters, sort and test for equality.

Equal@@ Sort/@Characters[#]&

Usage

%@{"BOAT", "TOAB"}

Output

True
\$\endgroup\$
1
\$\begingroup\$

Jelly, 3 bytes (probably non-competing)

Ṣ€E

Try it online!

Similar to X88B88's solution, but this takes a list of strings instead of two arguments, like ["String1", "String2"].

Explanation:

Ṣ€      Sort each input
  E     Check equality
\$\endgroup\$
0
1
\$\begingroup\$

Wolfram Language 26 bytes ( Mathematica )

ContainsAll@@Characters@#&

Usage:

%@{"BOAT","TOAB"}

Output:

True

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.