On Sat, Feb 28, 2009 at 14:56, Chas. Owens <[email protected]> wrote:
snip
> This seems close to what you want, but it needs work to make it take
> steps larger than 1:
snip
Here is another version that takes steps larger than one:
#!/usr/bin/perl
use strict;
use warnings;
# 12345678901
# *
# 5/11 chance of moving right or left
# 1/11 chance of staying still
#
# 12345678901
# *
# 4/11 chance of moving left
# 6/11 change of moving right
# 1/11 chance of staying still
#
# and so on
sub random_move {
my ($pos, $max, $maxstep) = @_;
$maxstep = int $max/10 + 1 unless defined $maxstep;
my $left = ($pos - 1)/$max;
my $nomove = $left + 1/$max;
my $rand = rand;
my $move = (int rand $maxstep) + 1;
if ($rand < $left) {
$pos -= $move;
$pos = 1 if $pos < 1;
} elsif ($rand < $nomove) {
return $pos;
} else {
$pos += $move;
$pos = $max if $pos > $max;
}
return $pos;
}
my $max = 77;
my $pos = 1;
while (1) {
print
"|", #left wall
" " x ($pos - 1), #left space
"*", #position
" " x ($max - $pos), #right space
"|\n"; #right wall
$pos = random_move($pos, $max, 3);
select undef, undef, undef, .1;
}
--
Chas. Owens
wonkden.net
The most important skill a programmer can have is the ability to read.
--
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]
http://learn.perl.org/