Code golf: find all anagrams

后端 未结 8 2022
再見小時候
再見小時候 2021-02-04 06:00

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

相关标签:
8条回答
  • 2021-02-04 06:05

    C++, 542 chars

    #include <iostream>
    #include <map>
    #include <vector>
    #include <boost/algorithm/string.hpp>
    #define ci const_iterator
    int main(){using namespace std;typedef string s;typedef vector<s> vs;vs l;
    copy(istream_iterator<s>(cin),istream_iterator<s>(),back_inserter(l));map<s, vs> r;
    for (vs::ci i=l.begin(),e=l.end();i!=e;++i){s a=boost::to_lower_copy(*i);
    sort(a.begin(),a.end());r[a].push_back(*i);}for (map<s,vs>::ci i=r.begin(),e=r.end();
    i!=e;++i)if(i->second.size()>1)*copy(i->second.begin(),i->second.end(),
    ostream_iterator<s>(cout," "))="\n";}
    
    0 讨论(0)
  • 2021-02-04 06:05

    Python, O(n^2)

    import sys;
    words=sys.stdin.readlines()
    def s(x):return sorted(x.lower());
    print '\n'.join([''.join([a.replace('\n',' ') for a in words if(s(a)==s(w))]) for w in words])
    
    0 讨论(0)
  • 2021-02-04 06:10

    Python, 167 characters, includes I/O

    import sys
    d={}
    for l in sys.stdin.readlines():
     l=l[:-1]
     k=''.join(sorted(l)).lower()
     d[k]=d.pop(k,[])+[l]
    for k in d:
     if len(d[k])>1: print(' '.join(d[k]))
    

    Without the input code (i.e. if we assume the wordlist already in a list w), it's only 134 characters:

    d={}
    for l in w:
     l=l[:-1]
     k=''.join(lower(sorted(l)))
     d[k]=d.pop(k,[])+[l]
    for k in d:
     if len(d[k])>1: print(' '.join(d[k]))
    
    0 讨论(0)
  • 2021-02-04 06:15

    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.

    0 讨论(0)
  • 2021-02-04 06:18

    Perl, 59 characters

    chop,$_{join'',sort split//,lc}.="$_ "for<>;/ ./&&say for%_
    

    Note that this requires Perl 5.10 (for the say function).

    0 讨论(0)
  • 2021-02-04 06:22

    Ruby, 94 characters

    h={};(h[$_.upcase.bytes.sort]||=[])<<$_ while gets&&chomp;h.each{|k,v|puts v.join' 'if v.at 1}
    
    0 讨论(0)
提交回复
热议问题