random bits efficiently

J

jidanni

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.
 
D

Danny Woods

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'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) ? "-" : "_");
}

Cheers,
Danny.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top