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

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
    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\$ Oct 5, 2015 at 17:04
  • \$\begingroup\$ You can also shave off 3 bytes by replacing x.split`` with [...x] \$\endgroup\$
    – Scott
    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\$

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

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
    Oct 7, 2016 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
  • 1
    \$\begingroup\$ Please do not vandalize your posts. \$\endgroup\$
    – DJMcMayhem
    Oct 20, 2016 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\$

J, 8 bytes

-:&(/:~)

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

Try it online!

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

Axiom, 45 bytes

f(a:String,b:String):Boolean==sort(a)=sort(b)
\$\endgroup\$
0
\$\begingroup\$

Julia, 41 bytes

g(a,b)=sort(collect(a))==sort(collect(b))
\$\endgroup\$
0
\$\begingroup\$

Python, 99 chars

f=lambda w,x,y:w==y if x==""else any([f(w+a,x.replace(a,"",1),y)for a in x]) 
g=lambda x,y:f("",x,y)

Try it Online!

Recursively finds all permutations of x and compares them to y.

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

Pyth, 4 bytes

_ISM

Try it Online

Explanation

_ISM
  SMQ   Sort both (implicit) inputs.
_I      Check if the result is invariant under reversing.
\$\endgroup\$
0
\$\begingroup\$

Perl, 60 bytes

Perl one-liner

perl -lanF -e 'push@a,join"",sort@F;END{exit($a[0]ne$a[1])}'

Takes first two lines of STDIN and compares them. Exits 0 if they're anagrams, 1 otherwise.

$ echo -e "word\nwrdo" | \
> perl -lanF -e 'push@a,join"",sort@F;END{exit($a[0]ne$a[1])}' && echo anagram
anagram
$ echo -e "word\nwrro" | \
> perl -lanF -e 'push@a,join"",sort@F;END{exit($a[0]ne$a[1])}' && echo anagram
$
\$\endgroup\$
0
\$\begingroup\$

Perl, 26 bytes

Includes +1 for p (using -F and @F ends up with the same score)

Give the input strings as 2 lines on STDIN.

(echo word; echo wrdo) | perl -pE '$\=${join W,sort/./g}++}{'

This prints 0 if not an anagram or 1 if it is an anagram

(echo word; echo wrdo) | perl -pE '$_=${join W,sort/./g}++'

comes in at 24 bytes and prints 00 if not an anagram and 01 if it is. If these values are numbers they are in fact valid falsy and thruthy in perl, but as strings they are both thruthy. It's probably fairer to consider them as strings so this solution is invalid

So this is the same length (but without warnings) as Xcali's answer (after optimizing):

(echo word; echo wrdo) | perl -F -E '@{$.}=sort@F}{say@1~~@2'
\$\endgroup\$
0
\$\begingroup\$

Tcl, 82 bytes

proc A x\ y {expr {[string le $x]==[string le $y]&[lsort -u [split $x $y]]=="{}"}}

Try it online!


Tcl, 83 bytes

proc A x\ y {expr {[string le $x]==[string le $y]&&[lsort -u [split $x $y]]=="{}"}}

Try it online!

Tcl, 84 bytes

proc S s {lsort [split $s ""]}
proc A x\ y {set x [S $x]
set y [S $y]
expr {$x==$y}}

Try it online!

Previous version was failing for comparing 2 to 20, because after the lsort and join the comparison became 2==02, and == was doing a numerical comparison instead of a numerical one!


Tcl, 94 bytes

proc S s {join [lsort [split $s ""]] ""}
proc A x\ y {set x [S $x]
set y [S $y]
expr {$x==$y}}

Try it online!

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

MathGolf, 4 bytes

ms~=

Try it online!

Explanation

m      explicit map
 s     sort(array)
  ~    dump array to stack
   =   pop(a, b), push(a==b)
\$\endgroup\$
0
\$\begingroup\$

Pepe, 58 bytes

REEREEEEeEERREEeREEEEeEeErRREEEEEeEEreerrEEREEeeReEErEereE

Try it online! Input is in the form a;b. Outputs 0 for truthy and none for falsy.

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

Pushy, 13 bytes

Assumes the two inputs are separated by a space.

K32-$v;.gFgx#

Try it online!

                 \ Implicit: input on stack as character codes
K32-             \ Subtract 32 from all, making SPACE = 0
    $            \ Until 0 (space) on top of stack:
     v;          \   Send last char to auxiliary stack
       .         \ Space has been reached, pop it.
                 \ Now each stack contains all the letters of one of the words.
        gFg      \ Sort both stacks
           x     \ Check their equality
            #    \ Print result (1 if true, 0 if false)
\$\endgroup\$
0
\$\begingroup\$

C# (.NET Core), 108 bytes

Without LINQ. Returns 1 for true, 0 for false.

(a,b)=>{int x=a.Length==b.Length?1:0;foreach(char c in a){try{b.Remove(b.IndexOf(c));}catch{x=0;}}return x;}

Try it online!

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

Lua 112

function q(a,b)s=table.sort;t=table.concat;a={a:byte(1,#a)}s(a);b={b:byte(1,#b)}s(b)return t(a,".")==t(b,".")end
\$\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.