| Bytes | Lang | Time | Link |
|---|---|---|---|
| 002 | Vyxal 3 l | 250422T035722Z | lyxal |
| 014 | Juby | 221122T161505Z | Jordan |
| 065 | Tcl | 171105T235352Z | sergiol |
| 087 | AWK | 241127T184407Z | xrs |
| 065 | Regex PCRE | 220804T003020Z | Deadcode |
| 073 | Regex .NET | 241022T211923Z | Deadcode |
| 003 | TinyAPL | 241021T214250Z | noodle p |
| 037 | JavaScript Node.js | 240725T150740Z | Fhuvi |
| 072 | Setanta 72 Bytes | 240806T211134Z | colmmurp |
| 007 | UiuaSBCS | 240725T064901Z | Europe20 |
| 036 | R | 240722T081507Z | pajonk |
| 030 | Swift 5.9 | 240315T005424Z | macOSist |
| 077 | YASEPL | 240209T214157Z | madeforl |
| 005 | APLNARS | 240208T162136Z | Rosario |
| 023 | Labyrinth | 240206T041434Z | Bubbler |
| 002 | Nekomata + e | 230528T154521Z | alephalp |
| 003 | Thunno 2 | 230528T143038Z | The Thon |
| 043 | Zsh | 221122T043235Z | roblogic |
| 022 | Raku | 221118T201152Z | Sean |
| 003 | BQN | 221118T162114Z | DLosc |
| 004 | Pyke | 160517T184843Z | Blue |
| 004 | 05AB1E | 161006T171955Z | Geno Rac |
| 051 | Knight | 220814T232157Z | Sampersa |
| 052 | Knight | 220803T232956Z | 97.100.9 |
| 047 | R | 220804T153347Z | corvus |
| 011 | Alice | 220804T050113Z | Julian |
| 068 | Knight | 220802T193922Z | DLosc |
| 002 | Vyxal | 220804T014909Z | Deadcode |
| 031 | Haskell | 220802T092425Z | xnor |
| 112 | Knight | 220802T062424Z | Bubbler |
| 007 | Pyth | 150803T203627Z | JPeroute |
| 046 | Ruby | 220413T151019Z | oeuf |
| 083 | TIBasic | 220408T123542Z | Youserna |
| 115 | C 115 Bytes | 220408T015210Z | user1117 |
| 026 | Julia | 220408T092513Z | MarcMush |
| 029 | Ly | 210529T090425Z | cnamejj |
| 045 | PHP7.4 | 220407T220305Z | user1117 |
| 022 | Factor + math.combinatorics | 220407T225046Z | chunes |
| 049 | Curry | 220407T181100Z | Wheat Wi |
| 085 | Java 16 | 210529T043843Z | Unmitiga |
| 002 | Husk | 210222T054500Z | Razetime |
| 003 | 05AB1E | 200515T054756Z | user9206 |
| 026 | Symja | 200515T031027Z | lyxal |
| 112 | Lua | 190324T125514Z | cfenner |
| 049 | SmileBASIC | 190319T031910Z | 12Me21 |
| 002 | Brachylog | 190301T030448Z | Unrelate |
| 170 | BrainFlak | 190131T193122Z | MegaTom |
| 004 | Japt | 170623T161900Z | Shaggy |
| 108 | C# .NET Core | 190131T222403Z | Destroig |
| 050 | Common Lisp | 171030T110145Z | Renzo |
| 013 | Pushy | 181218T165814Z | FlipTack |
| 058 | Pepe | 181218T111328Z | u-ndefin |
| 004 | MathGolf | 181217T170106Z | maxb |
| 054 | R | 181217T120311Z | J.Doe |
| nan | Perl | 180204T121443Z | Ton Hosp |
| 088 | Bash | 110309T043559Z | Martin |
| 084 | Scala | 110308T223940Z | Gareth |
| 079 | Python 2 | 110308T231139Z | Will Har |
| 060 | Perl | 110309T045220Z | Simon Wh |
| 032 | Python | 110308T211107Z | Quixotic |
| 032 | Python | 110308T202659Z | gnibbler |
| 008 | Golfscript | 110308T203636Z | gnibbler |
| 140 | Lua | 110308T211254Z | jpjacobs |
| 041 | JavaScript | 110308T194316Z | zzzzBov |
| 058 | Perl | 110308T162215Z | Timwi |
| 031 | Haskell | 110308T162222Z | Joey Ada |
| 034 | Ruby | 110308T162008Z | steensla |
| 118 | C program | 110308T174238Z | Joey Ada |
| 064 | Python 3 | 110308T193523Z | Wooble |
| 062 | Perl | 110308T155234Z | user475 |
| 125 | Javascript | 110308T160219Z | Tom Gull |
| 089 | Python | 110308T153949Z | Hoa Long |
| 129 | C# | 110308T160218Z | Timwi |
| 075 | Perl | 110308T155531Z | Peter Ta |
| 004 | Pyth | 171127T202712Z | user4854 |
| 099 | Python | 171031T070348Z | Zachary |
| 041 | Julia | 171031T030739Z | EricSher |
| nan | Perl 5 | 171031T015810Z | Xcali |
| 045 | Axiom | 171030T095101Z | user5898 |
| 008 | J | 171026T040843Z | Jonah |
| 026 | Wolfram Language | 170926T224629Z | Vitaliy |
| 087 | Excel VBA | 170926T220712Z | Taylor R |
| 010 | APL Dyalog | 170623T163934Z | user4180 |
| 003 | Jelly | 161227T194129Z | Erik the |
| 063 | awk | 161227T225155Z | James Br |
| 028 | Mathematica 28 Bytes | 161227T210008Z | Kelly Lo |
| 104 | C++14 | 161205T102152Z | Karl Nap |
| 134 | Java | 161006T220940Z | codecube |
| 110 | C | 161007T083417Z | user5898 |
| 041 | Perl | 161007T110224Z | Dom Hast |
| 087 | C | 161007T094051Z | user5898 |
| 092 | Racket | 161007T003321Z | rnso |
| 064 | Scala 64 Bytes | 161007T004008Z | user1492 |
| 044 | PHP | 161005T101937Z | Jör |
| 020 | Python | 140404T000157Z | Maltysen |
| 069 | R | 160817T161927Z | user5957 |
| 005 | Jelly | 160817T155714Z | X88B88 |
| 010 | Retina | 160817T151855Z | Martin E |
| nan | JavaScript | 140130T090824Z | user2428 |
| 015 | Q | 160521T172206Z | J. Sendr |
| 048 | Powershell | 151007T183818Z | Jonathan |
| 035 | Javascript ES6 | 151005T155906Z | lethern |
| 051 | PowerShell | 150811T164259Z | AdmBorkB |
| nan | 151005T174315Z | Mutador | |
| 108 | C | 151005T160510Z | ehmu |
| 035 | rs | 150803T213033Z | kirbyfan |
| 119 | Javascript | 150803T165421Z | SuperJed |
| 107 | C | 150731T140941Z | Cole Cam |
| 032 | Ruby | 150227T211120Z | nwhirsch |
| nan | Woohoo | 150130T061008Z | Mints97 |
| 006 | Pyth | 150124T072701Z | Maltysen |
| 019 | Pyth | 150124T071459Z | ericmark |
| 057 | Javascript | 140914T215517Z | Kevin Wu |
| 036 | Julia | 140915T071659Z | Cruor |
| 136 | pure bash | 140914T111812Z | F. Hauri |
| 048 | Haskell | 140401T122659Z | Flonk |
| 013 | APL | 140331T032646Z | Elias M& |
| 042 | Groovy | 140331T030236Z | md_rasle |
| 044 | Groovy | 140331T025448Z | md_rasle |
| 138 | C | 140331T013648Z | bacchusb |
| 137 | Python | 140329T134220Z | Dan the |
| nan | 140209T203103Z | Adam Spe | |
| 002 | APL | 140209T191318Z | Tobia |
| 058 | Bash 66 | 140209T184010Z | christof |
| 045 | sed | 140202T224904Z | Tomas |
| 144 | C# | 140202T175212Z | user3188 |
| nan | 140202T131933Z | learner | |
| 087 | JavaScript | 140130T054929Z | Eliseo D |
| 010 | Matlab | 140129T110231Z | Dennis J |
| 077 | R | 120316T144412Z | Paolo |
| 032 | Scala in REPL | 110309T055742Z | ebruchez |
| nan | 120601T172119Z | Liam | |
| 129 | CoffeeScript | 120425T141822Z | Johno |
| 025 | Q | 120311T022134Z | tmartin |
| 173 | Java | 111207T125117Z | Averroes |
| 054 | Groovy | 110309T150441Z | Espen Sc |
| 046 | Groovy | 111207T081402Z | Armand |
| 104 | C++ 104 nonws chars | 110308T165520Z | Matthew |
| 011 | k4 | 110913T220124Z | frank |
| 066 | Python 3 | 110913T180057Z | Steven R |
| 121 | Python 121 Characters | 110803T230809Z | Andbdrew |
| 052 | Coffee Script | 110913T131332Z | Billy Mo |
| nan | C 79 | 110803T223607Z | Harry K. |
| 218 | Ada 2005 | 110804T140039Z | Rommudoh |
| 059 | F# | 110729T063844Z | alun |
| 030 | Clojure | 110609T130415Z | mikera |
| 104 | Python 2 | 110508T144555Z | cemper93 |
| 064 | Python 3 | 110319T065407Z | user1011 |
| 032 | Ruby 1.9 | 110309T093414Z | david4de |
| 078 | Perl | 110311T200123Z | user503 |
| nan | 110311T172918Z | Greg Sch | |
| 039 | Ruby | 110311T172116Z | Magnus H |
| nan | C++ Counting sort | 110309T064025Z | Dave Gam |
| 041 | Clojure REPL | 110310T031448Z | Squid |
| nan | 110309T055205Z | richardt | |
| 118 | C# | 110309T142156Z | Yngve B- |
| 024 | Matlab | 110309T130922Z | Hannesh |
| 035 | Ruby | 110309T125855Z | user814 |
| nan | PHP 51 chars | 110309T114105Z | user353 |
| nan | C function 147 chars | 110309T071531Z | Dave Gam |
| nan | 110309T072938Z | user796 | |
| 046 | Another Ruby | 110309T065131Z | user792 |
| 040 | Ruby | 110309T064342Z | user793 |
| nan | 110309T061713Z | user775 | |
| 043 | Yet another Python answer . | 110309T060412Z | MAK |
| 067 | JavaScript | 110309T054934Z | Sophisti |
| nan | 110309T054927Z | Blair Mi | |
| 023 | Clojure | 110308T211546Z | mikera |
| 087 | PHP command line | 110308T175609Z | ts01 |
| 003 | Golfscript | 110308T173049Z | YOU |
| 008 | J | 110308T155017Z | J B |
J-uby, 17 14 bytes
(A|:sort)**:==
Attempt This Online! (Uses the working ** operator from an older version of J-uby.)
Tcl, 65 bytes
proc A x\ y {expr {[lsort [split $x ""]]==[lsort [split $y ""]]}}
---
Tcl, 82 bytes
proc A x\ y {expr {[string le $x]==[string le $y]&[lsort -u [split $x $y]]=="{}"}}
proc A x\ y {expr {[string le $x]==[string le $y]&&[lsort -u [split $x $y]]=="{}"}}
proc S s {lsort [split $s ""]}
proc A x\ y {set x [S $x]
set y [S $y]
expr {$x==$y}}
Previous version was failing for comparing 2 to 20, because after the lsort and join the comparison became 2==02, and == was doing a numerical comparison instead of a numerical one!
proc S s {join [lsort [split $s ""]] ""}
proc A x\ y {set x [S $x]
set y [S $y]
expr {$x==$y}}
AWK, 87 bytes
{if(split($1,a,X)!=split($2,b,X))exit
asort(a);asort(b)
for(i in a)if(a[i]!~b[i])exit}1
Prints the input string on success, otherwise nothing.
{if(split($1,a,X)!=split($2,b,X))exit # different length strings
asort(a);asort(b) # line things up
for(i in a)if(a[i]!~b[i])exit}1 # print string if no fails
Regex (PCRE), 65 bytes
^((?=(.))(?!(.*?\2(?=.*
(\4?+.*?\2)))*+.*\2)(?=.*
(\5?+.)).)*
\5$
Try it online! - test cases
Try it on regex101 - try it on your own
Takes the input strings delimited by newline.
This asserts that both:
- For each character in the first string, the second string contains that character at least as many times as it occurs in the first string
- The second string is equal in length to the first
^ # Assert that we're starting at the beginning of the first word.
(
(?=(.)) # Match and capture a character in \2, without consuming it.
# Assert that the second has at least as many occurrences of \2 as there
# are subsequent occurrences of it in the first word (including the one we
# just captured above).
(?! # Negative lookahead - assert the following can't match, and also
# conveniently erase whatever capture groups it creates when finished.
(
.*?\2 # Match up to the next occurrence of \2 in the first word
# (which will be the first one when this loop starts)
(?=
.*¶ # Skip to the second word.
( # \4 = the following:
\4?+ # previous value of \4, if any
.*?\2 # Match up to the first subsequent occurrence of
# \2 in the second word (which will be the first
# occurrence when this loop starts)
)
)
)*+ # Loop the above possessively, locking in each iteration
# atomically as it matches.
.*\2 # Assert \2 occurs again in the first word.
)
# Append one more character from the second word onto \5, building up \5
# to have the same number of characters of the second word as characters
# we have finished processing in the first word.
(?=
.*¶ # Skip to the second word.
( # \5 = the following:
\5?+ # Previous value of \5, if any
. # One additional character
)
)
. # Skip over the \2 just processed in the first word.
)* # Iterate the above as many times as possible.
¶ # Assert we've reached a newline, meaning we've processed the
# entire first word, and advance to the second word.
\5$ # Assert that the second word is of equal length to the first.
It only takes +1 byte (66 bytes) to add support for zero-length words:
^((?=(.))(?!(.*?\2(?=.*
(\4?+.*?\2)))*+.*\2)(?=.*
(\5?+.)).)*
\5?$
Try it online! - test cases
Try it on regex101 - try it on your own
Regex (.NET), 70 66 62 bytes
^(((.))(?=(?>(?<2>\2)|.)*
((?<-2>\2)|.)*$(?(2)^)))*
(?<-3>.)*$
Try it online! - test cases
Try it on regex101 - try it on your own
This asserts that both:
- For each character in the first string, the second string contains that character at least as many times as it occurs in the first string
- The second string is not longer than the first
Although it is not required, this works even with zero-length words (for free; there is no golf sacrifice in doing so).
^ # Assert that we're starting at the beginning of the first word.
(
((.)) # Consume a character and capture it in both \2 and \3.
# Assert that the second word has at least as many occurrences of \2 as
# there are subsequent occurrences of it in the first word (including the
# occurrence we just consumed). This only needs to be asserted for the first
# occurrence of each character in the first word (because on each subsequent
# occurrence, the count of subsequent occurrences will be one fewer than
# before) but for golf reasons, it's harmless to do it for every occurrence.
(?= # Atomic lookahead
# Step 1: Push every subsequent occurrence of \2 onto the \2 stack.
(?> # Atomic group - prevent backtracking from changing what's
# done inside it once it's been done.
# For each subsequent character in the first word:
(?<2>\2) # If it matches \2, push another copy of it onto the
# \2 stack, and consume the character.
| # or
. # Consume the character.
)* # Iterate the above as many times as possible.
¶ # Consume the newline to begin reading the second word,
# preventing the number of loop iterations in the above
# loop from being backtracked.
# Step 2: Assert that the second word has at least as many occurrences
# of \2 as were counted above.
( # For each character in the second word:
(?<-2>\2) # If it matches \2, pop it off the \2 stack, and consume
# the character.
| # or
. # Consume the character.
)*$ # Iterate the above until reaching end of string.
(?(2)^) # Assert that the \2 stack is empty.
)
)* # Iterate the above as many times as possible.
¶ # Assert we've reached a newline; advance to the second word.
(?<-3>.)*$ # Assert that this word is not longer than the first word, by
# popping every capture from the \3 stack and matching one
# character of the second word (it doesn't have to match \3)
# for each.
Regex (Perl / PCRE), 71 bytes
^((?=(.))(?4)(?=.*
(\3?+.)).)*
\3$((?!(.*?\2(?=.*
(\6?+.*?\2)))*+.*\2))
Try it online! - Perl
Try it online! - PCRE2
Perl doesn't erase capture groups upon exiting from a negative lookahead. For compatibility with it, this version uses a subroutine call (?4) instead of a negative lookahead to erase the necessary capture group. The subroutine is then executed again, harmlessly, after the regex finishes and reaches the end of the string (for golf reasons, it is not hidden in a (?(DEFINE)...) block or similar construct).
Regex (PCRE / .NET), 74 bytes
^((?=(.))(?!(?>(.*?\2(?=.*
((?>\4?).*?\2)))*).*\2)(?=.*
((?>\5?).)).)*
\5$
Try it online! - PCRE2
Try it online! - .NET
This is the PCRE version ported to be compatible with .NET, replacing possessive quantifiers with atomic groups.
Regex (PCRE / Ruby), 87 bytes
^((?=(.))(?!(.*?\2(?=.*
(\5?+.*?\2))(?=.*
(\4)))*+.*\2)(?=.*
(\7?+.))(?=.*
(\6)).)*
\6?$
Try it online! - PCRE
Try it online! - Ruby
This is a port of the 65 byte PCRE version, using back-and-forth copying of \4↔\5 and \6↔\7 to avoid use of nested backreferences, which aren't supported by Ruby.
For a reason I have yet to determine, this doesn't work on Pythonregex, even its latest version.
Regex (Perl / PCRE / Ruby / .NET), 147 bytes
^((?=(.))(?!(?>(.*?\2(?=((?!.*\2)|.))(?=.*
((?!.*$\4)(?>\6?).*?\2|(?=.*$\4)(?=(?>\6?).*?\2)))(?=.*
(\5)))*).*\2)(?=.*
((?>\8?).))(?=.*
(\7)).)*
\7$
Try it online! - Perl
Try it online! - PCRE2
Try it online! - Ruby
Try it online! - .NET
This is a rather interesting challenge for writing a regex polyglot.
Supporting both Perl and Ruby/.NET is rather difficult. The problem is finding a way to erase the capture group that is created inside a negative lookahead in the PCRE version. Erasing capture groups in situations like this can be a challenge, and to support this combination of regex engines, we can't use negative lookahead (Perl doesn't erase it), a subroutine call (because Ruby's syntax is incompatible with Perl, and .NET doesn't have them), a branch reset group (neither Ruby nor .NET support them), or capture group aliasing or explicit erasure (only .NET has those).
So we must signal to the place where the capture is normally made, to erase it when it needs to be erased. The method I settled upon here is rather convoluted, but it works. (It would be shorter with a lookaround conditional, but we can't use one, as Ruby doesn't have them, and .NET's syntax for them is different.) This post is already pretty long, so here's a link to the commented version.
Regex (.NET), 74 73 bytes
^(.)*
((.)(?<=(?=\3(?<-4>.*?(?<1>\4))*)(?<-1>\1.*(?=(.)?))*
.*))*$(?(1)^)
Try it online! - test cases
Try it on regex101 - try it on your own
This uses a completely different algorithm than my other answer which includes a 70 66 byte .NET version. Like it, this takes the input strings delimited by newline, and works even with zero-length words.
Simply put, it pushes each letter of the first word onto a stack, then goes through each letter of the second word, removing a matching letter from the stack. Iff that completes successfully, and the stack ends up empty, then the two words are anagrams of each other.
What complicates this is that it's a stack, not a random-access array, so to find a matching letter in it, the letters above it need to be moved to a temporary stack, then moved back after the matching letter has been removed.
When interpreting the explanation below, remember that lookbehinds in .NET are evaluated from right to left – so read those from bottom to top, one quantified token at a time. When entering a lookahead inside a lookbehind, go back to reading from top to bottom.
^ # Go to beginning of first word
(.)* # Push each letter of first word onto \1 stack
¶ # Go to beginning of second word
( # Begin main loop
(.) # \3 = next letter from second word
(?<= # Lookbehind
(?= # Lookahead
\3 # Assert that the last letter popped from the \1
# stack matches \3 (which may make the (?<-1>...)
# loop backtrack), and skip it
# Transfer \4 stack back onto \1 stack in original order
(?<-4> # Pop a letter from the \4 stack as many times as
# can be done, each time doing the following:
.*? # Skip letters that have already been removed from
# the stack in this pass or previous passes
(?<1>\4) # Push the letter from \4 back onto the \1 stack
)*
)
(?<-1> # Pop a letter from the \1 stack as many times as
# can be done, each time doing the following:
\1 # Match and consume the letter from the \1 stack
.* # Skip letters that have already been removed from
# the stack in previous passes
(?=(.)?) # Push the last letter removed from the \1 stack
# onto the \4 stack
)*
¶.* # Skip back to the end of the first word
)
)* # End main loop
$ # Assert end of second word has been reached
(?(1)^) # Assert \1 stack has been emptied
JavaScript (Node.js), 37 38 bytes
-1 byte thanks to emanresu A
Here is a more up-to-date JS answer.
a=>b=>(g=x=>[...x].sort()+0)(a)==g(b)
Setanta 72 Bytes
gniomh(a,b){toradh sortáil@(go_liosta@a())()==sortáil@(go_liosta@b())()}
Naive solution for a very limited language. Accepts two strings and returns true if their sorted char arrays are equal
UiuaSBCS, 7 bytes
≍∩(⊏⍏.)
Explanation
≍ Are the strings identical
∩( ) when both of them
⊏⍏. are sorted?
Notice that the process is identical to that of the BQN solution.
R, 45 39 36 bytes
Edit: -9 bytes thanks to @Dominic van Essen.
\(x,y)identical(table(x),table(x=y))
Takes input as two character vectors.
Swift 5.9, 30 bytes
let f={Set($0+"")==Set($1+"")}
The obvious method. Initializes unordered Sets from the inputs (after concatenating empty strings to assist the type checker) and compares them.
YASEPL, 77 bytes
=1'=2'=c=e®1=f®2`1!g¥c,1=d=i`2!h¥d,2}7,g,3!i$`3!d+}2,f,2!i]4!c+}2,e>1|5`4>0`5
prompts you twice for both words, outputs either a one or zero for if its true or false respectively
APL(NARS), 5 chars
≢⎕§⍦⎕
It return 0 if the two string are anagram each of other, or one number different of 0 otherwise. Test & how to use:
≢⎕§⍦⎕
⎕:
'123'
⎕:
'312'
0
≢⎕§⍦⎕
⎕:
'123'
⎕:
'2143'
1
Labyrinth, 23 bytes
1
,:#
* 0
1;/----+}=-!@
Takes two words separated by a newline. For each word, computes the product of c * 10 + 1 for each char c, and compares the two values. Prints 0 for true and a nonzero integer for false.
Such product is unique for lowercase words up to permutation, since the counts of 25 out of 26 letters can be recovered from the exponents of 25 unique prime factors:
971 is prime
981 = 109 * 3 * 3
991 is prime
1001 = 7 * 11 * 13 (no unique prime factor)
1011 = 337 * 3
1021 is prime
1031 is prime
1041 = 347 * 3
1051 is prime
1061 is prime
1071 = 17 * 7 * 3 * 3
1081 = 47 * 23
1091 is prime
1101 = 367 * 3
1111 = 101 * 11
1121 = 59 * 19
1131 = 29 * 13 * 3
1141 = 163 * 7
1151 is prime
1161 = 43 * 3 * 3 * 3
1171 is prime
1181 is prime
1191 = 397 * 3
1201 is prime
1211 = 173 * 7
1221 = 37 * 11 * 3
Therefore this approach works for arbitrary length inputs.
Since a lowercase letter has value of 97 or higher, the newline has value 10, and -1 is pushed on EOF, a three-way branch is possible via dividing the input value by any number between 11 and 97 inclusive.
By a little bit of planetary alignment, letting the IP reflect on newline (instead of creating a 4-way junction) magically sets up the stack for the second word. This part works because the words are guaranteed to be nonempty.
1 push 1 on empty stack
,:# loop: compute the value of word1 until newline
* 0 ,: getchar, dup [word1 c c]
1;/ #0/ divide by 30 [word1 c c/30]
if positive:
;1* drop, multiply 10c+1 [word1']
if zero: reflect
1 [word1 10 0]
,:# 0#: push some garbage [word1 10 0 3 3]
0 , getchar (1st char of word2)
1 times 10 plus 1
[word1 10 0 3 3 word2]
enter the loop again to compute the value of word2
same flow as first loop, except that # gives 8 and
IP turns left on EOF
[word1 10 0 3 3 word2 -1 -1]
----+}=-!@ clean up the stack and compare word1 and word2
----+ [word1 10 word2]
}= [word1 word2 | 10]
-!@ print the difference and halt
Nekomata + -e, 2 bytes
↕=
↕ Check if any permutation of the first string
= is equal to the second string
Thunno 2, 3 bytes
€Ṡạ
Explanation
€Ṡạ # Implicit input
€ # Apply to both strings:
Ṡ # Sort the string
ạ # Are they both equal?
# Implicit output
Zsh, 43 bytes
<<<${${(j::)${(os::)1}}/${(j::)${(os::)2}}}
Truthy: empty string (i.e. the inputs are anagrams). Falsy: a string of characters. Link goes to a test harness where Truthy is printed as T, Falsy as F.
Raku, 22 bytes
{[~~] @_».comb».Bag}
.combconverts each input string to a list of its characters..Bagconverts each list of characters into a Bag object (a set with multiplicity).[~~]inserts the~~smartmatch operator between the two Bags, which returns true if and only if they have the same contents.
BQN, 3 bytes
≡○∧
Anonymous tacit function that takes two strings; returns 1 if they are anagrams, 0 otherwise. Try it at BQN online!
Explanation
≡ Are the strings identical
○ when both of them
∧ are sorted?
05AB1E, 6 4 bytes
{I{Q
This took a while because of input difficulties. Golfed down due to pop.
Explanation:
{I{Q Original code
{ Takes first input e.g. word and sorts -> 'dorw'
I Takes second input e.g. 'wrdo'
{ Sorts second input -> 'dorw'
Q Compare if sorted 1 = sorted 2, then print result. 'dorw' = 'dorw', so prints 1.
Knight, 51 bytes
O?C=cB;=iP;=x*'0'256;Wi;=xSx=aAiT+1Gx aT=iSiF1""xCc
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)
Knight, 59 52 bytes
O?C=bB;=aP;=x*"0"128;Wa;=xSxAa 1+1GxAa 1=aGa 1La xCb
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
R, 47 bytes
\(x,y)all(table(strsplit(paste0(x,y),""))%%2==0)
Alice, 11 bytes
/@Mn/
\MOX\
Prints Jabberwocky if the two words are anagrams
Flattened
MM Reads the two arguments
X Compute their symmetric difference
n Empty string becomes Jabberwocky, anything else becomes empty string
O Print it out
@ Bye
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
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)
Vyxal, 2 bytes
Þ⊍
Takes two strings pushed separately onto the stack as input. Returns inverted output (falsey if the strings are anagrams of each other, truthy if they are not).
Þ⊍ # Multiset Symmetric Difference - yields a list of the characters in A that
# aren't in B and the characters in B that aren't in A. Will be empty iff A
# is an anagram of B.
Vyxal, 3 bytes
Þ⊍¬
Takes two strings pushed separately onto the stack as input. Returns 1 if the strings are anagrams of each other and 0 otherwise.
Þ⊍ # Multiset Symmetric Difference - yields a list of the characters in A that
# aren't in B and the characters in B that aren't in A. Will be empty iff A
# is an anagram of B.
¬ # Logical Not - When used on a list (as is the case here) returns 1 for an
# empty list and 0 for a non-empty list (even a list containing one 0 in it)
Vyxal, 3 bytes
vs≈
Takes a list of two strings as input. Returns 1 if the strings are anagrams of each other and 0 otherwise.
vs # Vectorized sort (sort the characters in each individual item)
≈ # All Equal
Haskell, 31 bytes
import Data.List
s%t=s\\t==t\\s
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)
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]
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.
Knight, 112 bytes
;=dF;C=mB;=a 123W<96=a-a 1Id=d!E+"a"aE++"=a"a" 0";=w"+1a";C=lB;=bP:Wb;E++"=a"Ab+wAb=bGb 1Lb;=w"+~1a";Cl;=dT;CmOd
Knight doesn't have arrays. It does have strings, but it only allows a subset of valid ASCII character codes. So I emulated an array by constructing strings that looks like "=a{charcode} 0" and evaling it.
Knight also has blocks. A block works like a niladic function, which can change its behavior depending on global variables. This code uses two blocks: m loops over all 26 variables a97 - a122 initializing or testing something, and l handles the part of taking input and iterating over its chars to count occurrences.
; = d F d = False
; C = m B define and run block m:
; = a 123 a = 123
: W < 96 = a - a 1 while 96 < (a = a - 1):
I d if d:
= d ! E + "a" a d = ! eval("a" + a)
E + + "=a" a " 0" else: eval("=a" + a + " 0") (aNN = 0)
i.e. d is false on start, so initialize all of a97..a122 to 0
; = w "+1a" w = "+1a" (which is necessary to run l)
; C = l B define and run block l:
; = b P b = one line of input
: W b while b is not empty:
; E + eval(concatenation of
+ "=a" A b "=aNN"
+ w A b w+"NN") (aNN = 1 + aNN)
(w = "+~1a" changes this to aNN = -1 + aNN)
: = b G b 1 L b b = b[1:length(b)]
i.e. count occurrences of chars in the first line
; = w "+~1a" w = "+~1a"
; C l run block l i.e. count negative occurrences in the second line
; = d T d = True
; C m run block m
for each of a122..a97, check if aNN is zero
if true, keep checking; otherwise do useless thing
: O d print d
Pyth 10 7
qFSMczd
Takes input as two space-separated words.
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)
Ruby, 46 bytes
I hope there's a way better than this.
p gets.strip.chars.sort==gets.strip.chars.sort
TI-Basic, 83 bytes
Prompt Str1,Str2
"seq(inString(Str1+Str2,sub(Ans,I,1)),I,1,length(Ans→u
Str1
u→A
SortA(ʟA
Str2
u→B
SortA(ʟB
0
If dim(ʟA)=dim(ʟB
min(ʟA=ʟB
Ans
Output is stored in Ans and displayed. Outputs 1 if the inputs are anagrams, otherwise 0.
C - 115 Bytes
a[127],b[127],i,o=1;f(char*s,char*z){for(;*s;a[*s++]++);for(;*z;b[*z++]++);for(;i++<128&&o;o=a[i]==b[i]);return o;}
Ungolfed
a[127], b[127], i, o = 1;
f(char* s, char* z)
{
for(; *s; a[*s++]++);
for(; *z; b[*z++]++);
for(; i++ < 128 && o; o = a[i] == b[i]);
return o;
}
Alternative way (By @ceilingcat)
*a,*b,i,o;f(char*s,char*z){for(a=calloc(i=128,8);*s;a[*s++]++);for(b=a+i;*z;b[*z++]++);for(;i--&&(o=a[i]==b[i]););return o;}
Explanation
A function that receives two ASCII character strings with arbitrary length and checks if one is an anagram of the other.
To accomplish this, both entire strings are iterated over and the number of matches for each character is stored in a list for each string; later it is checked if both lists have the same number of matches, if so, then the strings are anagrams and true (1) is returned, otherwise false (0) is returned.
Ly, 46 29 bytes
iayr>iay&s<l[0I=![0u;]pprp]1u
I know Ly better now. :) At a high level, this code constructs two stacks, each with a sorted (by codepoint) list of characters in the associated input string, with the length of the string included as another entry on the list.
One stack is reversed and then the two are concatenated. Once that setup is done, the code loops comparing the top and bottom of the stack. The first time the codepoints aren't the same, the code write out a 0 and exits. If the loop exhausts the stack, the strings are anagrams so the code writes out a 1 and exits.
It's still nowhere near the shortest, but the way it works might be interesting to people?
# parse the first string
i - read in one line
a - sort by codepoint value
y - push the stack length
r - reverse the stack
# parse the second string
> - switch to a new stack
i - read in one line
a - sort by coidepoint
y - push the stack length
&s - stash the entire stack
# setup for processing
< - back to stack with string 1
l - append the parsed second string
# compare pairs of codepoints while stack isn't empty
[ ] - loop, process one char per iteration
0I - copy bottom of stack
=! - compare top two negate
[ ]p - if/then, if they don't match
0u; - print "0" and exit
prp - delete pair we just checked
# if lengths and all the codepoints matched...
1u - success! print "1"
PHP7.4 (45 chars)
The function $f will return the answer using count_chars :
$f=fn($a,$b)=>($x='count_chars')($a)==$x($b);
Try it Online - in PHP4 the XOR cipher passes all tests using 48 chars :
function f($a,$b){return$a==chop($a.$b^$b^$b);};
C gcc (69 chars)
The function f compute the product of both string and implicitly return the comparison :
i;j;f(char*a,char*b){i=j=1;for(;*a;i*=*a++);for(;*b;j*=*b++);a=i==j;}
C version isn't shaved up to 65 chars by XOR cipher due to some ae == bf misses :
i;f(char*a,char*b){i=1;for(;*a;i^=*a++);for(;*b;i^=*b++);a=i==1;}
Factor + math.combinatorics, 22 bytes
[ <permutations> in? ]
Is the first input in the permutations of the second input? Not the fastest, but shorter than sorting or counting.
Curry, 49 bytes
Tested in PAKCS
e#x=e:x
e#(x:y)=x:e#y
p(x:y)=x#p y
p[]=[]
(=:=).p
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.
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())
05AB1E, 3 bytes
Aargh! I can't beat GolfScript!
œså
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?
Lua 112
function q(a,b)s=table.sort;t=table.concat;a={a:byte(1,#a)}s(a);b={b:byte(1,#b)}s(b)return t(a,".")==t(b,".")end
SmileBASIC, 49 bytes
INPUT A$,B$WHILE""<A$B$[INSTR(B$,POP(A$))]="
WEND
Throws an error when the strings aren't anagrams.
Brachylog, 2 bytes
pᵈ
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.
Brain-Flak, 170 bytes
{({}[(()()()()()){}]<>)<>}<>([]){{}(<>())<>{({}[(((((()()()()()){}){}){})){}])({({})({}[()])()}{}{}())({<({}[()])><>({})<>}{}<><{}>)<>}{}([])}<>({}[{}])((){[()](<{}>)}{})
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.
Japt, 10 9 5 4 bytes
á øV
á øV :Implicit input of strings U & V
á :Permutations of U
øV :Contains V?
C# (.NET Core), 108 bytes
Without LINQ. Returns 1 for true, 0 for false.
(a,b)=>{int x=a.Length==b.Length?1:0;foreach(char c in a){try{b.Remove(b.IndexOf(c));}catch{x=0;}}return x;}
Pushy, 13 bytes
Assumes the two inputs are separated by a space.
K32-$v;.gFgx#
\ Implicit: input on stack as character codes
K32- \ Subtract 32 from all, making SPACE = 0
$ \ Until 0 (space) on top of stack:
v; \ Send last char to auxiliary stack
. \ Space has been reached, pop it.
\ Now each stack contains all the letters of one of the words.
gFg \ Sort both stacks
x \ Check their equality
# \ Print result (1 if true, 0 if false)
Pepe, 58 bytes
REEREEEEeEERREEeREEEEeEeErRREEEEEeEEreerrEEREEeeReEErEereE
Try it online! Input is in the form a;b. Outputs 0 for truthy and none for falsy.
MathGolf, 4 bytes
ms~=
Explanation
m explicit map
s sort(array)
~ dump array to stack
= pop(a, b), push(a==b)
Perl, 26 bytes
Includes +1 for p (using -F and @F ends up with the same score)
Give the input strings as 2 lines on STDIN.
(echo word; echo wrdo) | perl -pE '$\=${join W,sort/./g}++}{'
This prints 0 if not an anagram or 1 if it is an anagram
(echo word; echo wrdo) | perl -pE '$_=${join W,sort/./g}++'
comes in at 24 bytes and prints 00 if not an anagram and 01 if it is. If these values are numbers they are in fact valid falsy and thruthy in perl, but as strings they are both thruthy. It's probably fairer to consider them as strings so this solution is invalid
So this is the same length (but without warnings) as Xcali's answer (after optimizing):
(echo word; echo wrdo) | perl -F -E '@{$.}=sort@F}{say@1~~@2'
Bash, 88 characters
diff <(grep -o .<<<$1|sort) <(grep -o .<<<$2|sort)>/dev/null && echo true || echo false
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)}}
Python 2, 79 bytes
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))
Perl, 60 bytes
Perl one-liner
perl -lanF -e 'push@a,join"",sort@F;END{exit($a[0]ne$a[1])}'
Takes first two lines of STDIN and compares them. Exits 0 if they're anagrams, 1 otherwise.
$ echo -e "word\nwrdo" | \
> perl -lanF -e 'push@a,join"",sort@F;END{exit($a[0]ne$a[1])}' && echo anagram
anagram
$ echo -e "word\nwrro" | \
> perl -lanF -e 'push@a,join"",sort@F;END{exit($a[0]ne$a[1])}' && echo anagram
$
Python, 32 bytes
p=sorted
f=lambda a,b:p(a)==p(b)
Python, 32 bytes
f=lambda a,b,S=sorted:S(a)==S(b)
Golfscript, 8 bytes
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
Lua, 140 chars
t={io.read():match"(%w+), (%w+)"}T=table for k=1,2 do w={t[k]:byte(1,-1)}T.sort(w)t[k]=T.concat{string.char(unpack(w))}end print(t[1]==t[2])
... like driving a screw with a light weight hammer, at least for code-golfing
JavaScript, 41
Comparison function (41):
a=b=>''+[...b].sort()
b=(c,d)=>a(c)==a(d)
alert(b('abc', 'cba')) // true
Comparator function (21):
a=b=>''+[...b].sort()
alert(a('abc') == a('bca')); //true
Comparator function (48):
function a(b){return String(b.split('').sort())}
alert(a('abc')==a('bca')); //true
Comparison function (78):
function a(b,c){return String(b.split('').sort())==String(c.split('').sort())}
alert(a('abc','bca')); //true
Assumes String has split and Array has sort.
Perl, 58 bytes
(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"}
Haskell, 31 bytes
function - 31
import List
f=(.sort).(==).sort
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.
Ruby, 34 bytes
Using the IO scheme of Peter Taylors Perl solution:
p gets.chars.sort==gets.chars.sort
C program, 118
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");}
Python 3, 107 97 76 64
s=sorted;a,b=input().split(', ')
print(str(s(a)==s(b)).lower())
Obviously this can be shortened if we don't take the OP's wording literally and lowercase "true" and "false"...
Perl, 62 bytes
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.
Javascript, 192 157 152 147 125 bytes
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"));
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())
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(_ => _)));
}
}
}
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)
Pyth, 4 bytes
_ISM
Explanation
_ISM
SMQ Sort both (implicit) inputs.
_I Check if the result is invariant under reversing.
Python, 99 chars
f=lambda w,x,y:w==y if x==""else any([f(w+a,x.replace(a,"",1),y)for a in x])
g=lambda x,y:f("",x,y)
Recursively finds all permutations of x and compares them to y.
Julia, 41 bytes
g(a,b)=sort(collect(a))==sort(collect(b))
Axiom, 45 bytes
f(a:String,b:String):Boolean==sort(a)=sort(b)
Wolfram Language 26 bytes ( Mathematica )
ContainsAll@@Characters@#&
Usage:
%@{"BOAT","TOAB"}
Output:
True
Excel VBA, 87 Bytes
Anonymous VBE immediate window function that takes input from range A1:B1 and outputs whether the two inputs are anagrams of one another to the VBE immediate window. This a destructive process as the value inputted into range B1 is destroyed
For i=1To[Len(A1)]:[B1]=Replace([B1],Mid([A1],i,1),"|",,1):Next:?[B1=Rept("|",len(A1))]
APL (Dyalog), 10 bytes
≡/(⊂∘⍋⌷⊢)¨
The program takes in two strings in a single array as its right argument.
Explanation
¨ For each string
(⊂∘⍋⌷⊢) Sort it
≡/ And check if both strings are equal
Jelly, 3 bytes (probably non-competing)
Ṣ€E
Similar to X88B88's solution, but this takes a list of strings instead of two arguments, like ["String1", "String2"].
Explanation:
Ṣ€ Sort each input
E Check equality
awk, 63 65 bytes
It only accepts chars a-z (0141-0172). gsub counts occurrances of each char in alphabet, appends them to a variable (variable looks something like 140213000000000000..., starts with 140 for initialization) and compares frequencies in variables in the end. It returns the value of the comparison on exit:
{for(a=i=140;++i<173;)a=a gsub("\\"i,1);if(p>1)exit(p==a);p=a}
Test it:
$ cat file
aabccc
abcacc
$ awk '{for(a=i=140;++i<173;)a=a gsub("\\"i,"");if(p>1)exit(p==a);p=a}' file
$ echo $? # will output 0 or 1 where 1=true and 0=false
1
Mathematica 28 Bytes
Split into list of characters, sort and test for equality.
Equal@@ Sort/@Characters[#]&
Usage
%@{"BOAT", "TOAB"}
Output
True
C++14, 104 bytes
As generic function returning via reference parameter. Accepts char[] or std::string or any other container that supports range-based for loop.
Returns 0 for anagram, anything else for non-anagram
#define F(X) for(auto x:X)
void f(auto&A,auto&B,int&r){int C[256]={r=0};F(A)C[x]++;F(B)C[x]--;F(C)r|=x;}
Ungolfed and usage:
#include<iostream>
#define F(X) for(auto x:X)
void f(auto&A,auto&B,int&r){
int C[256]={r=0}; //declare counting array and set return value to 0
F(A)C[x]++; //increase first string chars
F(B)C[x]--; //decrease second string chars
F(C)r|=x; //if any char is not zero
}
int main(){
int r;
#define P(a,b) f(a,b,r); std::cout << a << ", " << b << " -> " << r << "\n"
P("hello","wrong");
P("hello","olleh");
P("zz","zzzzzz");
}
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.
C 110 bytes
char*a,*b;l(i,j,k){y:if(!b[j]||!a[i])return i==k+1;if(a[i]==b[j]){b[j]=1;return l(i+1,0,j>k?j:k);}++j;goto y;}
this is one recursive function that has one not common way to have its input and write in one its argument... but not use library functions....
/*
l(i,j,k)
{y: if(!b[j]||!a[i])return i==k+1;
if(a[i]==b[j]){b[j]=1;return l(i+1,0,j>k?j:k);}
++j;goto y;
}
//110
r=1 m1=12345 m2=?????
r=0 m3=a m4=e
*/
main()
{char m1[]="12345", m2[]="54321", m3[]="a", m4[]="e";
int r;
a=m1;b=m2;r=l(0,0,0);printf("r=%d m1=%s m2=%s\n", r, m1, m2);
a=m3;b=m4;r=l(0,0,0);printf("r=%d m3=%s m4=%s\n", r, m3, m4);
}
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
C 87 bytes
char*a,*b,*c;d(i,k){return!a[i]||!(c=strchr(b,a[i]))?i==k+1:(*c=1,d(i+1,k<c-b?c-b:k));}
this is one recursive function that has one not common way to have its input and write in one its argument...this use recursion + library function...
/*
char*a,*b,*c;
d(i,k)
{return !a[i]||!(c=strchr(b,a[i]))?i==k+1:(*c=1,d(i+1,k<c-b?c-b:k));}
87
*/
main()
{char m1[]="12345", m2[]="54321", m3[]="a", m4[]="e";
int r;
a=m1;b=m2;r=d(0,0);printf("r=%d m1=%s m2=%s\n", r, m1, m2);
a=m3;b=m4;r=d(0,0);printf("r=%d m3=%s m4=%s\n", r, m3, m4);
}
Racket 92 bytes
(λ(a b)(define(g s)(sort(map(λ(x)(char->integer x))(string->list s))>))(equal?(g a)(g b)))
Ungolfed:
(define f
(λ (a b)
(define (g s) ; fn to get sorted list of string chars as numbers.
(sort
(map
(λ(x)(char->integer x))
(string->list s))
>))
(equal? (g a) (g b))))
Testing:
(f "test" "ttse")
(f "boat" "boat")
(f "toab" "boat")
(f "oabt" "toab")
(f "zyyyzzzz" "yyzzzzzy")
(f "a" "aa")
(f "zzz" "zzzzzzzz")
(f "sleepy" "pyels")
Output:
#t
#t
#t
#t
#t
#f
#f
#f
Scala - 64 Bytes
Could be made shorter (the toList could be changed to toSeq, I believe)
('a'to'z').forall(c=>y.toList.count(_==c)==z.toList.count(_==c))
PHP, 44 Bytes
<?=($c=count_chars)($argv[1])==$c($argv[2]);
Python, 20 bytes
lose to golfscript again...... :(
sorted(x)==sorted(y)
R, 69 bytes
a=function(b,d)identical(table(strsplit(b,"")),table(strsplit(d,"")))
I think this is the shortest R implementation which deals with a("b","bb") being FALSE.
Jelly, 5 Bytes (Non-competitive)
Ṣ⁼⁴Ṣ¤
Special thanks to Leaky Nun for helping me fix a problem.
Outputs one if true. Try it Online!
Retina, 10 bytes
This answer is non-competing since Retina is much newer than this challenge. Byte count assumes ISO 8859-1 encoding.
%O`.
D`
¶$
Input is linefeed-separated.
Explanation
%O`.
This sorts (O) the individual characters (.) in each line (%), i.e. it sorts each input string separately.
D`
This deduplicates the input on the (implicit) regex .*, which means it removes the characters from the second line if both strings are equal.
¶$
Finally, this tries to match a linefeed followed by the end of the string. Since the input strings are guaranteed to be non-empty, this can only happen if the second string was removed in the previous stage.
JavaScript, shortest JS answer so far: 57 56 characters, acccepts user input
This prompts the user for a value to compare.
function _(){return prompt().split(0).sort()+''}_()==_()
If no user input is required, this can be trimmed down to 53 52 characters.
Assuming the following variables are set:
var a='test', b='sets';
you can test for it with the following:
function _(a){return a.split(0).sort()+''}_(a)==_(b)
Note: this answer relies on some quirk that allowed using .split(0) instead of .split(""). This behavior no longer exists (at least in Firefox), so to get it running today, you have to replace 0 with "".
Q, 15 Bytes
f:{~/{x@<x}'x}
f is the name of the function
Test
f("boat";"boat") /1b
f("toab";"boat") /1b
f("oabt";"toab") /1b
f(,"a";"aa") /0b
f("zzz";"zzzzzzzz") /0b
f("zyyyzzzz";"yyzzzzzy") /1b
f("sleepy";"pyels") /0b
f(,"p";,"p") /1b
Explanation
Argument of the function is a sequence with both words. At each word applies {x@<x}, that sorts x (take from x in ascending index ordering). ~/ reads as "match over", and compares both transformed words
Powershell 48 bytes
param([char[]]$a,[char[]]$b)
Cast incoming strings as an array of char. Use diff (compare-object) on the two objects and cast as bool. Since a blank result (diff only shows differences not similarities) is False, negating it with ! will result in true for identical strings.
Added benefit: it will work on any arbitrary length strings (if equal whitespace).
Javascript (ES6) 35
Requires lambdas
Just like the other solutions, but with lambda
f=x=>x.split``.sort()
f(a)==f(b)+""
Usage
// a, b = input
f=x=>x.split``.sort()
console.log(f(a)==f(b)+"")
thanks @comment
PowerShell, 78 51 bytes
param([char[]]$a,[char[]]$b)(diff $a $b).Length-eq0
Takes the two string inputs, and re-casts them as char-arrays. The diff function (an alias for Compare-Object) takes the two arrays and returns items that are different between the two. We leverage that by re-casting the return as an array with (), and then checking its length. If the length is zero, that means that all items of both character arrays are exactly the same (because nothing was returned). PowerShell has an implicit write for evaluated statements like this, so will automatically write out True or False as required.
R, 63 Bytes
length(unique(lapply(strsplit(c(s,m),''),sort))[[1]])==nchar(m)
It seens it passes the test cases.
(just realized this question is 4 year old, but posting anyway)
C, (108)
char c[192]={};main(){for(;*a;c[127-*a++]++);for(;*b;c[223-*b++]++);puts(memcmp(c,c+96,95)?"false":"true");}
rs, 35 bytes
+(.)(.*) (.*)\1/\2 \3
\s/
.+/0
^$/1
Yay regexes!!
BTW, rs was created way after this was posted, so this technically doesn't count. Still cool.
Javascript, 143 119 bytes
a=prompt()[s="split"](" ");a[0]=a[0][s]("");a[1]=a[1][s]("");a[0].sort();a[1].sort();alert(a[0][j="join"]()==a[1][j]())
Takes a single space-seperated pair of strings as input.
C - 107 chars
Mark off chars in second string as we go. At the end, if we've passed over the entirety of both strings, then we've got a match.
i;main(p,v)char**v,*p;{for(;*v[1]&(p=strchr(v[2],*v[1]++));)*p=1,i++;puts(*(v[2]+i)|*v[1]?"false":"true");}
Ruby, 32
h=->{gets.chars.sort}
p h[]==h[]
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
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
Pyth - 19
qS@cz", "0S@cz", "1
Try it here. Note that the two words in the input must be separated by a comma and a space.
Python Mapping and explanation
q # equal( "Check equality"
S # sorted( "Sort"
@ # list looku "Extract element from list"
c # chop( "Separate by delimiter"
z # input( "Input variable"
", " # ", " "This delimiter"
0 # 0 "The 0th element"
S@cz", "1 # .. "The same thing with the 1st element
I'm sure someone can come up with a shorter implementation, but I've only been learning Pyth for a few days. It would also be a lot shorter if I didn't stick strictly to the input format given in the question.
For instance:
qS@Q0S@Q1
Which is only 9 bytes, works if the input is formatted like 'parse','spare'. So which one do you count?
Good practice though!
Javascript - 57 chars
function o(a,b){return b?o(a)==o(b):1+a.split("").sort()}
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
pure bash 136
There is a method without sorting step!
anagramCmp() {
x=0 y=0
for((i=0;i<${#1};i++));do
((x+=7**(36#${1:i:1}-10)))
((y+=7**(36#${2:i:1}-10)))2>/dev/null
done
return $((${#1}$x==${#2}$y?0:1))
}
Then now:
if anagramCmp Blah Halb ; then echo Yo; else echo Uh; fi
Yo
if anagramCmp Blahblah Hhaallab ; then echo Yo; else echo Uh; fi
Uh
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
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.
Groovy 42
def f(a,b){print ((b as Set)==(a as Set))}
Groovy 44
def f(a,b){print !(a-b)&&a.size()==b.size()}
C 138
Code finds the sum of the differences of the characters then checks if they are same length and sum == 0.
int s,t,i,j;
void f(char*a,char*b)
{
while (*a&&*b){
s+=*a-*b;
a++;b++;
i++;j++;
}
if (i==j&&s==0)t=1;
puts(t?"true":"false");
}
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
VB.net
Module Q
Sub Main(a As String())
Console.WriteLine(a(0).Count=-a(0).Sum(Function(c)a(1).Sum(function(x)x=c)))
End Sub
End Module
APL, 2 chars
≡⍦
This is the Multiset Match function from Nars2000, one of the leading-edge APL implementations. When applied to strings, it computes exactly the function required:
'elvis' ≡⍦ 'lives'
1
'alec guinness' ≡⍦ 'genuine class'
1
Bash (66 58)
f(){ fold -w1<<<$1|sort;}
g(){ [ "$(f $1)" == "$(f $2)" ];}
Call it with g <word1> <word2>.
Edit:
Stupid me, I do not need to unic -c after I sort
sed, 45 chars
It's even possible in my favourite - sed! Just one regular expression to solve the anagram! Just keep removing the corresponding letters:
:
s/(.)(.*,.*)\1/\2/
t
/\w/{i\false
d}
i\true
(to be invoked with -nE)
Perl, 48
1while s/(.)(.*,.*)\1/\2/;$_=/\w/?"false":"true"
To be invoked with -p.
Perl function, 39
sub f{$,while s/(.)(.*,.*)\1/\2/;!/\w/}
C#, 144 chars
namespace System.Linq{class m{static void Main(string[]a){Console.Write(a[0].Select(t=>a[1].Select(y=>t!=y)).Count()*2==(a[0]+a[1]).Length);}}}
Function: 90 chars
bool i(string a,string b){return a.Select(t=>b.Select(y=>t!=y)).Count()*2==(a+b).Length;}
import java.util.Scanner;
public class Match
{
public static void main(String[] args)
{
Scanner s=new Scanner(System.in);
String s1=s.nextLine();
String s2=s1.toLowerCase();
char []a=s2.toCharArray();
String s3=s.nextLine();
String s4=s3.toLowerCase();
char []e=s4.toCharArray();
int h,g = 0,l=0,r=0,h1=0,m=0;
int b=(int)a[0];
int f=(int)e[0];
//System.out.println();
for(int k=0;k<a.length;k++)
{
for(h=1+k;h<a.length;h++)
{
if(b>(int)a[h])
{
b=a[h];
char temp=a[h];
a[h]=a[k];
a[k]=temp;
}
}
if(l<a.length-1)
{
b=a[++l];
}
}
for(int k1=0;k1<e.length;k1++)
{
for(h1=1+k1;h1<e.length;h1++)
{
if(f>(int)e[h1])
{
f=e[h1];
char temp=e[h1];
e[h1]=e[k1];
e[k1]=temp;
}
}
if(m<e.length-1)
{
f=e[++m];
}
}
if(a.length==e.length)
{
int flag=0;
for(int j=0;j<a.length;j++)
{
if(a[j]==e[j])
{
flag++;
}
}
if(flag==e.length)
{
System.out.println("True");
}
else
{
System.out.println("false");
}
}
else
{
System.out.println("False");
}
}
}
JavaScript 87
alert((a=prompt().split(","))[0].split("").sort().join()==a[1].split("").sort().join())
Prompt requires comma separated list of two "words"
[Prompt]
btoa,boat
Output: true
Matlab: 10 characters without using sort
a*a'==b*b'
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
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.
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/
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.
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
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.
Groovy, 54
print args[0].toList().sort()==args[1].toList().sort()
Groovy, 46
b={args[it].toList().sort()}
print b(0)==b(1)
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;
}
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
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))
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'
Coffee Script (52)
a=(b,c)->`b.split('').sort()==c.split('').sort()+''`
usage
console.log a 'god', 'dog'
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).
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;
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.
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
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)
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()))
Ruby 1.9 - 32
x=->{gets.chars.sort}
p x[]==x[]
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.
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...
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
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)
Clojure REPL 41 chars
(= (sort (read-line)) (sort (read-line)))
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)
}
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());
}
}
}
Matlab (24)
Given two strings a and b.
isequal(sort(a),sort(b))
Ruby (35)
a,b=ARGV;a.chars.sort==b.chars.sort
PHP (51 chars, compressed)
function d($s){$s=str_split($s);sort($s);return$s;}
(Split string into an array, sort the array and return)
Example:
var_dump(d("word")===d("drow"));
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);}
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()+""}
Another Ruby (46)
(a.size==b.size)&&(a<<b.count(a,b)==a<<b.size)
Ruby (40)
a.unpack('c*').sort==b.unpack('c*').sort
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.
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())
JavaScript (67)
function(a,b){return ""+a.split("").sort()==""+b.split("").sort()}
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
Clojure - 23 chars
As an anonymous function:
#(apply = (map sort %))
Test case example:
(#(apply = (map sort %)) ["boat" "boat"])
=> true
PHP (command line, 87 characters)
function d($s){
return array_count_values(str_split($s));
}
echo d($argv[1]) == d($argv[2]);
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
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?