Beefy Boxes and Bandwidth Generously Provided by pair Networks
more useful options
 
PerlMonks  

Re: randomly generating A-Za-z

by thinker (Parson)
on Oct 12, 2001 at 18:02 UTC ( [id://118479]=note: print w/replies, xml ) Need Help??


in reply to randomly generating A-Za-z

Hi princepawn,

Here's my solution. I'm sure it's not as efficient as some of the others, but its mine, and I like it.:-)

sub letter{ return rand(2)%2 ? chr rand(26)+65 : chr rand(26)+97; }
Fortunately chr() rounds down the random value, saving a couple of int() calls.
I hope this is correct.
cheers

thinker

Replies are listed 'Best First'.
Re: Re: randomly generating A-Za-z
by belden (Friar) on Oct 13, 2001 at 00:32 UTC
    Hi thinker
    I'm sure it's not as efficient as some of the others,
    but its mine, and I like it.:-)

    Looking back up the thread, I see plenty of hyperefficient
    solutions to this. Well, here's my shot at the least efficient
    solution... apologies to princepawn who probably isn't aided
    in the least by this post

    sub fisher_yates() { for(my $i = @_; --$i) { my $j = int rand ($i+1); next if $j == $i; @_[$i,$j] = @_[$j,$i]; } return @_; } sub letter() { for(@_) { my $k = int(rand 52) - 1; return chr $_[$k] if($_[$k] eq $_); } &letter; } # &letter isn't completely random... # print(&letter(65..90,97..122),"\n"); # ...so use Perl Cookbook's Fisher- # Yate Shuffle to randomize the list print(&letter(&fisher_yates(65..90,97..122),"\n");

    blyman

    Update: Running above code several times has
    confirmed my initial suspicion: &letter() as written is
    more likely to return an 'A' than a 'z'. Fixed this by adding
    a Fisher-Yates shuffle; this helps fulfill my original goal
    of writing the least-efficient algorithm for returning a
    random letter...

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://118479]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others cooling their heels in the Monastery: (7)
As of 2024-04-16 10:10 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found