Take the 2-minute tour ×
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
5  
9 answers in 13 views... wow! –  Tom Gullen Mar 8 '11 at 16:44
    
@Tom, because everyone wanted to prove that your comment about using a 64-bit integer was pointing in the wrong direction :P –  Peter Taylor Mar 8 '11 at 18:15
9  
ARGH! Why is this question marked community wiki? –  Tom Gullen Mar 9 '11 at 10:39
18  
@Martin, part of the fun of this site for me is the competition in collecting rep! –  Tom Gullen Mar 9 '11 at 11:27
5  
@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

81 Answers 81

Python - 32 chars

f=lambda a,b,S=sorted:S(a)==S(b)
share|improve this answer
    
Nice one!it makes me inquisitive to learn about lambda. –  Quixotic Mar 8 '11 at 20:58
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
    
Yes,and it's also saves few keystrokes,in my answer i further modified your answer to 2 bytes shorter :-) –  Quixotic Mar 8 '11 at 22:48
    
@Debanjan, I think it only saves you one character. I have used a variation here, but it works out the same length as yours because I swap a newline for a comma –  gnibbler Mar 9 '11 at 0:09
1  
I have one question,this approach does require calling of input and print and other stripping functions right? –  Quixotic Mar 9 '11 at 0:09
show 8 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
15  
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
8  
@st0le, seriously? I don't know golfscript, but it's obviously $ (sort), $ (sort), = (compare) –  Peter Taylor Mar 9 '11 at 8:10
9  
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
1  
to correctly handle the input use something like ", "/~$/$= –  user1502040 Apr 4 at 1:52
add comment

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
    
Great idea using primes. –  user475 Mar 8 '11 at 16:06
    
@Tim thanks! Got it down to 157 now. –  Tom Gullen Mar 8 '11 at 16:12
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 17 more comments

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
    
Is it not possible to write functions/subroutines in J? –  user475 Mar 8 '11 at 15:57
    
@Tim Nordenfur: they're called "verbs", and take either one argument on their right as in v arg (monads) or two on both sides as in arg1 v arg2 (dyads). The one I submitted is obviously a dyad. I didn't bother to name it, since it wasn't requested and is shorter this way. Should you really want to give it a name, you'd do that like this: is_anagram_of =: -:&(/:~) and then use as 'a' is_anagram_of 'aa'. –  J B Mar 8 '11 at 16:21
    
It felt a bit cheap to substitute the arguments into the code, but I see now that it's essentially a dyad. Never mind. –  user475 Mar 8 '11 at 16:26
17  
J always looks like the remains of an emoticon factory explosion. –  st0le Mar 9 '11 at 6:58
add comment

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
add comment

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
    
Can Haskell code that only does what's wanted under runghc, but not when compiled, still be called "program"? –  J B Mar 8 '11 at 21:29
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
    
J B: Todays functional languages skew the meaning of a program making it a higher order abstraction. Rather than just a list of instruction to be executed, as haskell program can just be seen as a collection of functions, even if they are not called. –  Callum Rogers Mar 9 '11 at 17:45
    
@Callum Rogers: my point is: his code behaves differently whether run under runghc or compiled, in a problem-sensitive area. The "function" is fine. The "program" does not solve the problem under anything else than runghc, and runghc is not the only legitimate way to run Haskell programs. In that context, that makes the snippet a "runghc script", not a "Haskell program". --not that I'd consider the issue important, as I said, the function is fine anyway and it's shorter. –  J B Mar 9 '11 at 21:09
1  
x#y=sort x==sort y is 1 character shorter –  Rotsor Aug 6 '11 at 10:58
show 2 more comments

Ruby 34

Using the IO scheme of Peter Taylors Perl solution:

p gets.chars.sort==gets.chars.sort
share|improve this answer
    
Throws an error: -e:1:in '<main>': undefined method 'chars' for nil:NilClass (NoMethodError) –  Tomas Feb 2 at 22:53
add comment

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
7  
@muntoo: have you seen anything in the IOCCC? This is way too readable for that. –  R. Martinho Fernandes Mar 9 '11 at 5:39
    
@Martinho Yes, the IOCCC source codes are so beautiful. Symphonies. But he should at least try composing a small piece. :) –  muntoo Mar 9 '11 at 6:59
    
@muntoo: I didn't even know they were still active. –  Joey Adams Mar 9 '11 at 7:21
1  
Just saw this one... Very nice. But can be shorter: t[256],i;main(c){for(;c+3;)(i=getchar())>10?t[i]+=c:(c-=2);for(i=257;--i&&!t[i-‌​1];);puts(i?"false":"true");} - that's 108 characters. Very importantly, your c initialization trick is still employed. –  ugoren Feb 29 '12 at 16:18
add comment

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
    
of course you can save 4 chars in the program by removing the " around true and false, since without using strict/warnings a bareword is a string. –  Joel Berger Sep 17 '11 at 17:30
    
Thanks! –  Timwi Sep 17 '11 at 20:21
add comment

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
    
In C, if you declare a variable in the global scope, it is initialized to zero. I guess this is also true for C++. –  Joey Adams Mar 8 '11 at 17:24
    
Local variables, on the other hand, are not initialized to zero automatically. –  Joey Adams Mar 8 '11 at 17:35
    
OK, I removed my caveat since I found ways to do without it. –  Matthew Read Mar 8 '11 at 18:09
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 3 more comments

C# (129 chars)

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

Readable:

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

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
    
Clever using the +"" to coerce to string. –  Casey Chu Jun 16 '11 at 6:01
add comment

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
add comment

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
    
Something is wrong. $a=;? Also, you can skip the parens of sort and the space after print. –  user475 Mar 8 '11 at 16:00
    
@Tim, the genius who developed this platform for sharing code over the net decided that in code blocks people should have to escape less-than characters. But hey, no big deal: it's not as though anyone uses them in code, right? Keeps catching me out. –  Peter Taylor Mar 8 '11 at 16:32
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
    
Ok, so there are three ways of formatting code (one inline and two block), and both the block ones are inconvenient in different ways. Sigh. –  Peter Taylor Mar 8 '11 at 18:13
add comment

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
add comment

Clojure - 23 chars

As an anonymous function:

#(apply = (map sort %))

Test case example:

(#(apply = (map sort %)) ["boat" "boat"])
=> true
share|improve this answer
    
Cool, I like it. –  Chiron Dec 5 '11 at 23:48
add 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
add comment

Clojure REPL 41 chars

(= (sort (read-line)) (sort (read-line)))
share|improve this answer
    
Welcome to the Stack Exchange network. Formatting help here. –  dmckee Mar 10 '11 at 4:17
add comment

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
add comment

Python (32 bytes)

p=sorted
f=lambda a,b:p(a)==p(b)
share|improve this answer
    
Does nothing in python. Are you sure it is a complete program that takes the input and produces the output as requested? –  Tomas Feb 2 at 23:48
add comment

bash

88 characters

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

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
add 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
add comment

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
    
Mwahaha, first time I see a Python solution longer than C# :) –  Timwi Mar 8 '11 at 16:05
1  
Won't this return True for aab, bba? –  gnibbler Mar 8 '11 at 20:28
    
@gnibbler; Yes, it will, I wasn't thinking this morning. Fixed –  Hoa Long Tam Mar 9 '11 at 1:52
add comment

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
    
131 characters if I pass the values seperatly. function s(a,b):c=0:for x=1 to len(a):if instr(b,mid(a,x,1)) then c=c+1 next:if len(b)-c=0 then s=true else s=false end function –  user775 Mar 9 '11 at 14:40
add comment

Ruby (40)

a.unpack('c*').sort==b.unpack('c*').sort
share|improve this answer
    
I've formatted your code for you. The tool bar above the edit box has the most commonly used functions, and the sidebar has a link to more detailed info. –  dmckee Mar 9 '11 at 6:47
add comment

Another Ruby (46)

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

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
add comment

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
add comment

Ruby 1.9 - 32

x=->{gets.chars.sort}
p x[]==x[]
share|improve this answer
    
Cool! x=->{gets.sum} passes the test cases but is kind of a cheat. –  Jonas Elfström Mar 17 '11 at 16:18
    
BTW, why 1.9.1 and not 1.9.2? It works in 1.9.2. –  Jonas Elfström Mar 17 '11 at 16:19
    
That's just the version of Ruby 1.9 I have. –  david4dev Mar 17 '11 at 20:40
add comment

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.