[Question]
  [
**Closed**. This question needs to be more [focused](/help/closed-questions). It is not currently accepting answers.
 
 
Closed 8 years ago.
**Locked**. This question and its answers are [locked](/help/locked-posts) because the question is off-topic but has historical significance. It is not currently accepting new answers or interactions.
 
 
Integer math can generate amazing patterns when laid out over a grid. Even the most basic functions can yield stunningly elaborate designs!
# Your challenge
Write 3 Tweetable (meaning 140 characters or less) function bodies for the red, green, and blue values for a 1024x1024 image.
The input to the functions will be two integers i (column number for the given pixel) and j (row number for the given pixel) and the output will be an unsigned short between 0 and 1023, inclusive, which represents the amount of the given color present in the pixel (i,j).
For example, the following three functions produce the picture below:
```
/* RED */
    return (unsigned short)sqrt((double)(_sq(i-DIM/2)*_sq(j-DIM/2))*2.0);
/* GREEN */
    return (unsigned short)sqrt((double)(
        (_sq(i-DIM/2)|_sq(j-DIM/2))*
        (_sq(i-DIM/2)&_sq(j-DIM/2))
    )); 
/* BLUE */
    return (unsigned short)sqrt((double)(_sq(i-DIM/2)&_sq(j-DIM/2))*2.0);
```
![Pattern-1](https://i.stack.imgur.com/da9MA.jpg)
```
/* RED */
    return i&&j?(i%j)&(j%i):0;
/* GREEN */
    return i&&j?(i%j)+(j%i):0;
/* BLUE */
    return i&&j?(i%j)|(j%i):0;
```
![Pattern-2](https://i.stack.imgur.com/3z2pa.jpg)
# The Rules
* Given [this C++ code](http://pastebin.com/uQkCQGhz), substitute in your functions. I have provided a few macros and have included the library, and you may include complex.h. You may use any functions from these libraries and/or my macros. Please do not use any external resources beyond this.
* If that version isn't working for you, make sure you're compiling with:
```
g++ filename.cpp -std=c++11
```
If that doesn't work, please use the [alternate version](http://pastebin.com/12quxkA9) using unsigned chars instead of unsigned shorts.
Michaelangelo has provided a cleaned up [24-bit or 48-bit color output](http://pastebin.com/HWKWzebh) version.
* You may implement your own version in another language, but it must behave in the same way as the provided C++ version, and only functions from C++'s built-ins, the library, or the provided macros may be used to make it fair.
* Post only your three function bodies - please don't include my code in your post
* Please include either a smaller version or an embedded copy of your image. They are made into a ppm format and may need to be converted to another for proper viewing on stackexchange.
* Function bodies (not including signature) must be 140 characters or less.
* This is a popularity contest - most votes wins
  
[Answer]
# Table cloths
# Flat
I started out putting a plaid/gingham pattern into perspective like a boundless table cloth:
```
unsigned char RD(int i,int j){
    float s=3./(j+99);
    return (int((i+DIM)*s+j*s)%2+int((DIM*2-i)*s+j*s)%2)*127;
}
unsigned char GR(int i,int j){
    float s=3./(j+99);
    return (int((i+DIM)*s+j*s)%2+int((DIM*2-i)*s+j*s)%2)*127;
}
unsigned char BL(int i,int j){
    float s=3./(j+99);
    return (int((i+DIM)*s+j*s)%2+int((DIM*2-i)*s+j*s)%2)*127;
}
```
![flat table cloth](https://i.stack.imgur.com/boPfJ.png "flat table cloth")
# Ripple
Then I introduced a ripple (not strictly correct perspective, but still in 140 characters):
```
unsigned char RD(int i,int j){
    float s=3./(j+99);
    float y=(j+sin((i*i+_sq(j-700)*5)/100./DIM)*35)*s;
    return (int((i+DIM)*s+y)%2+int((DIM*2-i)*s+y)%2)*127;
}
unsigned char GR(int i,int j){
    float s=3./(j+99);
    float y=(j+sin((i*i+_sq(j-700)*5)/100./DIM)*35)*s;
    return (int((i+DIM)*s+y)%2+int((DIM*2-i)*s+y)%2)*127;
}
unsigned char BL(int i,int j){
    float s=3./(j+99);
    float y=(j+sin((i*i+_sq(j-700)*5)/100./DIM)*35)*s;
    return (int((i+DIM)*s+y)%2+int((DIM*2-i)*s+y)%2)*127;
}
```
![rippled table cloth](https://i.stack.imgur.com/LbR64.png "rippled table cloth")
# Colour
Then I made some of the colours more fine grained to give detail on a wider range of scales, and to make the picture more colourful...
```
unsigned char RD(int i,int j){
    float s=3./(j+99);
    float y=(j+sin((i*i+_sq(j-700)*5)/100./DIM)*35)*s;
    return (int((i+DIM)*s+y)%2+int((DIM*2-i)*s+y)%2)*127;
}
unsigned char GR(int i,int j){
    float s=3./(j+99);
    float y=(j+sin((i*i+_sq(j-700)*5)/100./DIM)*35)*s;
    return (int(5*((i+DIM)*s+y))%2+int(5*((DIM*2-i)*s+y))%2)*127;
}
unsigned char BL(int i,int j){
    float s=3./(j+99);
    float y=(j+sin((i*i+_sq(j-700)*5)/100./DIM)*35)*s;
    return (int(29*((i+DIM)*s+y))%2+int(29*((DIM*2-i)*s+y))%2)*127;
}
```
![coloured table cloth](https://i.stack.imgur.com/ril9E.png "coloured table cloth")
# In motion
Reducing the code just slightly more allows for defining a wave phase P with 2 decimal places, which is just enough for frames close enough for smooth animation. I've reduced the amplitude at this stage to avoid inducing sea sickness, and shifted the whole image up a further 151 pixels (at the cost of 1 extra character) to push the aliasing off the top of the image. Animated aliasing is mesmerising.
```
unsigned char RD(int i,int j){
#define P 6.03
float s=3./(j+250),y=(j+sin((i*i+_sq(j-700)*5)/100./DIM+P)*15)*s;return (int((i+DIM)*s+y)%2+int((DIM*2-i)*s+y)%2)*127;}
unsigned char GR(int i,int j){
float s=3./(j+250);
float y=(j+sin((i*i+_sq(j-700)*5)/100./DIM+P)*15)*s;
return (int(5*((i+DIM)*s+y))%2+int(5*((DIM*2-i)*s+y))%2)*127;}
unsigned char BL(int i,int j){
float s=3./(j+250);
float y=(j+sin((i*i+_sq(j-700)*5)/100./DIM+P)*15)*s;
return (int(29*((i+DIM)*s+y))%2+int(29*((DIM*2-i)*s+y))%2)*127;}
```
![animated table cloth](https://i.stack.imgur.com/8Pcmp.gif "animated table cloth")
[Answer]
## Random painter
![enter image description here](https://i.stack.imgur.com/8UAOh.png)
```
char red_fn(int i,int j){
#define r(n)(rand()%n)
    static char c[1024][1024];return!c[i][j]?c[i][j]=!r(999)?r(256):red_fn((i+r(2))%1024,(j+r(2))%1024):c[i][j];
}
char green_fn(int i,int j){
    static char c[1024][1024];return!c[i][j]?c[i][j]=!r(999)?r(256):green_fn((i+r(2))%1024,(j+r(2))%1024):c[i][j];
}
char blue_fn(int i,int j){
    static char c[1024][1024];return!c[i][j]?c[i][j]=!r(999)?r(256):blue_fn((i+r(2))%1024,(j+r(2))%1024):c[i][j];
}
```
Here is a randomness-based entry. For about 0.1% of the pixels it chooses a random colour, for the others it uses the same colour as a random adjacent pixel. Note that each colour does this independently, so this is actually just an overlay of a random green, blue and red picture. To get different results on different runs, you'll need to add `srand(time(NULL))` to the `main` function.
Now for some variations.
By skipping pixels we can make it a bit more blurry.
![enter image description here](https://i.stack.imgur.com/uy9s7.png)
And then we can slowly change the colours, where the overflows result in abrupt changes which make this look even more like brush strokes
![enter image description here](https://i.stack.imgur.com/JEsbA.jpg)
Things I need to figure out:
* For some reason I can't put `srand` within those functions without getting a segfault.
* If I could make the random walks the same across all three colours it might look a bit more orderly.
You can also make the random walk isotropic, like
```
static char c[1024][1024];return!c[i][j]?c[i][j]=r(999)?red_fn((i+r(5)+1022)%1024,(j+r(5)+1022)%1024):r(256):c[i][j];
```
to give you
![enter image description here](https://i.stack.imgur.com/pC84j.png)
## More random paintings
I've played around with this a bit more and created some other random paintings. Not all of these are possible within the limitations of this challenge, so I don't want to include them here. But you can see them in [**this imgur gallery**](https://i.stack.imgur.com/YhHgg.jpg) along with some descriptions of how I produced them.
I'm tempted to develop all these possibilities into a framework and put it on GitHub. (Not that stuff like this doesn't already exist, but it's fun anyway!)
[Answer]
# Some swirly pointy things
Yes, I knew exactly what to name it.
![Some swirly pointy things](https://i.stack.imgur.com/as0BL.png)
```
unsigned short RD(int i,int j){
    return(sqrt(_sq(73.-i)+_sq(609-j))+1)/(sqrt(abs(sin((sqrt(_sq(860.-i)+_sq(162-j)))/115.0)))+1)/200;
}
unsigned short GR(int i,int j){
    return(sqrt(_sq(160.-i)+_sq(60-j))+1)/(sqrt(abs(sin((sqrt(_sq(86.-i)+_sq(860-j)))/115.0)))+1)/200;
}
unsigned short BL(int i,int j){
    return(sqrt(_sq(844.-i)+_sq(200-j))+1)/(sqrt(abs(sin((sqrt(_sq(250.-i)+_sq(20-j)))/115.0)))+1)/200;
}
```
**EDIT:** No longer uses `pow`.
**EDIT 2:** @PhiNotPi pointed out that I don't need to use abs as much.
You can change the reference points pretty easily to get a different picture:
![Some more swirly pointy things](https://i.stack.imgur.com/4pEBN.png)
```
unsigned short RD(int i,int j){
    return(sqrt(_sq(148.-i)+_sq(1000-j))+1)/(sqrt(abs(sin((sqrt(_sq(500.-i)+_sq(400-j)))/115.0)))+1)/200;
}
unsigned short GR(int i,int j){
    return(sqrt(_sq(610.-i)+_sq(60-j))+1)/(sqrt(abs(sin((sqrt(_sq(864.-i)+_sq(860-j)))/115.0)))+1)/200;
}
unsigned short BL(int i,int j){
    return(sqrt(_sq(180.-i)+_sq(100-j))+1)/(sqrt(abs(sin((sqrt(_sq(503.-i)+_sq(103-j)))/115.0)))+1)/200;
}
```
@EricTressler pointed out that my pictures have Batman in them.
![Batman](https://i.stack.imgur.com/0IgLZ.png)
[Answer]
Of course, there has to be a Mandelbrot submission.
![enter image description here](https://i.stack.imgur.com/bJZHw.png)
```
char red_fn(int i,int j){
    float x=0,y=0;int k;for(k=0;k++<256;){float a=x*x-y*y+(i-768.0)/512;y=2*x*y+(j-512.0)/512;x=a;if(x*x+y*y>4)break;}return k>31?256:k*8;
}
char green_fn(int i,int j){
    float x=0,y=0;int k;for(k=0;k++<256;){float a=x*x-y*y+(i-768.0)/512;y=2*x*y+(j-512.0)/512;x=a;if(x*x+y*y>4)break;}return k>63?256:k*4;
}
char blue_fn(int i,int j){
    float x=0,y=0;int k;for(k=0;k++<256;){float a=x*x-y*y+(i-768.0)/512;y=2*x*y+(j-512.0)/512;x=a;if(x*x+y*y>4)break;}return k;
}
```
Trying to improve the colour scheme now. Is it cheating if I define the computation as a macro is `red_fn` and use that macro in the other two so I have more characters for fancy colour selection in green and blue?
**Edit:** It's really hard to come up with decent colour schemes with these few remaining bytes. Here is one other version:
```
/* RED   */ return log(k)*47;
/* GREEN */ return log(k)*47;
/* BLUE  */ return 128-log(k)*23;
```
![enter image description here](https://i.stack.imgur.com/ha0lJ.png)
And as per githubphagocyte's suggestion and with Todd Lehman's improvements, we can easily pick smaller sections:
E.g.
```
char red_fn(int i,int j){
    float x=0,y=0,k=0,X,Y;while(k++<256e2&&(X=x*x)+(Y=y*y)<4)y=2*x*y+(j-89500)/102400.,x=X-Y+(i-14680)/102400.;return log(k)/10.15*256;
}
char green_fn(int i,int j){
    float x=0,y=0,k=0,X,Y;while(k++<256e2&&(X=x*x)+(Y=y*y)<4)y=2*x*y+(j-89500)/102400.,x=X-Y+(i-14680)/102400.;return log(k)/10.15*256;
}
char blue_fn(int i,int j){
    float x=0,y=0,k=0,X,Y;while(k++<256e2&&(X=x*x)+(Y=y*y)<4)y=2*x*y+(j-89500)/102400.,x=X-Y+(i-14680)/102400.;return 128-k/200;
}
```
gives
![enter image description here](https://i.stack.imgur.com/20cg2.png)
[Answer]
## Mandelbrot 3 x 133 chars
The first thing that popped into my mind was "Mandelbrot!".
Yes, I know there already is a mandelbrot submission. After confirming that I'm able to get it below 140 characters myself, I have taken the tricks and optimizations from that solution into mine (thanks Martin and Todd). That left space to choose an interesting location and zoom, as well as a nice color theme:
![mandelbrot](https://i.stack.imgur.com/ogqlO.png)
```
unsigned char RD(int i,int j){
   double a=0,b=0,c,d,n=0;
   while((c=a*a)+(d=b*b)<4&&n++<880)
   {b=2*a*b+j*8e-9-.645411;a=c-d+i*8e-9+.356888;}
   return 255*pow((n-80)/800,3.);
}
unsigned char GR(int i,int j){
   double a=0,b=0,c,d,n=0;
   while((c=a*a)+(d=b*b)<4&&n++<880)
   {b=2*a*b+j*8e-9-.645411;a=c-d+i*8e-9+.356888;}
   return 255*pow((n-80)/800,.7);
}
unsigned char BL(int i,int j){
   double a=0,b=0,c,d,n=0;
   while((c=a*a)+(d=b*b)<4&&n++<880)
   {b=2*a*b+j*8e-9-.645411;a=c-d+i*8e-9+.356888;}
   return 255*pow((n-80)/800,.5);
}
```
## 132 chars total
I tried to get it down to 140 for all 3 channels. There is a bit of color noise near the edge, and the location is not as interesting as the first one, but: 132 chars
![mandelbrot-reduced](https://i.stack.imgur.com/zqGfD.png)
```
unsigned char RD(int i,int j){
  double a=0,b=0,d,n=0;
  for(;a*a+(d=b*b)<4&&n++<8192;b=2*a*b+j/5e4+.06,a=a*a-d+i/5e4+.34);
  return n/4;
}
unsigned char GR(int i,int j){
  return 2*RD(i,j);
}
unsigned char BL(int i,int j){
  return 4*RD(i,j);
}
```
[Answer]
# Julia sets
If there's a Mandelbrot, there should be a Julia set too.
![enter image description here](https://i.stack.imgur.com/LJMzd.png)
You can spend hours tweaking the parameters and functions, so this is just a quick one that looks decent.
Inspired from Martin's participation.
```
unsigned short red_fn(int i, int j){
#define D(x) (x-DIM/2.)/(DIM/2.)
float x=D(i),y=D(j),X,Y,n=0;while(n++<200&&(X=x*x)+(Y=y*y)<4){x=X-Y+.36237;y=2*x*y+.32;}return log(n)*256;}
unsigned short green_fn(int i, int j){
float x=D(i),y=D(j),X,Y,n=0;while(n++<200&&(x*x+y*y)<4){X=x;Y=y;x=X*X-Y*Y+-.7;y=2*X*Y+.27015;}return log(n)*128;}
unsigned short blue_fn(int i, int j){
float x=D(i),y=D(j),X,Y,n=0;while(n++<600&&(x*x+y*y)<4){X=x;Y=y;x=X*X-Y*Y+.36237;y=2*X*Y+.32;}return log(n)*128;}
```
# Would you like some RNG?
OK, Sparr's comment put me on the track to randomize the parameters of these little Julias. I first tried to do bit-level hacking with the result of `time(0)` but C++ doesn't allow hexadecimal floating point litterals so this was a dead-end (with my limited knowledge at least). I could have used some heavy casting to achieve it, but that wouldn't have fit into the 140 bytes.
I didn't have much room left anyway, so I had to drop the red Julia to put my macros and have a more conventional RNG (`time`d seed and real `rand()`, woohoo!).
![enter image description here](https://i.stack.imgur.com/AgjFi.png)
Whoops, something is missing. Obviously, these parameters have to be static or else you have some weird results (but funny, maybe I'll investigate a bit later if I find something interesting).
So here we are, with only green and blue channels:
![enter image description here](https://i.stack.imgur.com/7YgFy.png)
![enter image description here](https://i.stack.imgur.com/U1zez.png)
![enter image description here](https://i.stack.imgur.com/omSaB.png)
Now let's add a simple red pattern to fill the void. Not really imaginative, but I'm not a graphic programer ... yet :-)
![enter image description here](https://i.stack.imgur.com/MkvMA.jpg)
![enter image description here](https://i.stack.imgur.com/A9sIn.jpg)
And finally the new code with random parameters:
```
unsigned short red_fn(int i, int j){
static int n=1;if(n){--n;srand(time(0));}
#define R rand()/16384.-1
#define S static float r=R,k=R;float
return _cb(i^j);}
unsigned short green_fn(int i, int j){
#define D(x) (x-DIM/2.)/(DIM/2.),
S x=D(i)y=D(j)X,Y;int n=0;while(n++<200&&(X=x)*x+(Y=y)*y<4){x=X*X-Y*Y+r;y=2*X*Y+k;}return log(n)*512;}
unsigned short blue_fn(int i, int j){
S x=D(i)y=D(j)X,Y;int n=0;while(n++<200&&(X=x)*x+(Y=y)*y<4){x=X*X-Y*Y+r;y=2*X*Y+k;}return log(n)*512;}
```
There's still room left now ...
[Answer]
This one is interesting because it doesn't use the i, j parameters at all. Instead it remembers state in a static variable.
```
unsigned char RD(int i,int j){
   static double k;k+=rand()/1./RAND_MAX;int l=k;l%=512;return l>255?511-l:l;
}
unsigned char GR(int i,int j){
   static double k;k+=rand()/1./RAND_MAX;int l=k;l%=512;return l>255?511-l:l;
}
unsigned char BL(int i,int j){
   static double k;k+=rand()/1./RAND_MAX;int l=k;l%=512;return l>255?511-l:l;
}
```
![colorful](https://i.stack.imgur.com/55zop.png)
[Answer]
![Image](https://i.stack.imgur.com/568Tf.png)
```
/* RED */
    int a=(j?i%j:i)*4;int b=i-32;int c=j-32;return _sq(abs(i-512))+_sq(abs(j-512))>_sq(384)?a:int(sqrt((b+c)/2))^_cb((b-c)*2);
/* GREEN */
    int a=(j?i%j:i)*4;return _sq(abs(i-512))+_sq(abs(j-512))>_sq(384)?a:int(sqrt((i+j)/2))^_cb((i-j)*2);
/* BLUE */
    int a=(j?i%j:i)*4;int b=i+32;int c=j+32;return _sq(abs(i-512))+_sq(abs(j-512))>_sq(384)?a:int(sqrt((b+c)/2))^_cb((b-c)*2);
```
[Answer]
## Buddhabrot (+ Antibuddhabrot)
**Edit:** It's a proper Buddhabrot now!
**Edit:** I managed to cap the colour intensity within the byte limit, so there are no more falsely black pixels due to overflow.
I really wanted to stop after four... but...
![enter image description here](https://i.stack.imgur.com/eNqJu.jpg)
This gets slightly compressed during upload (and shrunk upon embedding) so if you want to admire all the detail, here is the interesting 512x512 cropped out (which doesn't get compressed and is displayed in its full size):
![enter image description here](https://i.stack.imgur.com/ao30A.png)
Thanks to githubphagocyte for the idea. This required some rather complicated abuse of all three colour functions:
```
unsigned short RD(int i,int j){
    #define f(a,b)for(a=0;++a<b;)
    #define D float x=0,y=0
    static int z,m,n;if(!z){z=1;f(m,4096)f(n,4096)BL(m-4096,n-4096);};return GR(i,j);
}
unsigned short GR(int i,int j){
    #define R a=x*x-y*y+i/1024.+2;y=2*x*y+j/1024.+2
    static float c[DIM][DIM],p;if(i>=0)return(p=c[i][j])>DM1?DM1:p;c[j+DIM][i/2+DIM]+=i%2*2+1;
}
unsigned short BL(int i,int j){
    D,a,k,p=0;if(i<0)f(k,5e5){R;x=a;if(x*x>4||y*y>4)break;GR(int((x-2)*256)*2-p,(y-2)*256);if(!p&&k==5e5-1){x=y=k=0;p=1;}}else{return GR(i,j);}
}
```
There are some bytes left for a better colour scheme, but so far I haven't found anything that beats the grey-scale image.
The code as given uses 4096x4096 starting points and does up to 500,000 iterations on each of them to determine if the trajectories escape or not. That took between 6 and 7 hours on my machine. You can get decent results with a 2k by 2k grid and 10k iterations, which takes two minutes, and even just a 1k by 1k grid with 1k iterations looks quite nice (that takes like 3 seconds). If you want to fiddle around with those parameters, there are a few places that need to change:
* To change the Mandelbrot recursion depth, adjust both instances of `5e5` in `BL` to your iteration count.
* To change the grid resolution, change all four `4096` in `RD` to your desired resolution and the `1024.` in `GR` by the same factor to maintain the correct scaling.
* You will probably also need to scale the `return c[i][j]` in `GR` since that only contains the absolute number of visits of each pixel. The maximum colour seems to be mostly independent of the iteration count and scales linearly with the total number of starting points. So if you want to use a 1k by 1k grid, you might want to `return c[i][j]*16;` or similar, but that factor sometimes needs some fiddling.
For those not familiar with the Buddhabrot (like myself a couple of days ago), it's based on the Mandelbrot computation, but each pixel's intensity is how often that pixel was visited in the iterations of the escaping trajectories. If we're counting the visits during non-escaping trajectories, it's an Antibuddhabrot. There is an even more sophisticated version called Nebulabrot where you use a different recursion depth for each colour channel. But I'll leave that to someone else. For more information, as always, [Wikipedia](http://en.wikipedia.org/wiki/Buddhabrot).
Originally, I didn't distinguish between escaping and non-escaping trajectories. That generated a plot which is the union of a Buddhabrot and an Antibuddhabrot (as pointed out by githubphagocyte).
```
unsigned short RD(int i,int j){
    #define f(a)for(a=0;++a<DIM;)
    static int z;float x=0,y=0,m,n,k;if(!z){z=1;f(m)f(n)GR(m-DIM,n-DIM);};return BL(i,j);
}
unsigned short GR(int i,int j){
    float x=0,y=0,a,k;if(i<0)f(k){a=x*x-y*y+(i+256.0)/512;y=2*x*y+(j+512.0)/512;x=a;if(x*x+y*y>4)break;BL((x-.6)*512,(y-1)*512);}return BL(i,j);
}
unsigned short BL(int i,int j){
    static float c[DIM][DIM];if(i<0&&i>-DIM-1&&j<0&&j>-DIM-1)c[j+DIM][i+DIM]++;else if(i>0&&i<DIM&&j>0&&j<DIM)return log(c[i][j])*110;
}
```
![enter image description here](https://i.stack.imgur.com/IEVQn.jpg)
This one looks a bit like a faded photograph... I like that.
[Answer]
# Sierpinski Pentagon
You may have seen the [chaos game](http://en.wikipedia.org/wiki/Sierpinski_triangle#Chaos_game "plotting Sierpinski's triangle by chaos game") method of approximating Sierpinski's Triangle by plotting points half way to a randomly chosen vertex. Here I have taken the same approach using 5 vertices. The shortest code I could settle on included hard coding the 5 vertices, and there was no way I was going to fit it all into 140 characters. So I've delegated the red component to a simple backdrop, and used the spare space in the red function to define a macro to bring the other two functions under 140 too. So everything is valid at the cost of having no red component in the pentagon.
```
unsigned char RD(int i,int j){
#define A int x=0,y=0,p[10]={512,9,0,381,196,981,827,981,DM1,381}
auto s=99./(j+99);return GR(i,j)?0:abs(53-int((3e3-i)*s+j*s)%107);}
unsigned char GR(int i,int j){static int c[DIM][DIM];if(i+j<1){A;for(int n=0;n<2e7;n++){int v=(rand()%11+1)%5*2;x+=p[v];x/=2;y+=p[v+1];y/=2;c[x][y]++;}}return c[i][j];}
unsigned char BL(int i,int j){static int c[DIM][DIM];if(i+j<1){A;for(int n=0;n<3e7;n++){int v=(rand()%11+4)%5*2;x+=p[v];x/=2;y+=p[v+1];y/=2;c[x][y]++;}}return c[i][j];}
```
Thanks to [Martin Büttner](https://codegolf.stackexchange.com/users/8478/martin-b%C3%BCttner) for the idea mentioned in the question's comments about defining a macro in one function to then use in another, and also for using memoisation to fill the pixels in an arbitrary order rather than being restricted to the raster order of the main function.
![pentagon](https://i.stack.imgur.com/VApm6.jpg "Sierpinski style pentagon")
The image is over 500KB so it gets automatically converted to jpg by stack exchange. This blurs some of the finer detail, so I've also included just the top right quarter as a png to show the original look:
![top right](https://i.stack.imgur.com/xesJU.png "top right quarter at original quality")
[Answer]
# Sheet Music
Sierpinski music. :D The guys on chat say it looks more like the punched paper for music boxes.
![Sheet music](https://i.stack.imgur.com/xh7Iv.png)
```
unsigned short RD(int i,int j){
    return ((int)(100*sin((i+400)*(j+100)/11115)))&i;
}
unsigned short GR(int i,int j){
    return RD(i,j);
}
unsigned short BL(int i,int j){
    return RD(i,j);
}
```
Some details on how this works...um, it's actually just a zoom-in on a render of some wavy Sierpinski triangles. The sheet-music look (and also the blockiness) is the result of integer truncation. If I change the red function to, say, 
```
return ((int)(100*sin((i+400)*(j+100)/11115.0)));
```
the truncation is removed and we get the full resolution render:
![Non-blocky sheet music](https://i.stack.imgur.com/Ktt6U.jpg)
So yeah, that's interesting.
[Answer]
# Random [Voronoi diagram](http://en.wikipedia.org/wiki/Voronoi_diagram) generator anyone?
OK, this one gave me a hard time. I think it's pretty nice though, even if the results are not so *arty* as some others. That's the deal with randomness. Maybe some intermediate images look better, but I really wanted to have a fully working algorithm with voronoi diagrams.
![enter image description here](https://i.stack.imgur.com/Nr8zQ.png)
# Edit:
![enter image description here](https://i.stack.imgur.com/FbbJr.png)
This is one example of the final algorithm. The image is basically the superposition of three voronoi diagram, one for each color component (red, green, blue).
## Code
**ungolfed, commented version at the end**
```
unsigned short red_fn(int i, int j){
int t[64],k=0,l,e,d=2e7;srand(time(0));while(k<64){t[k]=rand()%DIM;if((e=_sq(i-t[k])+_sq(j-t[42&k++]))<d)d=e,l=k;}return t[l];
}
unsigned short green_fn(int i, int j){
static int t[64];int k=0,l,e,d=2e7;while(k<64){if(!t[k])t[k]=rand()%DIM;if((e=_sq(i-t[k])+_sq(j-t[42&k++]))<d)d=e,l=k;}return t[l];
}
unsigned short blue_fn(int i, int j){
static int t[64];int k=0,l,e,d=2e7;while(k<64){if(!t[k])t[k]=rand()%DIM;if((e=_sq(i-t[k])+_sq(j-t[42&k++]))<d)d=e,l=k;}return t[l];
}
```
It took me a lot of efforts, so I feel like sharing the results at different stages, and there are nice (incorrect) ones to show.
## First step: have some points placed randomly, with `x=y`
![enter image description here](https://i.stack.imgur.com/mRi8x.jpg)
I have converted it to jpeg because the original png was too heavy for upload (`>2MB`), I bet that's way more than 50 shades of grey!
## Second: have a better y coordinate
I couldn't afford to have another table of coordinates randomly generated for the `y` axis, so I needed a simple way to get **"** random **"** ones in as few characters as possible. I went for using the `x` coordinate of another point in the table, by doing a bitwise `AND` on the index of the point.
![enter image description here](https://i.stack.imgur.com/SWSow.png)
## 3rd: I don't remember but it's getting nice
But at this time I was way over 140 chars, so I needed to golf it down quite a bit.
![enter image description here](https://i.stack.imgur.com/FtUNH.png)
## 4th: scanlines
Just kidding, this is not wanted but kind of cool, methinks.
![enter image description here](https://i.stack.imgur.com/AnSXs.png)
![enter image description here](https://i.stack.imgur.com/IxHqh.png)
Still working on reducing the size of the algorithm, I am proud to present:
### StarFox edition
![enter image description here](https://i.stack.imgur.com/Jmoz4.png)
### Voronoi instagram
![enter image description here](https://i.stack.imgur.com/2fSkP.jpg)
## 5th: increase the number of points
I have now a working piece of code, so let's go from 25 to 60 points.
![enter image description here](https://i.stack.imgur.com/NlpsC.png)
That's hard to see from only one image, but the points are nearly all located in the same `y` range. Of course, I didn't change the bitwise operation, `&42` is much better:
![enter image description here](https://i.stack.imgur.com/efACY.png)
And here we are, at the same point as the very first image from this post. 
Let's now explain the code for the rare ones that would be interested.
## Ungolfed and explained code
```
unsigned short red_fn(int i, int j)
{
    int t[64],          // table of 64 points's x coordinate
        k = 0,          // used for loops
        l,              // retains the index of the nearest point
        e,              // for intermediary results
        d = 2e7;        // d is the minimum distance to the (i,j) pixel encoutnered so far
        // it is initially set to 2e7=2'000'000 to be greater than the maximum distance 1024²
    srand(time(0));     // seed for random based on time of run
    // if the run overlaps two seconds, a split will be observed on the red diagram but that is
    // the better compromise I found
    while(k < 64)       // for every point
    {
        t[k] = rand() % DIM;        // assign it a random x coordinate in [0, 1023] range
        // this is done at each call unfortunately because static keyword and srand(...)
        // were mutually exclusive, lenght-wise
        if (
            (e=                         // assign the distance between pixel (i,j) and point of index k
                _sq(i - t[k])           // first part of the euclidian distance
                +
                _sq(j - t[42 & k++])    // second part, but this is the trick to have "" random "" y coordinates
                // instead of having another table to generate and look at, this uses the x coordinate of another point
                // 42 is 101010 in binary, which is a better pattern to apply a & on; it doesn't use all the table
                // I could have used 42^k to have a bijection k <-> 42^k but this creates a very visible pattern splitting the image at the diagonal
                // this also post-increments k for the while loop
            ) < d                       // chekcs if the distance we just calculated is lower than the minimal one we knew
        )
        // {                            // if that is the case
            d=e,                        // update the minimal distance
            l=k;                        // retain the index of the point for this distance
            // the comma ',' here is a trick to have multiple expressions in a single statement
            // and therefore avoiding the curly braces for the if
        // }
    }
    return t[l];        // finally, return the x coordinate of the nearest point
    // wait, what ? well, the different areas around points need to have a
    // "" random "" color too, and this does the trick without adding any variables
}
// The general idea is the same so I will only comment the differences from green_fn
unsigned short green_fn(int i, int j)
{
    static int t[64];       // we don't need to bother a srand() call, so we can have these points
    // static and generate their coordinates only once without adding too much characters
    // in C++, objects with static storage are initialized to 0
    // the table is therefore filled with 60 zeros
    // see http://stackoverflow.com/a/201116/1119972
    int k = 0, l, e, d = 2e7;
    while(k<64)
    {
        if( !t[k] )                 // this checks if the value at index k is equal to 0 or not
        // the negation of 0 will cast to true, and any other number to false
            t[k] = rand() % DIM;    // assign it a random x coordinate
        // the following is identical to red_fn
        if((e=_sq(i-t[k])+_sq(j-t[42&k++]))<d)
            d=e,l=k;
    }
    return t[l];
}
```
**Thanks for reading so far.**
[Answer]
The Lyapunov Fractal
![Lyapunov Fractal](https://i.stack.imgur.com/CJO8p.jpg)
The string used to generate this was AABAB and the parameter space was [2,4]x[2,4]. ([explanation of string and parameter space here](http://en.wikipedia.org/wiki/Lyapunov_fractal))
With limited code space I thought this colouring was pretty cool.
```
    //RED
    float r,s=0,x=.5;for(int k=0;k++<50;)r=k%5==2||k%5==4?(2.*j)/DIM+2:(2.*i)/DIM+2,x*=r*(1-x),s+=log(fabs(r-r*2*x));return abs(s);
    //GREEN
    float r,s=0,x=.5;for(int k=0;k++<50;)r=k%5==2||k%5==4?(2.*j)/DIM+2:(2.*i)/DIM+2,x*=r*(1-x),s+=log(fabs(r-r*2*x));return s>0?s:0;
    //BLUE
    float r,s=0,x=.5;for(int k=0;k++<50;)r=k%5==2||k%5==4?(2.*j)/DIM+2:(2.*i)/DIM+2,x*=r*(1-x),s+=log(fabs(r-r*2*x));return abs(s*x);
```
I also made a variation of the Mandelbrot set. It uses a map similar to the Mandelbrot set map. Say M(x,y) is the Mandelbrot map. Then M(sin(x),cos(y)) is the map I use, and instead of checking for escaping values I use x, and y since they are always bounded.
```
//RED
float x=0,y=0;for(int k=0;k++<15;){float t=_sq(sin(x))-_sq(cos(y))+(i-512.)/512;y=2*sin(x)*cos(y)+(j-512.0)/512;x=t;}return 2.5*(x*x+y*y);
//GREEN
float x=0,y=0;for(int k=0;k++<15;){float t=_sq(sin(x))-_sq(cos(y))+(i-512.)/512;y=2*sin(x)*cos(y)+(j-512.0)/512;x=t;}return 15*fabs(x);
//BLUE
float x=0,y=0;for(int k=0;k++<15;){float t=_sq(sin(x))-_sq(cos(y))+(i-512.)/512;y=2*sin(x)*cos(y)+(j-512.0)/512;x=t;}return 15*fabs(y);
```
![enter image description here](https://i.stack.imgur.com/byvJz.jpg)
**EDIT**
After much pain I finally got around to creating a gif of the second image morphing. Here it is:
![Party Time](https://i.stack.imgur.com/aQBpp.gif)
[Answer]
Because unicorns.
![Because unicorns](https://i.stack.imgur.com/6ANq3.png)
I couldn't get the OPs version with `unsigned short` and colour values up to 1023 working, so until that is fixed, here is a version using `char` and maximum colour value of 255.
```
char red_fn(int i,int j){
    return (char)(_sq(cos(atan2(j-512,i-512)/2))*255);
}
char green_fn(int i,int j){
    return (char)(_sq(cos(atan2(j-512,i-512)/2-2*acos(-1)/3))*255);
}
char blue_fn(int i,int j){
    return (char)(_sq(cos(atan2(j-512,i-512)/2+2*acos(-1)/3))*255);
}
```
[Answer]
## Logistic Hills
![enter image description here](https://i.stack.imgur.com/wmfTl.png)
## The functions
```
unsigned char RD(int i,int j){    
    #define A float a=0,b,k,r,x
    #define B int e,o
    #define C(x) x>255?255:x
    #define R return
    #define D DIM
    R BL(i,j)*(D-i)/D;
}
unsigned char GR(int i,int j){      
    #define E DM1
    #define F static float
    #define G for(
    #define H r=a*1.6/D+2.4;x=1.0001*b/D
    R BL(i,j)*(D-j/2)/D;
}
unsigned char BL(int i,int j){
    F c[D][D];if(i+j<1){A;B;G;a<D;a+=0.1){G b=0;b<D;b++){H;G k=0;k<D;k++){x=r*x*(1-x);if(k>D/2){e=a;o=(E*x);c[e][o]+=0.01;}}}}}R C(c[j][i])*i/D;
}
```
## Ungolfed
All of the #defines are to fit BL under 140 chars. Here is the ungolfed version of the blue algorithm, slightly modified:
```
for(double a=0;a<DIM;a+=0.1){       // Incrementing a by 1 will miss points
    for(int b=0;b<DIM;b++){         // 1024 here is arbitrary, but convenient
        double r = a*(1.6/DIM)+2.4; // This is the r in the logistic bifurcation diagram (x axis)
        double x = 1.0001*b/DIM;    // This is x in the logistic bifurcation diagram (y axis). The 1.0001 is because nice fractions can lead to pathological behavior.
        for(int k=0;k<DIM;k++){
            x = r*x*(1-x);          // Apply the logistic map to x
            // We do this DIM/2 times without recording anything, just to get x out of unstable values
            if(k>DIM/2){
                if(c[(int)a][(int)(DM1*x)]<255){
                    c[(int)a][(int)(DM1*x)]+=0.01; // x makes a mark in c[][]
                } // In the golfed code, I just always add 0.01 here, and clip c to 255
            }
        }            
    }    
}
```
Where the values of x fall the most often for a given r (j value), the plot becomes lighter (usually depicted as darker).
[Answer]
# Diffusion Limited Aggregation
I've always been fascinated by [diffusion limited aggregation](http://en.wikipedia.org/wiki/Diffusion-limited_aggregation) and the number of different ways it appears in the real world.
I found it difficult to write this in just 140 characters per function so I've had to make the code horrible (or beautiful, if you like things like `++d%=4` and `for(n=1;n;n++)`). The three colour functions call each other and define macros for each other to use, so it doesn't read well, but each function is just under 140 characters.
```
unsigned char RD(int i,int j){
#define D DIM
#define M m[(x+D+(d==0)-(d==2))%D][(y+D+(d==1)-(d==3))%D]
#define R rand()%D
#define B m[x][y]
return(i+j)?256-(BL(i,j))/2:0;}
unsigned char GR(int i,int j){
#define A static int m[D][D],e,x,y,d,c[4],f,n;if(i+j<1){for(d=D*D;d;d--){m[d%D][d/D]=d%6?0:rand()%2000?1:255;}for(n=1
return RD(i,j);}
unsigned char BL(int i,int j){A;n;n++){x=R;y=R;if(B==1){f=1;for(d=0;d<4;d++){c[d]=M;f=f<c[d]?c[d]:f;}if(f>2){B=f-1;}else{++e%=4;d=e;if(!c[e]){B=0;M=1;}}}}}return m[i][j];}
```
![diffusion limited aggregation](https://i.stack.imgur.com/44aOn.png "diffusion limited aggregation")
To visualise how the particles gradually aggregate, I produced snapshots at regular intervals. Each frame was produced by replacing the 1 in `for(n=1;n;n++)` with 0, -1<<29, -2<<29, -3<<29, 4<<29, 3<<29, 2<<29, 1<<29, 1. This kept it just under the 140 character limit for each run.
![animated aggregation](https://i.stack.imgur.com/G7aH9.gif "animated aggregation")
You can see that aggregates growing close to each other deprive each other of particles and grow more slowly.
---
By making a slight change to the code you can see the remaining particles that haven't become attached to the aggregates yet. This shows the denser regions where growth will happen more quickly and the very sparse regions between aggregates where no more growth can occur due to all the particles having been used up.
```
unsigned char RD(int i,int j){
#define D DIM
#define M m[(x+D+(d==0)-(d==2))%D][(y+D+(d==1)-(d==3))%D]
#define R rand()%D
#define B m[x][y]
return(i+j)?256-BL(i,j):0;}
unsigned char GR(int i,int j){
#define A static int m[D][D],e,x,y,d,c[4],f,n;if(i+j<1){for(d=D*D;d;d--){m[d%D][d/D]=d%6?0:rand()%2000?1:255;}for(n=1
return RD(i,j);}
unsigned char BL(int i,int j){A;n;n++){x=R;y=R;if(B==1){f=1;for(d=0;d<4;d++){c[d]=M;f=f<c[d]?c[d]:f;}if(f>2){B=f-1;}else{++e%=4;d=e;if(!c[e]){B=0;M=1;}}}}}return m[i][j];}
```
![DLA with visible particles](https://i.stack.imgur.com/woEEk.png "DLA with visible particles")
This can be animated in the same way as before:
![animated aggregation with particles](https://i.stack.imgur.com/54U8g.gif "animated aggregation with particles")
[Answer]
# Spiral (140 exactly)
![final product](https://i.stack.imgur.com/Ii8jM.jpg)
This is 140 characters exactly if you don't include the function headers and brackets. It's as much spiral complexity I could fit in the character limit.
```
unsigned char RD(int i,int j){
    return DIM-BL(2*i,2*j);
}
unsigned char GR(int i,int j){
    return BL(j,i)+128;
}
unsigned char BL(int i,int j){
    i-=512;j-=512;int d=sqrt(i*i+j*j);return d+atan2(j,i)*82+sin(_cr(d*d))*32+sin(atan2(j,i)*10)*64;
}
```
I gradually built on a simple spiral, adding patterns to the spiral edges and experimenting with how different spirals could be combined to look cool. Here is an ungolfed version with comments explaining what each piece does. Messing with parameters can produce some interesting results.
```
unsigned char RD(int i,int j){
    // *2 expand the spiral
    // DIM- reverse the gradient
    return DIM - BL(2*i, 2*j);
}
unsigned char GR(int i,int j){
    // notice swapped parameters
    // 128 changes phase of the spiral
    return BL(j,i)+128;
}
unsigned char BL(int i,int j){
    // center it
    i -= DIM / 2;
    j -= DIM / 2;
    double theta = atan2(j,i); //angle that point is from center
    double prc = theta / 3.14f / 2.0f; // percent around the circle
    int dist = sqrt(i*i + j*j); // distance from center
    // EDIT: if you change this to something like "prc * n * 256" where n
    //   is an integer, the spirals will line up for any arbitrarily sized
    //   DIM value, or if you make separate DIMX and DIMY values!
    int makeSpiral = prc * DIM / 2;
    // makes pattern on edge of the spiral
    int waves = sin(_cr(dist * dist)) * 32 + sin(theta * 10) * 64;
    return dist + makeSpiral + waves;
}
```
Messing with parameters:
Here, the spirals are lined up but have different edge patterns. Instead of the blocky edges in the main example, this has edges entirely comprised of sin waves.
![edges](https://i.stack.imgur.com/65mDZ.jpg)
Here, the gradient has been removed:
![no gradient](https://i.stack.imgur.com/0TzSP.png)
An animation (which for some reason doesn't appear to be looping after I uploaded it, sorry. Also, I had to shrink it. Just open it in a new tab if you missed the animation):
![animation](https://i.stack.imgur.com/f3AAU.gif)
And, here's the [imgur album](https://i.stack.imgur.com/tph5o.jpg) with all images in it. I'd love to see if anyone can find other cool spiral patterns. Also, I must say, this is by far one of the coolest challenges on here I have ever seen. Enjoy!
EDIT: Here are some [backgrounds](https://i.stack.imgur.com/8Uw23.jpg) made from these spirals with altered parameters.
Also, by combining my spiral edge patterns with some of the fractals I've seen on here through the use of xor/and/or operations, here is a final spiral:
![fractal spiral](https://i.stack.imgur.com/BMuOA.jpg)
[Answer]
## Tribute to a classic
*V1*: Inspired by DreamWarrior's "Be happy", this straightforward submission embeds a small pixel-art image in each colour channel. I didn't even have to golf the code!  
*V2*: now with considerably shorter code & a thick black border isolating only the "game screen".  
*V3*: spaceship, bullet, damaged aliens and blue border, oh my! Trying to aim for [this](http://upload.wikimedia.org/wikipedia/en/2/20/SpaceInvaders-Gameplay.gif), roughly.
```
// RED
#define g(I,S,W,M)j/128%8==I&W>>(j/32%4*16+i/64)%M&S[abs(i/4%16-8)-(I%2&i%64<32)]>>j/4%8&1
return g(1,"_\xB6\\\x98\0\0\0",255L<<36,64)?j:0;
// GREEN
#define S g(6,"\xFF\xFE\xF8\xF8\xF8\xF8\xF0\x0",1L<<22,64)|i/4==104&j/24==30
return g(2,"<\xBC\xB6}\30p\0\0",4080,32)|S?j:0;
// BLUE
return g(3,"_7\xB6\xFE\x5E\34\0",0x70000000FD0,64)|S|abs(i/4-128)==80&abs(j/4-128)<96|abs(j/4-128)==96&abs(i/4-128)<80?j:0;
```
![Space invaders](https://i.stack.imgur.com/3T1II.png)
---
I happened to stumble upon an edit by [Umber Ferrule](https://codegolf.stackexchange.com/users/3268/umber-ferrule) whose avatar inspired me to add another pixel-art-based entry. Since the core idea of the code is largely similar to the Space Invaders one, I'm appending it to this entry, though the two definitely had different challenging points. For this one, getting pink right (at the expense of white) and the fact that it's a rather big sprite proved nice challenges. The hexadecimal escapes (`\xFF` etc) in the red channel represent their corresponding characters in the source file (that is, the red channel in the source file contains binary data), whereas the octal escapes are literal (i.e. present in the source file).
```
// RED
#define g(S)(S[i/29%18*2+j/29/8%2]>>j/29%8&1)*DM1*(abs(i-512)<247&abs(j-464)<232)
return g("\xF3\xF2\xF2\x10\xF4\0\xF2\x10\xE1\xE0\x81\0\x80\0\x80\0\0\0\0\0@\0! \x03d8,=\x2C\x99\x84\xC3\x82\xE1\xE3");
// GREEN
return g(";\376z\34\377\374\372\30k\360\3\200\0\0\0\0\0\0\200\0\300\0\341 \373d\307\354\303\374e\374;\376;\377")? DM1 : BL(i,j)? DM1/2 : 0;
// BLUE
return g("\363\360\362\20\364\0\362\20\341\340\200\0\200\0\200\0\0\0\0\0\0\0\0\0\0\08\0<\0\230\0\300\0\341\340") / 2;
```
![Bub (Bubble Bobble)](https://i.stack.imgur.com/uxmib.png)
[Answer]
# Action Painting
I wanted to try recreating something similar to the work of [Jackson Pollock](http://en.wikipedia.org/wiki/Jackson_Pollock) - dripping and pouring paint over a horizontal canvas. Although I liked the results, the code was much too long to post to this question and my best efforts still only reduced it to about 600 bytes. So the code posted here (which has functions of 139 bytes, 140 bytes, and 140 bytes respectively) was produced with an enormous amount of help from some of the geniuses in [chat](http://chat.stackexchange.com/rooms/240/the-nineteenth-byte). Huge thanks to:
* [Eric Tressler](https://codegolf.stackexchange.com/users/17484/eric-tressler)
* [FireFly](https://codegolf.stackexchange.com/users/3918/firefly)
* [PhiNotPi](https://codegolf.stackexchange.com/users/2867/phinotpi)
* [Martin Büttner](https://codegolf.stackexchange.com/users/8478/martin-b%C3%BCttner)
for a relentless group golfing session.
```
unsigned char RD(int i,int j){
#define E(q)return i+j?T-((T-BL(i,j))*q):T;
#define T 255
#define R .1*(rand()%11)
#define M(v)(v>0&v<DIM)*int(v)
#define J [j]*250;
E(21)}
unsigned char GR(int i,int j){
#define S DIM][DIM],n=1e3,r,a,s,c,x,y,d=.1,e,f;for(;i+j<1&&n--;x=R*DM1,y=R*DM1,s=R*R*R*R,a=R*7,r=s*T)for(c=R;r>1;x+=s*cos(a),y+=s*sin
E(21)}
unsigned char BL(int i,int j){static float m[S(a),d=rand()%39?d:-d,a+=d*R,s*=1+R/99,r*=.998)for(e=-r;e++<r;)for(f=-r;f++<r;)m[M(x+e)*(e*e+f*f<r)][M(y+f)]=c;return T-m[i]J}
```
![action painting 21, 21](https://i.stack.imgur.com/ojtkU.png "action painting 21, 21")
The E(q) macro is used in the RD and GR functions. Changing the value of the argument changes the way the red and green components of the colours change. The J macro ends with a number which is used to determine how much the blue component changes, which in turn affects the red and green components because they are calculated from it. I've include some images with the red and green arguments of E varied to show the variety of colour combinations possible. Hover over the images for the red and green values if you want to run these yourself.
![action painting 14, 14](https://i.stack.imgur.com/7Piib.png "action painting 14, 14")
![action painting 63, 49](https://i.stack.imgur.com/uM9hh.png "action painting 63, 49")
![action painting 56, 42](https://i.stack.imgur.com/VyZwZ.png "action painting 56, 42")
![action painting 0, 49](https://i.stack.imgur.com/WvEEp.png "action painting 0, 49")
All of these images can be viewed at full size if you download them. The file size is small as the flat colour suits the PNG compression algorithm, so no lossy compression was required in order to upload to the site.
If you'd like to see images from various stages in the golfing process as we tried out different things, you can look in the [action painting chat](http://chat.stackexchange.com/rooms/16410/action-painting-golf).
[Answer]
Figured I'd play with [this code](https://codegolf.stackexchange.com/questions/35569/tweetable-mathematical-art/35739#35739)'s parameters... All credit goes to @Manuel Kasten. These are just so cool that I couldn't resist posting.
![Hot & Cold](https://i.stack.imgur.com/JDvb6.png)
```
/* RED */
double a=0,b=0,c,d,n=0;
while((c=a*a)+(d=b*b)<4&&n++<880){b=2*a*b+(j)*9e-9-.645411;a=c-d+(i)*9e-9+.356888;}
return 1000*pow((n)/800,.5);
/* GREEN */
double a=0,b=0,c,d,n=0;
while((c=a*a)+(d=b*b)<4&&n++<880){b=2*a*b+(j)*9e-9-.645411;a=c-d+(i)*9e-9+.356888;}
return 8000*pow((n)/800,.5);
/* BLUE */
double a=0,b=0,c,d,n=0;
while((c=a*a)+(d=b*b)<4&&n++<880){b=2*a*b+(j)*9e-9-.645411;a=c-d+(i)*9e-9+.356888;}
return 8000*pow((n)/800,.5);
```
[BubbleGumRupture http://i57.tinypic.com/3150eqa.png](http://i57.tinypic.com/3150eqa.png)
```
/* RED */
double a=0,b=0,c,d,n=0;
while((c=a*a)+(d=b*b)<4&&n++<880){b=2*a*b+(j)*9e-9-.645411;a=c-d+(i)*9e-9+.356888;}
return 8000*pow((n)/800,.5);
/* GREEN */
double a=0,b=0,c,d,n=0;
while((c=a*a)+(d=b*b)<4&&n++<880){b=2*a*b+(j)*9e-9-.645411;a=c-d+(i)*9e-9+.356888;}
return 40*pow((n)/800,.5);
/* BLUE */
double a=0,b=0,c,d,n=0;
while((c=a*a)+(d=b*b)<4&&n++<880){b=2*a*b+(j)*9e-9-.645411;a=c-d+(i)*9e-9+.356888;}
return 10*pow((n)/800,.5);
```
[SeussZoom http://i59.tinypic.com/am3ypi.png](http://i59.tinypic.com/am3ypi.png)
```
/* RED */
double a=0,b=0,c,d,n=0;
while((c=a*a)+(d=b*b)<4&&n++<880){b=2*a*b+j*8e-8-.645411;a=c-d+i*8e-8+.356888;}
return 2000*pow((n)/800,.5);
/* GREEN */
double a=0,b=0,c,d,n=0;
while((c=a*a)+(d=b*b)<4&&n++<880){b=2*a*b+j*8e-8-.645411;a=c-d+i*8e-8+.356888;}
return 1000*pow((n)/800,.5);
/* BLUE */
double a=0,b=0,c,d,n=0;
while((c=a*a)+(d=b*b)<4&&n++<880){b=2*a*b+j*8e-8-.645411;a=c-d+i*8e-8+.356888;}
return 4000*pow((n)/800,.5);
```
[SeussEternalForest http://i61.tinypic.com/35akv91.png](http://i61.tinypic.com/35akv91.png)
```
/* RED */
double a=0,b=0,c,d,n=0;
while((c=a*a)+(d=b*b)<4&&n++<880){b=2*a*b+j*8e-9-.645411;a=c-d+i*8e-9+.356888;}
return 2000*pow((n)/800,.5);
/* GREEN */
double a=0,b=0,c,d,n=0;
while((c=a*a)+(d=b*b)<4&&n++<880){b=2*a*b+j*8e-9-.645411;a=c-d+i*8e-9+.356888;}
return 1000*pow((n)/800,.5);
/* BLUE */
double a=0,b=0,c,d,n=0;
while((c=a*a)+(d=b*b)<4&&n++<880){b=2*a*b+j*8e-9-.645411;a=c-d+i*8e-9+.356888;}
return 4000*pow((n)/800,.5);
```
[Answer]
This calculates the [Joukowsky transform](http://en.wikipedia.org/wiki/Joukowsky_transform) of a set of concentric circles centred on a point slightly offset from the origin. I slightly modified the intensities in the blue channel to give a bit of colour variation.
```
unsigned short RD(int i,int j){
    double r=i/256.-2,s=j/256.-2,q=r*r+s*s,n=hypot(r+(.866-r/2)/q,s+(r*.866+s/2)/q),
    d=.5/log(n);if(d<0||d>1)d=1;return d*(sin(n*10)*511+512);
}
unsigned short GR(int i,int j){
    return 0;
}
unsigned short BL(int i,int j){
    double r=i/256.-2,s=j/256.-2,q=r*r+s*s;return RD(i,j)*sqrt(q/40);
}
```
![enter image description here](https://i.stack.imgur.com/qPR9v.jpg)
[Answer]
**Edit:** This is now a valid answer, thanks to the forward declarations of `GR` and `BL`.
Having fun with Hofstadter's Q-sequence! If we're using the radial distance from some point as the input and the output as the inverse colour, we get something which looks like coloured vinyl.
![enter image description here](https://i.stack.imgur.com/k5d8J.png)
The sequence is very similar to the Fibonacci sequence, but instead of going 1 and 2 steps back in the sequence, you take the two previous values to *determine* how far to go back before taking the sum. It grows roughly linear, but every now and then there's a burst of chaos (at increasing intervals) which then settles down to an almost linear sequence again before the next burst:
![enter image description here](https://i.stack.imgur.com/NqP82.png)
You can see these ripples in the image after regions which look very "flat" in colour.
Of course, using only one colour is boring.
![enter image description here](https://i.stack.imgur.com/uCS81.png)
Now for the code. I need the recursive function to compute the sequence. To do that I use `RD` whenever `j` is negative. Unfortunately, that does not leave enough characters to compute the red channel value itself, so `RD` in turn calls `GR` with an offset to produce the red channel.
```
unsigned short RD(int i,int j){
    static int h[1000];return j<0?h[i]?h[i]:h[i]=i<2?1:RD(i-RD(i-1,j),j)+RD(i-RD(i-2,j),j):GR(i+256,j+512);
}
unsigned short GR(int i,int j){
    return DIM-4*RD(sqrt((i-512)*(i-512)+(j-768)*(j-768))/2.9,-1);
}
unsigned short BL(int i,int j){
    return DIM-4*RD(sqrt((i-768)*(i-768)+(j-256)*(j-256))/2.9,-1);
}
```
Of course, this is pretty much the simplest possible usage of the sequence, and there are loads of characters left. Feel free to borrow it and do other crazy things with it!
Here is another version where the boundary and the colours are determined by the Q-sequence. In this case, there was enough room in `RD` so that I didn't even need the forward declaration:
```
unsigned short RD(int i,int j){
    static int h[1024];return j<0?h[i]?h[i]:h[i]=i<2?1:RD(i-RD(i-1,j),j)+RD(i-RD(i-2,j),j):RD(2*RD(i,-1)-i+512>1023-j?i:1023-i,-1)/0.6;
}
unsigned short GR(int i,int j){
    return RD(i, j);
}
unsigned short BL(int i,int j){
    return RD(i, j);
}
```
![enter image description here](https://i.stack.imgur.com/hHIBa.png)
[Answer]
# Objective-C
Rewrote the C++ code in Objective-C cos I couldn't get it to compile... It gave the same results as other answer when running on my iPad, so that's all good.
Here's my submission:
![Triangles Galore](https://i.stack.imgur.com/qlkCf.png)
The code behind it is fairly simple:
```
unsigned short red_fn(int i,int j)
{
    return j^j-i^i;
}
unsigned short green_fn(int i,int j)
{
    return (i-DIM)^2+(j-DIM)^2;
}
unsigned short blue_fn(int i,int j)
{
    return i^i-j^j;
}
```
You can zoom in on squares by multiplying `i` and `j` by `0.5`, `0.25` etc. before they are processed.
[Answer]
# Sierpinski Paint Splash
I wanted to play more with colors so I kept changing my other answer (the swirly one) and eventually ended up with this.
![Sierpinski Paint Splash](https://i.stack.imgur.com/xAofW.png)
```
unsigned short RD(int i,int j){
    return(sqrt(_sq(abs(73.-i))+_sq(abs(609.-j)))+1.)/abs(sin((sqrt(_sq(abs(860.-i))+_sq(abs(162.-j))))/115.)+2)/(115^i&j);
}
unsigned short GR(int i,int j){
    return(sqrt(_sq(abs(160.-i))+_sq(abs(60.-j)))+1.)/abs(sin((sqrt(_sq(abs(73.-i))+_sq(abs(609.-j))))/115.)+2)/(115^i&j);
}
unsigned short BL(int i,int j){
    return(sqrt(_sq(abs(600.-i))+_sq(abs(259.-j)))+1.)/abs(sin((sqrt(_sq(abs(250.-i))+_sq(abs(20.-j))))/115.)+2)/(115^i&j);
}
```
It's my avatar now. :P
[Answer]
# groovy
![groovy.png](https://i.stack.imgur.com/hKbKu.png)
Just some trigonometry and weird macro tricks.
RD:
```
#define I (i-512)
#define J (j-512)
#define A (sin((i+j)/64.)*cos((i-j)/64.))
return atan2(I*cos A-J*sin A,I*sin A+J*cos A)/M_PI*1024+1024;
```
GR:
```
#undef A
#define A (M_PI/3+sin((i+j)/64.)*cos((i-j)/64.))
return atan2(I*cos A-J*sin A,I*sin A+J*cos A)/M_PI*1024+1024;
```
BL:
```
#undef A
#define A (2*M_PI/3+sin((i+j)/64.)*cos((i-j)/64.))
return atan2(I*cos A-J*sin A,I*sin A+J*cos A)/M_PI*1024+1024;
```
EDIT: if `M_PI` isn't allowed due to only being present on POSIX-compatible systems, it can be replaced with the literal `3.14`.
[Answer]
I feel compelled to submit this entry that I will call "undefined behavior", which will illustrate what your compiler does with functions that are supposed to return a value but don't:
```
unsigned short red_fn(int i,int j){}
unsigned short green_fn(int i,int j){}
unsigned short blue_fn(int i,int j){}
```
All black pixels:
![all black pixels](https://i.stack.imgur.com/Atu6Z.png)
Pseudo-random pixels:
![pseudo-random pixels](https://i.stack.imgur.com/bbHmK.jpg)
And, of course, a host of other possible results depending on your compiler, computer, memory manager, etc.
[Answer]
I'm not good at math. I was always poor student at math class. So I made simple one.
![mathpic1.png](https://i.stack.imgur.com/hbvIy.png)
I used modified [user1455003's Javascript code](https://codegolf.stackexchange.com/a/35595/19759). And [this is my full code](http://bl.ocks.org/Snack-X/906e6d962c93293e2771).
```
function red(x, y) {
    return (x + y) & y;
}
function green(x, y) {
    return (255 + x - y) & x;
}
function blue(x, y) {
    // looks like blue channel is useless
    return Math.pow(x, y) & y;
}
```
It's very short so all three functions fits in one tweet.
---
![mathpic2.png](https://i.stack.imgur.com/iVcoa.png)
```
function red(x, y) {
    return Math.cos(x & y) << 16;
}
function green(x, y) {
    return red(DIM - x, DIM - y);
}
function blue(x, y) {
    return Math.tan(x ^ y) << 8;
}
```
Another very short functions. I found this sierpinski pattern (and some tangent pattern) while messing around with various math functions. [This is full code](http://bl.ocks.org/Snack-X/4b9b286e9c276b11d7dc)
[Answer]
# Planetary Painter
```
//red
static int r[DIM];int p=rand()%9-4;r[i]=i&r[i]?(r[i]+r[i-1])/2:i?r[i-1]:512;r[i]+=r[i]+p>0?p:0;return r[i]?r[i]<DIM?r[i]:DM1:0;
//green
static int r[DIM];int p=rand()%7-3;r[i]=i&r[i]?(r[i]+r[i-1])/2:i?r[i-1]:512;r[i]+=r[i]+p>0?p:0;return r[i]?r[i]<DIM?r[i]:DM1:0;
//blue
static int r[DIM];int p=rand()%15-7;r[i]=i&r[i]?(r[i]+r[i-1])/2:i?r[i-1]:512;r[i]+=r[i]+p>0?p:0;return r[i]?r[i]<DIM?r[i]:DM1:0;
```
Inspired by Martin's [obviously awesome entry](https://codegolf.stackexchange.com/a/35626/14215), this is a different take on it. Instead of randomly seeding a portion of the pixels, I start with the top left corner as RGB(512,512,512), and take random walks on each color from there. The result looks like something from a telescope (imo).
Each pixel takes the average of the pixels above/left of it and adds a bit o' random. You can play with the variability by changing the `p` variable, but I think what I'm using is a good balance (mainly because I like blue, so more blur volatility gives good results).
There's a slight negative bias from integer division when averaging. I think it works out, though, and give a nice darkening effect to the bottom corner.
Of course, to get more than just a single result, you'll need to add an `srand()` line to your main function.
![bands](https://i.stack.imgur.com/zv0Ct.png)
[Answer]
# JavaScript
```
var can = document.createElement('canvas');
can.width=1024;
can.height=1024;
can.style.position='fixed';
can.style.left='0px';
can.style.top='0px';
can.onclick=function(){
  document.body.removeChild(can);
};
document.body.appendChild(can);
var ctx = can.getContext('2d');
var imageData = ctx.getImageData(0,0,1024,1024);
var data = imageData.data;
var x = 0, y = 0;
for (var i = 0, len = data.length; i < len;) {
    data[i++] = red(x, y) >> 2;
    data[i++] = green(x, y) >> 2;
    data[i++] = blue(x, y) >> 2;
    data[i++] = 255;
    if (++x === 1024) x=0, y++;
}
ctx.putImageData(imageData,0,0);
function red(x,y){
if(x>600||y>560) return 1024
x+=35,y+=41
return y%124<20&&x%108<20?1024:(y+62)%124<20&&(x+54)%108<20?1024:0
}
function green(x,y){
if(x>600||y>560) return y%160<80?0:1024
x+=35,y+=41
return y%124<20&&x%108<20?1024:(y+62)%124<20&&(x+54)%108<20?1024:0
}
function blue(x,y) {
return ((x>600||y>560)&&y%160<80)?0:1024;
}
```
![usa](https://i.stack.imgur.com/csXrZ.png)
Another version. function bodies are tweetable.
```
function red(x,y){
c=x*y%1024
if(x>600||y>560) return c
x+=35,y+=41
return y%124<20&&x%108<20?c:(y+62)%124<20&&(x+54)%108<20?c:0
}
function green(x,y){
c=x*y%1024
if(x>600||y>560) return y%160<80?0:c
x+=35,y+=41
return y%124<20&&x%108<20?c:(y+62)%124<20&&(x+54)%108<20?c:0
}
function blue(x,y) {
return ((x>600||y>560)&&y%160<80)?0:x*y%1024;
}
```
![enter image description here](https://i.stack.imgur.com/tnWuI.png)
Revised image render function. draw(rgbFunctions, setCloseEvent);
```
function draw(F,e){
    var D=document
    var c,id,d,x,y,i,L,s=1024,b=D.getElementsByTagName('body')[0]
    c=D.createElement('canvas').getContext('2d')
    if(e)c.canvas.onclick=function(){b.removeChild(c.canvas)}
    b.appendChild(c.canvas)
    c.canvas.width=c.canvas.height=s
    G=c.getImageData(0,0,s,s)
    d=G.data
    x=y=i=0;
    for (L=d.length;i<L;){
        d[i++]=F.r(x,y)>>2
        d[i++]=F.g(x,y)>>2
        d[i++]=F.b(x,y)>>2
        d[i++]=255;
        if(++x===s)x=0,y++
    }
    c.putImageData(G,0,0)
}
```
# Purple
```
var purple = {
    r: function(i,j) {
        if (j < 512) j=1024-j
        return (i % j) | i
    },
    g: function(i,j){
        if (j < 512) j = 1024 -j
        return (1024-i ^ (i %j)) % j
    },
    b: function(i,j){
        if (j < 512) j = 1024 -j
        return 1024-i | i+j %512
    }
};
draw(purple,true);
```
![enter image description here](https://i.stack.imgur.com/5HPJT.jpg)
[Answer]
# Reflected waves
```
unsigned char RD(int i,int j){
#define A static double w=8000,l,k,r,d,p,q,a,b,x,y;x=i;y=j;for(a=8;a+9;a--){for(b=8;b+9;b--){l=i-a*DIM-(int(a)%2?227:796);
return 0;}
unsigned char GR(int i,int j){
#define B k=j-b*DIM-(int(b)%2?417:606);r=sqrt(l*l+k*k);d=16*cos((r-w)/7)*exp(-_sq(r-w)/120);p=d*l/r;q=d*k/r;x-=p;y-=q;}}
return 0;}
unsigned char BL(int i,int j){AB
return (int(x/64)+int(y/64))%2*255;}
```
A basic chess board pattern distorted according to the position of a wave expanding from a point like a stone dropped in a pond (very far from physically accurate!). The variable `w` is the number of pixels from that point that the wave has moved. If `w` is large enough, the wave reflects from the sides of the image.
## `w` = 225
![waves with w=225](https://i.stack.imgur.com/pcXbG.png "waves with 2=225")
## `w` = 360
![waves with w=360](https://i.stack.imgur.com/HkJlZ.png "waves with w=360")
## `w` = 5390
![waves with w=5390](https://i.stack.imgur.com/baL5V.png "waves with w=5390")
Here is a GIF showing a succession of images as the wave expands. I've provided a number of different sizes, each showing as many frames as the 500KB file size limit will allow.
![waves large GIF](https://i.stack.imgur.com/E5P5j.gif "waves large GIF")
![waves small GIF](https://i.stack.imgur.com/TFaIn.gif "waves small GIF") ![waves medium GIF](https://i.stack.imgur.com/nNOs0.gif "waves medium GIF")
---
If I can find a way to fit it in, I'd ideally like to have wave interference modelled so that the waves look more realistic when they cross. I'm pleased with the reflection though.
Note that I haven't really modelled wave reflection in 3 lots of 140 bytes. There's not really any reflection going on, it just happens to look like it. I've hidden the explanation in case anyone wants to guess first:
> 
>  The first reflected wave is identical to a wave originating from the other side of the image edge, the same distance away as the original point. So the code calculates the correct position for the 4 points required to give the effect of reflection from each of the 4 edges. Further levels of reflected wave are all identical to a wave originating in a further away tile, if you imagine the image as one tile in a plane. The code gives the illusion of 8 levels of reflection by displaying 189 separate expanding circles, each placed in the correct point in a 17 by 17 grid, so that they pass through the central square of the grid (that is, the image square) at just the right times to give the impression of the required current level of reflection. This is simple (and short!) to code, but runs quite slowly...
> 
> 
> 
]