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

Java 16, 85 bytes

a->b->a.chars().sorted().boxed().toList().equals(b.chars().sorted().boxed().toList())

Java 16 added the Stream#toList method.

Java 8, 88 bytes

a->b->java.util.Arrays.equals(a.chars().sorted().toArray(),b.chars().sorted().toArray())

Try it online!

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

PHP7.4 (45 chars)

The function $f will return the answer using count_chars :

$f=fn($a,$b)=>($x='count_chars')($a)==$x($b);

Try it Online - in PHP4 the XOR cipher passes all tests using 48 chars :

function f($a,$b){return$a==chop($a.$b^$b^$b);};

C gcc (69 chars)

The function f compute the product of both string and implicitly return the comparison :

i;j;f(char*a,char*b){i=j=1;for(;*a;i*=*a++);for(;*b;j*=*b++);a=i==j;}

Try it Online

C version isn't shaved up to 65 chars by XOR cipher due to some ae == bf misses :

i;f(char*a,char*b){i=1;for(;*a;i^=*a++);for(;*b;i^=*b++);a=i==1;}
\$\endgroup\$
3
  • \$\begingroup\$ You can put the $f= into the header, as as long as the function does not reference itself, you can drop the function name from the char count. like this \$\endgroup\$
    – naffetS
    Apr 7, 2022 at 23:18
  • \$\begingroup\$ also you can remove the quotes around count_chars. it will spout all sorts of stuff to stderr, but who cares \$\endgroup\$
    – naffetS
    Apr 7, 2022 at 23:20
  • \$\begingroup\$ 68 bytes \$\endgroup\$
    – ceilingcat
    Apr 10, 2022 at 18:36
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\$

C - 115 Bytes

a[127],b[127],i,o=1;f(char*s,char*z){for(;*s;a[*s++]++);for(;*z;b[*z++]++);for(;i++<128&&o;o=a[i]==b[i]);return o;}

Ungolfed

a[127], b[127], i, o = 1;

f(char* s, char* z)
{
    for(; *s; a[*s++]++);
    for(; *z; b[*z++]++);
    for(; i++ < 128 && o; o = a[i] == b[i]);

    return o;
}

Alternative way (By @ceilingcat)

*a,*b,i,o;f(char*s,char*z){for(a=calloc(i=128,8);*s;a[*s++]++);for(b=a+i;*z;b[*z++]++);for(;i--&&(o=a[i]==b[i]););return o;}

Explanation

A function that receives two ASCII character strings with arbitrary length and checks if one is an anagram of the other.

To accomplish this, both entire strings are iterated over and the number of matches for each character is stored in a list for each string; later it is checked if both lists have the same number of matches, if so, then the strings are anagrams and true (1) is returned, otherwise false (0) is returned.

\$\endgroup\$
2
  • \$\begingroup\$ Fixed some bugs 124 bytes \$\endgroup\$
    – ceilingcat
    Apr 11, 2022 at 7:59
  • \$\begingroup\$ @ceilingcat thanks for your comments. \$\endgroup\$
    – user111743
    Apr 11, 2022 at 13:09
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
    Apr 13, 2022 at 15:52
  • \$\begingroup\$ 38 \$\endgroup\$
    – Razetime
    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\$

Raku, 22 bytes

{[~~] @_».comb».Bag}

Try it online!

  • .comb converts each input string to a list of its characters.
  • .Bag converts each list of characters into a Bag object (a set with multiplicity).
  • [~~] inserts the ~~ smartmatch operator between the two Bags, which returns true if and only if they have the same contents.
\$\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\$

Labyrinth, 23 bytes

1
,:#
* 0
1;/----+}=-!@

Try it online!

Takes two words separated by a newline. For each word, computes the product of c * 10 + 1 for each char c, and compares the two values. Prints 0 for true and a nonzero integer for false.

Such product is unique for lowercase words up to permutation, since the counts of 25 out of 26 letters can be recovered from the exponents of 25 unique prime factors:

971 is prime
981 = 109 * 3 * 3
991 is prime
1001 = 7 * 11 * 13 (no unique prime factor)
1011 = 337 * 3
1021 is prime
1031 is prime
1041 = 347 * 3
1051 is prime
1061 is prime
1071 = 17 * 7 * 3 * 3
1081 = 47 * 23
1091 is prime
1101 = 367 * 3
1111 = 101 * 11
1121 = 59 * 19
1131 = 29 * 13 * 3
1141 = 163 * 7
1151 is prime
1161 = 43 * 3 * 3 * 3
1171 is prime
1181 is prime
1191 = 397 * 3
1201 is prime
1211 = 173 * 7
1221 = 37 * 11 * 3

Therefore this approach works for arbitrary length inputs.

Since a lowercase letter has value of 97 or higher, the newline has value 10, and -1 is pushed on EOF, a three-way branch is possible via dividing the input value by any number between 11 and 97 inclusive.

By a little bit of planetary alignment, letting the IP reflect on newline (instead of creating a 4-way junction) magically sets up the stack for the second word. This part works because the words are guaranteed to be nonempty.

1    push 1 on empty stack

,:#  loop: compute the value of word1 until newline
* 0    ,:   getchar, dup  [word1 c c]
1;/    #0/  divide by 30  [word1 c c/30]
       if positive:
         ;1*  drop, multiply 10c+1  [word1']
       if zero: reflect

1    [word1 10 0]
,:#  0#:  push some garbage [word1 10 0 3 3]
  0  ,    getchar (1st char of word2)
     1    times 10 plus 1
     [word1 10 0 3 3 word2]
     enter the loop again to compute the value of word2
     same flow as first loop, except that # gives 8 and
     IP turns left on EOF
     [word1 10 0 3 3 word2 -1 -1]
----+}=-!@  clean up the stack and compare word1 and word2
     ----+ [word1 10 word2]
     }=    [word1 word2 | 10]
     -!@   print the difference and halt
\$\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\$
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.