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

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
    Commented 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\$ Commented Sep 13, 2011 at 14:45
  • \$\begingroup\$ Algorithm fails with s[1]='the',s[2]='them'. \$\endgroup\$ Commented Sep 13, 2011 at 14:54
  • \$\begingroup\$ You could avoid the need to dereference s by from sys import* (newline) _,a,b=argv. \$\endgroup\$ Commented 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\$ Commented 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\$ Commented Dec 7, 2011 at 14:04
  • \$\begingroup\$ Hmmm... Why buggier? \$\endgroup\$
    – Averroes
    Commented 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
    Commented 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\$ Commented 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
    Commented 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
    Commented 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
    Commented Sep 15, 2014 at 22:25
  • \$\begingroup\$ @Optimizer did you even try running it? \$\endgroup\$
    – Kevin Wu
    Commented Sep 15, 2014 at 22:37
  • \$\begingroup\$ Ah, I see. In that case, it will be fine. \$\endgroup\$
    – Optimizer
    Commented Sep 16, 2014 at 6:43
0
\$\begingroup\$

Pyth - 19

qS@cz", "0S@cz", "1

Try it here. Note that the two words in the input must be separated by a comma and a space.

Python Mapping and explanation

q                     #      equal(              "Check equality"
 S                    #      sorted(             "Sort"
  @                   #      list looku          "Extract element from list"
   c                  #      chop(               "Separate by delimiter"
    z                 #      input(              "Input variable"
     ", "             #      ", "                "This delimiter"
         0            #      0                   "The 0th element"
          S@cz", "1   #      ..                  "The same thing with the 1st element

I'm sure someone can come up with a shorter implementation, but I've only been learning Pyth for a few days. It would also be a lot shorter if I didn't stick strictly to the input format given in the question.

For instance:

qS@Q0S@Q1

Which is only 9 bytes, works if the input is formatted like 'parse','spare'. So which one do you count?

Good practice though!

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

Ruby, 32

h=->{gets.chars.sort}
p h[]==h[]
\$\endgroup\$
0
0
\$\begingroup\$

Javascript, 143 119 bytes

a=prompt()[s="split"](" ");a[0]=a[0][s]("");a[1]=a[1][s]("");a[0].sort();a[1].sort();alert(a[0][j="join"]()==a[1][j]())

Takes a single space-seperated pair of strings as input.

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

rs, 35 bytes

+(.)(.*) (.*)\1/\2 \3
\s/
.+/0
^$/1

Yay regexes!!

BTW, rs was created way after this was posted, so this technically doesn't count. Still cool.

Live demo and all test cases.

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

R, 63 Bytes

length(unique(lapply(strsplit(c(s,m),''),sort))[[1]])==nchar(m)

It seens it passes the test cases.

(just realized this question is 4 year old, but posting anyway)

\$\endgroup\$
1
  • \$\begingroup\$ Passing the test cases does not necessary make a working function. Your function only works when the number of unique characters in s is equal to the number of characters in m. For instance, s="boatee" and m="toobee" yields TRUE, when it should actually be FALSE. \$\endgroup\$
    – Sumner18
    Commented Dec 17, 2018 at 21:31
0
\$\begingroup\$

Javascript (ES6) 35

Requires lambdas

Just like the other solutions, but with lambda

f=x=>x.split``.sort()
f(a)==f(b)+""

Usage

// a, b = input
f=x=>x.split``.sort()
console.log(f(a)==f(b)+"")

thanks @comment

\$\endgroup\$
2
  • \$\begingroup\$ Welcome to PPCG! Since you're using ES6, you could replace split('')... with split``... to save two bytes. \$\endgroup\$ Commented Oct 5, 2015 at 17:04
  • \$\begingroup\$ You can also shave off 3 bytes by replacing x.split`` with [...x] \$\endgroup\$
    – Scott
    Commented May 17, 2016 at 19:36
0
\$\begingroup\$

Powershell 48 bytes

param([char[]]$a,[char[]]$b)![bool](diff $a $b)

Cast incoming strings as an array of char. Use diff (compare-object) on the two objects and cast as bool. Since a blank result (diff only shows differences not similarities) is False, negating it with ! will result in true for identical strings.

Added benefit: it will work on any arbitrary length strings (if equal whitespace).

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

Jelly, 5 Bytes (Non-competitive)

Ṣ⁼⁴Ṣ¤

Special thanks to Leaky Nun for helping me fix a problem.

Outputs one if true. Try it Online!

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

Python, 20 bytes

lose to golfscript again...... :(

sorted(x)==sorted(y)
\$\endgroup\$
1
  • \$\begingroup\$ This will work, but it does not include the parsing of x and y, which can contribute to the length of the answer. \$\endgroup\$ Commented Jan 24, 2015 at 7:17
0
\$\begingroup\$

Scala - 64 Bytes

Could be made shorter (the toList could be changed to toSeq, I believe) ('a'to'z').forall(c=>y.toList.count(_==c)==z.toList.count(_==c))

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

Racket 92 bytes

(λ(a b)(define(g s)(sort(map(λ(x)(char->integer x))(string->list s))>))(equal?(g a)(g b)))

Ungolfed:

(define f
  (λ (a b)
    (define (g s)    ; fn to get sorted list of string chars as numbers.
      (sort
       (map
        (λ(x)(char->integer x))
        (string->list s))
       >))
    (equal? (g a) (g b))))

Testing:

(f "test" "ttse")
(f "boat" "boat")
(f "toab" "boat")
(f "oabt" "toab")
(f "zyyyzzzz" "yyzzzzzy")
(f "a" "aa")
(f "zzz" "zzzzzzzz")
(f "sleepy" "pyels")

Output:

#t
#t
#t
#t
#t
#f
#f
#f
\$\endgroup\$
0
\$\begingroup\$

awk, 63 65 bytes

It only accepts chars a-z (0141-0172). gsub counts occurrances of each char in alphabet, appends them to a variable (variable looks something like 140213000000000000..., starts with 140 for initialization) and compares frequencies in variables in the end. It returns the value of the comparison on exit:

{for(a=i=140;++i<173;)a=a gsub("\\"i,1);if(p>1)exit(p==a);p=a}

Test it:

$ cat file
aabccc
abcacc
$ awk '{for(a=i=140;++i<173;)a=a gsub("\\"i,"");if(p>1)exit(p==a);p=a}' file
$ echo $?  # will output 0 or 1 where 1=true and 0=false
1
\$\endgroup\$
0
\$\begingroup\$

APL (Dyalog), 10 bytes

≡/(⊂∘⍋⌷⊢)¨

Try it online!

The program takes in two strings in a single array as its right argument.

Explanation

¨            For each string
 (⊂∘⍋⌷⊢)      Sort it
≡/           And check if both strings are equal
\$\endgroup\$
0
\$\begingroup\$

Excel VBA, 87 Bytes

Anonymous VBE immediate window function that takes input from range A1:B1 and outputs whether the two inputs are anagrams of one another to the VBE immediate window. This a destructive process as the value inputted into range B1 is destroyed

For i=1To[Len(A1)]:[B1]=Replace([B1],Mid([A1],i,1),"|",,1):Next:?[B1=Rept("|",len(A1))]
\$\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.