Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Perl > Perl Misc > random bits efficiently

Reply
Thread Tools

random bits efficiently

 
 
jidanni@jidanni.org
Guest
Posts: n/a
 
      09-21-2009
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.
 
Reply With Quote
 
 
 
 
Danny Woods
Guest
Posts: n/a
 
      09-21-2009
http://www.velocityreviews.com/forums/(E-Mail Removed) writes:

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

 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
Math.random() and Math.round(Math.random()) and Math.floor(Math.random()*2) VK Javascript 15 05-02-2010 03:43 PM
How to efficiently get a random set of records from a DB Laphan ASP General 4 10-03-2008 08:51 PM
random.random(), random not defined!? globalrev Python 4 04-20-2008 08:12 AM
Efficiently generating bits nish.sinnadurai@gmail.com C Programming 3 07-16-2006 03:58 PM
8-Bits vs 12 or 16 bits/pixel; When does more than 8 bits count ? Al Dykes Digital Photography 3 12-29-2003 07:08 PM



Advertisments