86
\$\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
  • 6
    \$\begingroup\$ "Falcon Rage, go mad!" \$\endgroup\$ – Geobits Oct 6 '16 at 17:25
  • 10
    \$\begingroup\$ My name suggestion: "are they anagrams" → "manage the arrays" \$\endgroup\$ – Esolanging Fruit Oct 31 '17 at 4:32

135 Answers 135

1
\$\begingroup\$

C - 107 chars

Mark off chars in second string as we go. At the end, if we've passed over the entirety of both strings, then we've got a match.

i;main(p,v)char**v,*p;{for(;*v[1]&(p=strchr(v[2],*v[1]++));)*p=1,i++;puts(*(v[2]+i)|*v[1]?"false":"true");}
| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

C, (108)

char c[192]={};main(){for(;*a;c[127-*a++]++);for(;*b;c[223-*b++]++);puts(memcmp(c,c+96,95)?"false":"true");}
| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

PowerShell, 78 51 bytes

param([char[]]$a,[char[]]$b)(diff $a $b).Length-eq0

Takes the two string inputs, and re-casts them as char-arrays. The diff function (an alias for Compare-Object) takes the two arrays and returns items that are different between the two. We leverage that by re-casting the return as an array with (), and then checking its length. If the length is zero, that means that all items of both character arrays are exactly the same (because nothing was returned). PowerShell has an implicit write for evaluated statements like this, so will automatically write out True or False as required.

| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

Q, 15 Bytes

f:{~/{x@<x}'x}

f is the name of the function

Test

f("boat";"boat")            /1b
f("toab";"boat")            /1b
f("oabt";"toab")            /1b
f(,"a";"aa")                /0b
f("zzz";"zzzzzzzz")         /0b
f("zyyyzzzz";"yyzzzzzy")    /1b
f("sleepy";"pyels")         /0b
f(,"p";,"p")                /1b

Explanation

Argument of the function is a sequence with both words. At each word applies {x@<x}, that sorts x (take from x in ascending index ordering). ~/ reads as "match over", and compares both transformed words

| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ If you're using k rather than Q you can just do ~/x@'<:'x: for 10 bytes. No need to create the outer function f nor the inner function if you set x to be the input. \$\endgroup\$ – streetster Oct 31 '17 at 9:19
1
\$\begingroup\$

JavaScript, shortest JS answer so far: 57 56 characters, acccepts user input

This prompts the user for a value to compare.

function _(){return prompt().split(0).sort()+''}_()==_()

If no user input is required, this can be trimmed down to 53 52 characters.

Assuming the following variables are set:

var a='test', b='sets';

you can test for it with the following:

function _(a){return a.split(0).sort()+''}_(a)==_(b)

Note: this answer relies on some quirk that allowed using .split(0) instead of .split(""). This behavior no longer exists (at least in Firefox), so to get it running today, you have to replace 0 with "".

| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

C++14, 104 bytes

As generic function returning via reference parameter. Accepts char[] or std::string or any other container that supports range-based for loop.

Returns 0 for anagram, anything else for non-anagram

#define F(X) for(auto x:X)
void f(auto&A,auto&B,int&r){int C[256]={r=0};F(A)C[x]++;F(B)C[x]--;F(C)r|=x;}

Ungolfed and usage:

#include<iostream>

#define F(X) for(auto x:X)

void f(auto&A,auto&B,int&r){
  int C[256]={r=0}; //declare counting array and set return value to 0
  F(A)C[x]++;       //increase first string chars
  F(B)C[x]--;       //decrease second string chars
  F(C)r|=x;         //if any char is not zero
}

int main(){
  int r;
  #define P(a,b) f(a,b,r); std::cout << a << ", " << b << " -> " << r << "\n"
  P("hello","wrong");
  P("hello","olleh");
  P("zz","zzzzzz");
}
| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

Mathematica 28 Bytes

Split into list of characters, sort and test for equality.

Equal@@ Sort/@Characters[#]&

Usage

%@{"BOAT", "TOAB"}

Output

True
| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

Jelly, 3 bytes (probably non-competing)

Ṣ€E

Try it online!

Similar to X88B88's solution, but this takes a list of strings instead of two arguments, like ["String1", "String2"].

Explanation:

Ṣ€      Sort each input
  E     Check equality
| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

Perl 5, 27 + 3 (-lF) = 30 bytes

@{$.}=sort@F}{say"@1"eq"@2"

Try it online!

| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ The -l option is not needed. It would still count as +3 though since you must count the space too (since you cannot bundle the -F with -E. You can however do the final match using @1~~@2 saving 4 bytes (or 3 if you add an extra X option letter to supress the warning). Very neat solution by the way. Have a +1 \$\endgroup\$ – Ton Hospel Feb 4 '18 at 11:43
1
\$\begingroup\$

Lua, 140 chars

t={io.read():match"(%w+), (%w+)"}T=table for k=1,2 do w={t[k]:byte(1,-1)}T.sort(w)t[k]=T.concat{string.char(unpack(w))}end print(t[1]==t[2])

... like driving a screw with a light weight hammer, at least for code-golfing

| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

Python 2, 79 bytes

I thought I would add a different Python approach:

import sys
for l in sys.stdin: not reduce(cmp,map(sorted,l.strip().split(',')))

Or as a function:

def f(*v): return not reduce(cmp,map(sorted,v))
| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

Scala, 84 characters

object A{def main(a: Array[String]){println(a(0).sortWith(_<_)==a(1).sortWith(_<_))}}

This one's slightly longer, but doesn't use sorting (92 characters):

object A{def main(a:Array[String]){print((a(0)diff a(1)).isEmpty&&(a(1)diff a(0)).isEmpty)}}
| improve this answer | |
\$\endgroup\$
  • 1
    \$\begingroup\$ You can use sorted instead of sortWith. I posted another reply with sorted as well as REPL and function versions. \$\endgroup\$ – ebruchez Mar 9 '11 at 6:15
  • \$\begingroup\$ @ebruchez Thanks, I'm just learning Scala at the moment and these make good exercises. :-) \$\endgroup\$ – Gareth Mar 9 '11 at 10:19
  • \$\begingroup\$ Still learning myself ;) \$\endgroup\$ – ebruchez Mar 9 '11 at 16:17
1
\$\begingroup\$

Common Lisp, 50 bytes

(lambda(a b)(string=(sort a'char<)(sort b'char<)))

Try it online!

| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

Japt, 10 9 5 4 bytes

á øV

Try it

á øV     :Implicit input of strings U & V
á        :Permutations of U
  øV     :Contains V?
| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ As of v2.0a0, ¬n eV¬n works with 7 bytes. \$\endgroup\$ – Bubbler May 21 '18 at 7:42
  • \$\begingroup\$ øVá \$\endgroup\$ – Oliver Feb 1 '19 at 2:22
1
\$\begingroup\$

SmileBASIC, 49 bytes

INPUT A$,B$WHILE""<A$B$[INSTR(B$,POP(A$))]="
WEND

Throws an error when the strings aren't anagrams.

| improve this answer | |
\$\endgroup\$
0
\$\begingroup\$

PHP (51 chars, compressed)

function d($s){$s=str_split($s);sort($s);return$s;}

(Split string into an array, sort the array and return)

Example:

var_dump(d("word")===d("drow"));
| improve this answer | |
\$\endgroup\$
0
\$\begingroup\$

Ruby (35)

a,b=ARGV;a.chars.sort==b.chars.sort
| improve this answer | |
\$\endgroup\$
  • 1
    \$\begingroup\$ (Five years later...) $* is a handy alias for ARGV for 2 bytes. \$\endgroup\$ – Jordan Aug 18 '16 at 5:32
0
\$\begingroup\$

C# 118 chars

using System.Linq;namespace A{class P{static void Main(string[] a){System.Console.Write(!a[0].Except(a[1]).Any());}}}

Readable:

using System.Linq;

namespace A
{
    class P
    {
        static void Main(string[] a)
        {
            System.Console.Write(!a[0].Except(a[1]).Any());
        }
    }
}
| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ You can remove an extra character: string[]a You also don't need a namespace. \$\endgroup\$ – ICR Dec 7 '11 at 13:54
0
\$\begingroup\$

C#

bool IsJumbledPair(string a, string b) {
   if(a.Length!=b.Length) return false;
   foreach(char c in a.ToCharArray()) {
      int i = b.IndexOf(c);
      if(i<0) return false;
      b = b.Remove(i,1)
   }
   return (b.Length==0);
}

Readable, and does not require sorting.

Another method:

bool IsJumbledPair(string a, string b) {
   string c;
   while {
     if(a.Length!=b.Length) return false;
     if(a.Length==0) return true;
     c = a.Chars(0).ToString();
     b = b.Replace(c, "");
     a = a.Replace(c, "");
   }
}

The above version works better when the strings contain a number of duplicated characters, as each distinct character is only compared once using the relatively fast Replace() method.

VB.NET

Same as the first C# example, slightly simpler using Replace() method, but doesn't short-cut like the C# version:

Function IsJumbledPair(a As String, b As String) As Boolean
   If a.Length <> b.Length Then Return false
   For Each(c As Char In a.ToCharArray())
      b = Replace(b, c.ToString(), "", 1, 1)
   Next
   Return (b.Length=0)
}
| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ It is likely that the downvotes are because you have made no effort to golf (see the tag?) your solutions, or because you have mixed several distinct solutions in one answer. \$\endgroup\$ – dmckee --- ex-moderator kitten Mar 9 '11 at 22:50
  • 1
    \$\begingroup\$ Meh. If I play real golf, it's for socializing or beer, not score-keeping. Guess I should have actually been playing to win... :) \$\endgroup\$ – richardtallent Mar 11 '11 at 6:17
  • \$\begingroup\$ People generally respond well to solutions in wordy languages (I play in Fortran 77 from time to time), as long as you make an effort to write aggressively compacted <wordy language>, and especially if your languages supports a interesting trick (i.e. fortran has computed branches). \$\endgroup\$ – dmckee --- ex-moderator kitten Mar 11 '11 at 16:10
0
\$\begingroup\$

F# (59 chars)

let f a b=(Seq.sort>>Seq.toArray)a=(Seq.sort>>Seq.toArray)b

Very annyoying that sequences can' be directly compared.

| improve this answer | |
\$\endgroup\$
0
\$\begingroup\$

Ada 2005 - 314 218

type V is array(Character)of Natural;function A(L,R:String)return Boolean is
C,D:V:=(others=>0);begin
for I in L'Range loop
C(L(I)):=C(L(I))+1;end loop;for I in R'Range loop
D(R(I)):=D(R(I))+1;end loop;return C=D;end;
| improve this answer | |
\$\endgroup\$
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).

| improve this answer | |
\$\endgroup\$
  • \$\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 Oct 7 '16 at 10:48
0
\$\begingroup\$

Coffee Script (52)

a=(b,c)->`b.split('').sort()==c.split('').sort()+''`

usage

console.log a 'god', 'dog'
| improve this answer | |
\$\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'
| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ You can save 2 characters by changing the import to from sys import* (newline) s=argv. \$\endgroup\$ – Steven Rumbalski Sep 13 '11 at 14:45
  • \$\begingroup\$ Algorithm fails with s[1]='the',s[2]='them'. \$\endgroup\$ – Steven Rumbalski Sep 13 '11 at 14:54
  • \$\begingroup\$ You could avoid the need to dereference s by from sys import* (newline) _,a,b=argv. \$\endgroup\$ – Steven Rumbalski Sep 13 '11 at 17:19
0
\$\begingroup\$

Groovy, 46

b={args[it].toList().sort()}
print b(0)==b(1)
| improve this answer | |
\$\endgroup\$
0
\$\begingroup\$

Groovy, 54

print args[0].toList().sort()==args[1].toList().sort()
| improve this answer | |
\$\endgroup\$
  • \$\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\$ – dmckee --- ex-moderator kitten Mar 9 '11 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.

| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ So it's no shorter but it is buggier? \$\endgroup\$ – Peter Taylor Dec 7 '11 at 14:04
  • \$\begingroup\$ Hmmm... Why buggier? \$\endgroup\$ – Averroes Dec 7 '11 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 Dec 7 '11 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\$ – Peter Taylor Dec 7 '11 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.

| improve this answer | |
\$\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/

| improve this answer | |
\$\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

| improve this answer | |
\$\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.