Apache/2.4.7 (Ubuntu) Linux sman1baleendah 3.13.0-24-generic #46-Ubuntu SMP Thu Apr 10 19:11:08 UTC 2014 x86_64 uid=33(www-data) gid=33(www-data) groups=33(www-data) safemode : OFF MySQL: ON | Perl: ON | cURL: OFF | WGet: ON > / usr / share / doc / gawk / examples / prog / | server ip : 104.21.89.46 your ip : 172.69.130.125 H O M E |
Filename | /usr/share/doc/gawk/examples/prog/anagram.awk |
Size | 1.32 kb |
Permission | rw-r--r-- |
Owner | root : root |
Create time | 27-Apr-2025 09:55 |
Last modified | 29-Mar-2012 04:03 |
Last accessed | 08-Jul-2025 06:18 |
Actions | edit | rename | delete | download (gzip) |
View | text | code | image |
# anagram.awk --- An implementation of the anagram finding algorithm
# from Jon Bentley's "Programming Pearls", 2nd edition.
# Addison Wesley, 2000, ISBN 0-201-65788-0.
# Column 2, Problem C, section 2.8, pp 18-20.
#
# This program requires gawk 4.0 or newer.
# Required gawk-specific features:
# - True multidimensional arrays
# - split() with "" as separator splits out individual characters
# - asort() and asorti() functions
#
# See http://savannah.gnu.org/projects/gawk.
#
# Arnold Robbins
# [email protected]
# Public Domain
# January, 2011
/'s$/ { next } # Skip possessives
{
key = word2key($1) # Build signature
data[key][$1] = $1 # Store word with signature
}
# word2key --- split word apart into letters, sort, joining back together
function word2key(word, a, i, n, result)
{
n = split(word, a, "")
asort(a)
for (i = 1; i <= n; i++)
result = result a[i]
return result
}
END {
sort = "sort"
for (key in data) {
# Sort words with same key
nwords = asorti(data[key], words)
if (nwords == 1)
continue
# And print. Minor glitch: trailing space at end of each line
for (j = 1; j <= nwords; j++)
printf("%s ", words[j]) | sort
print "" | sort
}
close(sort)
}
# from Jon Bentley's "Programming Pearls", 2nd edition.
# Addison Wesley, 2000, ISBN 0-201-65788-0.
# Column 2, Problem C, section 2.8, pp 18-20.
#
# This program requires gawk 4.0 or newer.
# Required gawk-specific features:
# - True multidimensional arrays
# - split() with "" as separator splits out individual characters
# - asort() and asorti() functions
#
# See http://savannah.gnu.org/projects/gawk.
#
# Arnold Robbins
# [email protected]
# Public Domain
# January, 2011
/'s$/ { next } # Skip possessives
{
key = word2key($1) # Build signature
data[key][$1] = $1 # Store word with signature
}
# word2key --- split word apart into letters, sort, joining back together
function word2key(word, a, i, n, result)
{
n = split(word, a, "")
asort(a)
for (i = 1; i <= n; i++)
result = result a[i]
return result
}
END {
sort = "sort"
for (key in data) {
# Sort words with same key
nwords = asorti(data[key], words)
if (nwords == 1)
continue
# And print. Minor glitch: trailing space at end of each line
for (j = 1; j <= nwords; j++)
printf("%s ", words[j]) | sort
print "" | sort
}
close(sort)
}