The Random Walker Printer
Matlab, 112
The core idea is generating a list of possible next positions and then uniformly drawing one of them. If we are e.g. at position $l=1$ the possible steps would be [-1,0,1,2,3]
Of course if we would chose -1
that would be invalid and we would have to stay at the same position. Thats why we replace the invalid positions with the current position, [1,0,1,2,3]
, and then randomly chose an element from this updated list.
The OP asked us tho draw the program, so here we go:
The transcription:
function c(n,s);
l=19; %initialize position
for k=1:n;
disp([ones(1,l)*32,'.']); %print the line
z=(-2:2)+l; %get vector of possible next steps (for l=1 we get [-1,0,1,2,3])
z(z<0)=l; %prune invalids: here we just replace the the invalid positions with the current position
z(z>39)=l; % this ensures the same behaivour as staying in the same spot when going outside of the range
l=z(randi(5)); %draw random sample of those
pause(s);
end
Perl, 136 128 116 106 101 90 86
$p=19;map{say$"x$p.".";sleep $ARGV[0];$x=rand(5)+$p-2;$p=$x>0&&$x<40?$x:$p}1..$ARGV[1]
Requires the seconds to be an integer.
Run with perl <filename> <second delay> <number of steps>
.
There may be more golfing potential here, although honestly, I'm surprised it got this far. (Come on, only 6 more bytes to beat the bash answer...)
Changes
- Saved 8 bytes by removing unneeded parentheses and spelling out ARGV (it's actually shorter that way)
- Saved 12 more bytes by removing
$s
and$n
and just using the plain$ARGV[0]
and$ARGV[1]
- Saved another 10 bytes when I realized I could use
$"
and didn't need to specifically define$u
as$undef
. - Saved 5 more bytes by rearranging the ternary and how
$x
is used and by usingmap
instead offor
. - Saved 11 bytes by no longer accepting the seconds as decimals (challenge spec says it's OK.)
- Saved another 5 bytes by using
say
instead ofprint
.
Pyth, 39
J19VEK+.d0QW<.d0K)+*d=JhtS[Z39-+O5J2)\.
Takes s
as the first line of input and n
as the second. Works on the command line but not with the online interpreter. My first Pyth program ever! Golfing tips are appreciated.