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