Python -> Piet, 385 345 char
It's possible to generate any Piet program with this. I could've just stopped at random pixels, but I wanted to make "interesting" programs. The function m
paints a pixel a color, and recursively steps into each of that pixels neighbors. There are better ways to draw random blobs, but this is tuned to terminate in a reasonable number of steps, so it's good enough for golf. The function R(w,h,n)
draws n random blobs onto a (w x h) white image, and prints the result in PPM format.
I'm especially proud of how I generate the colors -- for a random choice of 0 <= c < 20
,
`[0,192,255][int(x)]`for x in'0002212220200101121100'[c:c+3]
is the decimal code for a valid color in the Piet palette by way of a single-track Gray code. That is, each color is represented by 3 adjacent bits, and every slice '0003...0'[c:c+3]
represents a different color. Since this isn't the full list of 27 words on 3 letters, I really lucked out in finding the Gray code.
from random import*
r=randint
def R(w,h,n):
M=[6]*h*w
def m(x,y,c,d):M[y%h*w+x%w]=c;t=r(0,15)*(r(0,d)<2);t&8and m(x+1,y,c,d+1);t&4and m(x-1,y,c,d+1);t&2and m(x,y+1,c,d+1);t&1and m(x,y-1,c,d+1)
while n:m(r(0,w),r(0,h),r(0,19),0);n-=1
print"P3 %s %s 255 "%(w,h)+' '.join(`[0,192,255][int(x)]`for c in M for x in'0002212220200101121100'[c:c+3])
Sample output, generated by the command R(30,40,500)
Without the import, I can write it as a proper (semicolon-free) 1-liner, too:
import random
R=(lambda P,I,E,T:lambda w,h,n:E(w,h,I(w,h,n,lambda z,c,d,t:sum((((z,c),)*t*T(0,1)or m((z[0]+a,z[1]+b),c,d+1,T(0,d)>1)for a,b in((0,1),(1,0),(-1,0),(0,-1))),()))))(range,lambda w,h,n,m:dict(sum((m((T(0,w),T(0,h)),T(0,19),0,0)for _ in P(n)),())),lambda w,h,M:"P3 %s %s 255 "%(w,h)+' '.join(' '.join(`(x&1)*255+(x&2)*96`for x in map(int,'0001121110100202212200'[c:c+3]))for c in(M[z]if z in M else 6for z in((x,y)for y in P(h)for x in P(w)))),random.randint)
but it's ridiculously slow (and almost 100 characters longer)... though I'm not entirely sure why (and not terribly inclined to find out).
main(seed) { return 4; // Chosen by dice roll - Guaranteed to be random }
Reference \$\endgroup\$