Tell me more ×
Programming Puzzles & Code Golf Stack Exchange is a question and answer site for programming puzzle enthusiasts and code golfers. It's 100% free, no registration required.

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 A-Z
  • 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

Good luck!

The shorter an answer is, the better!

Edit

Shame this question is marked community wiki... I thought that was the purpose of the site?!?!

enter image description here

share|improve this question
2  
9 answers in 13 views... wow! – Tom Gullen Mar 8 '11 at 16:44
8  
ARGH! Why is this question marked community wiki? – Tom Gullen Mar 9 '11 at 10:39
14  
@Martin, part of the fun of this site for me is the competition in collecting rep! – Tom Gullen Mar 9 '11 at 11:27
2  
@TomGullen As to “why”, you can see it in the post's history: “more than 60 answers”. Perhaps you should propose on Meta that that automatic rule should be removed for this site. – Kevin Reid Jun 2 '12 at 14:43
show 3 more comments

63 Answers

1 2 3

Scala in REPL (32)

readLine.sorted==readLine.sorted

Scala function (43)

def f(a:String,b:String)=a.sorted==b.sorted

Scala program (61)

object A extends App{println(args(0).sorted==args(1).sorted)}

These leverage a neat feature of Scala whereby a String can also be treated as a sequence of characters (Seq), with all the operations on Seq being available.

share|improve this answer

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/

share|improve this answer

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.

share|improve this answer

R, 91

f=function(x,y) ifelse(identical(sort(strsplit(x,"")[[1]]),sort(strsplit(y,"")[[1]])),T,F)

Sample output:

f("boat","boat")
[1] TRUE
f("toab","boat")
[1] TRUE
f("oabt","toab")
[1] TRUE
f("a","aa")
[1] FALSE
f("zzz","zzzzzzzz")
[1] FALSE
f("zyyyzzzz","yyzzzzzy")
[1] TRUE
f("sleepy","pyels")
[1] FALSE
f("p","p")
[1] TRUE
share|improve this answer

Q, 25

{(~). asc each(,/)each x}  

sample output:

q){(~). asc each(,/)each x}("boat";"boat")
1b
q){(~). asc each(,/)each x}("toab";"boat")
1b
q){(~). asc each(,/)each x}("oabt";"toab")
1b
q){(~). asc each(,/)each x}("a";"aa")
0b
q){(~). asc each(,/)each x}("zzz";"zzzzz")
0b
q){(~). asc each(,/)each x}("zyyyzzzzz";"yyzyzzzzz")
1b
q){(~). asc each(,/)each x}("p";"p")
1b
share|improve this answer

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.

share|improve this answer
show 4 more comments

Groovy, 54

print args[0].toList().sort()==args[1].toList().sort()
share|improve this answer
show 1 more comment

Groovy, 46

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

C++ (104 non-ws chars)


Based on counting sort. Note: Assumes strings of the same length, which seems to be implied (though not stated) by the question.

int u[123], i;

int a(char **c) {
    for(; c[0][i]; ) {
        u[c[0][i]]++;
        u[c[1][i++]]--;
    }

    i=123;
    while(i && !u[--i]);
    return !i;
}
share|improve this answer
1  
Bzzzt. You pass the test cases, but "helle" and "hollo" are apparently the same. Easy fix: change one of the ++ to a --. Then just if (u[i++]) return 0; – Dave Gamble Mar 9 '11 at 6:30
1  
I haven't tested this, but the last three lines can be written as i=123;while(i&&u[--i]);return!i; – st0le Dec 7 '11 at 4:38
show 6 more comments

Perl (58)

(complete program, unlike the other Perl answer which is only a function)

($c,$d)=map{[sort split//]}<>;print"@$c"eq"@$d"?true:false

49 as a function

sub f{($c,$d)=map{[sort split//]}<>;"@$c"eq"@$d"}
share|improve this answer
show 2 more comments

k4 - 11 chars

Given strings a and b:

(a@<a)~b@<b

  a:"word"
  b:"wrdo"
  (a@<a)~b@<b
1b

At the cost of 2 chars this can be made into a function:

{(x@<x)~y@<y}["word";"wrdo"]
1b

Implementation is same as the J implementation; sort the vectors then compare equivalence.

~ is match

< is grade up (indices were the vector to be sorted ascending)

@ is index

share|improve this answer

Python 3 (66)

Like jloy's answer, I eschewed using sorted because so many other answers did so. I also didn't want to rehash his use of collections.Counter so I used str.count instead. With these constraints I got within 3 characters of jloy.

i=input;a=i();b=i();print(all(a.count(s)==b.count(s)for s in a+b))
share|improve this answer
show 1 more comment

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'
share|improve this answer
show 4 more comments

Coffee Script (52)

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

usage

console.log a 'god', 'dog'
share|improve this answer

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).

share|improve this answer

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;
share|improve this answer

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.

share|improve this answer

PHP (71)

function a($a){while($i<$r=strlen($a))$t+=ord($a[$i++]);return"$r|$t";}

Use:

echo (a("abc")==a("cba"));
share|improve this answer
show 1 more comment

Clojure - 30 chars

Too many people seem to be relying on sorting so I thought of an interesting alternative way to do this via a histogram:

#(apply = (map frequencies %))

Use this as a function, i.e.:

(#(apply = (map frequencies %)) ["boat" "toab"])
=> true
share|improve this answer

Python 2, without sorting as that starts to get boring - 104 chars

def f(a,b):
 a,b=list(a),list(b)
 while a:
    try:b.remove(a.pop())
    except:return
 return len(a)==len(b)
share|improve this answer

Python 3 (64)

This is not a particularly good golf given how short some of the earlier Python solutions that use sorted() are, but here's a version that uses collections.Counter (an unlovable module from a golfing perspective, but with some neat stuff). It reads two lines from input and outputs True or False. Going with Python 3 versus 2.7 saved 4 chars with input() instead of raw_input(), but lost 1 for the parens for print since it is now a function.

from collections import *;c,i=Counter,input;print(c(i())==c(i()))
share|improve this answer
show 2 more comments

Ruby 1.9 - 32

x=->{gets.chars.sort}
p x[]==x[]
share|improve this answer
show 3 more comments

Perl - 78 characters[1]

@x=map{join("",sort(split("")))}split(",",<>);print$x[0]eq$x[1]?"true":"false"; 

[1] Unlike some other Perl code above, this actually reads the input in "foo,bar" format and prints "true" or "false". Could be shorter otherwise.

share|improve this answer

Java

(everyone's favorite language apparently!)

173 chars:

import java.util.*;class g{public static void main(String[]p){String[]a=p[0].split(""),b=p[1].split("");Arrays.sort(a);Arrays.sort(b);System.out.print(Arrays.equals(a,b));}}

(Doesn't print newline char to save 2 chars from println)

Compile and run:

javac g.java
java -cp . g abcdef fedcba
true

Love to see a shorter one...

share|improve this answer

Ruby (39)

Accepts the input as given in the question. Run with ruby -n.

$ cat t.rb
$_=~/, /;p $'.chars.sort==$`.chars.sort

$ echo -n "word, wrdo" | ruby -n t.rb
true
share|improve this answer

C++ Counting sort, fixed version

int a(char*x,char*y){int i=0,u[256];while(i<256)u[i++]=0;
while(*x&&*y)u[*x++]++,u[*y++]--;if(*x||*y)return 0; 
for(i=255;i&&!u[i--];);return!i;}

Unrolled, so you can see what's going on:

int a(const char *x,const char *y) {
    int i=0,u[256];for(;i<256;u[i++]=0);
    for(i=0;x[i]&&y[i];i++)u[x[i]]++,u[y[i]]--;
    if(x[i]||y[i])return 0;
    for(i=0;i<256 && !u[i];i++);
    return (i==256);
}

(with due credit to Matthew Read's very elegant counting sort strategy)

share|improve this answer
show 2 more comments

Clojure REPL 41 chars

(= (sort (read-line)) (sort (read-line)))
share|improve this answer
show 1 more comment

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)}}
share|improve this answer
1  
You can use sorted instead of sortWith. I posted another reply with sorted as well as REPL and function versions. – ebruchez Mar 9 '11 at 6:15
show 2 more comments

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)
}
share|improve this answer
1  
Meh. If I play real golf, it's for socializing or beer, not score-keeping. Guess I should have actually been playing to win... :) – richardtallent Mar 11 '11 at 6:17
show 2 more comments

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());
        }
    }
}
share|improve this answer
show 1 more comment
1 2 3

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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