Code golf: find all anagrams

2019-03-12 10:58发布

A word is an anagram if the letters in that word can be re-arranged to form a different word.

Task:

  • The shortest source code by character count to find all sets of anagrams given a word list.
  • Spaces and new lines should be counted as characters
  • Use the code ruler

    ---------10--------20--------30--------40--------50--------60--------70--------80--------90--------100-------110-------120

Input:

a list of words from stdin with each word separated by a new line.

e.g.

A
A's
AOL
AOL's
Aachen
Aachen's
Aaliyah
Aaliyah's
Aaron
Aaron's
Abbas
Abbasid
Abbasid's

Output:

All sets of anagrams, with each set separated by a separate line.

Example run:

./anagram < words
marcos caroms macros
lump's plum's
dewar's wader's
postman tampons
dent tend
macho mocha
stoker's stroke's
hops posh shop
chasity scythia
...

I have a 149 char perl solution which I'll post as soon as a few more people post :)

Have fun!

EDIT: Clarifications

  • Assume anagrams are case insensitive (i.e. upper and lower case letters are equivalent)
  • Only sets with more than 1 item should be printed
  • Each set of anagrams should only be printed once
  • Each word in an anagram set should only occur once

EDIT2: More Clarifications

  • If two words differ only in capitalization, they should be collapsed into the same word, and it's up to you to decide which capitalization scheme to use for the collapsed word
  • sets of words only have to end in a new line, as long as each word is separated in some way, e.g. comma separated, or space separated is valid. I understand some languages have quick array printing methods built in so this should allow you to take advantage of that if it doesn't output space separated arrays.

8条回答
\"骚年 ilove
2楼-- · 2019-03-12 11:53

AWK - 119

{split(toupper($1),a,"");asort(a);s="";for(i=1;a[i];)s=a[i++]s;x[s]=x[s]$1" "}
END{for(i in x)if(x[i]~/ .* /)print x[i]}

AWK does not have a join function like Python, or it could have been shorter...

It assumes uppercase and lowercase as different.

查看更多
混吃等死
3楼-- · 2019-03-12 11:57

Ruby, 94 characters

h={};(h[$_.upcase.bytes.sort]||=[])<<$_ while gets&&chomp;h.each{|k,v|puts v.join' 'if v.at 1}
查看更多
登录 后发表回答