Determine whether strings are anagrams

85

11

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

Tom Gullen

Posted 15 years ago

Reputation: 1 159

5Title request: Cod Elf, Go! – None – 9 years ago

109 answers in 13 views... wow! – Tom Gullen – 15 years ago

@Tom, because everyone wanted to prove that your comment about using a 64-bit integer was pointing in the wrong direction :P – Peter Taylor – 15 years ago

@user54200 Nah... it should be "Nag a ram Cod Elf, Go!"

– Erik the Outgolfer – 9 years ago

5"Falcon Rage, go mad!" – Geobits – 9 years ago

8My name suggestion: "are they anagrams" → "manage the arrays" – Esolanging Fruit – 8 years ago

Answers

39

Python, 32 bytes

f=lambda a,b,S=sorted:S(a)==S(b)

gnibbler

Posted 15 years ago

Reputation: 14 170

Even in questions that allow you to write a function, usually the input to the function has to be the string. I'd accept from operator import*;f=lambda x,S=sorted:eq(*map(S,x.split(', '))) or something similar... – Alex Van Liew – 10 years ago

Nice one!it makes me inquisitive to learn about lambda. – Quixotic – 15 years ago

3@Debanjan, This is just the same as def f(a,b):return sorted(a)==sorted(b) The trade off is that you get to replace def+return with lambda in exchange for not using any statements – gnibbler – 15 years ago

Yes,and it's also saves few keystrokes,in my answer i further modified your answer to 2 bytes shorter :-) – Quixotic – 15 years ago

1@Debanjan, I think it only saves you one character. I have used a variation here, but it works out the same length as yours because I swap a newline for a comma – gnibbler – 15 years ago

1I have one question,this approach does require calling of input and print and other stripping functions right? – Quixotic – 15 years ago

1You don't need to include the f=. – Oliver Ni – 9 years ago

f(*'word,wrdo'.split(',')) – poke – 15 years ago

Doesn't work. Does nothing when I run it in python. You have to write a complete program! – Tomas – 12 years ago

4@Tomas, nonsense. The question doesn't specify complete program, so either a function or a complete program are acceptable. – gnibbler – 12 years ago

Have you seen the input and output in the question? Input is "toab, boat" and output is "true". Your code doesn't accomlish that. – Tomas – 12 years ago

2@Tomas, The majority of answers here fail to pass your criteria. Why not give an upvote to all those that do? – gnibbler – 12 years ago

You are correct, this answer is cluttered with nonsense answers that fail not my criteria, but the challenge criteria. I don't even see the few correct answers in this bulk of noise. Thanks god the rest of the site is not a pure rule abuse like in this thread. – Tomas – 12 years ago

One more thing: rule abuse is not an excuse to do it also, especially not when you are a moderator.. – Tomas – 12 years ago

4

@Tomas, it's not rule abuse. Some questions are deliberately openended like this one appears to be. Compare with a well specified question like this. If you don't like these answers complain to the question asker

– gnibbler – 12 years ago

27

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

YOU

Posted 15 years ago

Reputation: 4 321

6

This isn't valid by our current rules. You could, however, change it to @JanDvorak's 4-byte function, which would accept input via a valid input format.

– Doorknob – 9 years ago

1@doorknob, I wouldn't know current rules at 2011. do as you wish, while you have power. – YOU – 9 years ago

23This is an interesting interpretation of how to supply the input :) – gnibbler – 15 years ago

5Explanation please :( – st0le – 15 years ago

10@st0le, seriously? I don't know golfscript, but it's obviously (sort), (sort), = (compare) – Peter Taylor – 15 years ago

1to correctly handle the input use something like ", "/~$/$= – user1502040 – 12 years ago

11Isn't this cheating a little? I mean, it isn't variable input. It has to be hard-coded. In any case, I would add 4 to the character count for the quote (') characters. – Thomas Eding – 14 years ago

3As a function: $\$= – John Dvorak – 11 years ago

20

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?

J B

Posted 15 years ago

Reputation: 9 638

Is it not possible to write functions/subroutines in J? – None – 15 years ago

2@Tim Nordenfur: they're called "verbs", and take either one argument on their right as in v arg (monads) or two on both sides as in arg1 v arg2 (dyads). The one I submitted is obviously a dyad. I didn't bother to name it, since it wasn't requested and is shorter this way. Should you really want to give it a name, you'd do that like this: is_anagram_of =: -:&(/:~) and then use as 'a' is_anagram_of 'aa'. – J B – 15 years ago

It felt a bit cheap to substitute the arguments into the code, but I see now that it's essentially a dyad. Never mind. – None – 15 years ago

29J always looks like the remains of an emoticon factory explosion. – st0le – 15 years ago

19

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"));

Tom Gullen

Posted 15 years ago

Reputation: 1 159

Great idea using primes. – None – 15 years ago

@Tim thanks! Got it down to 157 now. – Tom Gullen – 15 years ago

2You can shave a couple of characters off the dictionary initialisation using the sieve. a=[2];for(p=3,j=0;j<26;)if(a[j]){if(p%a[j++]==0){p++;j=0}}else{a[j]=p;j=0} – Peter Taylor – 15 years ago

I feel like I read about this trick on some blog talking about interview questions... – Yahel – 15 years ago

@yc01, you may well have read about it in a book about computation theory. It's a classic way of encoding tuples for systems such as the Minsky register machine. – Peter Taylor – 15 years ago

@Peter, thanks! I think it's important to note with this technique it will be miles faster than anything else, as no sorting is involved. – Tom Gullen – 15 years ago

1@Tom, depends on how well optimised the sorting routines are, given that you've limited inputs to 8 characters :P – Peter Taylor – 15 years ago

@Peter, a sorting algorithm best case would be O(n), realistically though this is not the case especially when using built in sorting algorithms. Multiplying the values is always O(n) with very little overhead as well. I was thinking about uses for this, and I think it would be a fast generic algorithm for search engines to find typos in user inputs, but they probably just use some sort of synonym list which is more efficient. – Tom Gullen – 15 years ago

@Tom, not so. If you're going to bring big-O notation into it then you have to start taking account of the fact that (over a 26-char alphabet) a 64-bit integer is only good for 9 characters. Beyond that the size of the integer required is O(n), and multiplication is not O(1). But for very small inputs you've got to weigh the extra costs of sorting (which may well have special cases for n up to about 8) against the extra costs of handling the primes. – Peter Taylor – 15 years ago

You can shorten the code more by initializing j and p to 2 within the dictionary's initialization, looping to 28, and then in b change 97 to 95. Also, you can initialize i in the primes generator and save another character there. – David Murdoch – 15 years ago

Because stackexchange will not implement multi-line comments I'm just going to spam this space with an explanation as to why I'm posting a revised code-snippet in a separate comment. – David Murdoch – 15 years ago

a=[r=j=p=2];for(;j<28;)if(a[j]){if(p%a[j++]==0){p++;i=j=0}}else{a[j]=p;j=0}function b(c){for(;i<c.length;i++)r*=a[c[i].charCodeAt(0)-95];return r} – David Murdoch – 15 years ago

In the snippet above I'm also initializing r to 2 instead of 1...it saves another character. I don't think this will mess up any results; the unique ids will just be 2x larger. In total, the changes I made bring it down to 146 characters. – David Murdoch – 15 years ago

@David, awesome thanks! – Tom Gullen – 15 years ago

Would it be cheating to pass c.length in as a parameter I wonder – Tom Gullen – 15 years ago

hrm, initializing r outside of b() causes it to not work. – David Murdoch – 15 years ago

1125 characters. Recursion and ternaries FTW: for(a=[j=p=2];j<123;)a[j]?p%a[++j]<1&&p++&&(j=0):(a[j]=p,j=0);function b(c,i){return c[i=i||0]?a[c.charCodeAt(i)]*b(c,++i):1} – David Murdoch – 15 years ago

@David, that's ridiculously clever well done! – Tom Gullen – 15 years ago

@Peter I remember, I'd seen it here: http://news.ycombinator.com/item?id=1923298, but it was used in an answer to a different question. Still very cool, +1.

– Yahel – 15 years ago

@David, you applied a trick once which could be applied twice: replacing p++&&(j=0) with (p++,j=0) saves a character. But you're overflowing a long with 'zzzzzzz', so proving correctness just got a whole lot harder. – Peter Taylor – 15 years ago

i was wonder about accuracy myself. I tested "zzzzzzzz"!="zzzzzzzy" and it was false so I called it a day. :-) – David Murdoch – 15 years ago

Not much longer then a more "standard" approach of: function t(a,b){a.split('').forEach(function(t){if(b.indexOf(t)==-1)return !1;});return(a.length==b.length)} 108 chars – path411 – 14 years ago

15

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

gnibbler

Posted 15 years ago

Reputation: 14 170

11

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.

Joey Adams

Posted 15 years ago

Reputation: 9 929

Can Haskell code that only does what's wanted under runghc, but not when compiled, still be called "program"? – J B – 15 years ago

3@J B: Can Perl code that only does what's wanted under perl still be called a "program"? :-) – Joey Adams – 15 years ago

J B: Todays functional languages skew the meaning of a program making it a higher order abstraction. Rather than just a list of instruction to be executed, as haskell program can just be seen as a collection of functions, even if they are not called. – Callum Rogers – 15 years ago

@Callum Rogers: my point is: his code behaves differently whether run under runghc or compiled, in a problem-sensitive area. The "function" is fine. The "program" does not solve the problem under anything else than runghc, and runghc is not the only legitimate way to run Haskell programs. In that context, that makes the snippet a "runghc script", not a "Haskell program". --not that I'd consider the issue important, as I said, the function is fine anyway and it's shorter. – J B – 15 years ago

I think you missed the "but not when compiled" part of my comment :-) – J B – 15 years ago

Where is the List module? Is that in some utterly ancient base library, or somewhere else? – dfeuer – 7 years ago

@dfeuer Does this not compile with modern GHC? It exists in Haskell 98, but maybe they got rid of it for good in Haskell 2010.

– Joey Adams – 7 years ago

@JoeyAdams, the List module moved into the haskell98 compatibility package many years ago, when hierarchical modules showed up. As far as I can tell, that package is only available for GHC versions up to 7.8. I'm not sure if support was withdrawn intentionally, or if no one's gotten around to updating it in the last few years. – dfeuer – 7 years ago

Alternate 55 char solution: import List main=fmap(length.nub.map sort.words)getLine – Thomas Eding – 14 years ago

2x#y=sort x==sort y is 1 character shorter – Rotsor – 14 years ago

10

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(_ => _)));
        }
    }
}

Timwi

Posted 15 years ago

Reputation: 12 158

I think you could golf a few bytes with using System.Linq; instead of namespacing it? – Stackstuck – 7 years ago

10

Ruby, 34 bytes

Using the IO scheme of Peter Taylors Perl solution:

p gets.chars.sort==gets.chars.sort

steenslag

Posted 15 years ago

Reputation: 2 070

Throws an error: -e:1:in '<main>': undefined method 'chars' for nil:NilClass (NoMethodError) – Tomas – 12 years ago

9

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");}

Joey Adams

Posted 15 years ago

Reputation: 9 929

1Just saw this one... Very nice. But can be shorter: t[256],i;main(c){for(;c+3;)(i=getchar())>10?t[i]+=c:(c-=2);for(i=257;--i&&!t[i-1];);puts(i?"false":"true");} - that's 108 characters. Very importantly, your c initialization trick is still employed. – ugoren – 14 years ago

@ugoren: Nice. You add 1 for each character typed in the first line, then subtract 1 for each character typed in the second line. – Joey Adams – 11 years ago

1

Ever considered applying for IOCCC?

– Mateen Ulhaq – 15 years ago

9@muntoo: have you seen anything in the IOCCC? This is way too readable for that. – R. Martinho Fernandes – 15 years ago

@Martinho Yes, the IOCCC source codes are so beautiful. Symphonies. But he should at least try composing a small piece. :) – Mateen Ulhaq – 15 years ago

@muntoo: I didn't even know they were still active. – Joey Adams – 15 years ago

7

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"}

Timwi

Posted 15 years ago

Reputation: 12 158

I prefer this as ($c,$d)=map{[sort split//]}@ARGV;exit("@$c"ne"@$d") (51 chars) so it can take command line arguments and use the command line exit codes. It'd be 48 chars retaining <> with a multi-line input. – Adam Katz – 10 years ago

of course you can save 4 chars in the program by removing the " around true and false, since without using strict/warnings a bareword is a string. – Joel Berger – 14 years ago

Thanks! – Timwi – 14 years ago

6

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;
}

Matthew Read

Posted 15 years ago

Reputation: 521

In C, if you declare a variable in the global scope, it is initialized to zero. I guess this is also true for C++. – Joey Adams – 15 years ago

Local variables, on the other hand, are not initialized to zero automatically. – Joey Adams – 15 years ago

OK, I removed my caveat since I found ways to do without it. – Matthew Read – 15 years ago

If you call the above function a() with 2 words not anagrams, the next time one call that function can be not return the right result without zeroing the array u[123] – RosLuP – 9 years ago

@RosLuP Code golf is for the shortest programs that solve the problem ("Given two strings..."), not for reliability. You should also probably not bother critiquing posts here that are more than 5 years old. – Matthew Read – 9 years ago

1Bzzzt. You pass the test cases, but "helle" and "hollo" are apparently the same. Easy fix: change one of the ++ to a --. Then just if (u[i++]) return 0; – Dave Gamble – 15 years ago

@Dave Thanks for the catch, I was originally using 2 arrays and didn't think about that when I removed one. Best part is, the correction makes it shorter! – Matthew Read – 15 years ago

1I haven't tested this, but the last three lines can be written as i=123;while(i&&u[--i]);return!i; – st0le – 14 years ago

@st0le Brilliant, thanks (you just missed a !). – Matthew Read – 14 years ago

@MatthewRead, doh! :) – st0le – 14 years ago

6

Clojure - 23 chars

As an anonymous function:

#(apply = (map sort %))

Test case example:

(#(apply = (map sort %)) ["boat" "boat"])
=> true

mikera

Posted 15 years ago

Reputation: 1 233

1Nice answer. I particularly like the test strings you chose ;-) – coredump – 10 years ago

Cool, I like it. – Chiron – 14 years ago

6

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()+""}

user796

Posted 15 years ago

Reputation:

Clever using the +"" to coerce to string. – Casey Chu – 14 years ago

4

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.

user475

Posted 15 years ago

Reputation:

4

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)

Peter Taylor

Posted 15 years ago

Reputation: 41 901

Something is wrong. $a=;? Also, you can skip the parens of sort and the space after print. – None – 15 years ago

@Tim, the genius who developed this platform for sharing code over the net decided that in code blocks people should have to escape less-than characters. But hey, no big deal: it's not as though anyone uses them in code, right? Keeps catching me out. – Peter Taylor – 15 years ago

2Ok, I removed the downvote. You might want to use the code formatting in the future, i.e. indent code with four spaces. – None – 15 years ago

1Ok, so there are three ways of formatting code (one inline and two block), and both the block ones are inconvenient in different ways. Sigh. – Peter Taylor – 15 years ago

4

PHP (command line, 87 characters)

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

echo d($argv[1]) == d($argv[2]);

ts01

Posted 15 years ago

Reputation: 111

4

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"...

Wooble

Posted 15 years ago

Reputation: 139

You can shave off a few characters if you append ;s=sorted to the first line and then replace the two instances of sorted with s in the second line. Should save... 3 characters? – Alex Van Liew – 10 years ago

1Indeed. Python 3 also saves a bit of space, and is probably reasonable to use now, 5 years after this answer was posted. Also, the .strip() was redundant, given the specified inputs. – Wooble – 10 years ago

Yeah, sorry. I didn't notice how old this question was when I commented, only that it was on the frontpage. ^^; – Alex Van Liew – 10 years ago

4

Python, 32 bytes

p=sorted
f=lambda a,b:p(a)==p(b)

Quixotic

Posted 15 years ago

Reputation: 2 199

1@Tomas It's a function – TuxCrafting – 9 years ago

Does nothing in python. Are you sure it is a complete program that takes the input and produces the output as requested? – Tomas – 12 years ago

4

Bash, 88 characters

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

Martin

Posted 15 years ago

Reputation: 111

4

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

Blair Mitchelmore

Posted 15 years ago

Reputation: 131

3this is answer ID 1337. congratz – TheDoctor – 10 years ago

4

Clojure REPL 41 chars

(= (sort (read-line)) (sort (read-line)))

Squid

Posted 15 years ago

Reputation: 101

Welcome to the Stack Exchange network. Formatting help here.

– dmckee --- ex-moderator kitten – 15 years ago

4

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...

Greg Schueler

Posted 15 years ago

Reputation: 151

I know it's been more than 6.5 years (lol), but you can golf it by 10 bytes by adding java.util.Arrays x=null; and use x. instead of Arrays.: class g{public static void main(String[]p){java.util.Arrays x=null;String[]a=p[0].split(""),b=p[1].split("");x.sort(a);x.sort(b);System.out.print(x.equals(a,b));}} (163 bytes) And by converting it to Java 8, class g{public static void main could be interface g{static void main as well, but I guess Java 8 wasn't around yet in 2011, so keeping class is also fine. ;p

– Kevin Cruijssen – 8 years ago

4

R, 54 bytes

function(x,y,`~`=sort,`+`=utf8ToInt)identical(~+x,~+y)

Try it online!

J.Doe

Posted 15 years ago

Reputation: 2 379

I'm highly intrigued by your use of utf8ToInt, not only in this answer, but in many others that I have seen. – Sumner18 – 7 years ago

1

Have you seen tips for golfing in R? utf8ToInt and its reverse tend to make for shorter string-splitting than the conventional functions.

– J.Doe – 7 years ago

4

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/}

Tomas

Posted 15 years ago

Reputation: 2 333

4

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

Tobia

Posted 15 years ago

Reputation: 5 455

Just curious, how many bytes is this? 4? 6? – Maltysen – 11 years ago

It depends on the encoding. 6 bytes in UTF-8, 4 bytes in UCS-2, 2 bytes if any of the legacy single-byte APL charsets have the symbol, which I doubt. – Tobia – 11 years ago

4

05AB1E, 6 4 bytes (non-competing)

{I{Q

Try it online!

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.

Geno Racklin Asher

Posted 15 years ago

Reputation: 466

1Since 05AB1E is newer than this challenge, this answer is non-competing. – Loovjo – 9 years ago

Sorry - didn't realise. – Geno Racklin Asher – 9 years ago

3

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.

zzzzBov

Posted 15 years ago

Reputation: 2 915

38 bytes: c=>d=>(a=b=>''+[...b].sort())(c)==a(d) – Shieru Asakoto – 7 years ago

3

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.

ebruchez

Posted 15 years ago

Reputation: 101

3

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.

Elias Mårtenson

Posted 15 years ago

Reputation: 209

3

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.

codecubed

Posted 15 years ago

Reputation: 131

1Welcome to PPCG! Nice first post! There are 2 spaces you can remove, (c[0], c[1]) and for (int i=0;. – Rɪᴋᴇʀ – 9 years ago

2

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())

Hoa Long Tam

Posted 15 years ago

Reputation: 1 902

Mwahaha, first time I see a Python solution longer than C# :) – Timwi – 15 years ago

1Won't this return True for aab, bba? – gnibbler – 15 years ago

@gnibbler; Yes, it will, I wasn't thinking this morning. Fixed – Hoa Long Tam – 15 years ago

2

JavaScript (67)

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

Sophistifunk

Posted 15 years ago

Reputation: 111

Wanted to post the same solution before I even saw yours – dwana – 11 years ago

2

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.

user775

Posted 15 years ago

Reputation:

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 – None – 15 years ago

2

Ruby (40)

a.unpack('c*').sort==b.unpack('c*').sort

user793

Posted 15 years ago

Reputation:

I've formatted your code for you. The tool bar above the edit box has the most commonly used functions, and the sidebar has a link to more detailed info. – dmckee --- ex-moderator kitten – 15 years ago

2

Another Ruby (46)

(a.size==b.size)&&(a<<b.count(a,b)==a<<b.size)

user792

Posted 15 years ago

Reputation:

2

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);}

Dave Gamble

Posted 15 years ago

Reputation: 101

2

Ruby 1.9 - 32

x=->{gets.chars.sort}
p x[]==x[]

david4dev

Posted 15 years ago

Reputation: 665

Cool! x=->{gets.sum} passes the test cases but is kind of a cheat. – Jonas Elfström – 15 years ago

BTW, why 1.9.1 and not 1.9.2? It works in 1.9.2. – Jonas Elfström – 15 years ago

That's just the version of Ruby 1.9 I have. – david4dev – 15 years ago

2

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

Magnus Holm

Posted 15 years ago

Reputation: 277

(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 $.

– Jordan – 9 years ago

Finally a nice solution that works! – Tomas – 12 years ago

2

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.

MegaTom

Posted 15 years ago

Reputation: 3 787

2

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.

Unrelated String

Posted 15 years ago

Reputation: 5 300

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). – Unrelated String – 7 years ago

2

Matlab: 10 characters without using sort

a*a'==b*b'

Dennis Jaheruddin

Posted 15 years ago

Reputation: 1 848

2

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

Cruor

Posted 15 years ago

Reputation: 31

2

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

Mints97

Posted 15 years ago

Reputation: 561

2

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

Paolo

Posted 15 years ago

Reputation: 696

1Why not simply f=function(x,y) identical(sort(strsplit(x,"")[[1]]),sort(strsplit(y,"")[[1]]))? – plannapus – 12 years ago

You're completely right! Stupid me! I replaced the code with your solution. – Paolo – 12 years ago

2

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.

JPeroutek

Posted 15 years ago

Reputation: 734

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! :)

– Martin Ender – 10 years ago

I got this to 8 bytes: !.{SMczd. If you accept input in the form ['wrod','word'], you can get it to 6 bytes: !.{SMQ. – kirbyfan64sos – 10 years ago

Also, you can replace !.{ with qF, giving you 7 bytes with the current input method and 5 with the other one I mentioned. – kirbyfan64sos – 10 years ago

Thank you both! I made a note mentioning how the answer is valid for the problem, and changed my code accordingly. – JPeroutek – 10 years ago

2

PHP, 44 Bytes

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

Jörg Hülsermann

Posted 15 years ago

Reputation: 13 026

2

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.

Dom Hastings

Posted 15 years ago

Reputation: 16 415

1

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");
}

Karl Napf

Posted 15 years ago

Reputation: 4 131

1

Jelly, 3 bytes (probably non-competing)

Ṣ€E

Try it online!

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

Erik the Outgolfer

Posted 15 years ago

Reputation: 38 134

1

Mathematica 28 Bytes

Split into list of characters, sort and test for equality.

Equal@@ Sort/@Characters[#]&

Usage

%@{"BOAT", "TOAB"}

Output

True

Kelly Lowder

Posted 15 years ago

Reputation: 3 225

1

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

jpjacobs

Posted 15 years ago

Reputation: 3 440

1

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)}}

Gareth

Posted 15 years ago

Reputation: 11 678

1You can use sorted instead of sortWith. I posted another reply with sorted as well as REPL and function versions. – ebruchez – 15 years ago

@ebruchez Thanks, I'm just learning Scala at the moment and these make good exercises. :-) – Gareth – 15 years ago

Still learning myself ;) – ebruchez – 15 years ago

1

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))

Will Hardy

Posted 15 years ago

Reputation: 111

1

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())

MAK

Posted 15 years ago

Reputation: 111

1

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)

Dave Gamble

Posted 15 years ago

Reputation: 101

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.

– dmckee --- ex-moderator kitten – 15 years ago

Cheers. Edited :) – Dave Gamble – 15 years ago

1

Matlab (24)

Given two strings a and b.

isequal(sort(a),sort(b))

Hannesh

Posted 15 years ago

Reputation: 1 013

1

Common Lisp, 50 bytes

(lambda(a b)(string=(sort a'char<)(sort b'char<)))

Try it online!

Renzo

Posted 15 years ago

Reputation: 2 260

1

Perl 5, 27 + 3 (-lF) = 30 bytes

@{$.}=sort@F}{say"@1"eq"@2"

Try it online!

Xcali

Posted 15 years ago

Reputation: 7 671

The -l option is not needed. It would still count as +3 though since you must count the space too (since you cannot bundle the -F with -E. You can however do the final match using @1~~@2 saving 4 bytes (or 3 if you add an extra X option letter to supress the warning). Very neat solution by the way. Have a +1 – Ton Hospel – 8 years ago

1

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.

barrycarter

Posted 15 years ago

Reputation: 179

1

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()))

user1011

Posted 15 years ago

Reputation:

Shave one character by changing import * to import*. – Steven Rumbalski – 14 years ago

I tried your challenge of not using sorted, but also avoided using collections.Counter. Best I was able to get was 66 character. – Steven Rumbalski – 14 years ago

1

SmileBASIC, 49 bytes

INPUT A$,B$WHILE""<A$B$[INSTR(B$,POP(A$))]="
WEND

Throws an error when the strings aren't anagrams.

12Me21

Posted 15 years ago

Reputation: 6 110

1

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 "".

user2428118

Posted 15 years ago

Reputation: 2 000

1

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

Dan the Man

Posted 15 years ago

Reputation: 141

1

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)

cemper93

Posted 15 years ago

Reputation: 670

1

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

Flonk

Posted 15 years ago

Reputation: 7 621

1

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

mikera

Posted 15 years ago

Reputation: 1 233

1

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))

Steven Rumbalski

Posted 15 years ago

Reputation: 1 353

good use of semicolons! – Andbdrew – 14 years ago

1

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

frank

Posted 15 years ago

Reputation: 21

1If you take input as a list of two strings you can do slightly better: ~/{x@<x}'("baot";"boat") – JohnE – 10 years ago

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

Maltysen

Posted 15 years ago

Reputation: 25 023

How would qSS work? I am trying to learn pyth and I am curious. – ericmarkmartin – 11 years ago

@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 – Maltysen – 11 years ago

1

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

tmartin

Posted 15 years ago

Reputation: 3 917

1

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");}

Cole Cameron

Posted 15 years ago

Reputation: 1 013

1

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.

AdmBorkBork

Posted 15 years ago

Reputation: 41 581

1

C, (108)

char c[192]={};main(){for(;*a;c[127-*a++]++);for(;*b;c[223-*b++]++);puts(memcmp(c,c+96,95)?"false":"true");}

ehmu

Posted 15 years ago

Reputation: 11

1

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

J. Sendra

Posted 15 years ago

Reputation: 396

If you're using k rather than Q you can just do ~/x@'<:'x: for 10 bytes. No need to create the outer function f nor the inner function if you set x to be the input. – streetster – 8 years ago

0

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

James Brown

Posted 15 years ago

Reputation: 663

0

Japt, 10 9 5 4 bytes

á øV

Try it

á øV     :Implicit input of strings U & V
á        :Permutations of U
  øV     :Contains V?

Shaggy

Posted 15 years ago

Reputation: 24 623

As of v2.0a0, ¬n eV¬n works with 7 bytes.

– Bubbler – 7 years ago

øVá – Oliver – 7 years ago

0

APL (Dyalog), 10 bytes

≡/(⊂∘⍋⌷⊢)¨

Try it online!

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

user41805

Posted 15 years ago

Reputation: 16 320

0

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
$

Simon Whitaker

Posted 15 years ago

Reputation: 101

0

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)
}

richardtallent

Posted 15 years ago

Reputation: 101

It is likely that the downvotes are because you have made no effort to golf (see the tag?) your solutions, or because you have mixed several distinct solutions in one answer.

– dmckee --- ex-moderator kitten – 15 years ago

1Meh. If I play real golf, it's for socializing or beer, not score-keeping. Guess I should have actually been playing to win... :) – richardtallent – 15 years ago

People generally respond well to solutions in wordy languages (I play in Fortran 77 from time to time), as long as you make an effort to write aggressively compacted <wordy language>, and especially if your languages supports a interesting trick (i.e. fortran has computed branches). – dmckee --- ex-moderator kitten – 15 years ago

0

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"));

user353

Posted 15 years ago

Reputation:

0

Ruby (35)

a,b=ARGV;a.chars.sort==b.chars.sort

user814

Posted 15 years ago

Reputation:

1(Five years later...) $* is a handy alias for ARGV for 2 bytes. – Jordan – 9 years ago

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());
        }
    }
}

Yngve B-Nilsen

Posted 15 years ago

Reputation: 151

You can remove an extra character: string[]a

You also don't need a namespace. – ICR – 14 years ago

0

Groovy, 54

print args[0].toList().sort()==args[1].toList().sort()

Espen Schulstad

Posted 15 years ago

Reputation: 441

I've fixed up the formatting for you. Stack Exchange site use MarkDown (though they do accept a subset of html). THe sidebar on the edit page has some hints, the edit toolbar has common operations, and there is a detailed help page.

– dmckee --- ex-moderator kitten – 15 years ago

0

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))]

Taylor Scott

Posted 15 years ago

Reputation: 6 709

0

Wolfram Language 26 bytes ( Mathematica )

ContainsAll@@Characters@#&

Usage:

%@{"BOAT","TOAB"}

Output:

True

Vitaliy Kaurov

Posted 15 years ago

Reputation: 1 561

0

J, 8 bytes

-:&(/:~)

Match -: after sorting /:~ both args &.

Try it online!

Jonah

Posted 15 years ago

Reputation: 8 729

0

Axiom, 45 bytes

f(a:String,b:String):Boolean==sort(a)=sort(b)

RosLuP

Posted 15 years ago

Reputation: 3 036

0

Julia, 41 bytes

g(a,b)=sort(collect(a))==sort(collect(b))

EricShermanCS

Posted 15 years ago

Reputation: 121

0

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)

Try it Online!

Recursively finds all permutations of x and compares them to y.

Zachary Cotton

Posted 15 years ago

Reputation: 679

0

Tcl, 82 bytes

proc A x\ y {expr {[string le $x]==[string le $y]&[lsort -u [split $x $y]]=="{}"}}

Try it online!


Tcl, 83 bytes

proc A x\ y {expr {[string le $x]==[string le $y]&&[lsort -u [split $x $y]]=="{}"}}

Try it online!

Tcl, 84 bytes

proc S s {lsort [split $s ""]}
proc A x\ y {set x [S $x]
set y [S $y]
expr {$x==$y}}

Try it online!

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!


Tcl, 94 bytes

proc S s {join [lsort [split $s ""]] ""}
proc A x\ y {set x [S $x]
set y [S $y]
expr {$x==$y}}

Try it online!

sergiol

Posted 15 years ago

Reputation: 3 055

0

Pyth, 4 bytes

_ISM

Try it Online

Explanation

_ISM
  SMQ   Sort both (implicit) inputs.
_I      Check if the result is invariant under reversing.

user48543

Posted 15 years ago

Reputation:

0

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'

Ton Hospel

Posted 15 years ago

Reputation: 14 114

0

MathGolf, 4 bytes

ms~=

Try it online!

Explanation

m      explicit map
 s     sort(array)
  ~    dump array to stack
   =   pop(a, b), push(a==b)

maxb

Posted 15 years ago

Reputation: 5 754

0

Pepe, 58 bytes

REEREEEEeEERREEeREEEEeEeErRREEEEEeEEreerrEEREEeeReEErEereE

Try it online! Input is in the form a;b. Outputs 0 for truthy and none for falsy.

u_ndefined

Posted 15 years ago

Reputation: 1 253

0

Pushy, 13 bytes

Assumes the two inputs are separated by a space.

K32-$v;.gFgx#

Try it online!

                 \ 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)

FlipTack

Posted 15 years ago

Reputation: 13 242

0

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;}

Try it online!

Destroigo

Posted 15 years ago

Reputation: 401

0

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

cfenner

Posted 15 years ago

Reputation: 1

0

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

WallyWest

Posted 15 years ago

Reputation: 6 949

0

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");
        }   
    }
}

Boopathi

Posted 15 years ago

Reputation: 179

0

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;}

user3188175

Posted 15 years ago

Reputation: 329

0

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

christofsteel

Posted 15 years ago

Reputation: 11

0

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

Adam Speight

Posted 15 years ago

Reputation: 1 234

0

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");
}

bacchusbeale

Posted 15 years ago

Reputation: 1 235

This can not be ok every input... What about string has the same value example "caa" and "bba" ? – RosLuP – 7 years ago

0

Groovy 44

def f(a,b){print !(a-b)&&a.size()==b.size()}

md_rasler

Posted 15 years ago

Reputation: 201

0

Groovy 42

def f(a,b){print ((b as Set)==(a as Set))}

md_rasler

Posted 15 years ago

Reputation: 201

0

Python, 20 bytes

lose to golfscript again...... :(

sorted(x)==sorted(y)

Maltysen

Posted 15 years ago

Reputation: 59

This will work, but it does not include the parsing of x and y, which can contribute to the length of the answer. – ericmarkmartin – 11 years ago

0

PHP (71)

function a($a){while($i<$r=strlen($a))$t+=ord($a[$i++]);return"$r|$t";}

Use:

echo (a("abc")==a("cba"));

moteutsch

Posted 15 years ago

Reputation: 121

The equality check should be part of the function (and therefore, the character count). And I'm not even sure that this would solve the problem - wouldn't a("ad")==a("bc") return true? – Gareth – 13 years ago

0

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.

alun

Posted 15 years ago

Reputation: 101

0

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).

Harry K.

Posted 15 years ago

Reputation: 215

You use the table 256 char; if you call that function more that one time it is necessary make that 256 table 0. – RosLuP – 9 years ago

0

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'

Andbdrew

Posted 15 years ago

Reputation: 221

You can save 2 characters by changing the import to from sys import* (newline) s=argv. – Steven Rumbalski – 14 years ago

Algorithm fails with s[1]='the',s[2]='them'. – Steven Rumbalski – 14 years ago

You could avoid the need to dereference s by from sys import* (newline) _,a,b=argv. – Steven Rumbalski – 14 years ago

0

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;

oenone

Posted 15 years ago

Reputation: 161

0

Coffee Script (52)

a=(b,c)->`b.split('').sort()==c.split('').sort()+''`

usage

console.log a 'god', 'dog'

Billy Moon

Posted 15 years ago

Reputation: 101

0

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

F. Hauri

Posted 15 years ago

Reputation: 2 654

0

Javascript - 57 chars

function o(a,b){return b?o(a)==o(b):1+a.split("").sort()}

Kevin Wu

Posted 15 years ago

Reputation: 49

1Your function will fail if in the first try, b was empty. – Optimizer – 11 years ago

All inputs will be at least 1 char long, you give the function the 2 strings you want to compare so that won't happen – Kevin Wu – 11 years ago

@Optimizer did you even try running it? – Kevin Wu – 11 years ago

Ah, I see. In that case, it will be fine. – Optimizer – 11 years ago

0

Groovy, 46

b={args[it].toList().sort()}
print b(0)==b(1)

Armand

Posted 15 years ago

Reputation: 499

0

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.

Averroes

Posted 15 years ago

Reputation: 3 771

So it's no shorter but it is buggier? – Peter Taylor – 14 years ago

Hmmm... Why buggier? – Averroes – 14 years ago

Maybe this? "The behavior of this method when this string cannot be encoded in the default charset is unspecified." :P – Averroes – 14 years ago

My bad, forgot to check the spec. I was thinking about characters in the range \u0080 to the end of the BMP, which become more than one byte, and which would allow collisions. – Peter Taylor – 14 years ago

0

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!

ericmarkmartin

Posted 15 years ago

Reputation: 323

0

Ruby, 32

h=->{gets.chars.sort}
p h[]==h[]

nwhirschfeld

Posted 15 years ago

Reputation: 1

0

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.

SuperJedi224

Posted 15 years ago

Reputation: 11 342

0

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.

Live demo and all test cases.

kirbyfan64sos

Posted 15 years ago

Reputation: 8 730

0

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.

Johno

Posted 15 years ago

Reputation: 301

0

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

lethern

Posted 15 years ago

Reputation: 1

Welcome to PPCG! Since you're using ES6, you could replace split('')... with split``... to save two bytes. – ETHproductions – 10 years ago

You can also shave off 3 bytes by replacing x.split\`` with [...x] – Scott – 9 years ago

0

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)

Mutador

Posted 15 years ago

Reputation: 1 361

Passing the test cases does not necessary make a working function. Your function only works when the number of unique characters in s is equal to the number of characters in m. For instance, s="boatee" and m="toobee" yields TRUE, when it should actually be FALSE. – Sumner18 – 7 years ago

0

Powershell 48 bytes

param([char[]]$a,[char[]]$b)![bool](diff $a $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).

Jonathan Leech-Pepin

Posted 15 years ago

Reputation: 273

0

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/

Liam Newmarch

Posted 15 years ago

Reputation: 101

0

Pyke, 4 bytes (non-competing)

Pyke is FAR newer than this challenge

mSXq

Try it here!

Also 4 bytes

SRSq

Try it here!

Blue

Posted 15 years ago

Reputation: 26 661

0

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.

Try it online!

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.

Martin Ender

Posted 15 years ago

Reputation: 184 808

0

Jelly, 5 Bytes (Non-competitive)

Ṣ⁼⁴Ṣ¤

Special thanks to Leaky Nun for helping me fix a problem.

Outputs one if true. Try it Online!

X88B88

Posted 15 years ago

Reputation: 91

0

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.

user5957401

Posted 15 years ago

Reputation: 699

0

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

rnso

Posted 15 years ago

Reputation: 1 635

0

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))

user1492032

Posted 15 years ago

Reputation: 11

0

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);
}

RosLuP

Posted 15 years ago

Reputation: 3 036

1Please do not vandalize your posts. – James – 9 years ago

0

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);
}

RosLuP

Posted 15 years ago

Reputation: 3 036

How it is possible 20 min ago I not remember a C solution less than 109 bytes, now I read C solutions less bytes than 80 bytes edited in 2011... – RosLuP – 9 years ago