random bits efficiently

Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

Threaded View

Gentlemen, no big deal, but in
$ w3m -dump http://en.wikipedia.org/wiki/Talk:The_Hum |grep -A1 perl
$ perl -we 'for(0..33){print int rand 2?"_":"-"}'

how could I make such strings more efficiently, perhaps via
pack(), unpack(), vec(), sprintf "%b", tr/01/_-/, etc.?

I.e., I want to print a line of random _ and -'s. However, being a nerd,
I want to know the most efficient, even though I'm only doing it once in
a lifetime, for that Wikipedia comment, which you are welcome to add to too.

Re: random bits efficiently

jidanni@jidanni.org writes:

Quoted text here. Click to load it

I'm suspicious of the repeated calls to rand().  Nothing quite beats
avoiding function calls if at all possible, so my (half-hearted, wide
open to criticism/corrections) attempt looks like this:

for ( $value = rand(2 ** 32), $mask = 1 << (32 - 1) ; $mask ; $mask >>= 1 )
  print (($value & $mask) ? "-" : "_");


Site Timeline