97
\$\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\$
7
  • 11
    \$\begingroup\$ 9 answers in 13 views... wow! \$\endgroup\$ Commented Mar 8, 2011 at 16:44
  • 5
    \$\begingroup\$ Title request: Cod Elf, Go! \$\endgroup\$ Commented Jul 9, 2016 at 12:48
  • 7
    \$\begingroup\$ "Falcon Rage, go mad!" \$\endgroup\$ Commented Oct 6, 2016 at 17:25
  • 16
    \$\begingroup\$ My name suggestion: "are they anagrams" → "manage the arrays" \$\endgroup\$ Commented Oct 31, 2017 at 4:32
  • 2
    \$\begingroup\$ Suggested test case: aaab, bbba = false \$\endgroup\$ Commented Aug 3, 2022 at 23:56

171 Answers 171

3
\$\begingroup\$

Ruby (40)

a.unpack('c*').sort==b.unpack('c*').sort 
\$\endgroup\$
1
  • \$\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\$ Commented Mar 9, 2011 at 6:47
3
\$\begingroup\$

Another Ruby (46)

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

APL - 13 chars

{(⍺[⍋⍺])≡⍵[⍋⍵]} 

Call like this:

 'boat' {(⍺[⍋⍺])≡⍵[⍋⍵]} 'baot' 1 'baot' {(⍺[⍋⍺])≡⍵[⍋⍵]} 'boat' 1 (,'a') {(⍺[⍋⍺])≡⍵[⍋⍵]} 'aa' 0 

In the last example, 'a' represents a single character, and the prefix , will convert it into a string.

\$\endgroup\$
3
\$\begingroup\$

Java (134 bytes)

int[][]c=new int[2][26]; for(int i=0;i<2;i++)for(byte a:args[i].getBytes())c[i][a-97]++; System.out.print(Arrays.equals(c[0],c[1]));` 

This makes an array to count the number of times each letter appears, and then compares the arrays to check if they are equal.

\$\endgroup\$
1
  • 1
    \$\begingroup\$ Welcome to PPCG! Nice first post! There are 2 spaces you can remove, (c[0], c[1]) and for (int i=0;. \$\endgroup\$ Commented Oct 6, 2016 at 22:23
3
\$\begingroup\$

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)

\$\endgroup\$
4
  • \$\begingroup\$ Something is wrong. $a=;? Also, you can skip the parens of sort and the space after print. \$\endgroup\$ Commented Mar 8, 2011 at 16:00
  • \$\begingroup\$ @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. \$\endgroup\$ Commented Mar 8, 2011 at 16:32
  • 2
    \$\begingroup\$ Ok, I removed the downvote. You might want to use the code formatting in the future, i.e. indent code with four spaces. \$\endgroup\$ Commented Mar 8, 2011 at 16:46
  • 1
    \$\begingroup\$ 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. \$\endgroup\$ Commented Mar 8, 2011 at 18:13
3
\$\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\$
3
\$\begingroup\$

Husk, 2 bytes

€P 

Try it online!

Returns index of the permutation found, or 0.

\$\endgroup\$
3
\$\begingroup\$

Haskell, 31 bytes

import Data.List s%t=s\\t==t\\s 

Try it online!

The \\ operator from Data.List is multiset difference. If s and t and anagrams, then s\\t is empty, as is t\\s. However, if any character appears in s more times than in t, then s\\t will contain it whereas t\\s won't, making them unequal, and vice versa is the character appears in t more than s.

36 bytes

(.q).(==).q q=sum.map((9^).fromEnum) 

Try it online!

A shot at an import-less solution. Each string is converted to a base-9 representation of its character counts, and these are checked for equality. The i'th digit base 9 is the number of appearances of the character with fromEnum ASCII value i. This takes advantage of the spec guaranteeing each string is no longer than 9 characters, so there's no rollover in base 9.

39 bytes

s%t=and[q s==q t|q<-filter.(==)<$>s++t] 

Try it online!

A more general solution following the principles of avoiding sorting. Checks that each character in s++t appears as many times in s as it does in t.

\$\endgroup\$
3
\$\begingroup\$

Knight, 92 68 bytes

Saved 21 bytes (and indirectly 3 more) thanks to Bubbler

O?C=sB;=wP;=j~9;W=j+1j;=i 8Wi=wI>=bGw i 1=aGw=i-i 1 1wSw i 2+b a wCs 

Try it online!

Explanation

Sorts both strings using a bubble-sort algorithm and checks if they are equal. The sorting algorithm takes advantage of the "input will be ... no longer than 8 chars" rule.

Ungolfed:

;= sort_input BLOCK ;= word PROMPT ;= j ~9 ;WHILE = j (+ 1 j) ;= i 8 :WHILE i := word ;= char2 GET word i 1 ;= char1 GET word (= i (- i 1)) 1 :IF > char2 char1 :word :SUB word i 2 (+ char2 char1) :word :OUTPUT ? (CALL sort_input) (CALL sort_input) 
\$\endgroup\$
2
  • 1
    \$\begingroup\$ 71B: O?C=sB;=wP;=j~9;W=j+1j;=i~1W>9=i+1i=wI<=xGw+1i 1=yGw i 1wSw i 2+x y wCs Changes: move ;=wP into the block body; use return value of C to avoid =v w; move increments into the loop condition; store 1-char substrings in variables; swap two branches of I to save a space. \$\endgroup\$ Commented Aug 2, 2022 at 23:37
  • \$\begingroup\$ @Bubbler Thanks! I started thinking of blocks as subroutines because they don't take arguments--forgot that they do have return values. I found another golf by running the i loop in the opposite direction and updating i in the loop body instead of the header. \$\endgroup\$ Commented Aug 4, 2022 at 4:06
3
\$\begingroup\$

Knight, 59 52 bytes

O?C=bB;=aP;=x*"0"128;Wa;=xSxAa 1+1GxAa 1=aGa 1La xCb 

Try it online!

For both inputs, it creates a 128-character string of 0s, then iterates through the input and increases the value in the index associated with the ASCII code of the given character. Finally, it compares these strings.

This only works because the input strings are less than 8 characters, meaning there can be at most 8 of a single character (less than the 9 that can be stored in a single index by this encoding).

Expanded code:

;=b BLOCK ;=a PROMPT ;=x *"0" 128 WHILE a ;= x (SET x (ASCII a) 1 (+1 (GET x (ASCII a) 1)) = a (GET a 1 (LENGTH a)) ;CALL b ;=y x ;CALL b OUTPUT (? x y) 

-7 bytes from @Bubbler

\$\endgroup\$
1
  • \$\begingroup\$ 52 bytes O?C=bB;=aP;=x*"0"128;Wa;=xSxAa 1+1GxAa 1=aGa 1La xCb using the same refactor as DLosc's solution. \$\endgroup\$ Commented Aug 4, 2022 at 6:28
3
\$\begingroup\$

Knight, 51 bytes

O?C=cB;=iP;=x*'0'256;Wi;=xSx=aAiT+1Gx aT=iSiF1""xCc 

Try it online!

This challenge was made a lot easier because inputs were length 8 maximum. That way, we could have a string of length 256, where each index is the amount of times that byte appeared in a word. Then, we can just compare them.

Ungolfed and reorganized slightly, with copious comments:

# Create a new block (ie a niladic function) named `char_counts`. ; = char_counts BLOCK # Set `i` to the input from stdin. ; = input PROMPT # Set `x` to a string of 256 `0`s. The number at each # index keeps track of how many times that ascii code # has been seen. ; = counts * '0' 256 # while `input` isn't empty ; WHILE input # Set the variable `ascii_code` to the ascii codepoint # of the first character. If `ASCII` is given a string # that's more than one character long, it uses the first. ; = ascii_code ASCII input # Set the variable `new_count` to one more than the # previous value at `ascii_code` within `counts`. This # will coerce the `GET` result to an integer, which is # a nice added bonus. ; = new_count + 1 (GET counts ascii_code 1) # Update `counts` by replacing the character at `ascii_code` # (or, more precisely, the range `ascii_code..ascii_code+1`) # with the new, updated count. : = counts SET counts ascii_code 1 new_count # The last value of a `BLOCK` is its return value. Here, # we return the occurances of each byte. : counts # Finally, print out whether calling `char_counts` twice # in a row yields the same count of characters. : OUTPUT ? (CALL char_counts) (CALL char_counts) 
\$\endgroup\$
3
  • \$\begingroup\$ You put the language as C (gcc).... but the code is written in Knight. \$\endgroup\$ Commented Aug 14, 2022 at 23:26
  • \$\begingroup\$ Oh true, thanks for catching that \$\endgroup\$ Commented Aug 15, 2022 at 17:00
  • \$\begingroup\$ Just a note: this link doesn't work: github.com/knight-lang/knight/knight.kn (it's linked on the language page: github.com/knight-lang/knight-lang). \$\endgroup\$ Commented Aug 15, 2022 at 20:05
2
\$\begingroup\$

JavaScript (67)

function(a,b){return ""+a.split("").sort()==""+b.split("").sort()} 
\$\endgroup\$
1
  • \$\begingroup\$ Wanted to post the same solution before I even saw yours \$\endgroup\$ Commented Jan 30, 2015 at 7:38
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\$
2
  • \$\begingroup\$ Finally a nice solution that works! \$\endgroup\$ Commented Feb 3, 2014 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\$ Commented Aug 18, 2016 at 5:29
2
\$\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\$
2
\$\begingroup\$

Ruby 1.9 - 32

x=->{gets.chars.sort} p x[]==x[] 
\$\endgroup\$
3
  • \$\begingroup\$ Cool! x=->{gets.sum} passes the test cases but is kind of a cheat. \$\endgroup\$ Commented Mar 17, 2011 at 16:18
  • \$\begingroup\$ BTW, why 1.9.1 and not 1.9.2? It works in 1.9.2. \$\endgroup\$ Commented Mar 17, 2011 at 16:19
  • \$\begingroup\$ That's just the version of Ruby 1.9 I have. \$\endgroup\$ Commented Mar 17, 2011 at 20:40
2
\$\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\$
2
  • \$\begingroup\$ Shave one character by changing import * to import*. \$\endgroup\$ Commented Sep 13, 2011 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\$ Commented Sep 13, 2011 at 18:03
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\$
2
  • 1
    \$\begingroup\$ Why not simply f=function(x,y) identical(sort(strsplit(x,"")[[1]]),sort(strsplit(y,"")[[1]]))? \$\endgroup\$ Commented Oct 19, 2013 at 8:28
  • \$\begingroup\$ You're completely right! Stupid me! I replaced the code with your solution. \$\endgroup\$ Commented Oct 21, 2013 at 9:14
2
\$\begingroup\$

Matlab: 10 characters without using sort

a*a'==b*b' 
\$\endgroup\$
2
\$\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\$
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\$

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

05AB1E, 3 bytes

Aargh! I can't beat GolfScript!

œså 

Try it online!

Explanation

œ All permutations of the first input så Do the permutations contain the second input? 

œQà

œ All permutations Q Equality with input à Maximum 

€{Ë

€{ Map sort over the input list Ë Are all items equal? 
\$\endgroup\$
2
\$\begingroup\$

Java 16, 85 bytes

a->b->a.chars().sorted().boxed().toList().equals(b.chars().sorted().boxed().toList()) 

Java 16 added the Stream#toList method.

Java 8, 88 bytes

a->b->java.util.Arrays.equals(a.chars().sorted().toArray(),b.chars().sorted().toArray()) 

Try it online!

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

Curry, 49 bytes

Tested in PAKCS

e#x=e:x e#(x:y)=x:e#y p(x:y)=x#p y p[]=[] (=:=).p 

Try it online!

Try it on Smap!

This returns True if inputs are anagrams and nothing otherwise.

Explanation

This is a really fun Curry solution. First we define a function p which gives a non-deterministic permutation of the input.

Then our submission is just (=:=).p. Written more normally this is:

f x y = p x =:= y 

Meaning it tries to bind y to a permutation of x. If they are anagrams this succeeds and gives True, if they are not there is no binding and we get nothing.

\$\endgroup\$
1
  • \$\begingroup\$ 31 bytes. \$\endgroup\$ Commented Apr 11, 2022 at 9:01
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)

\$\endgroup\$
3
  • \$\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\$ Commented Aug 3, 2015 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\$ Commented Aug 3, 2015 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\$ Commented Aug 4, 2015 at 14:15

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.