random bits efficiently

Discussion in 'Perl Misc' started by jidanni@jidanni.org, Sep 21, 2009.

  1. Guest

    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.
     
    , Sep 21, 2009
    #1
    1. Advertising

  2. Danny Woods Guest

    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.
     
    Danny Woods, Sep 21, 2009
    #2
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. GGG
    Replies:
    10
    Views:
    12,566
    Donar
    Jul 6, 2006
  2. Efficiently generating bits

    , Jul 16, 2006, in forum: C Programming
    Replies:
    3
    Views:
    350
  3. globalrev
    Replies:
    4
    Views:
    771
    Gabriel Genellina
    Apr 20, 2008
  4. Laphan
    Replies:
    4
    Views:
    178
  5. VK
    Replies:
    15
    Views:
    1,175
    Dr J R Stockton
    May 2, 2010
Loading...

Share This Page