Friday, December 30, 2011

A Random Coupon Generator Written in Awk

Here is an awk script I use to generate 100 random 8-character coupon codes.

Each character has 62 possibilities (a-z, A-Z, and 0-9). This means there are 8^62 possible coupon codes.

BEGIN {

s="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"

srand()

for (i=1;i<=100;i++){ code="" for (j=1;j<=8;j++) code = code""substr(s,int(rand()*62)+1,1) print code } } Let's analyze the script. First, we set string s to hold all 62 possible characters.

Next, we call srand() to seed awk's random number generator. We left the argument blank, so that the current date is used for seeding.

We now loop 100 times, because we want to output 100 coupon codes.

In this loop, we first set the coupon code back to the empty string. Then, we have an inner loop that executes 8 times to build the code. Finally, we print the code.

Notice the command in the inner loop. This command uses the random (rand) function. Since rand() returns a number greater or equal to 0, and less than 1, we multiply it by 62 and use the integer (int) function.

This will return a number between 0 and 61. Why? Because int(0*62) = int(0) = 0 and int(.999...*62) = int(61.99...) = 61.

We then add 1 to the result to get a random number from 1-62. We then use this result in the substr function to randomly pick a character.

1 comments:

Unix Tech said...

Very nice. I've often used this little python script for similar purposes:

#!/bin/env python

import random

chars = "abcdefghijklmnopqrstuvwxyz"
chars = chars + chars.upper() + "0123456789"
print "".join([random.choice(chars) for i in xrange(8)])