85
\$\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\$
  • 10
    \$\begingroup\$ 9 answers in 13 views... wow! \$\endgroup\$ – Tom Gullen Mar 8 '11 at 16:44
  • \$\begingroup\$ @Tom, because everyone wanted to prove that your comment about using a 64-bit integer was pointing in the wrong direction :P \$\endgroup\$ – Peter Taylor Mar 8 '11 at 18:15
  • 5
    \$\begingroup\$ Title request: Cod Elf, Go! \$\endgroup\$ – user54200 Jul 9 '16 at 12:48
  • 5
    \$\begingroup\$ "Falcon Rage, go mad!" \$\endgroup\$ – Geobits Oct 6 '16 at 17:25
  • 7
    \$\begingroup\$ My name suggestion: "are they anagrams" → "manage the arrays" \$\endgroup\$ – Esolanging Fruit Oct 31 '17 at 4:32

133 Answers 133

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\$

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

Groovy 44

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

Groovy 42

def f(a,b){print ((b as Set)==(a as Set))}
\$\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\$
  • 1
    \$\begingroup\$ Your function will fail if in the first try, b was empty. \$\endgroup\$ – Optimizer Sep 14 '14 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 '14 at 22:25
  • \$\begingroup\$ @Optimizer did you even try running it? \$\endgroup\$ – Kevin Wu Sep 15 '14 at 22:37
  • \$\begingroup\$ Ah, I see. In that case, it will be fine. \$\endgroup\$ – Optimizer Sep 16 '14 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
\$\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\$
  • \$\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 Dec 17 '18 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\$
  • \$\begingroup\$ Welcome to PPCG! Since you're using ES6, you could replace split('')... with split``... to save two bytes. \$\endgroup\$ – ETHproductions Oct 5 '15 at 17:04
  • \$\begingroup\$ You can also shave off 3 bytes by replacing x.split`` with [...x] \$\endgroup\$ – Scott May 17 '16 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\$

Pyke, 4 bytes (non-competing)

Pyke is FAR newer than this challenge

mSXq

Try it here!

Also 4 bytes

SRSq

Try it here!

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

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

Python, 20 bytes

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

sorted(x)==sorted(y)
\$\endgroup\$
  • \$\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\$ – ericmarkmartin Jan 24 '15 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\$

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\$
  • \$\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\$ – RosLuP Oct 7 '16 at 10:56
0
\$\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
    \$\begingroup\$ Please do not vandalize your posts. \$\endgroup\$ – DJMcMayhem Oct 20 '16 at 17:49
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\$
0
\$\begingroup\$

Wolfram Language 26 bytes ( Mathematica )

ContainsAll@@Characters@#&

Usage:

%@{"BOAT","TOAB"}

Output:

True

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

J, 8 bytes

-:&(/:~)

Match -: after sorting /:~ both args &.

Try it online!

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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