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

Python - 32 chars

f=lambda a,b,S=sorted:S(a)==S(b)
share|improve this answer
1  
@Debanjan, This is just the same as def f(a,b):return sorted(a)==sorted(b) The trade off is that you get to replace def+return with lambda in exchange for not using any statements – gnibbler Mar 8 '11 at 22:23
show 5 more comments

Javascript - 192 157 152 147 125

Ok some of these languages are a lot more flexibile than I thought! Anyway this is the longer way I guess, but a different technique at least.

Compressed

Thanks to Peter and David for squeezing more chars out!

for(a=[j=p=2];j<123;)a[j]?p%a[++j]<1&&p++&&(j=0):(a[j]=p,j=0);function b(c,i){return c[i=i||0]?a[c.charCodeAt(i)]*b(c,++i):1}

Then do:

alert(b("hello")==b("elloh"));

Expanded Code

The compressed has had lots of changes, but this is the basic theory:

// Define dictionary of primes
a = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101];

// Returns the unique ID of the word (order irrelevant)
function b(c) {
    r = 1;
    for (i = 0; i < c.length; i++)
        r *= a[c[i].charCodeAt(0) - 97];
    return r
}

alert(b("hello") == b("hlleo"));
share|improve this answer
2  
You can shave a couple of characters off the dictionary initialisation using the sieve. a=[2];for(p=3,j=0;j<26;)if(a[j]){if(p%a[j++]==0){p++;j=0}}else{a[j]=p;j=0} – Peter Taylor Mar 8 '11 at 17:06
1  
@Tom, depends on how well optimised the sorting routines are, given that you've limited inputs to 8 characters :P – Peter Taylor Mar 9 '11 at 11:13
1  
125 characters. Recursion and ternaries FTW: for(a=[j=p=2];j<123;)a[j]?p%a[++j]<1&&p++&&(j=0):(a[j]=p,j=0);function b(c,i){return c[i=i||0]?a[c.charCodeAt(i)]*b(c,++i):1} – David Murdoch Mar 9 '11 at 14:03
show 19 more comments

Golfscript, 3 chars?

$$=

usage:

'boat'$'baot'$=
1

'toab'$'boat'$=
1

'oabt'$'toab'$=
1

'a'$'aa'$=
0

'zzz'$'zzzzzzzz'$=
0

'zyyyzzzz'$'yyzzzzzy'$=
1

'sleepy'$'pyels'$=
0

'p'$'p'$=
1
share|improve this answer
13  
This is an interesting interpretation of how to supply the input :) – gnibbler Mar 9 '11 at 0:10
4  
Explanation please :( – st0le Mar 9 '11 at 5:41
7  
@st0le, seriously? I don't know golfscript, but it's obviously $ (sort), $ (sort), = (compare) – Peter Taylor Mar 9 '11 at 8:10
5  
Isn't this cheating a little? I mean, it isn't variable input. It has to be hard-coded. In any case, I would add 4 to the character count for the quote (') characters. – Thomas Eding Jul 30 '11 at 0:18

J, 8

-:&(/:~)

Literaly, match (-:) on (&) sort up (/:~)

Sample use:

   'boat' -:&(/:~) 'boat'
1
   'toab' -:&(/:~) 'boat'
1
   'oabt' -:&(/:~) 'toab'
1
   'a' -:&(/:~) 'aa'
0
   'zzz' -:&(/:~) 'zzzzzzzz'
0
   'zyyyzzzz' -:&(/:~) 'yyzzzzzy'
1
   'sleepy' -:&(/:~) 'pyels'
0
   'p' -:&(/:~) 'p'
1

Where do the 64-bit integers come into play?

share|improve this answer
12  
J always looks like the remains of an emoticon factory explosion. – st0le Mar 9 '11 at 6:58
show 3 more comments

Golfscript - 8 chars

This defines a function called A

{$\$=}:A

Test cases

;
'boat' 'boat' A
'toab' 'boat' A
'oabt' 'toab' A
'a' 'aa' A
'zzz' 'zzzzzzzz' A
'zyyyzzzz' 'yyzzzzzy' A
'sleepy' 'pyels' A
'p' 'p' A
share|improve this answer

Haskell function - 31

import List
f=(.sort).(==).sort

Haskell program - 81 58 55

import List
g=sort`fmap`getLine
main=(`fmap`g).(==)=<<g

Usage:

$ runghc anagram.hs
boat
boat
True
$ runghc anagram.hs
toab
boat
True
$ runghc anagram.hs
a
aa
False

Kudos to lambdabot and its pointfree refactoring.

share|improve this answer
2  
@J B: Can Perl code that only does what's wanted under perl still be called a "program"? :-) – Joey Adams Mar 8 '11 at 23:06
1  
x#y=sort x==sort y is 1 character shorter – Rotsor Aug 6 '11 at 10:58
show 5 more comments

Ruby 34

Using the IO scheme of Peter Taylors Perl solution:

p gets.chars.sort==gets.chars.sort
share|improve this answer

C program - 118 necessary characters

t[52],i;main(c){for(;i<52;)(c=getchar())<11?i+=26:t[i+c-97]++;
for(i=27;--i&&t[i-1]==t[i+25];);puts(i?"false":"true");}
share|improve this answer
1  
Ever considered applying for IOCCC? – muntoo Mar 9 '11 at 3:54
6  
@muntoo: have you seen anything in the IOCCC? This is way too readable for that. – R. Martinho Fernandes Mar 9 '11 at 5:39
show 3 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

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

C# (131 chars)

using System.Linq;class X{static void Main(string[]a){System.Console.Write(a[0].OrderBy(_=>_).SequenceEqual(a[1].OrderBy(_=>_)));}}

Readable:

using System.Linq;
class X
{
    static void Main(string[] a)
    {
        System.Console.Write(a[0].OrderBy(_ => _)
              .SequenceEqual(a[1].OrderBy(_ => _)));
    }
}
share|improve this answer

Perl (62)

This function takes the strings as arguments and returns true or false.

sub f{my@a;for$.(1,-1){$a[ord]+=$.for split//,pop}!grep{$_}@a}

Stores the ASCII values in an array and checks if it evens out. Increments for the first word and decrements for the second word.

share|improve this answer

Perl - 77 75 chars

The I/O of the problem aren't well specified; this reads two lines from stdin and outputs true or false to stdout.

sub p{join'',sort split'',$a}$a=<>;$x=p;$a=<>;print$x eq p()?"true":"false"

(Thanks to Tim for 77 -> 75)

share|improve this answer
2  
Ok, I removed the downvote. You might want to use the code formatting in the future, i.e. indent code with four spaces. – user475 Mar 8 '11 at 16:46
show 3 more comments

PHP (command line, 87 characters)

function d($s){
    return array_count_values(str_split($s));
}

echo d($argv[1]) == d($argv[2]);
share|improve this answer

Clojure - 23 chars

As an anonymous function:

#(apply = (map sort %))

Test case example:

(#(apply = (map sort %)) ["boat" "boat"])
=> true
share|improve this answer
show 1 more comment

Python (107)(97)(76)

a,b=raw_input().strip().split(', ')
print str(sorted(a)==sorted(b)).lower()

Obviously this can be shortened if we don't take the OP's wording literally and lowercase "true" and "false"...

share|improve this answer

Clojure REPL 41 chars

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

Python (32 bytes)

p=sorted
f=lambda a,b:p(a)==p(b)
share|improve this answer

bash

88 characters

diff <(grep -o .<<<$1|sort) <(grep -o .<<<$2|sort)>/dev/null && echo true || echo false
share|improve this answer

Javascript

A (very) slightly shorter version of @zzzzBov's solution, that uses .join() instead of String boxing:

function a(b,c){return b.split('').sort().join()==c.split('').sort().join()}
alert(a('abc','bca')); //true

Similarly:

function a(b){return b.split('').sort().join()}
alert(a('abc')==a('bca')); //true
share|improve this answer

JavaScript

Based on @zzzzBov's solution.

Comparison, 65 chars (40 without function)

function f(a,b){return a.split('').sort()==b.split('').sort()+""}

Comparator, 43 chars

function f(a){return a.split('').sort()+""}
share|improve this answer
show 1 more comment

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

Comparison function (78):

function a(b,c){return String(b.split('').sort())==String(c.split('').sort())}
alert(a('abc','bca')); //true

Comparator function (48):

function a(b){return String(b.split('').sort())}
alert(a('abc')==a('bca')); //true

Assumes String has split and Array has sort.

share|improve this answer

Python

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

Python (151 89)

Handles arbitrarily many inputs from stdin. Comma separated, one pair per line.

import sys
f=sorted
for l in sys.stdin:a,b=l.split(',');print f(a.strip())==f(b.strip())
share|improve this answer
1  
Won't this return True for aab, bba? – gnibbler Mar 8 '11 at 20:28
show 2 more comments

VBScript

172 characters

wscript.echo "boat, boat         = " & s("boat, boat")
wscript.echo "toab, boat         = " & s("toab, boat")
wscript.echo "oabt, toab         = " & s("oabt, toab")
wscript.echo "a, aa              = " & s("a, aa")
wscript.echo "zzz, zzzzzzzz      = " & s("zzz, zzzzzzzz")
wscript.echo "zyyyzzzz, yyzzzzzy = " & s("zyyyzzzz, yyzzzzzy")
wscript.echo "sleepy, pyels      = " & s("sleepy, pyels")
wscript.echo "p,p                = " & s("p,p")

function s(a):b=split(replace(a," ",""),","):c=0:for x=1 to len(b(0)):if instr(b(1),mid(b(0),x,1)) then c=c+1 
next:if len(b(1))-c=0 then s=true else s=false
end function

I was kinda suprised I could get it under 200.

share|improve this answer
show 1 more comment

Ruby (40)

a.unpack('c*').sort==b.unpack('c*').sort
share|improve this answer
show 1 more comment

Another Ruby (46)

(a.size==b.size)&&(a<<b.count(a,b)==a<<b.size)
share|improve this answer

C function (147 chars), using brute-force

int c(char*x,char*y){int i=0,l=0;for(;y[l]&&x[l];l++);if(y[l]||x[l])return 0;
while(*x&&i!=l){for(i=0;i<l&&y[i]!=*x;i++);y[i]=0,x++;}return(i!=l);}
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
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.