diff options
author | Arnold D. Robbins <arnold@skeeve.com> | 2011-02-02 21:52:08 +0200 |
---|---|---|
committer | Arnold D. Robbins <arnold@skeeve.com> | 2011-02-02 21:52:08 +0200 |
commit | 8fae548a67ddd263e10fd80e768ac8906de7e576 (patch) | |
tree | 762bb383df3c39e8e4dc23af5dc1840203745783 /awklib | |
parent | c1b65c4a24b99a52022c6048e97e45e2ce474bce (diff) | |
download | egawk-8fae548a67ddd263e10fd80e768ac8906de7e576.tar.gz egawk-8fae548a67ddd263e10fd80e768ac8906de7e576.tar.bz2 egawk-8fae548a67ddd263e10fd80e768ac8906de7e576.zip |
Add more documentation, isarray, anagrams.
Diffstat (limited to 'awklib')
-rw-r--r-- | awklib/eg/lib/walkarray.awk | 9 | ||||
-rw-r--r-- | awklib/eg/prog/anagram.awk | 50 |
2 files changed, 59 insertions, 0 deletions
diff --git a/awklib/eg/lib/walkarray.awk b/awklib/eg/lib/walkarray.awk new file mode 100644 index 00000000..5e36f46f --- /dev/null +++ b/awklib/eg/lib/walkarray.awk @@ -0,0 +1,9 @@ +function walk_array(arr, name, i) +{ + for (i in arr) { + if (isarray(arr[i])) + walk_array(arr[i], (name "[" i "]")) + else + printf("%s[%s] = %s\n", name, i, arr[i]) + } +} diff --git a/awklib/eg/prog/anagram.awk b/awklib/eg/prog/anagram.awk new file mode 100644 index 00000000..550e9580 --- /dev/null +++ b/awklib/eg/prog/anagram.awk @@ -0,0 +1,50 @@ +# 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 separater splits out individual characters +# - asort() and asorti() functions +# +# See http://savannah.gnu.org/projects/gawk. +# +# Arnold Robbins +# arnold@skeeve.com +# 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) +} |