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

1 2 3 4 5
6
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\$

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

Factor + math.combinatorics, 22 bytes

[ <permutations> in? ]

Try it online!

Is the first input in the permutations of the second input? Not the fastest, but shorter than sorting or counting.

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

Ly, 46 29 bytes

iayr>iay&s<l[0I=![0u;]pprp]1u

Try it online!

I know Ly better now. :) At a high level, this code constructs two stacks, each with a sorted (by codepoint) list of characters in the associated input string, with the length of the string included as another entry on the list.

One stack is reversed and then the two are concatenated. Once that setup is done, the code loops comparing the top and bottom of the stack. The first time the codepoints aren't the same, the code write out a 0 and exits. If the loop exhausts the stack, the strings are anagrams so the code writes out a 1 and exits.

It's still nowhere near the shortest, but the way it works might be interesting to people?

 # parse the first string
 i                             - read in one line
  a                            - sort by codepoint value
   y                           - push the stack length
    r                          - reverse the stack
  # parse the second string
     >                         - switch to a new stack
      i                        - read in one line
       a                       - sort by coidepoint
        y                      - push the stack length
         &s                    - stash the entire stack
 # setup for processing 
           <                   - back to stack with string 1
            l                  - append the parsed second string
 # compare pairs of codepoints while stack isn't empty
             [             ]   - loop, process one char per iteration
              0I               - copy bottom of stack
                =!             - compare top two negate
                  [   ]p       - if/then, if they don't match
                   0u;         - print "0" and exit
                        prp    - delete pair we just checked
 # if lengths and all the codepoints matched...
                            1u - success! print "1" 
\$\endgroup\$
0
\$\begingroup\$

Ruby, 46 bytes

I hope there's a way better than this.

p gets.strip.chars.sort==gets.strip.chars.sort

Attempt This Online!

\$\endgroup\$
2
  • \$\begingroup\$ a lambda taking two args would be shorter \$\endgroup\$
    – Razetime
    Commented Apr 13, 2022 at 15:52
  • \$\begingroup\$ 38 \$\endgroup\$
    – Razetime
    Commented Aug 9, 2022 at 12:40
0
\$\begingroup\$

Pyke, 4 bytes

mSXq

Try it here!

Also 4 bytes

SRSq

Try it here!

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

Zsh, 43 bytes

Try it Online!

<<<${${(j::)${(os::)1}}/${(j::)${(os::)2}}}

Truthy: empty string (i.e. the inputs are anagrams). Falsy: a string of characters. Link goes to a test harness where Truthy is printed as T, Falsy as F.

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

APL(NARS), 5 chars

≢⎕§⍦⎕

It return 0 if the two string are anagram each of other, or one number different of 0 otherwise. Test & how to use:

      ≢⎕§⍦⎕
⎕:
      '123'
⎕:
      '312'
0
      ≢⎕§⍦⎕
⎕:
      '123'
⎕:
      '2143'

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

YASEPL, 77 bytes

=1'=2'=c=e®1=f®2`1!g¥c,1=d=i`2!h¥d,2}7,g,3!i$`3!d+}2,f,2!i]4!c+}2,e>1|5`4>0`5

prompts you twice for both words, outputs either a one or zero for if its true or false respectively

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

Swift 5.9, 30 bytes

let f={Set($0+"")==Set($1+"")}

The obvious method. Initializes unordered Sets from the inputs (after concatenating empty strings to assist the type checker) and compares them.

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

UiuaSBCS, 7 bytes

≍∩(⊏⍏.)

Try it online!

Explanation

≍       Are the strings identical
 ∩(   ) when both of them
   ⊏⍏.  are sorted?

Notice that the process is identical to that of the BQN solution.

\$\endgroup\$
1
  • \$\begingroup\$ 6 bytes \$\endgroup\$
    – nyxbird
    Commented Jul 25 at 17:54
0
\$\begingroup\$

AWK, 87 bytes

{if(split($1,a,X)!=split($2,b,X))exit
asort(a);asort(b)
for(i in a)if(a[i]!~b[i])exit}1

Prints the input string on success, otherwise nothing.

{if(split($1,a,X)!=split($2,b,X))exit # different length strings
asort(a);asort(b)                     # line things up
for(i in a)if(a[i]!~b[i])exit}1       # print string if no fails
\$\endgroup\$
1 2 3 4 5
6

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.