aboutsummaryrefslogtreecommitdiff
path: root/bin/rndi.awk
diff options
context:
space:
mode:
authorTom Ryder <tom@sanctum.geek.nz>2017-07-02 17:36:37 +1200
committerTom Ryder <tom@sanctum.geek.nz>2017-07-02 22:57:07 +1200
commit95276f25769a0607cda50041169197d0522b98ff (patch)
tree3a4738901390c94f76de6ee7b6394d39b4c1ed00 /bin/rndi.awk
parentCoerce seed to number (diff)
downloaddotfiles-95276f25769a0607cda50041169197d0522b98ff.tar.gz
dotfiles-95276f25769a0607cda50041169197d0522b98ff.zip
Lots of cleanup of awk scripts
Mostly inspired by suggestions from gawk --lint
Diffstat (limited to 'bin/rndi.awk')
-rw-r--r--bin/rndi.awk35
1 files changed, 28 insertions, 7 deletions
diff --git a/bin/rndi.awk b/bin/rndi.awk
index 49df4398..07c69bc7 100644
--- a/bin/rndi.awk
+++ b/bin/rndi.awk
@@ -1,20 +1,41 @@
# Get a low-quality random number between two integers. Depending on the awk
-# implementation, if you don't provide a third argument (a seed), you might get
-# very predictable random numbers based on the current epoch second.
+# implementation, if you don't have rnds(1df) available to generate a seed of
+# sufficient quality, you might get very predictable random numbers based on
+# the current epoch second.
BEGIN {
+ self = "rndi"
- # Seed with the third argument if given
- if (ARGV[3])
- srand(ARGV[3])
+ # Check we have two arguments
+ if (ARGC != 3)
+ fail("Need a lower and upper bound")
- # If not, just seed with what is probably a date/time-derived value
+ # Floor args and check for sanity
+ lower = int(ARGV[1] + 0)
+ upper = int(ARGV[2] + 0)
+ if (lower >= upper)
+ fail("Bounds must be numeric, first lower than second")
+
+ # Seed the random number generator
+ rnds = "rnds 2>/dev/null"
+ rnds | getline seed
+ close(rnds)
+ if (length(seed))
+ srand(seed + 0)
else
srand()
# Print a random integer bounded by the first and second arguments
- print int(ARGV[1] + rand() * (ARGV[2] - ARGV[1] + 1))
+ print int(lower + rand() * (upper - lower + 1))
# Bail before processing any lines
exit
}
+
+# Bailout function
+function fail(str) {
+ stderr = "cat >&2"
+ printf "%s: %s\n", self, str | stderr
+ close(stderr)
+ exit(2)
+}