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

163 Answers 163

1
\$\begingroup\$

05AB1E, 3 bytes

Aargh! I can't beat GolfScript!

œså

Try it online!

Explanation

œ   All permutations of the first input
 så Do the permutations contain the second input?

œQà

œ   All permutations
 Q  Equality with input
  à Maximum

€{Ë

€{  Map sort over the input list
  Ë Are all items equal?
\$\endgroup\$
1
\$\begingroup\$

Julia, 26 bytes

!a=sort([a...])
a\b=!a==!b

Try it online!

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

TI-Basic, 83 bytes

Prompt Str1,Str2
"seq(inString(Str1+Str2,sub(Ans,I,1)),I,1,length(Ans→u
Str1
u→A
SortA(ʟA
Str2
u→B
SortA(ʟB
0
If dim(ʟA)=dim(ʟB
min(ʟA=ʟB
Ans

Output is stored in Ans and displayed. Outputs 1 if the inputs are anagrams, otherwise 0.

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

Alice, 11 bytes

/@Mn/
\MOX\

Try it online!

Prints Jabberwocky if the two words are anagrams

Flattened

MM       Reads the two arguments
  X      Compute their symmetric difference
   n     Empty string becomes Jabberwocky, anything else becomes empty string
    O    Print it out
     @   Bye
\$\endgroup\$
1
\$\begingroup\$

R, 47 bytes

\(x,y)all(table(strsplit(paste0(x,y),""))%%2==0)
\$\endgroup\$
1
1
\$\begingroup\$

BQN, 3 bytes

≡○∧

Anonymous tacit function that takes two strings; returns 1 if they are anagrams, 0 otherwise. Try it at BQN online!

Explanation

≡    Are the strings identical
 ○   when both of them
  ∧  are sorted?
\$\endgroup\$
1
\$\begingroup\$

J-uby, 17 bytes

:*&(A|:sort)|+:==

Attempt This Online!

Explanation

:* & (A | :sort) | +:==

:* & (         )         # Map with...
      A | :sort          #   convert to character array, then sort
                 | +:==  # then compare
\$\endgroup\$
1
\$\begingroup\$

Nekomata + -e, 2 bytes

↕=

Attempt This Online!

↕       Check if any permutation of the first string
 =      is equal to the second string
\$\endgroup\$
0
\$\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\$
0
\$\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
    Aug 18, 2016 at 5:32
0
\$\begingroup\$

C# 118 chars

using System.Linq;namespace A{class P{static void Main(string[] a){System.Console.Write(!a[0].Except(a[1]).Any());}}}

Readable:

using System.Linq;

namespace A
{
    class P
    {
        static void Main(string[] a)
        {
            System.Console.Write(!a[0].Except(a[1]).Any());
        }
    }
}
\$\endgroup\$
1
  • \$\begingroup\$ You can remove an extra character: string[]a You also don't need a namespace. \$\endgroup\$
    – ICR
    Dec 7, 2011 at 13:54
0
\$\begingroup\$

C#

bool IsJumbledPair(string a, string b) {
   if(a.Length!=b.Length) return false;
   foreach(char c in a.ToCharArray()) {
      int i = b.IndexOf(c);
      if(i<0) return false;
      b = b.Remove(i,1)
   }
   return (b.Length==0);
}

Readable, and does not require sorting.

Another method:

bool IsJumbledPair(string a, string b) {
   string c;
   while {
     if(a.Length!=b.Length) return false;
     if(a.Length==0) return true;
     c = a.Chars(0).ToString();
     b = b.Replace(c, "");
     a = a.Replace(c, "");
   }
}

The above version works better when the strings contain a number of duplicated characters, as each distinct character is only compared once using the relatively fast Replace() method.

VB.NET

Same as the first C# example, slightly simpler using Replace() method, but doesn't short-cut like the C# version:

Function IsJumbledPair(a As String, b As String) As Boolean
   If a.Length <> b.Length Then Return false
   For Each(c As Char In a.ToCharArray())
      b = Replace(b, c.ToString(), "", 1, 1)
   Next
   Return (b.Length=0)
}
\$\endgroup\$
3
  • \$\begingroup\$ It is likely that the downvotes are because you have made no effort to golf (see the tag?) your solutions, or because you have mixed several distinct solutions in one answer. \$\endgroup\$ Mar 9, 2011 at 22:50
  • 1
    \$\begingroup\$ Meh. If I play real golf, it's for socializing or beer, not score-keeping. Guess I should have actually been playing to win... :) \$\endgroup\$ Mar 11, 2011 at 6:17
  • \$\begingroup\$ People generally respond well to solutions in wordy languages (I play in Fortran 77 from time to time), as long as you make an effort to write aggressively compacted <wordy language>, and especially if your languages supports a interesting trick (i.e. fortran has computed branches). \$\endgroup\$ Mar 11, 2011 at 16:10
0
\$\begingroup\$

F# (59 chars)

let f a b=(Seq.sort>>Seq.toArray)a=(Seq.sort>>Seq.toArray)b

Very annyoying that sequences can' be directly compared.

\$\endgroup\$
0
\$\begingroup\$

Ada 2005 - 314 218

type V is array(Character)of Natural;function A(L,R:String)return Boolean is
C,D:V:=(others=>0);begin
for I in L'Range loop
C(L(I)):=C(L(I))+1;end loop;for I in R'Range loop
D(R(I)):=D(R(I))+1;end loop;return C=D;end;
\$\endgroup\$
0
\$\begingroup\$

C - 79 90 chars (using strchr & strlen)

r(char*s,char*t){int i=0;for(;*s&&strchr(t,*s++);i++);return i==strlen(t)?1:0;}

Ungolfed...

r( char *s, char *t )
{
    int i=0;
    for (; *s && strchr(t, *s++); i++)
        ;
    return i == strlen(t) ? 1 : 0;
}

C - 115 110 chars (brute with histogram)

int k,u[256];ρ(char*s,char*t){char*v=s;for(;*s;)u[*s++]++;for(;*t;)u[*t++]--;while(*v&&!(k=u[*v++]));return k?0:1;}

Ungolfed...

int k, u[256];
r(char *s, char*t)
{
    char *v = s;

    for (;*s;)
        u[*s++]++;
    for (;*t;)
        u[*t++]--;

    while(*v && !(k=u[*v++]) )
        ;
    return k ? 0 : 1;
}

EDIT: fixed bug in brute version.

EDIT: added brute version (no library functions).

\$\endgroup\$
1
  • \$\begingroup\$ You use the table 256 char; if you call that function more that one time it is necessary make that 256 table 0. \$\endgroup\$
    – user58988
    Oct 7, 2016 at 10:48
0
\$\begingroup\$

Coffee Script (52)

a=(b,c)->`b.split('').sort()==c.split('').sort()+''`

usage

console.log a 'god', 'dog'
\$\endgroup\$
0
\$\begingroup\$

Python 121 Characters

It's not a winner wrt length, but I didn't use sorted!

from sys import argv as s
for i in s[1]+s[2]:
 if not s[1].count(i)==s[2].count(i):
  print 'False'
  break
else:
 print 'True'
\$\endgroup\$
3
  • \$\begingroup\$ You can save 2 characters by changing the import to from sys import* (newline) s=argv. \$\endgroup\$ Sep 13, 2011 at 14:45
  • \$\begingroup\$ Algorithm fails with s[1]='the',s[2]='them'. \$\endgroup\$ Sep 13, 2011 at 14:54
  • \$\begingroup\$ You could avoid the need to dereference s by from sys import* (newline) _,a,b=argv. \$\endgroup\$ Sep 13, 2011 at 17:19
0
\$\begingroup\$

Groovy, 46

b={args[it].toList().sort()}
print b(0)==b(1)
\$\endgroup\$
0
\$\begingroup\$

Groovy, 54

print args[0].toList().sort()==args[1].toList().sort()
\$\endgroup\$
1
  • \$\begingroup\$ I've fixed up the formatting for you. Stack Exchange site use MarkDown (though they do accept a subset of html). THe sidebar on the edit page has some hints, the edit toolbar has common operations, and there is a detailed help page. \$\endgroup\$ Mar 9, 2011 at 22:46
0
\$\begingroup\$

Java, 173 chars

import java.util.*;class C{public static void main(String[]a){byte[]d,f;Arrays.sort(d=a[0].getBytes());Arrays.sort(f=a[1].getBytes());System.out.print(Arrays.equals(f,d));}}

It's the same that Guus one but changing a couple of methods.

\$\endgroup\$
4
  • \$\begingroup\$ So it's no shorter but it is buggier? \$\endgroup\$ Dec 7, 2011 at 14:04
  • \$\begingroup\$ Hmmm... Why buggier? \$\endgroup\$
    – Averroes
    Dec 7, 2011 at 14:34
  • \$\begingroup\$ Maybe this? "The behavior of this method when this string cannot be encoded in the default charset is unspecified." :P \$\endgroup\$
    – Averroes
    Dec 7, 2011 at 14:36
  • \$\begingroup\$ My bad, forgot to check the spec. I was thinking about characters in the range \u0080 to the end of the BMP, which become more than one byte, and which would allow collisions. \$\endgroup\$ Dec 7, 2011 at 15:08
0
\$\begingroup\$

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.

\$\endgroup\$
0
\$\begingroup\$

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/

\$\endgroup\$
0
\$\begingroup\$

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

\$\endgroup\$
0
\$\begingroup\$
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");
        }   
    }
}
\$\endgroup\$
0
\$\begingroup\$

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;}
\$\endgroup\$
0
\$\begingroup\$

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

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");
}
\$\endgroup\$
1
  • \$\begingroup\$ This can not be ok every input... What about string has the same value example "caa" and "bba" ? \$\endgroup\$
    – user58988
    Dec 20, 2018 at 15:04
0
\$\begingroup\$

Groovy 44

def f(a,b){print !(a-b)&&a.size()==b.size()}
\$\endgroup\$
0
\$\begingroup\$

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

Javascript - 57 chars

function o(a,b){return b?o(a)==o(b):1+a.split("").sort()}
\$\endgroup\$
4
  • 1
    \$\begingroup\$ Your function will fail if in the first try, b was empty. \$\endgroup\$
    – Optimizer
    Sep 14, 2014 at 22:04
  • \$\begingroup\$ 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 \$\endgroup\$
    – Kevin Wu
    Sep 15, 2014 at 22:25
  • \$\begingroup\$ @Optimizer did you even try running it? \$\endgroup\$
    – Kevin Wu
    Sep 15, 2014 at 22:37
  • \$\begingroup\$ Ah, I see. In that case, it will be fine. \$\endgroup\$
    – Optimizer
    Sep 16, 2014 at 6:43

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.