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

133 Answers 133

2
\$\begingroup\$

JavaScript (67)

function(a,b){return ""+a.split("").sort()==""+b.split("").sort()}
\$\endgroup\$
  • \$\begingroup\$ Wanted to post the same solution before I even saw yours \$\endgroup\$ – dwana Jan 30 '15 at 7:38
2
\$\begingroup\$

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.

\$\endgroup\$
  • \$\begingroup\$ 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 \$\endgroup\$ – user775 Mar 9 '11 at 14:40
2
\$\begingroup\$

Ruby (40)

a.unpack('c*').sort==b.unpack('c*').sort
\$\endgroup\$
  • \$\begingroup\$ 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. \$\endgroup\$ – dmckee Mar 9 '11 at 6:47
2
\$\begingroup\$

Another Ruby (46)

(a.size==b.size)&&(a<<b.count(a,b)==a<<b.size)
\$\endgroup\$
2
\$\begingroup\$

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);}
\$\endgroup\$
2
\$\begingroup\$

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
\$\endgroup\$
  • \$\begingroup\$ Finally a nice solution that works! \$\endgroup\$ – Tomas Feb 3 '14 at 0:09
  • \$\begingroup\$ (Two years later...) You can omit the first three characters ($_=). In -n mode ~/x/ is equivalent to /x/ =~ $_. You can also omit the space between p and $. \$\endgroup\$ – Jordan Aug 18 '16 at 5:29
2
\$\begingroup\$

Ruby 1.9 - 32

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

R, 77

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

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
\$\endgroup\$
  • 1
    \$\begingroup\$ Why not simply f=function(x,y) identical(sort(strsplit(x,"")[[1]]),sort(strsplit(y,"")[[1]]))? \$\endgroup\$ – plannapus Oct 19 '13 at 8:28
  • \$\begingroup\$ You're completely right! Stupid me! I replaced the code with your solution. \$\endgroup\$ – Paolo Oct 21 '13 at 9:14
2
\$\begingroup\$

Matlab: 10 characters without using sort

a*a'==b*b'
\$\endgroup\$
2
\$\begingroup\$

Julia - 36

f=s->==(map(sort,map(collect,s))...)

Used as f(["foo", "bar"])

Using a list for calling it kind of feels like cheating though.

43 characters

f=(a,b)->sort(collect(a))==sort(collect(b))

Used as f("foo", "bar")

Both solutions just sort the words and compare the result

\$\endgroup\$
2
\$\begingroup\$

Woohoo, my first real CodeGolf submission ^_^

Mathcad, 38 chars including non-character keys

s(a):sort(str2vec(a))
f(a,b):s(a)©=s(b)

© stands for the Ctrl key.

Displayed by Mathcad formatted as:

s(a):=sort(str2vec(a))
f(a,b):=s(a)=s(b)

Converts the strings to vectors (one-dimensional arrays) of symbols' ASCII values, sorts them, then compares the vectors. Input is supplied to function f. Returns 1 on success and 0 on failure.

Example: f("toab","boat") returns 1

\$\endgroup\$
2
\$\begingroup\$

Pyth 10 7

qFSMczd

Takes input as two space-separated words.

Try it here.

Essentially, it splits the elements into an array, sorts each element, and checks if the elements are unique.

My first attempt at Code Golf. Any advice appreciated :o)

Edit: It should be noted that this is not a valid answer to the code-golf question, seeing as the language Pyth was invented after the question was asked.

\$\endgroup\$
  • \$\begingroup\$ Welcome to PPCG! You can't know this yet, but it's policy around here that languages invented after a challenge was created are not eligible for winning. You are still welcome to post an answer, but it's usually common to include a short disclaimer (in this case that Pyth was invented after the challenge was posted) so that the OP doesn't accidentally accept the answer. (This isn't even currently the shortest answer, but I tend to include the notice anyway.) Keep golfing! :) \$\endgroup\$ – Martin Ender Aug 3 '15 at 20:46
  • \$\begingroup\$ I got this to 8 bytes: !.{SMczd. If you accept input in the form ['wrod','word'], you can get it to 6 bytes: !.{SMQ. \$\endgroup\$ – kirbyfan64sos Aug 3 '15 at 21:15
  • \$\begingroup\$ Also, you can replace !.{ with qF, giving you 7 bytes with the current input method and 5 with the other one I mentioned. \$\endgroup\$ – kirbyfan64sos Aug 3 '15 at 21:17
  • \$\begingroup\$ Thank you both! I made a note mentioning how the answer is valid for the problem, and changed my code accordingly. \$\endgroup\$ – JPeroutek Aug 4 '15 at 14:15
2
\$\begingroup\$

PHP, 44 Bytes

<?=($c=count_chars)($argv[1])==$c($argv[2]);
\$\endgroup\$
2
\$\begingroup\$

Perl, 41 bytes

40 bytes code + 1 for -p.

Since this uses a slightly different trick to the other Perl answers I thought I'd share it. Input is separated by newlines.

@{$.}=sort/./g}{$_="@1"eq"@2"?true:false

Uses the magic variable $. which tracks the line number to store the words, as character lists, in @1 and @2 which are then compared.

Usage

perl -pe '@{$.}=sort/./g}{$_="@1"eq"@2"?true:false' <<< 'wrdo
word'
true

perl -pe '@{$.}=sort/./g}{$_="@1"eq"@2"?true:false' <<< 'word
wwro'
false

perl -pe '@{$.}=sort/./g}{$_="@1"eq"@2"?true:false' <<< 'boat
toba'
true

Try it online.

\$\endgroup\$
2
\$\begingroup\$

Python, 151, 89 bytes

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

Brain-Flak, 170 bytes

{({}[(()()()()()){}]<>)<>}<>([]){{}(<>())<>{({}[(((((()()()()()){}){}){})){}])({({})({}[()])()}{}{}())({<({}[()])><>({})<>}{}<><{}>)<>}{}([])}<>({}[{}])((){[()](<{}>)}{})

Try it online!

Takes input on two lines.

This program makes a Gödel encoding of letter frequencies in each string. This means I need to map each letter to a unique prime number. For that, I use the polynomial n^2 + n + 41, which is known to give prime results for 0 <= n <= 40. I subtract 90 from the ascii code for each letter before passing it to the polynomial, to get a number in the proper range. When the primes are multiplied together, the results should be equal only when the strings are permutations of each other.

\$\endgroup\$
2
\$\begingroup\$

Brachylog, 2 bytes

pᵈ

Try it online!

The p predicate is essentially a declaration that the variables on either side of it are permutations of each other. The meta-predicate modifies the predicate to which it is attached to interpret the input variable as a list of two items, which are effectively placed on either side of the predicate (with the output variable being unified with the second element of the input). So, given a pair of strings as input, the predicate pᵈ will succeed if they are anagrams, and fail if they are not.

If anyone's suspicious of the header on TIO, it just goes through the list of test cases and prints a list of "true"/"false" values based on whether the predicate succeeded or failed for each case. The predicate can be run as a standalone program that prints "true." if it succeeds for the single test case it is given and "false." if it fails.

\$\endgroup\$
  • \$\begingroup\$ Caveat (?): takes a list of two strings, doesn't do anything to parse a one-string input, some people seem to have been worried about that on their answers but those were also different times so I'm not sure what to think Also, technically, the one-byte p would count, but I'd have a hard time justifying that as an answer (plus it's nice to finally have a good use for the declare metapredicate). \$\endgroup\$ – Unrelated String Mar 1 at 3:18
1
\$\begingroup\$

Yet another Python answer :). (43 characters including whitespace)

This also includes reading in input and displaying output.

i,s=raw_input,sorted
print s(i())==s(i())
\$\endgroup\$
1
\$\begingroup\$

Matlab (24)

Given two strings a and b.

isequal(sort(a),sort(b))
\$\endgroup\$
1
\$\begingroup\$

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)

\$\endgroup\$
  • \$\begingroup\$ Are you aware of George's userscript for this site? Very nice, but it always scores the first codeblock in an answer, so it is helpful to put the golfed version at the top. \$\endgroup\$ – dmckee Mar 10 '11 at 0:11
  • \$\begingroup\$ Cheers. Edited :) \$\endgroup\$ – Dave Gamble Mar 11 '11 at 1:13
1
\$\begingroup\$

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.

\$\endgroup\$
1
\$\begingroup\$

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()))
\$\endgroup\$
  • \$\begingroup\$ Shave one character by changing import * to import*. \$\endgroup\$ – Steven Rumbalski Sep 13 '11 at 18:01
  • \$\begingroup\$ I tried your challenge of not using sorted, but also avoided using collections.Counter. Best I was able to get was 66 character. \$\endgroup\$ – Steven Rumbalski Sep 13 '11 at 18:03
1
\$\begingroup\$

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)
\$\endgroup\$
1
\$\begingroup\$

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
\$\endgroup\$
1
\$\begingroup\$

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))
\$\endgroup\$
  • \$\begingroup\$ good use of semicolons! \$\endgroup\$ – Andbdrew Sep 14 '11 at 21:29
1
\$\begingroup\$

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

\$\endgroup\$
  • 1
    \$\begingroup\$ If you take input as a list of two strings you can do slightly better: ~/{x@<x}'("baot";"boat") \$\endgroup\$ – JohnE Aug 3 '15 at 21:49
1
\$\begingroup\$

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
\$\endgroup\$
1
\$\begingroup\$

Python - 137 chars

def h(s):
    r={}
    for c in s:
        try:r[c]+=1
        except:r[c]=1
    return r
x=raw_input().split(',')
print h(x[0])==h(x[1])

Sample: (I defined a function anagram to do the work of the last 2 lines.)

   anagram('boat','boat')
True
    anagram('toab','boat')
True
    anagram('oabt','toab')
True
    anagram('a','aa')
False
    anagram('zzz','zzzzzzzz')
False
    anagram('zyyyzzzz','yyzzzzzy')
True
    anagram('sleepy','pyels')
False
    anagram('p','p')
True
\$\endgroup\$
1
\$\begingroup\$

Haskell, 48

Not counting imports, Haskell can do it in 10 chars:

import Data.List
import Data.Function
on(==)sort

Called like this:

λ> on(==)sort "balaclava" "aabllcav"
False

λ> on(==)sort "balaclava" "aabllcava"
True
\$\endgroup\$
1
\$\begingroup\$

Pyth - 8 7 6

MqSGSH

Defines function with two args, the two words.

M       define function g with two args, G and H
 q       equals
  SQ     sorted first arg
  SH     sorted last arg

If that cheating golfscript program counts with hardcoded input, we can do that too with : qSS

And for just two more characters you can have it check an infinite number of words:

ql{mSdQ1

q    1       Equals 1
 l           Length
  {          Set constructor (eliminate all duplicates)
   m  Q      Map on evaluated input
    Sd       Sort each element
\$\endgroup\$
  • \$\begingroup\$ How would qSS work? I am trying to learn pyth and I am curious. \$\endgroup\$ – ericmarkmartin Jan 27 '15 at 20:07
  • \$\begingroup\$ @ericmark26 its the same as the golfscript and its cheating because it need hardcoding. qss just means equals, sort, sort. You'll have to put the strings after the S's \$\endgroup\$ – Maltysen Jan 27 '15 at 20:35

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.