aboutsummaryrefslogtreecommitdiff
path: root/challenge-005/paulo-custodio/awk/ch-1.awk
blob: 24251da5d9fac23241df769c7964774e2e3ee42a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
#!/usr/bin/gawk

# Challenge 005
#
# Challenge #1
# Write a program which prints out all anagrams for a given word. For more
# information about Anagram, please check this wikipedia page.
# create a hash of all words in dictionary where key is sorted list of letters
# therefore two anagrams have the same key

function alen(a, i, k) {
    k = 0;
    for(i in a) k++;
    return k;
}

function join(array, start, end, sep,    result, i) {
    if (sep == "")
       sep = " ";
    else if (sep == SUBSEP) # magic value
       sep = "";
    result = array[start];
    for (i = start + 1; i <= end; i++)
        result = result sep array[i];
    return result;
}

function word_key(word,    i, letters, key) {
    for (i = 1; i <= length(word); i++)
        letters[i] = substr(word, i, 1);
    asort(letters);
    key = join(letters, 1, alen(letters), SUBSEP);
    return key;
}

BEGIN {
    word = tolower(ARGV[1]);
    key = word_key(word);
    while ((getline word < "words.txt") > 0 ) {
        word = tolower(word);
        if (word_key(word) == key)
            print word;
    }
    exit 0;
}