In C/C++, rand()
and srand()
are usually used by us when we want to get a random integer. But when I tried to rewrite it myself, I found it difficu
Prior to calling rand, since the man page for srand indicates that "If no seed value is provided, the rand() function is automatically seeded with a value of 1", then a better approach to invoking rand is to first invoke srand which will "set its argument as the seed for a new sequence of pseudo-random integers to be returned by rand()".
As an example, consider the following awk, nawk, gawk code which is used in a bash shell script to create a new (random) mac address - i.e. .genmacaddr referenced in code snippet:
enter code here
BEGIN {
n0 = "00"
srand()
n1 = sprintf("%02x", int(255 * rand()))
n2 = sprintf("%02x", int(255 * rand()))
n3 = sprintf("%02x", int(255 * rand()))
n4 = sprintf("%02x", int(255 * rand()))
n5 = sprintf("%02x", int(255 * rand()))
print n0":"n1":"n2":"n3":"n4":"n5
}
where the code snippet in the bash shell script is:
enter code here
ifconfig eth0 down
newmacaddr=`nawk -f .genmacaddr -`
ifconfig eth0 hw ether $newmacaddr
ifconfig eth0 up
If I am not mistaken, the seed value for srand is derived from the system clock.
I hope this helps you to understand an approach to your coding solution that will work.