Find all words containing characters in UNIX

后端 未结 6 950
误落风尘
误落风尘 2021-02-14 15:18

Given a word W, I want to find all words containing the letters in W from /usr/dict/words. For example, \"bat\" should return \"bat\" and \"tab\" (but not \"table\").

He

6条回答
  •  长情又很酷
    2021-02-14 15:42

    So we have the following:

    n = length of input word
    L = lines in dictionary file

    If n tends to be small and L tends to be huge, might we be better off finding all permutations of the input word and looking for those, rather than doing something (like sorting) to all L lines of the dictionary file? (Actually, since finding all permutations of a word is O(n!), and we have to run through the entire dictionary file once for each word, maybe not, but I wrote the code anyway.)

    This is Perl - I know you wanted command-line operations but I don't have a way to do that in shell script that's not super-hacky:

    sub dedupe {
        my (@list) = @_;
        my (@new_list, %seen_entries, $entry);
    
        foreach $entry (@list) {
            if (!(defined($seen_entries{$entry}))) {
                push(@new_list, $entry);
                $seen_entries{$entry} = 1;
            }
        }
    
        return @new_list;
    }
    
    sub find_all_permutations {
        my ($word) = @_;
        my (@permutations, $subword, $letter, $rest_of_word, $i);
    
        if (length($word) == 1) {
            push(@permutations, $word);
        } else {   
            for ($i=0; $i

提交回复
热议问题